| 1 | package callstest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "log/slog" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/rastrillo/rastrillo/db" |
| 12 | |
| 13 | "amadan.net/oficina/calls/internal/calls" |
| 14 | ) |
| 15 | |
| 16 | func openDB(t *testing.T) *db.DB { |
| 17 | t.Helper() |
| 18 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 19 | if err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | t.Cleanup(func() { d.Close() }) |
| 23 | return d |
| 24 | } |
| 25 | |
| 26 | // testCtx returns a context cancelled at the end of the test, so a |
| 27 | // successful calls.App build's hourly sweep ticker does not outlive it |
| 28 | // (Codex round 3, C3-2: App(context.Background(), ...) in a test leaves |
| 29 | // a goroutine running against a database the test is about to close). |
| 30 | func testCtx(t *testing.T) context.Context { |
| 31 | t.Helper() |
| 32 | ctx, cancel := context.WithCancel(context.Background()) |
| 33 | t.Cleanup(cancel) |
| 34 | return ctx |
| 35 | } |
| 36 | |
| 37 | func TestProductionRefusesToStartWithoutSecrets(t *testing.T) { |
| 38 | // validDEK is a valid 32-byte base64 DEK, used in the "no mailer" |
| 39 | // and "no allowlist" cases so each refuses for its own named |
| 40 | // reason rather than for a bad DEK. |
| 41 | const validDEK = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" |
| 42 | cases := map[string]calls.Config{ |
| 43 | "no origin": {Env: "production"}, |
| 44 | "no key": {Env: "production", Origin: "https://x.test"}, |
| 45 | "no dek": {Env: "production", Origin: "https://x.test", InstanceKey: "k"}, |
| 46 | "no mailer": {Env: "production", Origin: "https://x.test", InstanceKey: "k", DEK: validDEK}, |
| 47 | "no allowlist": {Env: "production", Origin: "https://x.test", InstanceKey: "k", DEK: validDEK, Mailer: nopMailer{}}, |
| 48 | } |
| 49 | for name, cfg := range cases { |
| 50 | if _, rt, err := calls.App(testCtx(t), openDB(t), cfg); err == nil { |
| 51 | rt.Close() |
| 52 | t.Errorf("%s: production started without it", name) |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func TestDevelopmentStartsWithNothing(t *testing.T) { |
| 58 | _, rt, err := calls.App(testCtx(t), openDB(t), calls.Config{Env: calls.EnvDevelopment}) |
| 59 | if err != nil { |
| 60 | t.Fatalf("development refused: %v", err) |
| 61 | } |
| 62 | t.Cleanup(rt.Close) |
| 63 | } |
| 64 | |
| 65 | func TestBadDEKIsRefusedEvenInDevelopment(t *testing.T) { |
| 66 | _, rt, err := calls.App(testCtx(t), openDB(t), calls.Config{Env: calls.EnvDevelopment, DEK: "not base64!"}) |
| 67 | if err == nil { |
| 68 | rt.Close() |
| 69 | } |
| 70 | if err == nil || !strings.Contains(err.Error(), "base64") { |
| 71 | t.Fatalf("want a base64 refusal, got %v", err) |
| 72 | } |
| 73 | } |
| 74 | |