public_keys_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2023 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "context"
  7. "fmt"
  8. "os"
  9. "path/filepath"
  10. "testing"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/dbtest"
  15. )
  16. func TestPublicKeys(t *testing.T) {
  17. if testing.Short() {
  18. t.Skip()
  19. }
  20. t.Parallel()
  21. ctx := context.Background()
  22. tables := []any{new(PublicKey)}
  23. db := &publicKeys{
  24. DB: dbtest.NewDB(t, "publicKeys", tables...),
  25. }
  26. for _, tc := range []struct {
  27. name string
  28. test func(t *testing.T, ctx context.Context, db *publicKeys)
  29. }{
  30. {"RewriteAuthorizedKeys", publicKeysRewriteAuthorizedKeys},
  31. } {
  32. t.Run(tc.name, func(t *testing.T) {
  33. t.Cleanup(func() {
  34. err := clearTables(t, db.DB, tables...)
  35. require.NoError(t, err)
  36. })
  37. tc.test(t, ctx, db)
  38. })
  39. if t.Failed() {
  40. break
  41. }
  42. }
  43. }
  44. func publicKeysRewriteAuthorizedKeys(t *testing.T, ctx context.Context, db *publicKeys) {
  45. // TODO: Use PublicKeys.Add to replace SQL hack when the method is available.
  46. publicKey := &PublicKey{
  47. OwnerID: 1,
  48. Name: "test-key",
  49. Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
  50. Content: "test-key-content",
  51. }
  52. err := db.DB.Create(publicKey).Error
  53. require.NoError(t, err)
  54. tempSSHRootPath := filepath.Join(os.TempDir(), "publicKeysRewriteAuthorizedKeys-tempSSHRootPath")
  55. conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
  56. err = db.RewriteAuthorizedKeys()
  57. require.NoError(t, err)
  58. authorizedKeys, err := os.ReadFile(authorizedKeysPath())
  59. require.NoError(t, err)
  60. assert.Contains(t, string(authorizedKeys), fmt.Sprintf("key-%d", publicKey.ID))
  61. assert.Contains(t, string(authorizedKeys), publicKey.Content)
  62. }