oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "database/sql"
5 "errors"
6 "log/slog"
7 "net/http"
8 "strings"
9
10 "amadan.net/oficina/estilo.git/chrome"
11 "amadan.net/rastrillo/rastrillo/auth"
12 "amadan.net/rastrillo/rastrillo/mail"
13 "github.com/keymaildev/signin"
14)
15
16// signinPath is where every sign-in outcome lands: the door. It is the
17// SigninPath given to auth.New, so rastrillo's outcomes and the guard's
18// AnswerAsSent land in the same place.
19const signinPath = "/signin"
20
21// beginPath is where Begin is mounted (app.go), behind beginGuard.
22const beginPath = "/auth/begin"
23
24// ParseOwners splits a comma-separated allowlist, lowercasing and
25// trimming.
26//
27// In the LONE shape this list is the whole admitted set. In the SUITE
28// shape (ruling 5) the home's roster is, and this list answers the
29// narrower question of who operates the instance — memoria §2 is careful
30// that those are two different things and that conflating them is how a
31// roster gets invented in the wrong app.
32func ParseOwners(raw string) []string {
33 var out []string
34 for _, part := range strings.Split(raw, ",") {
35 if addr := normaliseAddress(part); addr != "" {
36 out = append(out, addr)
37 }
38 }
39 return out
40}
41
42// normaliseAddress is the one spelling rule, and everything that compares
43// an address goes through it. A guard that spells an address differently
44// from the thing it guards is not guarding it.
45//
46// Addresses are case-sensitive before the @ per RFC 5321 and no mainstream
47// provider honours that, so this matches what an operator expects when
48// they type a list.
49func normaliseAddress(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
50
51// Admit is THE admission predicate: the one rastrillo runs at
52// verification, the one beginGuard runs before the classifier dials, and
53// the one requireSession runs per request.
54//
55// A method rather than a constructor over a list, because a constructor
56// gives a caller something to build twice — and in memoria it WAS built
57// twice, two closures over two copies guarding one rule, with a mutation
58// that stayed green because every test built its own.
59func (a *app) Admit(address string) bool {
60 addr := normaliseAddress(address)
61 if addr == "" {
62 return false
63 }
64 for _, o := range a.owners {
65 if o == addr {
66 return true
67 }
68 }
69 return false
70}
71
72// beginGuard stops an anonymous visitor making this instance dial a domain
73// of their choosing.
74//
75// rastrillo's sign-in classifier fetches
76// https://<the submitted address's domain>/.well-known/keymail inside
77// auth.Begin, BEFORE the Authorize callback runs. So POST /auth/begin with
78// any address makes fichas issue an outbound request to any host, leaking
79// the instance's existence, its egress address and a timing channel to
80// anyone who can reach the sign-in page. memoria §3.2 carries the same
81// entry and `SECURITY-DRAFT-rastrillo-signin.md` is the upstream half,
82// still unfiled.
83//
84// It answers a stranger with rastrillo's AnswerAsSent: Begin's own Sent,
85// down to the attempt cookie and the attempt= on the redirect, with no
86// mail. A plain ?sent=1 would lack both where an owner gets them, which
87// would turn this guard into an owners-list oracle on the first try
88// (Memoria #49) — worse than the dial: the dial confirms the instance
89// exists, an oracle confirms who runs it. It is not error hiding: it
90// answers before Begin, and Begin's own problems (a mistyped address, a
91// rate limit) reach the door as they are, for any address that gets that
92// far.
93//
94// **It is still an oracle after five submissions**, and memoria records
95// why: this guard sits in front of rastrillo's per-address rate limiter,
96// so a refused address never consumes budget while an admitted one does.
97// Six tries at an owner's address yields a rate-limit error, six at a
98// stranger's yields the same cheerful page every time. Closing that means
99// fixing the ordering upstream, which is the same fix the dial needs.
100// Response time is the other residual: AnswerAsSent sends no mail.
101func (a *app) beginGuard(next http.HandlerFunc) http.HandlerFunc {
102 return func(w http.ResponseWriter, r *http.Request) {
103 if a.auth == nil {
104 a.logger.Error("no sign-in configured")
105 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
106 return
107 }
108 // Fail closed. An empty owners list is a wiring bug — LoadConfig
109 // refuses to boot without one — and the version of this that
110 // defaults to allowing is the version that dials for everyone
111 // while looking configured.
112 if len(a.owners) == 0 {
113 a.logger.Error("no owners configured; refusing sign-in")
114 a.auth.AnswerAsSent(w, r)
115 return
116 }
117 // A malformed address is Begin's to answer, as for anybody: it
118 // refuses it (?err=address, keeping force, reauth and return_to)
119 // before the classifier can dial, and an address's shape says
120 // nothing about the owners list. Answered as Sent, a typo would
121 // hide behind "check your email" (no sameAnswer: Slides #49).
122 if _, _, err := signin.SplitAddress(r.FormValue("address")); err != nil {
123 next(w, r)
124 return
125 }
126 // Read the address EXACTLY as rastrillo does: FormValue, not
127 // PostFormValue, and no ParseForm error branch. memoria's first
128 // version got both wrong in one line — ParseForm reports a
129 // query-string error even when the body parsed, while rastrillo's
130 // FormValue ignores it, so `POST /auth/begin?a;b=1` skipped the
131 // check and dialled.
132 if !a.Admit(r.FormValue("address")) {
133 // No address in the log line, ever.
134 a.logger.Info("sign-in refused before classifier dial")
135 a.auth.AnswerAsSent(w, r)
136 return
137 }
138 next(w, r)
139 }
140}
141
142// AuthEnv is the sign-in configuration read from platform config.
143type AuthEnv struct {
144 Origin string
145 // InstanceKey seals auth's pending blob. auth.New refuses an empty
146 // one, and rightly: an empty input hashes to a fixed, publicly
147 // computable value identical across every deployment.
148 InstanceKey string
149 Mailer mail.Sender
150 // KeymailServers is auth.Config's: nil, as main.go and AppForTest
151 // leave it, is any server an address's own _keymail delegation
152 // names, which rastrillo (v0.45) dials at public addresses only. The
153 // Keymail door tests name their fake's hosts here, the one way a
154 // test's transport is still the one a probe goes through.
155 KeymailServers []string
156}
157
158// Gate is what the sign-in flow needs from the app: the admission
159// predicate, and the door it draws for the two pages auth renders itself
160// (the confirm step an emailed link opens, and the refusal). Only the
161// app implements it; main passes the *app App returned.
162type Gate interface {
163 Admit(address string) bool
164 renderConfirm(w http.ResponseWriter, r *http.Request, d auth.ConfirmPageData)
165 refused(w http.ResponseWriter, r *http.Request, id auth.Identity)
166}
167
168// NewAuth wires the sign-in flow. Exactly one per process: auth carries
169// rate-limiter state on the value, so one per request would get a fresh
170// empty budget every time and rate-limit nothing, silently.
171//
172// The door is rastrillo's sign-in screen, one way in per page
173// (SigninScreen, SigninOneWay), drawn inside estilo's door (signin.go;
174// Home spec 2026-11-19-smart-door.md, step 6). Fichas has no Home, so the
175// one way is email: "Continue as {address}" for a remembered one, else
176// the field, with "Use a different email" under it.
177func NewAuth(sqlDB *sql.DB, env AuthEnv, logger *slog.Logger, gate Gate) (*auth.Auth, error) {
178 if gate == nil {
179 // A nil Authorize admits every verified address, which on a
180 // public hostname means anyone who can receive mail. Refusing
181 // beats defaulting: a caller that forgot to pass one has a bug
182 // either way, and this is the version that says so.
183 return nil, errors.New("sign-in: refusing to wire auth with no admission gate")
184 }
185 return auth.New(auth.Config{
186 DB: sqlDB,
187 Origin: env.Origin,
188 InstanceKey: env.InstanceKey,
189 Mailer: env.Mailer,
190 Authorize: gate.Admit,
191 SigninPath: signinPath,
192 SignedInPath: "/",
193 Subject: chrome.EmailSubject("Fichas"),
194 Logger: logger,
195 KeymailServers: env.KeymailServers,
196 // No proof-of-work front door on POST /signin, as in Docs: the
197 // abuse controls are rastrillo's per-address and per-IP rate
198 // limits and the owners list, which never mails an address it
199 // does not hold. rastrillo refuses to start until this is chosen.
200 ProofOff: true,
201 // The smart door: rastrillo's screen, one way in per page. It
202 // remembers the way in (a sealed, host-only cookie), keeps the
203 // Keymail continuation on the door (?continue=), and posts to
204 // these two paths (app.go).
205 SigninScreen: true,
206 SigninOneWay: true,
207 BeginPath: beginPath,
208 ForgetPath: signinForgetPath,
209 // The emailed link opens the door's confirm step, with one Sign in
210 // button, and only its POST spends the token (signin.go).
211 RenderConfirm: gate.renderConfirm,
212 // A verified address the owners list refuses gets the door with
213 // the refusal, not rastrillo's bare-text 403.
214 Refused: gate.refused,
215 })
216}
217
218// identity is the signed-in address, or false.
219func (a *app) identity(r *http.Request) (string, bool) {
220 if a.testIdentity != "" {
221 return a.testIdentity, true
222 }
223 id, ok := auth.From(r)
224 if !ok {
225 return "", false
226 }
227 return normaliseAddress(id.Address), true
228}
229
230// requireSession guards every route that is not sign-in itself, and it
231// FAILS CLOSED.
232//
233// memoria's version once fell through when auth was nil so tests could
234// reach routes without a mailer, and the safety argument rested on a test
235// that did not exist — the name had survived a rename and lived on only in
236// comments. Deleting the wiring compiled, left the suite green, and served
237// every route unauthenticated. There is no fall-through here: a test that
238// wants a signed-in app says so by name.
239func (a *app) requireSession(next http.Handler) http.Handler {
240 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
241 if a.allowUnauthenticated {
242 next.ServeHTTP(w, r)
243 return
244 }
245 if a.auth == nil {
246 a.logger.Error("no sign-in configured; refusing every request")
247 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
248 return
249 }
250 guarded := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
251 address, ok := a.identity(r)
252 if !ok || !a.Admit(address) {
253 // 404, not 403: a route you may not use is a route that
254 // is not there.
255 notFound(w, r)
256 return
257 }
258 next.ServeHTTP(w, r)
259 })
260 a.auth.RequireSession(guarded).ServeHTTP(w, r)
261 })
262}
263