package fichastest import ( "context" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strings" "sync" "testing" fichas "amadan.net/oficina/fichas/internal/fichas" "amadan.net/rastrillo/rastrillo/db" ) // capturingMailer records what the app sends instead of sending it. type capturingMailer struct { mu sync.Mutex sent []string } func (m *capturingMailer) Send(_ context.Context, to, subject, body string) error { m.mu.Lock() defer m.mu.Unlock() m.sent = append(m.sent, to+"\n"+subject+"\n"+body) return nil } func (m *capturingMailer) last(t *testing.T) string { t.Helper() m.mu.Lock() defer m.mu.Unlock() if len(m.sent) == 0 { t.Fatal("no email was sent") } return m.sent[len(m.sent)-1] } // wiredApp is the app exactly as main.go builds it — App, then NewAuth, // then UseAuth — with a capturing mailer in place of SMTP and NO test // identity or bypass. Everything that reached production went through // this sequence, and until this test nothing in the suite did. func wiredApp(t *testing.T) (http.Handler, *capturingMailer, *db.DB) { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) cfg := testConfig(t) mux, app, err := fichas.App(d, cfg, logger) if err != nil { t.Fatalf("App: %v", err) } mailer := &capturingMailer{} au, err := fichas.NewAuth(d.Writer(), fichas.AuthEnv{ Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer, }, logger, app) if err != nil { t.Fatalf("NewAuth: %v", err) } app.UseAuth(au) return mux, mailer, d } // TestBootSchema: the tables sign-in depends on exist after a boot. // // BootSchema was migrate.Merge(Schema) for eight days in production: an // edit meant to add sessions and auth matched a different spelling of the // line and changed nothing. Every boot log said skipped=2 and nobody read // it as "two, not six". func TestBootSchema(t *testing.T) { _, _, d := wiredApp(t) for _, table := range []string{"auth_links", "sessions", "cards", "events"} { var n int64 if err := d.G.Raw("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", table).Scan(&n).Error; err != nil { t.Fatalf("sqlite_master: %v", err) } if n != 1 { t.Errorf("table %s does not exist after boot", table) } } } var linkToken = regexp.MustCompile(`/auth/verify\?token=([A-Za-z0-9_\-%.~]+)`) // TestASignInCompletesEndToEnd walks the email path the way a person does: // submit an address, receive a link, follow it, arrive signed in. // // No earlier test did this. They either bypassed auth or stopped at the // guard in front of it, so nothing exercised the path that touches the // database — and the deployed app could not complete a single sign-in. func TestASignInCompletesEndToEnd(t *testing.T) { h, mailer, _ := wiredApp(t) // force=1 takes the plain-email path, which skips the classifier and // so makes no network request: this test must not dial anything. rec := post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}}) if rec.Code != http.StatusSeeOther { t.Fatalf("POST /auth/begin: status %d\n%s", rec.Code, rec.Body.String()) } if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/signin?sent=1&attempt=") { t.Fatalf("POST /auth/begin redirected to %q, want the door's Sent", loc) } mail := mailer.last(t) if !strings.HasPrefix(mail, TestOwner+"\n") { t.Fatalf("the link went to the wrong address:\n%s", mail) } // The subject is the door's: "Sign in to Fichas", the app capitalised. if !strings.HasPrefix(mail, TestOwner+"\nSign in to Fichas\n") { t.Errorf("the email's subject is not the door's \"Sign in to Fichas\":\n%s", mail) } m := linkToken.FindStringSubmatch(mail) if m == nil { t.Fatalf("the email carries no sign-in link:\n%s", mail) } // The link must point at the configured origin, or it goes nowhere. if !strings.Contains(mail, testOrigin+"/auth/verify?token=") { t.Errorf("the link does not use FICHAS_ORIGIN:\n%s", mail) } // The link opens the door with one Sign in button and spends nothing: // a mail scanner's GET must not sign anybody in. confirm := get(t, h, "/auth/verify?token="+m[1]) if confirm.Code != http.StatusOK { t.Fatalf("GET /auth/verify: status %d, want the confirm page\n%s", confirm.Code, confirm.Body.String()) } if len(confirm.Result().Cookies()) != 0 { t.Fatal("GET /auth/verify set a cookie: the link's GET must spend nothing") } page := confirm.Body.String() for _, want := range []string{"estilo-door", "