| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "maps" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/url" |
| 11 | "slices" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | |
| 16 | "github.com/keymaildev/signin" |
| 17 | |
| 18 | "amadan.net/oficina/home/internal/home/sealtest" |
| 19 | ) |
| 20 | |
| 21 | // signIn posts the sign-in form. |
| 22 | // |
| 23 | // It sends an Origin header because csrf.Protect is mounted router-wide |
| 24 | // and refuses a POST without origin evidence — before chi matches, so |
| 25 | // without it every test here would fail for the wrong reason. |
| 26 | func signIn(t *testing.T, app *testApp, addr string) *httptest.ResponseRecorder { |
| 27 | t.Helper() |
| 28 | form := url.Values{"address": {addr}} |
| 29 | req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| 30 | req.Host = app.credentialHost |
| 31 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 32 | req.Header.Set("Origin", app.origins.Credential) |
| 33 | w := httptest.NewRecorder() |
| 34 | app.Router().ServeHTTP(w, req) |
| 35 | return w |
| 36 | } |
| 37 | |
| 38 | // capturedLink returns the token from the most recent magic link. |
| 39 | func capturedLink(t *testing.T, app *testApp) string { |
| 40 | t.Helper() |
| 41 | sent, ok := app.mailer.last() |
| 42 | if !ok { |
| 43 | t.Fatal("no mail was sent") |
| 44 | } |
| 45 | i := strings.Index(sent.Body, app.origins.Credential+linkPath) |
| 46 | if i < 0 { |
| 47 | t.Fatalf("no sign-in link in the mail body: %q", sent.Body) |
| 48 | } |
| 49 | rest := sent.Body[i:] |
| 50 | if j := strings.IndexAny(rest, " \r\n\t\""); j >= 0 { |
| 51 | rest = rest[:j] |
| 52 | } |
| 53 | u, err := url.Parse(rest) |
| 54 | if err != nil { |
| 55 | t.Fatalf("parse link %q: %v", rest, err) |
| 56 | } |
| 57 | token := u.Query().Get("token") |
| 58 | if token == "" { |
| 59 | t.Fatalf("link %q carries no token", rest) |
| 60 | } |
| 61 | return token |
| 62 | } |
| 63 | |
| 64 | // redeem posts the confirmation form. |
| 65 | func redeem(t *testing.T, app *testApp, token string) *httptest.ResponseRecorder { |
| 66 | t.Helper() |
| 67 | form := url.Values{"token": {token}} |
| 68 | req := httptest.NewRequest(http.MethodPost, linkPath, strings.NewReader(form.Encode())) |
| 69 | req.Host = app.credentialHost |
| 70 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 71 | req.Header.Set("Origin", app.origins.Credential) |
| 72 | w := httptest.NewRecorder() |
| 73 | app.Router().ServeHTTP(w, req) |
| 74 | return w |
| 75 | } |
| 76 | |
| 77 | func sessionCookie(rec *httptest.ResponseRecorder) *http.Cookie { |
| 78 | for _, c := range (&http.Response{Header: rec.Header()}).Cookies() { |
| 79 | if strings.Contains(c.Name, "session") && c.Value != "" { |
| 80 | return c |
| 81 | } |
| 82 | } |
| 83 | return nil |
| 84 | } |
| 85 | |
| 86 | // TestFullSigninLeavesNoReadableAddress is §12 gate 2: a full sign-in |
| 87 | // leaves no readable address anywhere, WAL included, and neither does |
| 88 | // loading the door afterwards with the cookie it wrote (gates 1 and 2's |
| 89 | // sign-in half; TestDoorLeavesNoReadableAddressAtRest adds the passkey). The directory and |
| 90 | // owner seed now extends the completed sign-in into separate role databases. |
| 91 | // The rekey half remains for its implementation. |
| 92 | func TestFullSigninLeavesNoReadableAddress(t *testing.T) { |
| 93 | app := newTestApp(t) |
| 94 | |
| 95 | if rec := signIn(t, app, sealtest.CanaryAddress); rec.Code != http.StatusSeeOther { |
| 96 | t.Fatalf("POST /signin = %d, want 303", rec.Code) |
| 97 | } |
| 98 | redeemed := redeem(t, app, capturedLink(t, app)) |
| 99 | if redeemed.Code != http.StatusSeeOther { |
| 100 | t.Fatalf("redeem = %d, want 303", redeemed.Code) |
| 101 | } |
| 102 | |
| 103 | exerciseOperatorSeedPrivacy(t, app) |
| 104 | sealtest.AssertNoPlaintext(t, app.dbPath) |
| 105 | |
| 106 | // Ruling 26: the sign-in remembered the address in this browser's |
| 107 | // cookie. Loading the door with it shows the address back, and still |
| 108 | // nothing at rest holds it. |
| 109 | written, _ := jarSet(redeemed) |
| 110 | if written == nil || !strings.Contains(doorGet(t, app, "/signin", written).Body.String(), sealtest.CanaryAddress) { |
| 111 | t.Fatal("the door does not show back the address the sign-in remembered") |
| 112 | } |
| 113 | sealtest.AssertNoPlaintext(t, app.dbPath) |
| 114 | } |
| 115 | |
| 116 | // A sign-in that completes must actually mint a session, or the gate |
| 117 | // above would pass on an app that stores nothing because it does |
| 118 | // nothing. |
| 119 | func TestSigninMintsASessionOnThePersonRef(t *testing.T) { |
| 120 | app := newTestApp(t) |
| 121 | signIn(t, app, "person@example.invalid") |
| 122 | rec := redeem(t, app, capturedLink(t, app)) |
| 123 | |
| 124 | if sessionCookie(rec) == nil { |
| 125 | t.Fatal("redemption set no session cookie") |
| 126 | } |
| 127 | |
| 128 | var subject string |
| 129 | if err := app.db.Writer().QueryRow("SELECT subject FROM sessions").Scan(&subject); err != nil { |
| 130 | t.Fatalf("no session row: %v", err) |
| 131 | } |
| 132 | if !ValidPersonRef(subject) { |
| 133 | t.Fatalf("session subject is %q, which is not a person ref", subject) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // Classification fails open: a resolver failure must still send a magic |
| 138 | // link, never a dead end. |
| 139 | func TestFailedClassificationStillSendsAMagicLink(t *testing.T) { |
| 140 | app := newTestApp(t) |
| 141 | app.flow.Classifier.LookupTXT = func(context.Context, string) ([]string, error) { |
| 142 | return nil, errors.New("servfail") |
| 143 | } |
| 144 | next, err := app.flow.Begin(context.Background(), "someone@example.invalid", "", signin.Method("")) |
| 145 | if err != nil { |
| 146 | t.Fatalf("Begin: %v", err) |
| 147 | } |
| 148 | if next.Kind != signin.NextMagicLink { |
| 149 | t.Fatalf("Kind = %v, want NextMagicLink: classification must fail open", next.Kind) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | // A returning person gets the SAME person ref. Without the blind index |
| 154 | // every sign-in minted a new one, so nobody could ever return. |
| 155 | func TestSecondSigninFindsTheSamePerson(t *testing.T) { |
| 156 | app := newTestApp(t) |
| 157 | |
| 158 | signIn(t, app, "person@example.invalid") |
| 159 | redeem(t, app, capturedLink(t, app)) |
| 160 | signIn(t, app, "Person@Example.Invalid") |
| 161 | redeem(t, app, capturedLink(t, app)) |
| 162 | |
| 163 | var n int |
| 164 | if err := app.db.Writer().QueryRow("SELECT count(*) FROM people").Scan(&n); err != nil { |
| 165 | t.Fatal(err) |
| 166 | } |
| 167 | if n != 1 { |
| 168 | t.Fatalf("%d person rows for one address, want 1", n) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // A GET does not redeem. A mail scanner's prefetch must leave the link |
| 173 | // usable, and must not sign anybody in — the second half is login CSRF, |
| 174 | // where any page the victim loads could embed the link as an image and |
| 175 | // silently put them in the attacker's session. |
| 176 | func TestGetDoesNotRedeemTheLink(t *testing.T) { |
| 177 | app := newTestApp(t) |
| 178 | signIn(t, app, "person@example.invalid") |
| 179 | token := capturedLink(t, app) |
| 180 | |
| 181 | req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(token), nil) |
| 182 | req.Host = app.credentialHost |
| 183 | w := httptest.NewRecorder() |
| 184 | app.Router().ServeHTTP(w, req) |
| 185 | |
| 186 | if w.Code != http.StatusOK { |
| 187 | t.Fatalf("GET %s = %d, want 200", linkPath, w.Code) |
| 188 | } |
| 189 | if c := sessionCookie(w); c != nil { |
| 190 | t.Fatal("a GET minted a session; that is login CSRF") |
| 191 | } |
| 192 | var n int |
| 193 | if err := app.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n); err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | if n != 0 { |
| 197 | t.Fatalf("a GET created %d sessions", n) |
| 198 | } |
| 199 | |
| 200 | // And the link still works afterwards, which is the prefetch half. |
| 201 | if rec := redeem(t, app, token); rec.Code != http.StatusSeeOther { |
| 202 | t.Fatalf("the link was burned by a GET: redeem = %d", rec.Code) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // The confirmation page must not look the token up. If it did, a valid |
| 207 | // token would render differently from an invalid one, and a prefetch |
| 208 | // could probe validity — the oracle the POST-redeems design closes. |
| 209 | func TestVerifyPageDoesNotDistinguishTokens(t *testing.T) { |
| 210 | app := newTestApp(t) |
| 211 | signIn(t, app, "person@example.invalid") |
| 212 | real := capturedLink(t, app) |
| 213 | |
| 214 | get := func(token string) *httptest.ResponseRecorder { |
| 215 | req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(token), nil) |
| 216 | req.Host = app.credentialHost |
| 217 | w := httptest.NewRecorder() |
| 218 | app.Router().ServeHTTP(w, req) |
| 219 | return w |
| 220 | } |
| 221 | |
| 222 | // A fake token of exactly the same length and alphabet as the real |
| 223 | // one. Length matters: each response is normalised by replacing its |
| 224 | // OWN token with a placeholder, so if the handler echoed a valid |
| 225 | // token twice — or padded it, or truncated it — the two normalised |
| 226 | // bodies would differ in length and be caught. The first version of |
| 227 | // this test replaced each token with the empty string, which erased |
| 228 | // any oracle that was a function of the token and let exactly that |
| 229 | // mutant through. |
| 230 | fake := strings.Repeat("z", len(real)) |
| 231 | if fake == real { |
| 232 | t.Fatal("the fake token collided with the real one") |
| 233 | } |
| 234 | // A stated limit: because the fake is the same length by |
| 235 | // construction, a response that differed only on token LENGTH would |
| 236 | // be invisible here. That is deliberate and not a hole — length |
| 237 | // separates well-formed from malformed, which a scanner already |
| 238 | // knows from the URL it was handed, and not live from dead, which is |
| 239 | // the only thing worth hiding. |
| 240 | |
| 241 | good, bad := get(real), get(fake) |
| 242 | |
| 243 | if good.Code != bad.Code { |
| 244 | t.Errorf("status differs: %d vs %d", good.Code, bad.Code) |
| 245 | } |
| 246 | |
| 247 | // Headers too. An oracle in a header — a Content-Length, a cache |
| 248 | // directive, anything set only on one branch — is just as readable |
| 249 | // to a prefetching scanner as one in the body, and comparing only |
| 250 | // bodies missed it. |
| 251 | if !maps.EqualFunc(good.Header(), bad.Header(), slices.Equal) { |
| 252 | t.Errorf("headers differ for a valid token:\n valid: %v\n invalid: %v", |
| 253 | good.Header(), bad.Header()) |
| 254 | } |
| 255 | |
| 256 | // A further stated limit, because the handler's comment claims more |
| 257 | // than any response comparison can check. "It touches no state" is |
| 258 | // asserted separately, by TestVerifyPageWritesNothing. TIMING is |
| 259 | // not asserted at all: a handler that slept only for a live token |
| 260 | // would pass everything here, and a prefetching scanner could read |
| 261 | // it. Closing that needs the handler to stay branch-free on the |
| 262 | // token, which is what it is — and is worth re-reading rather than |
| 263 | // re-testing whenever it changes. |
| 264 | placeholder := strings.Repeat("#", len(real)) |
| 265 | g := strings.ReplaceAll(good.Body.String(), real, placeholder) |
| 266 | b := strings.ReplaceAll(bad.Body.String(), fake, placeholder) |
| 267 | if g != b { |
| 268 | t.Errorf("the confirmation page renders differently for a valid token "+ |
| 269 | "(%d bytes vs %d after normalising the token)", len(g), len(b)) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // Unknown, expired and already-used must be one answer, byte for byte. |
| 274 | func TestFailedRedemptionsAreIndistinguishable(t *testing.T) { |
| 275 | app := newTestApp(t) |
| 276 | signIn(t, app, "person@example.invalid") |
| 277 | used := capturedLink(t, app) |
| 278 | if rec := redeem(t, app, used); rec.Code != http.StatusSeeOther { |
| 279 | t.Fatalf("setup redemption failed: %d", rec.Code) |
| 280 | } |
| 281 | |
| 282 | unknown := redeem(t, app, "no-such-token") |
| 283 | again := redeem(t, app, used) |
| 284 | empty := redeem(t, app, "") |
| 285 | |
| 286 | for _, tc := range []struct { |
| 287 | name string |
| 288 | rec *httptest.ResponseRecorder |
| 289 | }{{"already used", again}, {"empty", empty}} { |
| 290 | if tc.rec.Code != unknown.Code { |
| 291 | t.Errorf("%s: status %d, unknown token gave %d", tc.name, tc.rec.Code, unknown.Code) |
| 292 | } |
| 293 | if tc.rec.Body.String() != unknown.Body.String() { |
| 294 | t.Errorf("%s: body differs from an unknown token's", tc.name) |
| 295 | } |
| 296 | } |
| 297 | if unknown.Code == http.StatusSeeOther { |
| 298 | t.Fatal("an unknown token was accepted") |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | // Two clicks at the same moment mint one session, not two. |
| 303 | func TestConcurrentRedemptionMintsOneSession(t *testing.T) { |
| 304 | app := newTestApp(t) |
| 305 | signIn(t, app, "person@example.invalid") |
| 306 | token := capturedLink(t, app) |
| 307 | |
| 308 | const racers = 12 |
| 309 | var ( |
| 310 | wg sync.WaitGroup |
| 311 | mu sync.Mutex |
| 312 | winners int |
| 313 | ) |
| 314 | start := make(chan struct{}) |
| 315 | for range racers { |
| 316 | wg.Add(1) |
| 317 | go func() { |
| 318 | defer wg.Done() |
| 319 | <-start |
| 320 | rec := redeem(t, app, token) |
| 321 | mu.Lock() |
| 322 | defer mu.Unlock() |
| 323 | if rec.Code == http.StatusSeeOther { |
| 324 | winners++ |
| 325 | } |
| 326 | }() |
| 327 | } |
| 328 | close(start) |
| 329 | wg.Wait() |
| 330 | |
| 331 | if winners != 1 { |
| 332 | t.Errorf("%d of %d redemptions succeeded, want exactly 1", winners, racers) |
| 333 | } |
| 334 | var n int |
| 335 | if err := app.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n); err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | if n != 1 { |
| 339 | t.Errorf("%d sessions minted from one link, want 1", n) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | // csrf.Protect is mounted router-wide, so the mail-sending endpoint is |
| 344 | // covered too — it makes outbound DNS and HTTPS calls decided by the |
| 345 | // submitted address, which is a blind-SSRF surface by design. |
| 346 | func TestSigninPostRequiresOriginEvidence(t *testing.T) { |
| 347 | app := newTestApp(t) |
| 348 | for _, path := range []string{"/signin", linkPath} { |
| 349 | form := url.Values{"address": {"person@example.invalid"}} |
| 350 | req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) |
| 351 | req.Host = app.credentialHost |
| 352 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 353 | w := httptest.NewRecorder() |
| 354 | app.Router().ServeHTTP(w, req) |
| 355 | if w.Code < 400 { |
| 356 | t.Errorf("POST %s with no origin evidence = %d, want a refusal", path, w.Code) |
| 357 | } |
| 358 | } |
| 359 | if _, sent := app.mailer.last(); sent { |
| 360 | t.Error("a CSRF-refused POST still sent mail") |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | // The per-IP limiter key is the difference between a rate limit and a |
| 365 | // suite-wide outage. Over a unix socket RemoteAddr is "@", and signin |
| 366 | // skips the per-IP budget only for the empty string — so "@" would make |
| 367 | // every request in the world share one budget of 20 per 15 minutes. |
| 368 | func TestClientIPNeverCollapsesToOneBucket(t *testing.T) { |
| 369 | req := func(remote, xff string) *http.Request { |
| 370 | r := httptest.NewRequest(http.MethodPost, "/signin", nil) |
| 371 | r.Host = credentialHost |
| 372 | r.RemoteAddr = remote |
| 373 | if xff != "" { |
| 374 | r.Header.Set("X-Forwarded-For", xff) |
| 375 | } |
| 376 | return r |
| 377 | } |
| 378 | |
| 379 | if got := clientIP(req("@", "")); got != "" { |
| 380 | t.Errorf("clientIP over a unix socket = %q, want \"\" — %q would be one budget for everybody", got, got) |
| 381 | } |
| 382 | if got := clientIP(req("@", "203.0.113.7")); got != "203.0.113.7" { |
| 383 | t.Errorf("clientIP with X-Forwarded-For = %q, want 203.0.113.7", got) |
| 384 | } |
| 385 | // The last element is the edge's own view; earlier ones are |
| 386 | // whatever the client claimed. |
| 387 | if got := clientIP(req("@", "10.0.0.1, 203.0.113.7")); got != "203.0.113.7" { |
| 388 | t.Errorf("clientIP took %q rather than the last element", got) |
| 389 | } |
| 390 | if got := clientIP(req("192.0.2.4:5555", "")); got != "192.0.2.4" { |
| 391 | t.Errorf("clientIP from RemoteAddr = %q, want 192.0.2.4", got) |
| 392 | } |
| 393 | // Two different clients must not share a key. |
| 394 | if clientIP(req("@", "203.0.113.7")) == clientIP(req("@", "203.0.113.8")) { |
| 395 | t.Error("two clients share one limiter key") |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | // The keymail callback mints a session on a GET, which is only safe |
| 400 | // because the return is bound to the browser that began the flow. This |
| 401 | // asserts the binding rather than trusting the comment that claims it. |
| 402 | // |
| 403 | // An attacker holding a code and a state but no pending cookie must get |
| 404 | // nothing. Three things stop them, and this exercises the first: the |
| 405 | // blob is absent so openPending refuses before any network call; the |
| 406 | // blob is HMAC'd under Flow.Key so it cannot be forged; and state must |
| 407 | // match the one sealed inside it. |
| 408 | func TestCallbackWithNoPendingCookieMintsNothing(t *testing.T) { |
| 409 | app := newTestApp(t) |
| 410 | |
| 411 | for _, q := range []string{ |
| 412 | "?code=stolen&state=guessed", |
| 413 | "?code=&state=", |
| 414 | "?state=guessed", |
| 415 | "", |
| 416 | } { |
| 417 | req := httptest.NewRequest(http.MethodGet, callbackPath+q, nil) |
| 418 | req.Host = app.credentialHost |
| 419 | w := httptest.NewRecorder() |
| 420 | app.Router().ServeHTTP(w, req) |
| 421 | |
| 422 | if c := sessionCookie(w); c != nil { |
| 423 | t.Fatalf("callback%s minted a session with no pending cookie", q) |
| 424 | } |
| 425 | var n int |
| 426 | if err := app.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n); err != nil { |
| 427 | t.Fatal(err) |
| 428 | } |
| 429 | if n != 0 { |
| 430 | t.Fatalf("callback%s created %d sessions", q, n) |
| 431 | } |
| 432 | // And it is not a dead end: a failed round trip goes back to the |
| 433 | // form with the override set, so the next attempt takes the |
| 434 | // magic link. |
| 435 | if loc := w.Header().Get("Location"); loc != "/signin?force=1" { |
| 436 | t.Errorf("callback%s went to %q, want /signin?force=1", q, loc) |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | // No mail either: a callback must not be a way to make the home send |
| 441 | // anything to an address the caller named. |
| 442 | if _, sent := app.mailer.last(); sent { |
| 443 | t.Error("a failed callback sent mail") |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | // A forged pending blob must not open. It is HMAC'd under Flow.Key, and |
| 448 | // that key comes from config precisely because sign-in runs before any |
| 449 | // session exists. |
| 450 | func TestForgedPendingBlobIsRefused(t *testing.T) { |
| 451 | app := newTestApp(t) |
| 452 | |
| 453 | req := httptest.NewRequest(http.MethodGet, callbackPath+"?code=x&state=s", nil) |
| 454 | req.Host = app.credentialHost |
| 455 | req.AddCookie(&http.Cookie{ |
| 456 | Name: pendingCookie, |
| 457 | // Well-formed shape — payload.mac — with a MAC that is not one. |
| 458 | Value: "eyJzIjoicyIsInYiOiJ2IiwiaCI6ImV2aWwuaW52YWxpZCIsImEiOiJ2aWN0aW1AZXhhbXBsZS5pbnZhbGlkIiwiZSI6OTk5OTk5OTk5OX0.bm90LWEtdmFsaWQtbWFj", |
| 459 | }) |
| 460 | w := httptest.NewRecorder() |
| 461 | app.Router().ServeHTTP(w, req) |
| 462 | |
| 463 | if c := sessionCookie(w); c != nil { |
| 464 | t.Fatal("a forged pending blob minted a session") |
| 465 | } |
| 466 | var n int |
| 467 | if err := app.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n); err != nil { |
| 468 | t.Fatal(err) |
| 469 | } |
| 470 | if n != 0 { |
| 471 | t.Fatalf("a forged pending blob created %d sessions", n) |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | // The rate limiter, driven end to end. TestClientIPNeverCollapsesToOneBucket |
| 476 | // checks what clientIP returns; nothing checked that the budget it feeds |
| 477 | // actually bites, so handleSigninBegin's 429 branch was dead code as far |
| 478 | // as the suite was concerned. |
| 479 | func TestSigninIsRateLimitedPerIPNotGlobally(t *testing.T) { |
| 480 | app := newTestApp(t) |
| 481 | |
| 482 | post := func(ip, addr string) int { |
| 483 | form := url.Values{"address": {addr}} |
| 484 | req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| 485 | req.Host = app.credentialHost |
| 486 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 487 | req.Header.Set("Origin", app.origins.Credential) |
| 488 | req.Header.Set("X-Forwarded-For", ip) |
| 489 | w := httptest.NewRecorder() |
| 490 | app.Router().ServeHTTP(w, req) |
| 491 | return w.Code |
| 492 | } |
| 493 | |
| 494 | // One IP, distinct addresses so the per-address budget (5) is not |
| 495 | // what fires. The per-IP budget is 20 per 15 minutes. |
| 496 | var limited bool |
| 497 | for i := range 25 { |
| 498 | if post("198.51.100.7", fmt.Sprintf("p%d@example.invalid", i)) == http.StatusTooManyRequests { |
| 499 | limited = true |
| 500 | break |
| 501 | } |
| 502 | } |
| 503 | if !limited { |
| 504 | t.Error("25 sign-in attempts from one IP were never rate limited") |
| 505 | } |
| 506 | |
| 507 | // A different IP must have its own budget. If the key had collapsed |
| 508 | // — which is what "@" over a unix socket would have done — this |
| 509 | // request would already be refused. |
| 510 | if code := post("203.0.113.9", "someone-else@example.invalid"); code == http.StatusTooManyRequests { |
| 511 | t.Error("a second IP was refused on the first attempt: the budget is global, not per-IP") |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | // And the per-address budget exists too, independently of the per-IP |
| 516 | // one: the same address from many IPs is still bounded. |
| 517 | func TestSigninIsRateLimitedPerAddress(t *testing.T) { |
| 518 | app := newTestApp(t) |
| 519 | |
| 520 | var limited bool |
| 521 | for i := range 12 { |
| 522 | form := url.Values{"address": {"target@example.invalid"}} |
| 523 | req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| 524 | req.Host = app.credentialHost |
| 525 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 526 | req.Header.Set("Origin", app.origins.Credential) |
| 527 | req.Header.Set("X-Forwarded-For", fmt.Sprintf("198.51.100.%d", i+1)) |
| 528 | w := httptest.NewRecorder() |
| 529 | app.Router().ServeHTTP(w, req) |
| 530 | if w.Code == http.StatusTooManyRequests { |
| 531 | limited = true |
| 532 | break |
| 533 | } |
| 534 | } |
| 535 | if !limited { |
| 536 | t.Error("12 attempts at one address from 12 IPs were never rate limited: " + |
| 537 | "a mail bomb only needs a botnet") |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | // The confirmation page's comment says it TOUCHES NO STATE. The |
| 542 | // indistinguishability test cannot check that — a GET that quietly |
| 543 | // extended a live link's expiry would render identically and pass — so |
| 544 | // this checks the database directly. |
| 545 | func TestVerifyPageWritesNothing(t *testing.T) { |
| 546 | app := newTestApp(t) |
| 547 | signIn(t, app, "person@example.invalid") |
| 548 | token := capturedLink(t, app) |
| 549 | |
| 550 | before := dumpDatabase(t, app) |
| 551 | for _, tok := range []string{token, "not-a-real-token", ""} { |
| 552 | req := httptest.NewRequest(http.MethodGet, linkPath+"?token="+url.QueryEscape(tok), nil) |
| 553 | req.Host = app.credentialHost |
| 554 | app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| 555 | } |
| 556 | if after := dumpDatabase(t, app); after != before { |
| 557 | t.Errorf("GET %s changed stored state:\nbefore:\n%s\nafter:\n%s", linkPath, before, after) |
| 558 | } |
| 559 | } |
| 560 | |