package fichastest import ( "io" "log/slog" "net/http" "net/url" "path/filepath" "regexp" "strconv" "strings" "testing" fichas "amadan.net/oficina/fichas/internal/fichas" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" ) // productionApp wires the app the way main.go does — no test identity, no // bypass. func productionApp(t *testing.T) http.Handler { 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() }) mux, _, err := fichas.App(d, testConfig(t), logger) if err != nil { t.Fatalf("App: %v", err) } return mux } // THE test memoria did not have. // // Its requireSession carried a nil-auth fall-through so tests could reach // routes without a mailer, and the safety argument rested on a test named // TestProductionRefusesToStartWithoutSignin that did not exist — the name // had survived a rename and lived on only in comments. Deleting the // sign-in wiring compiled, left the suite green, and served every route // unauthenticated. // // So: an app built through App, with no bypass, must refuse everything. func TestProductionRefusesAnUnauthenticatedRequest(t *testing.T) { h := productionApp(t) for _, p := range []string{"/", "/cards/new", "/cards/1"} { rec := get(t, h, p) if rec.Code == http.StatusOK { t.Errorf("GET %s served an unauthenticated request:\n%s", p, rec.Body.String()) } } for _, p := range []string{"/cards", "/cards/1", "/cards/1/entries", "/cards/1/delete"} { if rec := post(t, h, p, url.Values{"f_name": {"x"}}); rec.Code == http.StatusSeeOther { t.Errorf("POST %s was accepted without a session", p) } } } // Sign-in itself must be reachable, or nobody can ever get in. func TestSigninPageIsReachableWithoutASession(t *testing.T) { h, _, _ := wiredApp(t) rec := get(t, h, "/signin") if rec.Code != http.StatusOK { t.Fatalf("GET /signin: status %d, want 200", rec.Code) } if !strings.Contains(rec.Body.String(), `name="address"`) { t.Errorf("the sign-in page has no form:\n%s", rec.Body.String()) } } // An app with no sign-in wired draws no door: closed, as requireSession // is, rather than a form that posts to nothing. func TestNoDoorWithoutSignin(t *testing.T) { if rec := get(t, productionApp(t), "/signin"); rec.Code != http.StatusInternalServerError { t.Errorf("GET /signin with no auth: status %d, want 500", rec.Code) } } // beginGuard must render the SAME outcome for an owner and a stranger. A // distinct rejection turns the guard into an owners-list oracle, which is // worse than the dial it removes: the dial confirms the instance exists, // an oracle confirms who runs it. With the smart door, Begin's Sent // carries an attempt= and sets an attempt cookie, so the guard answers a // stranger with rastrillo's AnswerAsSent, which does the same (Memoria // #49): a plain ?sent=1 would tell them apart on the first try. func TestSigninRefusalIsIndistinguishable(t *testing.T) { h, mailer, _ := wiredApp(t) shape := regexp.MustCompile(`^/signin\?sent=1&attempt=[A-Za-z0-9_-]{22}$`) answer := func(address string) (string, []string) { rec := post(t, h, "/auth/begin", url.Values{"address": {address}, "force": {"1"}}) if rec.Code != http.StatusSeeOther { t.Fatalf("%s: status %d, want 303", address, rec.Code) } if strings.Contains(rec.Body.String(), address) { t.Errorf("the answer to %s echoes the address back", address) } var names []string for _, c := range rec.Result().Cookies() { names = append(names, c.Name+"|"+c.Path+"|"+strconv.Itoa(c.MaxAge)+"|"+strconv.FormatBool(c.HttpOnly)+"|"+strconv.Itoa(len(c.Value))) } return rec.Header().Get("Location"), names } // Equal lengths, so the sealed attempt cookie's length says nothing. owner, ownerCookies := answer(TestOwner) stranger, strangerCookies := answer("zzz@example.com") if len(TestOwner) != len("zzz@example.com") { t.Fatal("the two addresses must be the same length") } if !shape.MatchString(owner) || !shape.MatchString(stranger) { t.Errorf("owner %q, stranger %q: want both /signin?sent=1&attempt=…", owner, stranger) } if strings.Join(ownerCookies, ",") != strings.Join(strangerCookies, ",") { t.Errorf("cookies differ:\nowner %v\nstranger %v", ownerCookies, strangerCookies) } mailer.mu.Lock() defer mailer.mu.Unlock() if len(mailer.sent) != 1 { t.Errorf("%d mails sent, want the owner's one", len(mailer.sent)) } } // The guard reads the address exactly as rastrillo does. memoria's first // version read PostFormValue where rastrillo reads FormValue, so an // address in the query string was invisible to the guard and visible to // the thing it guarded. func TestTheGuardSeesAQueryStringAddress(t *testing.T) { h, mailer, _ := wiredApp(t) rec := post(t, h, "/auth/begin?address=nobody@example.com", url.Values{"force": {"1"}}) if rec.Code != http.StatusSeeOther { t.Fatalf("status %d, want 303", rec.Code) } if got := rec.Header().Get("Location"); !strings.HasPrefix(got, "/signin?sent=1&attempt=") { t.Errorf("redirected to %q", got) } if len(mailer.sent) != 0 { t.Error("a stranger in the query string was sent a link") } } // The sign-in page is the suite's door: rastrillo's screen (one way in) // inside estilo's door (estilo-signin-screen), one card on the Oficina // sky, Fichas' own mark and name at its head, styled by the chrome.css // and sky.css static/ carries. The email field is named address, which // is what beginGuard and rastrillo both read. func TestSigninPageIsTheDoor(t *testing.T) { h, _, _ := wiredApp(t) body := get(t, h, "/signin").Body.String() for _, want := range []string{ "estilo-door", "