| 1 | package fichastest |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "log/slog" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "path/filepath" |
| 9 | "regexp" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | fichas "amadan.net/oficina/fichas/internal/fichas" |
| 15 | "amadan.net/rastrillo/rastrillo" |
| 16 | "amadan.net/rastrillo/rastrillo/db" |
| 17 | ) |
| 18 | |
| 19 | // productionApp wires the app the way main.go does — no test identity, no |
| 20 | // bypass. |
| 21 | func productionApp(t *testing.T) http.Handler { |
| 22 | t.Helper() |
| 23 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 24 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 25 | if err != nil { |
| 26 | t.Fatalf("db.Open: %v", err) |
| 27 | } |
| 28 | t.Cleanup(func() { d.Close() }) |
| 29 | mux, _, err := fichas.App(d, testConfig(t), logger) |
| 30 | if err != nil { |
| 31 | t.Fatalf("App: %v", err) |
| 32 | } |
| 33 | return mux |
| 34 | } |
| 35 | |
| 36 | // THE test memoria did not have. |
| 37 | // |
| 38 | // Its requireSession carried a nil-auth fall-through so tests could reach |
| 39 | // routes without a mailer, and the safety argument rested on a test named |
| 40 | // TestProductionRefusesToStartWithoutSignin that did not exist — the name |
| 41 | // had survived a rename and lived on only in comments. Deleting the |
| 42 | // sign-in wiring compiled, left the suite green, and served every route |
| 43 | // unauthenticated. |
| 44 | // |
| 45 | // So: an app built through App, with no bypass, must refuse everything. |
| 46 | func TestProductionRefusesAnUnauthenticatedRequest(t *testing.T) { |
| 47 | h := productionApp(t) |
| 48 | |
| 49 | for _, p := range []string{"/", "/cards/new", "/cards/1"} { |
| 50 | rec := get(t, h, p) |
| 51 | if rec.Code == http.StatusOK { |
| 52 | t.Errorf("GET %s served an unauthenticated request:\n%s", p, rec.Body.String()) |
| 53 | } |
| 54 | } |
| 55 | for _, p := range []string{"/cards", "/cards/1", "/cards/1/entries", "/cards/1/delete"} { |
| 56 | if rec := post(t, h, p, url.Values{"f_name": {"x"}}); rec.Code == http.StatusSeeOther { |
| 57 | t.Errorf("POST %s was accepted without a session", p) |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // Sign-in itself must be reachable, or nobody can ever get in. |
| 63 | func TestSigninPageIsReachableWithoutASession(t *testing.T) { |
| 64 | h, _, _ := wiredApp(t) |
| 65 | rec := get(t, h, "/signin") |
| 66 | if rec.Code != http.StatusOK { |
| 67 | t.Fatalf("GET /signin: status %d, want 200", rec.Code) |
| 68 | } |
| 69 | if !strings.Contains(rec.Body.String(), `name="address"`) { |
| 70 | t.Errorf("the sign-in page has no form:\n%s", rec.Body.String()) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | // An app with no sign-in wired draws no door: closed, as requireSession |
| 75 | // is, rather than a form that posts to nothing. |
| 76 | func TestNoDoorWithoutSignin(t *testing.T) { |
| 77 | if rec := get(t, productionApp(t), "/signin"); rec.Code != http.StatusInternalServerError { |
| 78 | t.Errorf("GET /signin with no auth: status %d, want 500", rec.Code) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // beginGuard must render the SAME outcome for an owner and a stranger. A |
| 83 | // distinct rejection turns the guard into an owners-list oracle, which is |
| 84 | // worse than the dial it removes: the dial confirms the instance exists, |
| 85 | // an oracle confirms who runs it. With the smart door, Begin's Sent |
| 86 | // carries an attempt= and sets an attempt cookie, so the guard answers a |
| 87 | // stranger with rastrillo's AnswerAsSent, which does the same (Memoria |
| 88 | // #49): a plain ?sent=1 would tell them apart on the first try. |
| 89 | func TestSigninRefusalIsIndistinguishable(t *testing.T) { |
| 90 | h, mailer, _ := wiredApp(t) |
| 91 | shape := regexp.MustCompile(`^/signin\?sent=1&attempt=[A-Za-z0-9_-]{22}$`) |
| 92 | answer := func(address string) (string, []string) { |
| 93 | rec := post(t, h, "/auth/begin", url.Values{"address": {address}, "force": {"1"}}) |
| 94 | if rec.Code != http.StatusSeeOther { |
| 95 | t.Fatalf("%s: status %d, want 303", address, rec.Code) |
| 96 | } |
| 97 | if strings.Contains(rec.Body.String(), address) { |
| 98 | t.Errorf("the answer to %s echoes the address back", address) |
| 99 | } |
| 100 | var names []string |
| 101 | for _, c := range rec.Result().Cookies() { |
| 102 | names = append(names, c.Name+"|"+c.Path+"|"+strconv.Itoa(c.MaxAge)+"|"+strconv.FormatBool(c.HttpOnly)+"|"+strconv.Itoa(len(c.Value))) |
| 103 | } |
| 104 | return rec.Header().Get("Location"), names |
| 105 | } |
| 106 | // Equal lengths, so the sealed attempt cookie's length says nothing. |
| 107 | owner, ownerCookies := answer(TestOwner) |
| 108 | stranger, strangerCookies := answer("zzz@example.com") |
| 109 | if len(TestOwner) != len("zzz@example.com") { |
| 110 | t.Fatal("the two addresses must be the same length") |
| 111 | } |
| 112 | if !shape.MatchString(owner) || !shape.MatchString(stranger) { |
| 113 | t.Errorf("owner %q, stranger %q: want both /signin?sent=1&attempt=…", owner, stranger) |
| 114 | } |
| 115 | if strings.Join(ownerCookies, ",") != strings.Join(strangerCookies, ",") { |
| 116 | t.Errorf("cookies differ:\nowner %v\nstranger %v", ownerCookies, strangerCookies) |
| 117 | } |
| 118 | mailer.mu.Lock() |
| 119 | defer mailer.mu.Unlock() |
| 120 | if len(mailer.sent) != 1 { |
| 121 | t.Errorf("%d mails sent, want the owner's one", len(mailer.sent)) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // The guard reads the address exactly as rastrillo does. memoria's first |
| 126 | // version read PostFormValue where rastrillo reads FormValue, so an |
| 127 | // address in the query string was invisible to the guard and visible to |
| 128 | // the thing it guarded. |
| 129 | func TestTheGuardSeesAQueryStringAddress(t *testing.T) { |
| 130 | h, mailer, _ := wiredApp(t) |
| 131 | rec := post(t, h, "/auth/begin?address=nobody@example.com", url.Values{"force": {"1"}}) |
| 132 | if rec.Code != http.StatusSeeOther { |
| 133 | t.Fatalf("status %d, want 303", rec.Code) |
| 134 | } |
| 135 | if got := rec.Header().Get("Location"); !strings.HasPrefix(got, "/signin?sent=1&attempt=") { |
| 136 | t.Errorf("redirected to %q", got) |
| 137 | } |
| 138 | if len(mailer.sent) != 0 { |
| 139 | t.Error("a stranger in the query string was sent a link") |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // The sign-in page is the suite's door: rastrillo's screen (one way in) |
| 144 | // inside estilo's door (estilo-signin-screen), one card on the Oficina |
| 145 | // sky, Fichas' own mark and name at its head, styled by the chrome.css |
| 146 | // and sky.css static/ carries. The email field is named address, which |
| 147 | // is what beginGuard and rastrillo both read. |
| 148 | func TestSigninPageIsTheDoor(t *testing.T) { |
| 149 | h, _, _ := wiredApp(t) |
| 150 | body := get(t, h, "/signin").Body.String() |
| 151 | for _, want := range []string{ |
| 152 | "estilo-door", |
| 153 | "<div estilo-signin-screen>", |
| 154 | `<div rst-signin-door="one-way">`, |
| 155 | "<span>Fichas</span>", |
| 156 | `<img estilo-sky-layer="grain"`, |
| 157 | `<img estilo-brand-icon="listing" src="/static/brand/icon.`, |
| 158 | `<form rst-signin-form method="post" action="/auth/begin">`, |
| 159 | `name="address"`, |
| 160 | `<h1 id="rst-signin-heading">Sign in to Fichas</h1>`, |
| 161 | `>Email</label>`, |
| 162 | `>Continue</button>`, |
| 163 | `href="/static/chrome.`, |
| 164 | `href="/static/sky.`, |
| 165 | } { |
| 166 | if !strings.Contains(body, want) { |
| 167 | t.Errorf("the sign-in page lacks %q:\n%s", want, body) |
| 168 | } |
| 169 | } |
| 170 | // No Home: no Oficina ID, and nothing else to choose between. |
| 171 | for _, gone := range []string{"Oficina ID", "Other ways to sign in", "/signin/oficina", "Colophon", "Open source"} { |
| 172 | if strings.Contains(body, gone) { |
| 173 | t.Errorf("the door offers %q, which Fichas does not have", gone) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // The sky's layers are served, sessionless, from estilo's prefix. |
| 178 | src := regexp.MustCompile(`estilo-sky-layer="filaments"[^>]*src="([^"]+)"`).FindStringSubmatch(body) |
| 179 | if src == nil { |
| 180 | t.Fatal("no filaments layer on the sign-in page") |
| 181 | } |
| 182 | layer := get(t, h, src[1]) |
| 183 | if layer.Code != http.StatusOK || layer.Header().Get("Content-Type") != "image/svg+xml" { |
| 184 | t.Errorf("GET %s: status %d, type %q", src[1], layer.Code, layer.Header().Get("Content-Type")) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | // The door's words are rastrillo's approved copy, and each state's tab |
| 189 | // title says what its heading says ("Sign in to Fichas"). |
| 190 | func TestTheDoorSpeaksTheSuitesWords(t *testing.T) { |
| 191 | h, _, _ := wiredApp(t) |
| 192 | form := get(t, h, "/signin").Body.String() |
| 193 | if got := titleOf(form); got != "Sign in to Fichas" { |
| 194 | t.Errorf("the sign-in page's title is %q, want %q", got, "Sign in to Fichas") |
| 195 | } |
| 196 | for _, gone := range []string{"Email me a link", "Only people this instance already knows", "Email address"} { |
| 197 | if strings.Contains(form, gone) { |
| 198 | t.Errorf("the sign-in page still says %q", gone) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | b := newBrowser() |
| 203 | rec := b.post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}}) |
| 204 | sent := b.get(t, h, rec.Header().Get("Location")).Body.String() |
| 205 | if got := titleOf(sent); got != "Check your email to sign in to Fichas" { |
| 206 | t.Errorf("the sent page's title is %q", got) |
| 207 | } |
| 208 | for _, want := range []string{ |
| 209 | `<h1 id="rst-signin-heading">Check your email</h1>`, |
| 210 | "We sent a link to <bdi>" + TestOwner + "</bdi>. The link works once and expires soon.", |
| 211 | `<form rst-signin-form method="post" action="/signin/forget">`, |
| 212 | "<span>Use a different email</span>", |
| 213 | } { |
| 214 | if !strings.Contains(sent, want) { |
| 215 | t.Errorf("the sent page lacks %q:\n%s", want, sent) |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // The door's sky draws its first frame from inline data: images, so the |
| 221 | // policy the page is actually served under must allow them. Built through |
| 222 | // rastrillo.Handler, the same assembly Serve uses, so the CSP is real. |
| 223 | func TestSigninPageCSPAllowsTheSky(t *testing.T) { |
| 224 | door, _, _ := wiredApp(t) |
| 225 | served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: door.(*http.ServeMux), ErrorPage: fichas.ErrorPage}) |
| 226 | if err != nil { |
| 227 | t.Fatalf("rastrillo.Handler: %v", err) |
| 228 | } |
| 229 | t.Cleanup(func() { closeDB() }) |
| 230 | rec := get(t, served, "/signin") |
| 231 | csp := rec.Header().Get("Content-Security-Policy") |
| 232 | if !strings.Contains(csp, "img-src 'self' data:") { |
| 233 | t.Errorf("CSP %q does not allow the sky's inline placeholder", csp) |
| 234 | } |
| 235 | if !strings.Contains(rec.Body.String(), `src="data:image/`) { |
| 236 | t.Error("the sky's placeholder is not inline") |
| 237 | } |
| 238 | } |
| 239 | |