| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "log/slog" |
| 10 | "path/filepath" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/carlosframework/docs/internal/docs" |
| 14 | ) |
| 15 | |
| 16 | func TestContentMaintenanceCommandActivatesExistingDatabase(t *testing.T) { |
| 17 | path := filepath.Join(t.TempDir(), "docs.db") |
| 18 | key := bytes.Repeat([]byte{91}, 32) |
| 19 | cfg := docs.Config{DBPath: path, Env: "development", ContentKey: base64.StdEncoding.EncodeToString(key)} |
| 20 | app, err := docs.New(cfg) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | if err := app.Close(); err != nil { |
| 25 | t.Fatal(err) |
| 26 | } |
| 27 | fingerprint := sha256.Sum256(key) |
| 28 | env := func(name string) string { |
| 29 | if name != "DOCS_CONTENT_KEY" { |
| 30 | t.Fatalf("unexpected env: %s", name) |
| 31 | } |
| 32 | return cfg.ContentKey |
| 33 | } |
| 34 | if err := runContentMaintenance(context.Background(), []string{"-db", path, "-expect-fingerprint", hex.EncodeToString(fingerprint[:]), "-scrub"}, env, slog.Default()); err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | cfg.ContentKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{92}, 32)) |
| 38 | app, err = docs.New(cfg) |
| 39 | if app != nil { |
| 40 | app.Close() |
| 41 | } |
| 42 | if err == nil { |
| 43 | t.Fatal("maintenance did not bind database to key") |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func TestContentMaintenanceCommandRequiresExplicitInputs(t *testing.T) { |
| 48 | for _, args := range [][]string{nil, {"-db", "somewhere"}, {"-expect-fingerprint", "something"}, {"-deactivate"}, {"-db", "somewhere", "-expect-fingerprint", "something", "extra"}} { |
| 49 | if err := runContentMaintenance(context.Background(), args, func(string) string { t.Fatal("invalid CLI reached key loading"); return "" }, slog.Default()); err == nil { |
| 50 | t.Fatalf("accepted args: %v", args) |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |