| 1 | package memoriatest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "log/slog" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | |
| 17 | "amadan.net/rastrillo/rastrillo/db" |
| 18 | |
| 19 | memoria "amadan.net/oficina/memoria/internal/memoria" |
| 20 | ) |
| 21 | |
| 22 | // dialRecorder stands in for the network — BOTH halves of it. |
| 23 | // |
| 24 | // The classifier resolves a TXT record for the submitted domain first and |
| 25 | // only fetches https://<domain>/.well-known/keymail if that finds a |
| 26 | // keymail delegation. So the DNS query is the outbound step that happens |
| 27 | // for every address, and the HTTP fetch is the one that happens for some. |
| 28 | // A recorder watching only HTTP would have called a reserved-TLD address |
| 29 | // "no dial" while the process had already asked the world about it — |
| 30 | // which is what the first draft of this gate did, and what its two-sided |
| 31 | // half caught within a minute of being written. |
| 32 | type dialRecorder struct { |
| 33 | hits atomic.Int64 |
| 34 | last atomic.Value // string |
| 35 | } |
| 36 | |
| 37 | func (d *dialRecorder) note(what string) { |
| 38 | d.hits.Add(1) |
| 39 | d.last.Store(what) |
| 40 | } |
| 41 | |
| 42 | func (d *dialRecorder) RoundTrip(r *http.Request) (*http.Response, error) { |
| 43 | d.note("HTTP " + r.URL.String()) |
| 44 | return nil, errRecorded |
| 45 | } |
| 46 | |
| 47 | func (d *dialRecorder) dialed() bool { return d.hits.Load() > 0 } |
| 48 | |
| 49 | func (d *dialRecorder) where() string { |
| 50 | if s, ok := d.last.Load().(string); ok { |
| 51 | return s |
| 52 | } |
| 53 | return "(none)" |
| 54 | } |
| 55 | |
| 56 | // errRecorded is returned instead of performing any request. The value is |
| 57 | // irrelevant; being called at all is the finding. |
| 58 | var errRecorded = errors.New("memoriatest: outbound request recorded, not sent") |
| 59 | |
| 60 | // stubMailer accepts a magic link and discards it. Never a real sender: |
| 61 | // the link is a live credential and this test does not need one sent. |
| 62 | type stubMailer struct{ sent atomic.Int64 } |
| 63 | |
| 64 | func (m *stubMailer) Send(ctx context.Context, to, subject, body string) error { |
| 65 | m.sent.Add(1) |
| 66 | return nil |
| 67 | } |
| 68 | |
| 69 | const dialTestOwner = "owner@example.test" |
| 70 | |
| 71 | // processTransport is http.DefaultTransport as the process started with |
| 72 | // it, before any test put a recorder or a fake in its place. |
| 73 | var processTransport = http.DefaultTransport |
| 74 | |
| 75 | // signinApp builds the app the way main.go does — production constructor, |
| 76 | // real auth, real owners list — and points the whole process's HTTP |
| 77 | // transport at a recorder. |
| 78 | func signinApp(t *testing.T) (http.Handler, *dialRecorder) { |
| 79 | t.Helper() |
| 80 | return signinAppWithOwners(t, []string{dialTestOwner}) |
| 81 | } |
| 82 | |
| 83 | // signinAppWithOwners is signinApp with the owners list under the test's |
| 84 | // control, so the fail-closed branch — an app wired with no owners at all |
| 85 | // — can be reached. NewAuth still gets a real predicate; it refuses to |
| 86 | // construct without one. |
| 87 | func signinAppWithOwners(t *testing.T, owners []string) (http.Handler, *dialRecorder) { |
| 88 | t.Helper() |
| 89 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 90 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 91 | if err != nil { |
| 92 | t.Fatalf("db.Open: %v", err) |
| 93 | } |
| 94 | t.Cleanup(func() { d.Close() }) |
| 95 | |
| 96 | mux, a, err := memoria.App(d, testOrigin, testDEK(t), logger) |
| 97 | if err != nil { |
| 98 | t.Fatalf("App: %v", err) |
| 99 | } |
| 100 | // Auth is built over the process's own transport, with KeymailServers |
| 101 | // nil as production has it. rastrillo v0.45.0 copies |
| 102 | // http.DefaultTransport into its public-addresses-only Keymail client |
| 103 | // when auth is built, and panics unless it is an *http.Transport; a |
| 104 | // subtest that builds a second app while an earlier app's recorder is |
| 105 | // still installed would hand it the recorder. The recorder goes in |
| 106 | // below, after: the classifier's first step, the _keymail DNS lookup, |
| 107 | // is what it sees, and an owner's sign-in still shows it. |
| 108 | installed := http.DefaultTransport |
| 109 | http.DefaultTransport = processTransport |
| 110 | au, err := memoria.NewAuth(d.Writer(), memoria.AuthEnv{ |
| 111 | Origin: testOrigin, |
| 112 | InstanceKey: "signin-dial-gate-instance-key", |
| 113 | Owners: []string{dialTestOwner}, |
| 114 | Mailer: &stubMailer{}, |
| 115 | }, logger, a) |
| 116 | http.DefaultTransport = installed |
| 117 | if err != nil { |
| 118 | t.Fatalf("NewAuth: %v", err) |
| 119 | } |
| 120 | a.UseAuth(au) |
| 121 | a.SetOwners(owners) |
| 122 | a.MountAuth(mux, testOrigin) |
| 123 | |
| 124 | rec := &dialRecorder{} |
| 125 | |
| 126 | prevTransport := http.DefaultTransport |
| 127 | http.DefaultTransport = rec |
| 128 | t.Cleanup(func() { http.DefaultTransport = prevTransport }) |
| 129 | |
| 130 | // PreferGo routes resolution through Go's own resolver, which calls |
| 131 | // Dial — the only hook that sees a DNS query from inside the process. |
| 132 | prevResolver := net.DefaultResolver |
| 133 | net.DefaultResolver = &net.Resolver{ |
| 134 | PreferGo: true, |
| 135 | Dial: func(ctx context.Context, network, address string) (net.Conn, error) { |
| 136 | rec.note("DNS " + address) |
| 137 | return nil, errRecorded |
| 138 | }, |
| 139 | } |
| 140 | t.Cleanup(func() { net.DefaultResolver = prevResolver }) |
| 141 | |
| 142 | return mux, rec |
| 143 | } |
| 144 | |
| 145 | func beginSignin(t *testing.T, h http.Handler, address string) *httptest.ResponseRecorder { |
| 146 | t.Helper() |
| 147 | form := url.Values{"address": {address}} |
| 148 | req := httptest.NewRequest(http.MethodPost, "/auth/begin", strings.NewReader(form.Encode())) |
| 149 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 150 | req.Header.Set("Origin", testOrigin) |
| 151 | rr := httptest.NewRecorder() |
| 152 | h.ServeHTTP(rr, req) |
| 153 | return rr |
| 154 | } |
| 155 | |
| 156 | // Gate 33 (spec §3.2, §4.3): an anonymous visitor cannot make this |
| 157 | // instance dial a domain of their choosing. |
| 158 | // |
| 159 | // rastrillo's sign-in classifier fetches the submitted address's domain |
| 160 | // inside auth.Begin, before the Authorize callback runs. memoria's |
| 161 | // beginGuard runs the owners predicate first, so a non-owner's address |
| 162 | // never reaches the classifier. |
| 163 | // |
| 164 | // The gate is deliberately TWO-SIDED, and that is the part worth reading. |
| 165 | // Asserting only "a non-owner causes no dial" is satisfied by a guard |
| 166 | // that refuses everybody, by auth being unwired, by the route being |
| 167 | // absent, and by the transport never being consulted at all — four ways |
| 168 | // to be green while the app is broken or the test is measuring nothing. |
| 169 | // So the owner case asserts the dial DOES happen, which proves the |
| 170 | // recorder is installed, the route is reachable, the classifier still |
| 171 | // runs for an admitted address, and the guard discriminates rather than |
| 172 | // blocks. |
| 173 | // |
| 174 | // MUTATION-TESTED 2026-09-05, in two passes, and the second is why this |
| 175 | // file is worth reading. |
| 176 | // |
| 177 | // The author's five, each verified red: |
| 178 | // |
| 179 | // M1 register a.auth.Begin bare, no guard -> non-owner case red |
| 180 | // M2 guard admits everyone -> non-owner case red |
| 181 | // M3 guard refuses everyone -> owner case red |
| 182 | // M4 guard returns 403 instead of ?sent=1 -> non-owner case red |
| 183 | // (since the smart door, Begin's Sent carries attempt=, and the |
| 184 | // guard answers with rastrillo's AnswerAsSent; a plain ?sent=1 is |
| 185 | // now the distinguishable answer, and red here too) |
| 186 | // M5 neither recorder installed -> owner case red |
| 187 | // |
| 188 | // Then an adversarial pass by someone who did not write the gate, per |
| 189 | // AGENTS.md. It found the five above were the cases already defended |
| 190 | // against, and that **the gate was green over two live bypasses in the |
| 191 | // shipped guard** — not mutations, the actual code: |
| 192 | // |
| 193 | // - `POST /auth/begin?a;b=1` with an ordinary body reached the |
| 194 | // classifier. The guard called ParseForm and passed the request |
| 195 | // through on error; ParseForm reports a query-string error even when |
| 196 | // the body parsed fine, and rastrillo's FormValue ignores it and uses |
| 197 | // what parsed. One character defeated the check. |
| 198 | // - An address supplied only in the query string was invisible to the |
| 199 | // guard's PostFormValue and visible to rastrillo's FormValue. |
| 200 | // |
| 201 | // Both are one mistake — a guard reading the request differently from the |
| 202 | // thing it guards — and the subtests below are the four payloads that |
| 203 | // proved it, each confirmed to go red against the old code with the |
| 204 | // resolver being asked for the attacker's domain. |
| 205 | // |
| 206 | // The same pass found three more green mutations, now closed: SigninPath |
| 207 | // drifting from the guard's own constant (they share it), dropping |
| 208 | // csrf.Protect from MountAuth (cross-origin now answers identically), and |
| 209 | // a nil predicate falling open (asserted). |
| 210 | // |
| 211 | // STILL OPEN, and stated rather than quietly carried: rate limiting makes |
| 212 | // owner and non-owner distinguishable after five submissions, because the |
| 213 | // guard sits in front of signin's per-address budget. See beginGuard's |
| 214 | // residual 2. Not closable from here. |
| 215 | func TestSigninDoesNotDialForANonOwner(t *testing.T) { |
| 216 | t.Run("a non-owner never reaches the classifier", func(t *testing.T) { |
| 217 | h, rec := signinApp(t) |
| 218 | rr := beginSignin(t, h, "stranger@attacker.example") |
| 219 | |
| 220 | if rec.dialed() { |
| 221 | t.Errorf("an unadmitted address made the instance dial %s", rec.where()) |
| 222 | } |
| 223 | if rr.Code != http.StatusSeeOther { |
| 224 | t.Errorf("status = %d, want %d — a non-owner must get the same "+ |
| 225 | "outcome as a sent link, not a distinguishable one", |
| 226 | rr.Code, http.StatusSeeOther) |
| 227 | } |
| 228 | if got := rr.Header().Get("Location"); !sentLocation(got) { |
| 229 | t.Errorf("Location = %q, want Begin's Sent (/signin?sent=1&attempt=…): a distinct destination turns "+ |
| 230 | "this guard into an owners-list oracle, which is a worse "+ |
| 231 | "leak than the dial it removes", got) |
| 232 | } |
| 233 | }) |
| 234 | |
| 235 | t.Run("an owner still reaches it, or this gate proves nothing", func(t *testing.T) { |
| 236 | h, rec := signinApp(t) |
| 237 | beginSignin(t, h, dialTestOwner) |
| 238 | |
| 239 | if !rec.dialed() { |
| 240 | t.Error("the classifier was never reached for an admitted address: " + |
| 241 | "either the guard refuses everybody, or the recorder is not " + |
| 242 | "installed, or the route is gone — in all three the other " + |
| 243 | "half of this gate is measuring nothing") |
| 244 | } |
| 245 | }) |
| 246 | |
| 247 | // A guard that reads the request differently from the thing it guards |
| 248 | // is not guarding it. Every case below defeated the first version, |
| 249 | // which called ParseForm and passed the request through on error — |
| 250 | // and ParseForm reports a query-string error even when the body is |
| 251 | // fine, while rastrillo's FormValue ignores it and uses what parsed. |
| 252 | // |
| 253 | // Found by an adversarial mutation pass, 2026-09-05. These are not |
| 254 | // mutations: they were live bypasses of shipped code. |
| 255 | t.Run("a malformed request does not skip the check", func(t *testing.T) { |
| 256 | const stranger = "stranger@attacker.example" |
| 257 | cases := []struct { |
| 258 | name, target, body, contentType string |
| 259 | }{ |
| 260 | {"semicolon in the query string", "/auth/begin?a;b=1", |
| 261 | "address=" + stranger, "application/x-www-form-urlencoded"}, |
| 262 | {"semicolon in the body", "/auth/begin", |
| 263 | "x;y=1&address=" + stranger, "application/x-www-form-urlencoded"}, |
| 264 | {"bad percent-escape in the body", "/auth/begin", |
| 265 | "x=%zz&address=" + stranger, "application/x-www-form-urlencoded"}, |
| 266 | {"malformed Content-Type, address in the query", |
| 267 | "/auth/begin?address=" + url.QueryEscape(stranger), |
| 268 | "", "application/x-www-form-urlencoded; charset"}, |
| 269 | {"address only in the query string, empty body", |
| 270 | "/auth/begin?address=" + url.QueryEscape(stranger), |
| 271 | "", "application/x-www-form-urlencoded"}, |
| 272 | } |
| 273 | for _, c := range cases { |
| 274 | t.Run(c.name, func(t *testing.T) { |
| 275 | h, rec := signinApp(t) |
| 276 | req := httptest.NewRequest(http.MethodPost, c.target, strings.NewReader(c.body)) |
| 277 | req.Header.Set("Content-Type", c.contentType) |
| 278 | req.Header.Set("Origin", testOrigin) |
| 279 | h.ServeHTTP(httptest.NewRecorder(), req) |
| 280 | if rec.dialed() { |
| 281 | t.Errorf("an unadmitted address reached the classifier via %s: dialed %s", |
| 282 | c.name, rec.where()) |
| 283 | } |
| 284 | }) |
| 285 | } |
| 286 | }) |
| 287 | |
| 288 | // A cross-site page can read the difference between an opaque redirect |
| 289 | // and an opaque response, so owner and stranger must be identical |
| 290 | // cross-origin too. Without this, removing csrf.Protect from MountAuth |
| 291 | // — plausible, since Begin re-checks the origin itself — turns the |
| 292 | // guard into an oracle: 403 for an owner, 303 for a stranger. |
| 293 | t.Run("cross-origin answers the same for both", func(t *testing.T) { |
| 294 | submit := func(address string) (int, string) { |
| 295 | h, _ := signinApp(t) |
| 296 | form := url.Values{"address": {address}} |
| 297 | req := httptest.NewRequest(http.MethodPost, "/auth/begin", strings.NewReader(form.Encode())) |
| 298 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 299 | req.Header.Set("Origin", "https://evil.example") |
| 300 | rr := httptest.NewRecorder() |
| 301 | h.ServeHTTP(rr, req) |
| 302 | return rr.Code, rr.Header().Get("Location") |
| 303 | } |
| 304 | ownerCode, ownerLoc := submit(dialTestOwner) |
| 305 | strangerCode, strangerLoc := submit("stranger@attacker.example") |
| 306 | if ownerCode != strangerCode || ownerLoc != strangerLoc { |
| 307 | t.Errorf("cross-origin is distinguishable: owner %d %q, stranger %d %q", |
| 308 | ownerCode, ownerLoc, strangerCode, strangerLoc) |
| 309 | } |
| 310 | }) |
| 311 | |
| 312 | // The fail-closed branch was untested prose until this existed: the |
| 313 | // gate always installed an owners list, so making the empty case fall |
| 314 | // through to rastrillo stayed green while dialing for everyone. |
| 315 | t.Run("no owners refuses rather than falling open", func(t *testing.T) { |
| 316 | h, rec := signinAppWithOwners(t, nil) |
| 317 | rr := beginSignin(t, h, "stranger@attacker.example") |
| 318 | if rec.dialed() { |
| 319 | t.Errorf("an app with no owners list dialed %s", rec.where()) |
| 320 | } |
| 321 | if rr.Code != http.StatusInternalServerError { |
| 322 | t.Errorf("status = %d, want %d: an empty owners list is a wiring "+ |
| 323 | "bug — LoadConfig refuses to boot without one — and must say "+ |
| 324 | "so rather than refuse quietly", rr.Code, http.StatusInternalServerError) |
| 325 | } |
| 326 | }) |
| 327 | } |
| 328 | |