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", "
", `method="post" action="/auth/verify"`, `name="token" value="` + m[1] + `"`, ">Sign in"} { if !strings.Contains(page, want) { t.Fatalf("the confirm page is not the door with a Sign in button (missing %q):\n%s", want, page) } } verify := post(t, h, "/auth/verify", url.Values{"token": {m[1]}}) if verify.Code != http.StatusSeeOther { t.Fatalf("GET /auth/verify: status %d\n%s", verify.Code, verify.Body.String()) } if loc := verify.Header().Get("Location"); strings.Contains(loc, "err=") { t.Fatalf("verify failed: redirected to %q", loc) } cookies := verify.Result().Cookies() if len(cookies) == 0 { t.Fatal("verify set no session cookie") } req := httptest.NewRequest(http.MethodGet, "/", nil) for _, c := range cookies { req.AddCookie(c) } home := httptest.NewRecorder() h.ServeHTTP(home, req) if home.Code != http.StatusOK { t.Fatalf("GET / with the new session: status %d, want 200 (Location %q)", home.Code, home.Header().Get("Location")) } if !strings.Contains(home.Body.String(), "Customers") { t.Error("signed in, but the index did not render") } // A link is single-use. again := post(t, h, "/auth/verify", url.Values{"token": {m[1]}}) if loc := again.Header().Get("Location"); !strings.Contains(loc, "err=expired") { t.Errorf("a used link was accepted a second time (redirected to %q)", loc) } } // A stranger must get the same outcome and no email — the anti-oracle // property — and the wiring must not change that. func TestAStrangerIsSentNothing(t *testing.T) { h, mailer, _ := wiredApp(t) rec := post(t, h, "/auth/begin", url.Values{"address": {"nobody@example.com"}, "force": {"1"}}) if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/signin?sent=1&attempt=") { t.Fatalf("a stranger was redirected to %q", loc) } mailer.mu.Lock() defer mailer.mu.Unlock() if len(mailer.sent) != 0 { t.Fatalf("a stranger was sent %d email(s)", len(mailer.sent)) } } // Every error code renders something a person can act on, in // rastrillo's approved words, and the email fallback survives a failed // keymail round trip. func TestSigninErrorsArePlainLanguage(t *testing.T) { h, _, _ := wiredApp(t) for code, want := range map[string]string{ "rate": "Too many tries. Try again in a few minutes.", "expired": "That link has expired or was already used. Send a new one.", "keymail": "We couldn't confirm it's you. Try again, or email yourself a sign-in link.", // rastrillo v0.45.0: never names Keymail "address": "That doesn't look like an email address.", "1": "Something went wrong. Try again.", } { body := get(t, h, "/signin?err="+code).Body.String() if !strings.Contains(body, want) { t.Errorf("?err=%s does not say %q", code, want) } } if !strings.Contains(get(t, h, "/signin?force=1&err=keymail").Body.String(), `name="force" value="1"`) { t.Error("after a keymail failure the form does not fall back to email") } } // The door's field is named address, and the POST it makes still signs a // person in: an owner's address= gets the sent page and a link; the // submission is exactly what the door's form sends, force included after // a keymail failure. func TestTheDoorsFormStillSignsIn(t *testing.T) { h, mailer, _ := wiredApp(t) form := get(t, h, "/signin?force=1&err=keymail").Body.String() for _, want := range []string{`name="address"`, `name="force" value="1"`, `action="/auth/begin"`} { if !strings.Contains(form, want) { t.Fatalf("the door's form lacks %q:\n%s", want, form) } } rec := post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}}) if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signin?sent=1&attempt=") { t.Fatalf("POST address=: status %d, Location %q", rec.Code, rec.Header().Get("Location")) } if mail := mailer.last(t); !linkToken.MatchString(mail) { t.Fatalf("no sign-in link was sent:\n%s", mail) } }