oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "database/sql"
5 "errors"
6 "log/slog"
7 "net/http"
8 "net/url"
9 "strings"
10
11 "amadan.net/oficina/estilo.git/chrome"
12 "amadan.net/oficina/home/connect"
13 "amadan.net/rastrillo/rastrillo/auth"
14 "amadan.net/rastrillo/rastrillo/mail"
15)
16
17// signinPath is the sign-in door (connect.SigninPath): every sign-in
18// outcome, every chooser link and Forget's way back land here. It must
19// match the SigninPath given to auth.New below, because beginGuard
20// answers in Begin's shape itself: if the two disagree, the guard becomes
21// distinguishable from the real thing by its destination alone.
22const signinPath = connect.SigninPath
23
24// beginPath is where Begin is mounted (MountAuth): the door's form posts
25// here, so auth.Config.BeginPath names it.
26const beginPath = "/auth/begin"
27
28// beginGuard stops an anonymous visitor making this instance dial a
29// domain of their choosing.
30//
31// rastrillo's sign-in classifier fetches https://<the submitted address's
32// domain>/.well-known/keymail inside auth.Begin, BEFORE the Authorize
33// callback runs. So POST /auth/begin with any address makes memoria issue
34// an outbound request to any host — leaking the instance's existence, its
35// egress IP and a timing channel to anyone who can reach the sign-in
36// page. Not content, but §3.2 records it, and it is why the footer no
37// longer claims "nothing leaves this instance".
38//
39// The real fix is upstream, in rastrillo/auth and keymaildev/signin: the
40// classifier should not fetch before the app's admission predicate has
41// run, and the fetcher should refuse redirects and private address ranges
42// regardless. This guard is memoria's half. It is cheap here precisely
43// because slice 0 has no guests — admission IS the owners list, so
44// refusing a non-owner before the dial changes no behaviour that exists
45// today. When slice 1 brings guests, the predicate becomes the roster
46// (§4.3) and this still runs before any fetch.
47//
48// It renders the same outcome as a successful magic-link send (the same
49// status, destination and attempt cookie: rastrillo's AnswerAsSent, which
50// is Begin's Sent without the mail), because a distinct rejection would
51// turn this guard into an owners-list oracle — worse than the dial it removes,
52// since the dial only confirms the instance exists while an oracle
53// confirms who owns it.
54//
55// FOUR RESIDUALS, and the second one means the sentence above is an aim
56// rather than an achievement. Stated here because an earlier version of
57// this comment claimed the guard was not an oracle, and it is one.
58//
59// 1. An owner whose domain delegates to keymail is sent on to Keymail
60// (since the smart door, by way of the door's ?continue= page)
61// rather than to ?sent=1, so those two paths differ.
62//
63// 2. **Rate limiting distinguishes them after five submissions.** This
64// guard sits in front of rastrillo, so a refused address never
65// reaches signin's per-address budget while an admitted one does:
66// six tries at an owner's address yields ?err=rate, six at a
67// stranger's yields ?sent=1 every time. Enumeration is also
68// unthrottled, because a refused address consumes no per-IP budget
69// either. The budget lives inside signin's flow and is not reachable
70// from here, so closing this means either duplicating upstream's
71// window and count — coupling to a constant we do not own — or
72// fixing the ordering upstream, which is the same fix the SSRF needs.
73// Found by an adversarial mutation pass, 2026-09-05.
74//
75// 3. A `force=1` submission skips the classifier, so no dial happens —
76// but rastrillo still mails a magic link to whatever address was
77// given. The guard refuses those before Begin, so memoria is covered;
78// it is listed because "no dial" and "no outbound anything" are not
79// the same claim.
80//
81// 4. **Response time.** An owner's answer waits for the classifier's
82// dial and the mailer inside Begin; a stranger's is answered here at
83// once. The two answers are the same bytes (AnswerAsSent), but how
84// long they take is not, and nothing here pads one to match the
85// other. Closing it needs the same upstream reordering as 2, or the
86// mail sent after the response as Calls does (signin_mail.go).
87//
88// All four are narrower than the status quo, where the dial happens for
89// every address at every domain, and all three close when the upstream
90// fix lands.
91func (a *app) beginGuard(origin string, next http.HandlerFunc) http.HandlerFunc {
92 return func(w http.ResponseWriter, r *http.Request) {
93 // Fail closed. An empty owners list is a wiring bug — LoadConfig
94 // refuses to boot without one — and the version of this that
95 // defaults to allowing is the version that dials for everyone
96 // while looking configured.
97 // In team mode an empty list is valid (Home sign-in only), and
98 // every address is refused below exactly as a stranger's is.
99 if len(a.owners) == 0 && !a.teamMode() {
100 a.logger.Error("sign-in guard has no owners list; refusing")
101 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
102 return
103 }
104
105 // Cross-origin goes straight to rastrillo, which refuses it
106 // uniformly with a 403 before it dials anything. Deciding it here
107 // would answer differently for an owner and a stranger — a
108 // cross-site page can read that difference through an opaque
109 // redirect — and this guard exists to remove distinguishable
110 // outcomes, not to add one on another axis.
111 if o := r.Header.Get("Origin"); o != "" && o != origin {
112 next(w, r)
113 return
114 }
115
116 // Read the address EXACTLY as rastrillo does. This is the whole
117 // correctness argument of the guard, and the first version got it
118 // wrong twice in one line.
119 //
120 // It called r.ParseForm() and passed the request through on error.
121 // url.ParseQuery keeps every well-formed pair AND returns the
122 // first error, and ParseForm reports a query-string error even
123 // when the body parsed perfectly — while rastrillo's FormValue
124 // ignores the error and uses what parsed. So `POST /auth/begin?a;b=1`
125 // with an ordinary body skipped the check entirely and dialled.
126 // One character.
127 //
128 // It also read PostFormValue where rastrillo reads FormValue, so
129 // an address supplied only in the query string was invisible here
130 // and visible there.
131 //
132 // Both are the same mistake: a guard that reads a request
133 // differently from the thing it guards is not guarding it. There
134 // is no error branch now, because FormValue has no error to
135 // branch on — the two calls cannot disagree.
136 // A shape check first, answered the same for everyone: the door's
137 // form leaves validation to the server, and "paul@" or an empty
138 // field should say so rather than claim a link was sent. It looks
139 // only at the text, never at who owns what, so it tells nothing.
140 if !plausibleAddress(r.FormValue("address")) {
141 http.Redirect(w, r, badAddress(r), http.StatusSeeOther)
142 return
143 }
144 if !a.isOwner(normaliseAddress(r.FormValue("address"))) {
145 // No address in the log line, ever: §3.2, gate 4.
146 a.logger.Info("sign-in refused before classifier dial")
147 // Begin's own Sent, without the mail (rastrillo's
148 // AnswerAsSent): the same redirect, attempt= and attempt
149 // cookie an owner's sent link gets. A plain ?sent=1 here
150 // would carry no attempt while an owner's carried one, an
151 // owners-list oracle on the first try.
152 a.auth.AnswerAsSent(w, r)
153 return
154 }
155 next(w, r)
156 }
157}
158
159// AuthEnv is the sign-in configuration read from platform config.
160type AuthEnv struct {
161 Origin string
162 // InstanceKey seals auth's pending blob. auth.New refuses an empty
163 // one, and rightly: an empty input hashes to a fixed, publicly
164 // computable value identical across every deployment.
165 InstanceKey string
166 Mailer mail.Sender
167 Owners []string
168 HomeEnabled bool
169 // KeymailServers is rastrillo's auth.Config.KeymailServers, and nil
170 // in production: any server an address's own _keymail delegation
171 // names, dialled only at a public address (rastrillo v0.45.0). A test
172 // lists its fake's host, because the listed-servers client is the one
173 // that sends through the process's default transport, where the fake
174 // sits; the public-only client copies the real transport when auth is
175 // built and would never reach it.
176 KeymailServers []string
177}
178
179// ParseOwners splits a comma-separated allowlist, lowercasing and
180// trimming. Slice 0's membership table is this list; slice 1 replaces it
181// with rows, because §4.3's admission gate has to admit whoever the
182// team's grants admit, and only a database knows that.
183func ParseOwners(raw string) []string {
184 var out []string
185 for _, part := range strings.Split(raw, ",") {
186 if addr := strings.ToLower(strings.TrimSpace(part)); addr != "" {
187 out = append(out, addr)
188 }
189 }
190 return out
191}
192
193// normaliseAddress is the one spelling rule. identity() lowercases and
194// trims what auth verified; the guard must do the same to what a form
195// submitted, or the two disagree about whether an address is an owner —
196// and a guard that disagrees with the thing it guards is the bug this
197// branch already shipped once, in a different clause.
198//
199// Addresses are case-sensitive before the @ per RFC 5321 and no mainstream
200// provider honours that, so this matches what an operator expects when
201// they type a list.
202func normaliseAddress(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
203
204// Admit is THE admission predicate: the one rastrillo runs at
205// verification, the one beginGuard runs before the classifier dials, and
206// the one requireOwner runs on the connector routes.
207//
208// A method on the app rather than a constructor over a list, because a
209// constructor gives a caller something to build twice — and it was built
210// twice. main.go passed `Admits(cfg.Owners)` to NewAuth and separately
211// called `SetOwners(cfg.Owners)`: two closures over two copies guarding
212// one rule, and a review's mutation (`Admits(nil)` in main) stayed green
213// because every test built its own. One list, one predicate, nothing to
214// pass a second version of.
215//
216// It normalises through normaliseAddress. The old constructor re-spelled
217// that inline, which is how a guard and the thing it guards start to
218// disagree.
219func (a *app) Admit(address string) bool {
220 return a.isOwner(normaliseAddress(address))
221}
222
223// NewAuth wires the sign-in flow. Exactly one per process: auth carries
224// rate-limiter state on the value, so one per request would get a fresh
225// empty budget every time and rate-limit nothing, silently.
226//
227// a supplies the three things auth asks of the app at redemption: the
228// admission gate (app.Admit), the door a verified but refused address is
229// shown (app.refused), and the door an emailed link opens on
230// (app.renderConfirm). The app rather than a predicate, for the reason
231// Admit gives: there is one of each, so there is nothing to pass a second
232// version of.
233func NewAuth(sqlDB *sql.DB, env AuthEnv, logger *slog.Logger, a *app) (*auth.Auth, error) {
234 if a == nil {
235 // A nil Authorize admits every verified address, which on a
236 // public hostname means anyone who can receive mail. Refusing
237 // beats defaulting, because a caller that forgot to pass one has
238 // a bug either way and this is the version that says so.
239 return nil, errors.New("sign-in: refusing to wire auth with no admission gate")
240 }
241 // Standalone, a verified link lands on /auth/landed, which goes on to
242 // the page the person was heading for (return.go).
243 landing := landedPath
244 if env.HomeEnabled {
245 landing = "/auth/local/complete"
246 }
247 au, err := auth.New(auth.Config{
248 DB: sqlDB,
249 Origin: env.Origin,
250 InstanceKey: env.InstanceKey,
251 Mailer: env.Mailer,
252 Authorize: a.Admit,
253 // Nil outside tests (AuthEnv.KeymailServers).
254 KeymailServers: env.KeymailServers,
255 // A verified address Admit refuses gets the door, with the
256 // refusal on it, in auth's own 403 (app.refused) — not
257 // rastrillo's bare-text "verified but not admitted".
258 Refused: a.refused,
259 // GET /auth/verify spends nothing: it opens the door with one
260 // Sign in button that POSTs the link back, so a mail scanner's
261 // fetch cannot spend it (app.renderConfirm).
262 RenderConfirm: a.renderConfirm,
263 // No proof-of-work on the sign-in form. Memoria never had one:
264 // beginGuard refuses every non-owner before Begin (gate 33), and
265 // rastrillo's rate budgets stand behind it. The door is
266 // rastrillo's screen with no Proof configured, so it renders no
267 // pow challenge. ProofOff keeps today's
268 // behaviour; wiring a pow.Guard is a decision of its own
269 // (schema, assets, a form that needs JavaScript).
270 ProofOff: true,
271 // The smart door (Home spec 2026-11-19-smart-door.md, step 6):
272 // rastrillo's screen, one way in per page. Every outcome, chooser
273 // link and Forget lands on /signin, which with Home configured is
274 // connect's SigninDoor, offering Continue with Oficina ID
275 // (home/connect MIGRATING.md, item 3). The door's form posts to
276 // Begin where MountAuth mounts it.
277 SigninScreen: true,
278 SigninOneWay: true,
279 SigninPath: signinPath,
280 BeginPath: beginPath,
281 ForgetPath: signinForgetPath,
282 SignedInPath: landing,
283 Subject: chrome.EmailSubject("Memoria"),
284 Logger: logger,
285 })
286 if err != nil {
287 return nil, err
288 }
289 return au, nil
290}
291
292// signinBegin is POST /auth/begin's whole handler chain, in one place with
293// its own tests rather than composed inline in MountAuth.
294//
295// **The guard is what keeps a non-admitted address from being dialled**
296// (gate 33), and it runs before Begin. Outside it, beginSignin takes
297// return_to off the form, whatever the guard then decides, so an owner
298// and a stranger are answered alike there too (return.go).
299//
300// There is no Keymail continuation page here any more. With the smart
301// door's SigninScreen on, Begin answers a Keymail address with a 303 to
302// the door (/signin?continue=), whose meta refresh leaves for Keymail, so
303// CSP's form-action 'self' (which Safari enforces across a form
304// submission's whole redirect chain, 2026-09-29) is never asked to allow
305// another origin. connect's OAuthContinuation and its page are gone.
306func (a *app) signinBegin(origin string, begin http.HandlerFunc) http.HandlerFunc {
307 return a.beginSignin(a.beginGuard(origin, begin))
308}
309
310// badAddress is the guard's answer to a malformed address, in Begin's own
311// shape (rastrillo's problemURL): ?err=address, keeping a failed
312// Keymail's force=1 and a step-up's reauth=1. return_to is put back by
313// beginSignin, which took it off the form.
314func badAddress(r *http.Request) string {
315 q := url.Values{"err": {"address"}}
316 if r.PostFormValue("force") != "" {
317 q.Set("force", "1")
318 }
319 if r.PostFormValue("reauth") == "1" {
320 q.Set("reauth", "1")
321 }
322 return signinPath + "?" + q.Encode()
323}
324
325// plausibleAddress is the shape of an email address and nothing more:
326// something, an @, something, no spaces. The last @ splits it (a quoted
327// local part may hold one), and a dotless domain is still an address.
328func plausibleAddress(v string) bool {
329 v = strings.TrimSpace(v)
330 at := strings.LastIndexByte(v, '@')
331 return at > 0 && at < len(v)-1 && !strings.ContainsAny(v, " \t\r\n")
332}
333