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", "
", `
`, "Fichas", ``, `name="address"`, `

Sign in to Fichas

`, `>Email`, `>Continue`, `href="/static/chrome.`, `href="/static/sky.`, } { if !strings.Contains(body, want) { t.Errorf("the sign-in page lacks %q:\n%s", want, body) } } // No Home: no Oficina ID, and nothing else to choose between. for _, gone := range []string{"Oficina ID", "Other ways to sign in", "/signin/oficina", "Colophon", "Open source"} { if strings.Contains(body, gone) { t.Errorf("the door offers %q, which Fichas does not have", gone) } } // The sky's layers are served, sessionless, from estilo's prefix. src := regexp.MustCompile(`estilo-sky-layer="filaments"[^>]*src="([^"]+)"`).FindStringSubmatch(body) if src == nil { t.Fatal("no filaments layer on the sign-in page") } layer := get(t, h, src[1]) if layer.Code != http.StatusOK || layer.Header().Get("Content-Type") != "image/svg+xml" { t.Errorf("GET %s: status %d, type %q", src[1], layer.Code, layer.Header().Get("Content-Type")) } } // The door's words are rastrillo's approved copy, and each state's tab // title says what its heading says ("Sign in to Fichas"). func TestTheDoorSpeaksTheSuitesWords(t *testing.T) { h, _, _ := wiredApp(t) form := get(t, h, "/signin").Body.String() if got := titleOf(form); got != "Sign in to Fichas" { t.Errorf("the sign-in page's title is %q, want %q", got, "Sign in to Fichas") } for _, gone := range []string{"Email me a link", "Only people this instance already knows", "Email address"} { if strings.Contains(form, gone) { t.Errorf("the sign-in page still says %q", gone) } } b := newBrowser() rec := b.post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}}) sent := b.get(t, h, rec.Header().Get("Location")).Body.String() if got := titleOf(sent); got != "Check your email to sign in to Fichas" { t.Errorf("the sent page's title is %q", got) } for _, want := range []string{ `

Check your email

`, "We sent a link to " + TestOwner + ". The link works once and expires soon.", `
`, "Use a different email", } { if !strings.Contains(sent, want) { t.Errorf("the sent page lacks %q:\n%s", want, sent) } } } // The door's sky draws its first frame from inline data: images, so the // policy the page is actually served under must allow them. Built through // rastrillo.Handler, the same assembly Serve uses, so the CSP is real. func TestSigninPageCSPAllowsTheSky(t *testing.T) { door, _, _ := wiredApp(t) served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: door.(*http.ServeMux), ErrorPage: fichas.ErrorPage}) if err != nil { t.Fatalf("rastrillo.Handler: %v", err) } t.Cleanup(func() { closeDB() }) rec := get(t, served, "/signin") csp := rec.Header().Get("Content-Security-Policy") if !strings.Contains(csp, "img-src 'self' data:") { t.Errorf("CSP %q does not allow the sky's inline placeholder", csp) } if !strings.Contains(rec.Body.String(), `src="data:image/`) { t.Error("the sky's placeholder is not inline") } }