forgejo/models/forgejo_migrations/v25_test.go
Gusted a8c61532d2
feat: migrate TOTP secrets to keying
- Currently the TOTP secrets are stored using the `secrets` module with
as key the MD5 hash of the Secretkey, the `secrets` module uses general
bad practices. This patch migrates the secrets to use the `keying`
module (#5041) which is easier to use and use better practices to store
secrets in databases.
- Migration test added.
- Remove the Forgejo migration databases, and let the gitea migration
databases also run forgejo migration databases. This is required as the
Forgejo migration is now also touching tables that the forgejo migration
didn't create itself.
2024-11-27 00:34:16 +01:00

50 lines
1.5 KiB
Go

// Copyright 2024 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package forgejo_migrations //nolint:revive
import (
"testing"
"code.gitea.io/gitea/models/auth"
migration_tests "code.gitea.io/gitea/models/migrations/test"
"code.gitea.io/gitea/modules/keying"
"code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_MigrateTwoFactorToKeying(t *testing.T) {
type TwoFactor struct { //revive:disable-line:exported
ID int64 `xorm:"pk autoincr"`
UID int64 `xorm:"UNIQUE"`
Secret string
ScratchSalt string
ScratchHash string
LastUsedPasscode string `xorm:"VARCHAR(10)"`
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
}
// Prepare and load the testing database
x, deferable := migration_tests.PrepareTestEnv(t, 0, new(TwoFactor))
defer deferable()
if x == nil || t.Failed() {
return
}
cnt, err := x.Table("two_factor").Count()
require.NoError(t, err)
assert.EqualValues(t, 1, cnt)
require.NoError(t, MigrateTwoFactorToKeying(x))
var twofactor auth.TwoFactor
_, err = x.Table("two_factor").ID(1).Get(&twofactor)
require.NoError(t, err)
secretBytes, err := keying.DeriveKey(keying.ContextTOTP).Decrypt(twofactor.Secret, keying.ColumnAndID("secret", twofactor.ID))
require.NoError(t, err)
assert.Equal(t, []byte("AVDYS32OPIAYSNBG2NKYV4AHBVEMKKKIGBQ46OXTLMJO664G4TIECOGEANMSNBLS"), secretBytes)
}