| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "net/url" |
| 9 | "path/filepath" |
| 10 | "regexp" |
| 11 | "sort" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | ) |
| 15 | |
| 16 | // loggingMailerStub is a minimal mail.Sender good enough to satisfy |
| 17 | // Config.Mailer's own "non-nil outside development" fail-closed |
| 18 | // check (buildMailer, auth.go), so |
| 19 | // TestNewRefusesMissingAllowlistOutsideDevelopment reaches the |
| 20 | // allowlist check it actually means to pin rather than failing |
| 21 | // earlier on an unrelated one. It never actually sends anything — |
| 22 | // nothing in that test signs in. |
| 23 | type loggingMailerStub struct{} |
| 24 | |
| 25 | func (loggingMailerStub) Send(ctx context.Context, to, subject, body string) error { return nil } |
| 26 | |
| 27 | // newAllowlistedTestApp builds a development App exactly like |
| 28 | // NewForTest (testing.go), except with AllowedAddresses set |
| 29 | // explicitly. NewForTest itself cannot exercise the allowlist at all: |
| 30 | // an empty AllowedAddresses in development means "admit everyone" |
| 31 | // (resolveAllowlist's own doc comment, auth.go) — precisely so |
| 32 | // TestSignIn and every other test built on NewForTest need no |
| 33 | // allowlist setup of their own. These tests are the ones that |
| 34 | // actually need a non-default allowlist configured, so they build |
| 35 | // their own App via New directly, package-internal (like |
| 36 | // origin_test.go and render_test.go) so they can also reach |
| 37 | // app.mailRecorder — unexported, and deliberately not something |
| 38 | // testing.go exposes outside this package: nothing outside auth.go's |
| 39 | // own tests should need to know whether mail was sent versus merely |
| 40 | // that a link came back, and TestSignIn already covers the latter. |
| 41 | func newAllowlistedTestApp(t *testing.T, allowed string) *App { |
| 42 | t.Helper() |
| 43 | app, err := New(Config{ |
| 44 | DBPath: filepath.Join(t.TempDir(), "docs.db"), |
| 45 | Env: "development", |
| 46 | AllowedAddresses: allowed, |
| 47 | }) |
| 48 | if err != nil { |
| 49 | t.Fatalf("New: %v", err) |
| 50 | } |
| 51 | t.Cleanup(func() { |
| 52 | if cerr := app.Close(); cerr != nil { |
| 53 | t.Errorf("App.Close: %v", cerr) |
| 54 | } |
| 55 | }) |
| 56 | return app |
| 57 | } |
| 58 | |
| 59 | // postSignin POSTs address to /signin as a same-origin browser form |
| 60 | // would, with force=1 — the same escape hatch TestSignIn (testing.go) |
| 61 | // uses to skip signin's own keymail classification (which would |
| 62 | // otherwise make a real outbound DNS/HTTPS call per address, per |
| 63 | // signin's own README, entirely beside the point of what these tests |
| 64 | // check). force=1 selects email but does not bypass the mail queue's admission check. |
| 65 | func postSignin(app *App, address string) *httptest.ResponseRecorder { |
| 66 | form := url.Values{"address": {address}, "force": {"1"}} |
| 67 | req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(form.Encode())) |
| 68 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 69 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 70 | rec := httptest.NewRecorder() |
| 71 | app.Handler().ServeHTTP(rec, req) |
| 72 | return rec |
| 73 | } |
| 74 | |
| 75 | // lastMailBody reads back app.mailRecorder's most recently recorded |
| 76 | // send, "" if nothing has been sent yet (or since the caller last |
| 77 | // cleared it) — the direct way to observe whether Begin actually ran, |
| 78 | // as opposed to TestSignIn's own success-shaped check (a link came |
| 79 | // back), which a test proving the ABSENCE of a send cannot use: there |
| 80 | // is no link to find in an empty body. |
| 81 | func lastMailBody(app *App) string { |
| 82 | app.signinMail.wait() // links are sent after the response |
| 83 | app.mailRecorder.mu.Lock() |
| 84 | defer app.mailRecorder.mu.Unlock() |
| 85 | return app.mailRecorder.lastBody |
| 86 | } |
| 87 | |
| 88 | // TestNonPermittedAddressSendsNoMail is this task's whole point, |
| 89 | // stated as literally as possible: the defect (Config.AllowedAddresses' |
| 90 | // own doc comment on Config has the full story — credited to the |
| 91 | // CARLOS Sheets session's finding on their own deployed instance) was |
| 92 | // never that a non-permitted address could sign in; rauth.Config. |
| 93 | // Authorize already stopped that, once wired. It was that Begin sends |
| 94 | // mail to any address at all, regardless of Authorize, because |
| 95 | // Authorize is only ever consulted afterward, at the callback. This |
| 96 | // is the test whose absence let that ship: every existing test in |
| 97 | // this package (before this task) proved something about admission, |
| 98 | // and none of them ever looked at whether a Send happened. Before |
| 99 | // the delivery gate existed, this test failed exactly this way — see this |
| 100 | // file's own commit message for how that was confirmed live, not |
| 101 | // assumed. |
| 102 | func TestNonPermittedAddressSendsNoMail(t *testing.T) { |
| 103 | app := newAllowlistedTestApp(t, "permitted@example.com") |
| 104 | |
| 105 | rec := postSignin(app, "stranger@evil.example") |
| 106 | |
| 107 | if rec.Code != http.StatusSeeOther { |
| 108 | t.Fatalf("POST /signin for a non-permitted address: status %d, want %d", rec.Code, http.StatusSeeOther) |
| 109 | } |
| 110 | if loc := rec.Header().Get("Location"); !strings.Contains(loc, "sent=1") { |
| 111 | t.Fatalf("POST /signin for a non-permitted address redirected to %q, want a %q outcome — the refusal must be invisible, not merely non-fatal", loc, "?sent=1") |
| 112 | } |
| 113 | if body := lastMailBody(app); body != "" { |
| 114 | t.Fatalf("POST /signin for a non-permitted address sent mail (recorded body: %q) — Begin must never run for an address the allowlist refuses", body) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // TestSigninResponseIdenticalForNonPermittedAddress is fix |
| 119 | // requirement 3, checked the way its own reasoning demands: not |
| 120 | // "both responses are a 303" but the actual bytes — status, Location |
| 121 | // and body — compared directly. Any observable difference here would |
| 122 | // turn POST /signin into a membership oracle: an attacker who can |
| 123 | // tell "sent" from "not sent" has learned whether a given address is |
| 124 | // on this instance's allowlist, which is exactly the kind of leak an |
| 125 | // admission check alone would not create (it would 403 visibly) but |
| 126 | // a badly-built send-time gate could. |
| 127 | func TestSigninResponseIdenticalForNonPermittedAddress(t *testing.T) { |
| 128 | app := newAllowlistedTestApp(t, "permitted@example.com") |
| 129 | |
| 130 | permitted := postSignin(app, "permitted@example.com") |
| 131 | nonPermitted := postSignin(app, "stranger@evil.example") |
| 132 | |
| 133 | if permitted.Code != http.StatusSeeOther { |
| 134 | t.Fatalf("POST /signin for the permitted address: status %d, want %d", permitted.Code, http.StatusSeeOther) |
| 135 | } |
| 136 | if got, want := nonPermitted.Code, permitted.Code; got != want { |
| 137 | t.Errorf("status differs: non-permitted=%d permitted=%d", got, want) |
| 138 | } |
| 139 | // The sign-in screen (SigninScreen) names each attempt with a fresh |
| 140 | // random id, so the two Locations differ there and only there; and both |
| 141 | // answers set the same cookies, the attempt's among them. |
| 142 | if got, want := attemptMasked(nonPermitted.Header().Get("Location")), attemptMasked(permitted.Header().Get("Location")); got != want || !strings.Contains(want, "attempt=*") { |
| 143 | t.Errorf("Location differs: non-permitted=%q permitted=%q", got, want) |
| 144 | } |
| 145 | if got, want := cookieNames(nonPermitted), cookieNames(permitted); got != want { |
| 146 | t.Errorf("cookies differ: non-permitted=%q permitted=%q", got, want) |
| 147 | } |
| 148 | if got, want := nonPermitted.Header().Get("Content-Type"), permitted.Header().Get("Content-Type"); got != want { |
| 149 | t.Errorf("Content-Type differs: non-permitted=%q permitted=%q", got, want) |
| 150 | } |
| 151 | if got, want := nonPermitted.Body.Bytes(), permitted.Body.Bytes(); !bytes.Equal(got, want) { |
| 152 | t.Errorf("body differs: non-permitted=%q permitted=%q", got, want) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // TestPermittedAddressStillSignsIn proves the fix does not break the |
| 157 | // working path: a permitted address must still complete the full |
| 158 | // magic-link ceremony end to end, mirroring |
| 159 | // TestMagicLinkThenSignedInRouteWorks (auth_test.go) but against an |
| 160 | // App with a real, non-empty allowlist instead of NewForTest's |
| 161 | // admit-everyone default. |
| 162 | func TestPermittedAddressStillSignsIn(t *testing.T) { |
| 163 | app := newAllowlistedTestApp(t, "permitted@example.com") |
| 164 | |
| 165 | link, err := app.TestSignIn(t, "permitted@example.com") |
| 166 | if err != nil { |
| 167 | t.Fatalf("TestSignIn: %v", err) |
| 168 | } |
| 169 | |
| 170 | verifyReq := confirmRequest(link) |
| 171 | verifyRec := httptest.NewRecorder() |
| 172 | app.Handler().ServeHTTP(verifyRec, verifyReq) |
| 173 | cookies := verifyRec.Result().Cookies() |
| 174 | if len(cookies) == 0 { |
| 175 | t.Fatal("following the magic link set no session cookie") |
| 176 | } |
| 177 | |
| 178 | req := httptest.NewRequest(http.MethodGet, "/", nil) |
| 179 | for _, c := range cookies { |
| 180 | req.AddCookie(c) |
| 181 | } |
| 182 | rec := httptest.NewRecorder() |
| 183 | app.Handler().ServeHTTP(rec, req) |
| 184 | if rec.Code != http.StatusOK { |
| 185 | t.Fatalf("GET / signed in as a permitted address: status %d, want 200", rec.Code) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | // TestAllowlistIsCaseAndWhitespaceInsensitive is fix requirement 1's |
| 190 | // own explicit demand: real config files have spaces after their |
| 191 | // commas, and people type capitals — $DOCS_ALLOWED_ADDRESSES= |
| 192 | // "Permitted@Example.com" must still admit |
| 193 | // "permitted@example.com" and vice versa, in both directions |
| 194 | // (the configured entry's own case/whitespace, and the submitted |
| 195 | // address's). |
| 196 | func TestAllowlistIsCaseAndWhitespaceInsensitive(t *testing.T) { |
| 197 | app := newAllowlistedTestApp(t, " Permitted@Example.com , other@example.com") |
| 198 | |
| 199 | for _, variant := range []string{ |
| 200 | "permitted@example.com", |
| 201 | "PERMITTED@EXAMPLE.COM", |
| 202 | " permitted@example.com ", |
| 203 | "Permitted@Example.com", |
| 204 | } { |
| 205 | if _, err := app.TestSignIn(t, variant); err != nil { |
| 206 | t.Errorf("TestSignIn(%q): %v, want the allowlisted address to be admitted regardless of case or surrounding whitespace", variant, err) |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // TestResolveAllowlistParsesCommaSeparatedList pins |
| 212 | // resolveAllowlist's own parsing directly: comma-separated, each |
| 213 | // entry trimmed and lowercased, blank entries (a trailing comma, or |
| 214 | // stray whitespace between two commas) dropped rather than becoming a |
| 215 | // spurious "" that could never match a real address anyway but would |
| 216 | // otherwise clutter the set. |
| 217 | func TestResolveAllowlistParsesCommaSeparatedList(t *testing.T) { |
| 218 | list, err := resolveAllowlist(Config{ |
| 219 | Env: "production", |
| 220 | AllowedAddresses: " Alice@Example.com, bob@example.com ,, carol@example.com ", |
| 221 | }) |
| 222 | if err != nil { |
| 223 | t.Fatalf("resolveAllowlist: %v", err) |
| 224 | } |
| 225 | for _, addr := range []string{"alice@example.com", "ALICE@EXAMPLE.COM", "bob@example.com", "carol@example.com"} { |
| 226 | if !list.admits(addr) { |
| 227 | t.Errorf("list.admits(%q) = false, want true", addr) |
| 228 | } |
| 229 | } |
| 230 | if list.admits("mallory@example.com") { |
| 231 | t.Error("list.admits(\"mallory@example.com\") = true, want false — not on the configured list") |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // TestResolveAllowlistEmptyOutsideDevelopmentRefuses is fix |
| 236 | // requirement 4's decision, pinned directly: an unset |
| 237 | // $DOCS_ALLOWED_ADDRESSES must never mean "allow everyone" outside |
| 238 | // development. resolveAllowlist's own doc comment has the full |
| 239 | // reasoning for refusing at startup rather than the alternative |
| 240 | // (silently admitting nobody) — this test only pins the outcome: |
| 241 | // New must refuse to start, the same fail-closed shape |
| 242 | // TestNewRefusesMissingInstanceKeyOutsideDevelopment and |
| 243 | // TestNewRefusesMissingMailOutsideDevelopment (auth_test.go) already |
| 244 | // pin for InstanceKey and Mailer. |
| 245 | func TestResolveAllowlistEmptyOutsideDevelopmentRefuses(t *testing.T) { |
| 246 | for _, env := range []string{"production", "staging", ""} { |
| 247 | if _, err := resolveAllowlist(Config{Env: env}); err == nil { |
| 248 | t.Errorf("resolveAllowlist with Env %q and no AllowedAddresses: err = nil, want a refusal", env) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // TestResolveAllowlistEmptyInDevelopmentAdmitsEveryone pins the other |
| 254 | // half of the same decision: development's own convenience default |
| 255 | // (TestSignIn, scripts/run-dev.sh) needs no allowlist configured at |
| 256 | // all, exactly as it needed no InstanceKey or Mailer configured |
| 257 | // before this task. |
| 258 | func TestResolveAllowlistEmptyInDevelopmentAdmitsEveryone(t *testing.T) { |
| 259 | list, err := resolveAllowlist(Config{Env: "development"}) |
| 260 | if err != nil { |
| 261 | t.Fatalf("resolveAllowlist: %v", err) |
| 262 | } |
| 263 | if !list.admits("anyone@example.com") { |
| 264 | t.Error("an empty AllowedAddresses in development must admit everyone") |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // TestNewRefusesMissingAllowlistOutsideDevelopment is the New-level |
| 269 | // version of TestResolveAllowlistEmptyOutsideDevelopmentRefuses, |
| 270 | // exercised the way a real misconfigured deployment would actually |
| 271 | // hit it — through New itself, alongside its own InstanceKey/Mailer |
| 272 | // siblings in auth_test.go. |
| 273 | func TestNewRefusesMissingAllowlistOutsideDevelopment(t *testing.T) { |
| 274 | _, err := New(Config{ |
| 275 | Env: "production", |
| 276 | Origin: "https://docs.example.com", |
| 277 | InstanceKey: "some-real-key", |
| 278 | Mailer: loggingMailerStub{}, |
| 279 | }) |
| 280 | if err == nil { |
| 281 | t.Fatal("New must refuse to start outside development with no allowlist configured") |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // attemptMasked is a sign-in Location with its random attempt id masked. |
| 286 | func attemptMasked(location string) string { |
| 287 | return regexp.MustCompile(`attempt=[^&]+`).ReplaceAllString(location, "attempt=*") |
| 288 | } |
| 289 | |
| 290 | // cookieNames is the sorted names of the cookies a response sets. |
| 291 | func cookieNames(rec *httptest.ResponseRecorder) string { |
| 292 | var names []string |
| 293 | for _, c := range rec.Result().Cookies() { |
| 294 | names = append(names, c.Name) |
| 295 | } |
| 296 | sort.Strings(names) |
| 297 | return strings.Join(names, ",") |
| 298 | } |
| 299 | |