| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "log" |
| 5 | "log/slog" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | |
| 12 | "github.com/go-chi/chi/v5" |
| 13 | |
| 14 | "amadan.net/oficina/home/internal/home/logtest" |
| 15 | "amadan.net/oficina/home/internal/home/sealtest" |
| 16 | "amadan.net/rastrillo/rastrillo/lastsignin" |
| 17 | ) |
| 18 | |
| 19 | // The privacy gates against the door's remembered address (ruling 26). |
| 20 | // The cookie's name is not secret and its ciphertext differs on every |
| 21 | // seal, so neither is a useful canary: each gate is driven with a VALIDLY |
| 22 | // SEALED cookie whose address is a canary. |
| 23 | |
| 24 | // credentialRoutes walks a credential router: every declared (method, |
| 25 | // path), with route parameters filled by a canary. |
| 26 | func credentialRoutes(t *testing.T, h http.Handler) [][2]string { |
| 27 | t.Helper() |
| 28 | routes, ok := h.(chi.Routes) |
| 29 | if !ok { |
| 30 | t.Fatalf("router is %T, not chi.Routes", h) |
| 31 | } |
| 32 | var out [][2]string |
| 33 | seen := map[[2]string]bool{} |
| 34 | if err := chi.Walk(routes, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { |
| 35 | path := fillParams(strings.ReplaceAll(route, "/*", "/x")) |
| 36 | for _, m := range []string{method, http.MethodGet, http.MethodPost} { |
| 37 | if k := [2]string{m, path}; !seen[k] { |
| 38 | seen[k] = true |
| 39 | out = append(out, k) |
| 40 | } |
| 41 | } |
| 42 | return nil |
| 43 | }); err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | if len(out) < 20 { |
| 47 | t.Fatalf("walked %d routes: the gate would pass by not looking", len(out)) |
| 48 | } |
| 49 | return out |
| 50 | } |
| 51 | |
| 52 | // Gate 9 (§12) with the door's cookie: every route on the credential |
| 53 | // origin, driven with a validly sealed cookie whose address is a canary |
| 54 | // (as the cookie a person's browser actually carries), plus full sign-ins |
| 55 | // that read and rewrite it, logs the address nowhere: neither the app's |
| 56 | // logger nor the default. |
| 57 | func TestNoContentInLogsWithTheDoorCookie(t *testing.T) { |
| 58 | rec := logtest.NewRecorder() |
| 59 | prevLogger, prevWriter, prevFlags := slog.Default(), log.Writer(), log.Flags() |
| 60 | slog.SetDefault(slog.New(rec.Handler())) |
| 61 | t.Cleanup(func() { |
| 62 | slog.SetDefault(prevLogger) |
| 63 | log.SetOutput(prevWriter) |
| 64 | log.SetFlags(prevFlags) |
| 65 | }) |
| 66 | p := newExchangePair(t) |
| 67 | app := p.credential |
| 68 | app.logger = slog.New(rec.Handler()) |
| 69 | canary := logtest.Canaries[0] |
| 70 | for _, method := range []string{lastsignin.MethodMagicLink, lastsignin.MethodKeymail, lastsignin.MethodPasskey} { |
| 71 | cookie := sealedRecord(t, app.App, lastsignin.Record{Method: method, Address: canary}) |
| 72 | if !strings.Contains(doorGet(t, app, "/signin?way=email", cookie).Body.String(), canary) { |
| 73 | t.Fatal("the canary cookie does not reach the door: the gate would scan nothing") |
| 74 | } |
| 75 | session := signInFully(t, app, "logs-session@example.invalid") |
| 76 | for _, rt := range credentialRoutes(t, app.Router()) { |
| 77 | for _, withSession := range []bool{false, true} { |
| 78 | body := url.Values{"address": {canary}, "return_to": {"/authorize/resume"}, "way": {"email"}, "return": {"https://" + logtest.Canaries[1] + ".example/signed-out"}}.Encode() |
| 79 | req := httptest.NewRequest(rt[0], Origin+rt[1]+"?ways=1&way=passkey&err=x&return="+url.QueryEscape(canary), strings.NewReader(body)) |
| 80 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 81 | req.Header.Set("Origin", Origin) |
| 82 | req.Header.Set("Accept", "text/html") |
| 83 | req.AddCookie(cookie) |
| 84 | if withSession { |
| 85 | req.AddCookie(session) |
| 86 | } |
| 87 | app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| 88 | } |
| 89 | } |
| 90 | // The CSRF refusal sees the cookie too. |
| 91 | req := httptest.NewRequest("POST", Origin+forgetPath, strings.NewReader("way=email")) |
| 92 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 93 | req.Header.Set("Sec-Fetch-Site", "cross-site") |
| 94 | req.AddCookie(cookie) |
| 95 | app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| 96 | } |
| 97 | // The sign-ins that write the cookie, with the canary address: a link, |
| 98 | // a passkey that keeps it (same person), and one that blanks it. |
| 99 | signIn(t, app, strings.ToLower(canary)) |
| 100 | linked := redeem(t, app, capturedLink(t, app)) |
| 101 | written, _ := jarSet(linked) |
| 102 | if written == nil { |
| 103 | t.Fatal("the canary sign-in remembered nothing") |
| 104 | } |
| 105 | key := enrol(t, app, sessionCookie(linked)) |
| 106 | directPasskey(t, app, key, written) |
| 107 | directPasskey(t, app, key, sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "other-" + strings.ToLower(canary)})) |
| 108 | rec.AssertNoContent(t) |
| 109 | } |
| 110 | |
| 111 | // Gate 5 (§12, amended by ruling 26): the credential origin renders no |
| 112 | // account-authored string, except exactly one, the address Home sealed |
| 113 | // into this browser's cookie, and only on the door. Every credential page |
| 114 | // is drawn with the canary cookie present, signed out and signed in; only |
| 115 | // the door's own sign-in states may show it, and none shows an address |
| 116 | // that arrived any other way: typed into the form, put in the query, or |
| 117 | // in a cookie Home did not seal. |
| 118 | func TestDoorRendersOnlyTheAddressItSealed(t *testing.T) { |
| 119 | p := newExchangePair(t) |
| 120 | app := p.credential |
| 121 | const canary = sealtest.CanaryAddress |
| 122 | session := signInFully(t, app, "gate5-session@example.invalid") |
| 123 | door := map[string]bool{"/signin": true} |
| 124 | for _, method := range []string{lastsignin.MethodMagicLink, lastsignin.MethodKeymail, lastsignin.MethodPasskey} { |
| 125 | cookie := sealedRecord(t, app.App, lastsignin.Record{Method: method, Address: canary}) |
| 126 | shown := 0 |
| 127 | for _, rt := range credentialRoutes(t, app.Router()) { |
| 128 | for _, withSession := range []bool{false, true} { |
| 129 | cookies := []*http.Cookie{cookie} |
| 130 | if withSession { |
| 131 | cookies = append(cookies, session) |
| 132 | } |
| 133 | var form url.Values |
| 134 | if rt[0] == http.MethodPost { |
| 135 | form = url.Values{"address": {"typed-canary@example.invalid"}} |
| 136 | } |
| 137 | target := Origin + rt[1] |
| 138 | if door[rt[1]] { |
| 139 | // The door's own query: an address there is never shown. |
| 140 | target += "?address=query-canary%40example.invalid" |
| 141 | } |
| 142 | r := exchangeRequest(app.App, rt[0], target, Origin, form, cookies...) |
| 143 | body := strings.ToLower(r.Body.String()) |
| 144 | for _, never := range []string{"typed-canary", "query-canary"} { |
| 145 | if strings.Contains(body, never) { |
| 146 | t.Errorf("%s %s %s rendered an address it did not seal (%s)", method, rt[0], rt[1], never) |
| 147 | } |
| 148 | } |
| 149 | if strings.Contains(body, canary) { |
| 150 | shown++ |
| 151 | if !door[rt[1]] { |
| 152 | t.Errorf("%s %s %s rendered the remembered address off the door", method, rt[0], rt[1]) |
| 153 | } |
| 154 | if r.Header().Get("Cache-Control") != "no-store" { |
| 155 | t.Errorf("%s %s %s rendered the address on a cacheable page", method, rt[0], rt[1]) |
| 156 | } |
| 157 | if where := outsideTextAndValue(body, canary); where != "" { |
| 158 | t.Errorf("%s %s %s rendered the address outside text and value=: %s", method, rt[0], rt[1], where) |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | // Each method's door shows its address somewhere: the one-tap for |
| 164 | // a link or Keymail, the chooser's Email row for a passkey. |
| 165 | if method == lastsignin.MethodPasskey { |
| 166 | body := strings.ToLower(doorGet(t, app, "/signin?ways=1&way=passkey", cookie).Body.String()) |
| 167 | if strings.Contains(body, canary) { |
| 168 | shown++ |
| 169 | if where := outsideTextAndValue(body, canary); where != "" { |
| 170 | t.Errorf("passkey chooser rendered the address outside text and value=: %s", where) |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | if shown == 0 { |
| 175 | t.Fatalf("%s: the door never showed the sealed address: the gate checked nothing", method) |
| 176 | } |
| 177 | } |
| 178 | // The door draws it only as text and as a form field's value, escaped. |
| 179 | hostile := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: `"><script>x</script>@example.invalid`}) |
| 180 | body := doorGet(t, app, "/signin", hostile).Body.String() |
| 181 | if strings.Contains(body, "<script>x</script>") || !strings.Contains(body, ""><script>x</script>@example.invalid") { |
| 182 | t.Fatal("the remembered address was not escaped") |
| 183 | } |
| 184 | // A posted address is never echoed, even on the door, even valid. |
| 185 | limited := returnRequest(app, "POST", "/signin", url.Values{"address": {"posted-canary"}}) |
| 186 | if strings.Contains(limited.Body.String(), "posted-canary") { |
| 187 | t.Fatal("a posted address was echoed") |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // outsideTextAndValue returns a description of the first place canary |
| 192 | // occurs in body other than a text node or a value="…" attribute, or "". |
| 193 | // Ruling 26 allows the address as text and as a form field's value, and |
| 194 | // nowhere else: not in another attribute (an href, a data-*), not in a |
| 195 | // tag name, comment or script. |
| 196 | func outsideTextAndValue(body, canary string) string { |
| 197 | for from := 0; ; { |
| 198 | i := strings.Index(body[from:], canary) |
| 199 | if i < 0 { |
| 200 | return "" |
| 201 | } |
| 202 | i += from |
| 203 | from = i + len(canary) |
| 204 | open, close := strings.LastIndex(body[:i], "<"), strings.LastIndex(body[:i], ">") |
| 205 | if open <= close { |
| 206 | // Between tags: a text node, unless inside a script or comment. |
| 207 | if s := strings.LastIndex(body[:i], "<script"); s > strings.LastIndex(body[:i], "</script") { |
| 208 | return "inside a script" |
| 209 | } |
| 210 | if c := strings.LastIndex(body[:i], "<!--"); c > strings.LastIndex(body[:i], "-->") { |
| 211 | return "inside a comment" |
| 212 | } |
| 213 | continue |
| 214 | } |
| 215 | // Inside a tag: only as the whole of a value="…". |
| 216 | if !strings.HasSuffix(body[:i], ` value="`) || !strings.HasPrefix(body[from:], `"`) { |
| 217 | end := min(len(body), from+20) |
| 218 | return "in a tag: " + body[open:end] |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // Gates 1 and 2, the sign-in half, with the door after: a full email |
| 224 | // sign-in and a passkey sign-in that keeps the address, each followed by |
| 225 | // loading the door with the cookie they wrote (which shows the address), |
| 226 | // leave no readable address in the database, its WAL or its SHM. The door |
| 227 | // reads the cookie and consults no store; the same-person check reads the |
| 228 | // blind index and writes nothing. Home has no store objects to scan (no |
| 229 | // object storage, no blob store: its only persistent state is this SQLite |
| 230 | // database, which Litestream ships with its WAL), so the database, WAL and |
| 231 | // SHM are the whole of what is at rest. |
| 232 | func TestDoorLeavesNoReadableAddressAtRest(t *testing.T) { |
| 233 | app := newTestApp(t) |
| 234 | signIn(t, app, sealtest.CanaryAddress) |
| 235 | linked := redeem(t, app, capturedLink(t, app)) |
| 236 | written, _ := jarSet(linked) |
| 237 | if written == nil || !strings.Contains(doorGet(t, app, "/signin", written).Body.String(), sealtest.CanaryAddress) { |
| 238 | t.Fatal("the door does not show the address the sign-in remembered") |
| 239 | } |
| 240 | sealtest.AssertNoPlaintext(t, app.dbPath) |
| 241 | key := enrol(t, app, sessionCookie(linked)) |
| 242 | done := directPasskey(t, app, key, written) |
| 243 | kept, _ := jarSet(done) |
| 244 | if kept == nil || readJar(t, app.App, kept).Address != sealtest.CanaryAddress { |
| 245 | t.Fatal("the same person's passkey sign-in did not keep the address") |
| 246 | } |
| 247 | for _, path := range []string{"/signin", "/signin?ways=1&way=passkey", "/signin?way=email", "/signin/sent"} { |
| 248 | doorGet(t, app, path, kept) |
| 249 | } |
| 250 | returnRequest(app, "POST", "/signin", url.Values{"address": {"bad"}}, kept) |
| 251 | returnRequest(app, "POST", forgetPath, url.Values{"way": {"email"}}, kept) |
| 252 | sealtest.AssertNoPlaintext(t, app.dbPath) |
| 253 | } |
| 254 | |
| 255 | // outsideTextAndValue must see the places gate 5 refuses, or the gate's |
| 256 | // text-and-value check is a check over nothing. |
| 257 | func TestOutsideTextAndValueSeesTheRefusedPlaces(t *testing.T) { |
| 258 | for body, refused := range map[string]bool{ |
| 259 | `<p>as <bdi>x@y</bdi></p><input value="x@y">`: false, |
| 260 | `<a href="/?a=x@y">`: true, |
| 261 | `<input data-v="x@y">`: true, |
| 262 | `<script>var a="x@y"</script>`: true, |
| 263 | `<!-- x@y -->`: true, |
| 264 | `<input value="x@y and">`: true, |
| 265 | } { |
| 266 | if got := outsideTextAndValue(body, "x@y") != ""; got != refused { |
| 267 | t.Errorf("%q: refused %v, want %v", body, got, refused) |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |