oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Local sign-in is Keymail for an address whose domain runs Keymail and an
2// emailed single-use link for every other address, decided by the domain
3// alone (beginSignin). Optional Home sign-in resolves an explicitly
4// connected existing account; it never creates a person.
5package calendar
6
7import (
8 "amadan.net/oficina/estilo.git/chrome"
9 "amadan.net/oficina/home/connect"
10 "context"
11 "database/sql"
12 "fmt"
13 "log/slog"
14 "net/http"
15 "net/url"
16 "regexp"
17 "strings"
18 "sync"
19
20 rauth "amadan.net/rastrillo/rastrillo/auth"
21 "amadan.net/rastrillo/rastrillo/mail"
22)
23
24// authSchema aliases rauth.Schema so BootSchema (migrations.go) reads
25// as a list of subsystems rather than a mix of import aliases. Its
26// position there is load-bearing: auth's own backfill migration reads
27// the sessions table, so sessions.Schema must apply first.
28var authSchema = rauth.Schema
29
30// devInstanceKey is resolveInstanceKey's development-only fallback. It
31// is not a secret — it is a fixed, public string, exactly as dangerous
32// and exactly as acceptable as leaving the key empty would be, except
33// spelled out here rather than left implicit. It never seals anything
34// outside a throwaway development database.
35const devInstanceKey = "calendar-development-instance-key-not-a-secret"
36
37// resolveInstanceKey applies Config.InstanceKey's fail-closed rule:
38// non-empty always wins; empty is fine only in development; anywhere
39// else it is a startup refusal.
40func resolveInstanceKey(cfg Config) (string, error) {
41 key := strings.TrimSpace(cfg.InstanceKey)
42 if key != "" {
43 return key, nil
44 }
45 if cfg.Env == "development" {
46 return devInstanceKey, nil
47 }
48 return "", fmt.Errorf("calendar: Config.InstanceKey is empty and Env is %q, not %q — refusing to start with no seal for the sign-in link's pending blob; set $CALENDAR_INSTANCE_KEY", cfg.Env, "development")
49}
50
51// buildMailer applies Config.Mailer's fail-closed rule: an explicit
52// Mailer always wins; nil is fine only in development, where it falls
53// back to rastrillo/mail's logging sender.
54//
55// In development the chosen sender is always wrapped in a
56// *recordingMailer, whether or not Config.Mailer was already set: that
57// is what lets TestSignIn (testing.go) read the last mailed link back
58// without a mail server. The returned *recordingMailer is nil outside
59// development — it holds the plaintext of the last link sent in
60// memory, and a real deployment has no reason to carry that.
61func buildMailer(cfg Config, logger *slog.Logger) (mail.Sender, *recordingMailer, error) {
62 sender := cfg.Mailer
63 if sender == nil {
64 if cfg.Env != "development" {
65 // Both prefixes named, in the order main.go tries them:
66 // the platform's own CARLOS_SMTP_* is what `carlos email
67 // enable` writes, and naming only the app's prefix sent
68 // the first deploy of this app into a wake loop against
69 // an instance whose mail was configured correctly.
70 return nil, nil, fmt.Errorf("calendar: mail is not configured (CARLOS mail submission sets $CARLOS_MAIL=submit; otherwise set $CARLOS_SMTP_HOST and $CARLOS_SMTP_FROM with `carlos email enable`, or $CALENDAR_SMTP_HOST and $CALENDAR_SMTP_FROM to override) and Env is %q, not %q — refusing to start: a sign-in that cannot send its link is not sign-in, and a reminder that cannot be delivered is not a reminder", cfg.Env, "development")
71 }
72 sender = mail.Logged(logger)
73 }
74 if cfg.Env != "development" {
75 return sender, nil, nil
76 }
77 rec := &recordingMailer{next: sender}
78 return rec, rec, nil
79}
80
81// recordingMailer wraps a mail.Sender, remembering the most recently
82// sent body so TestSignIn can read the magic link back out of it. It
83// still forwards every Send, so the ordinary dev behaviour — the link
84// lands in the log, clearly marked — is unchanged; this only adds a
85// second, in-memory place to find it.
86type recordingMailer struct {
87 mu sync.Mutex
88 next mail.Sender
89 lastBody string
90}
91
92func (m *recordingMailer) Send(ctx context.Context, to, subject, body string) error {
93 m.mu.Lock()
94 m.lastBody = body
95 m.mu.Unlock()
96 return m.next.Send(ctx, to, subject, body)
97}
98
99func (m *recordingMailer) last() string {
100 m.mu.Lock()
101 defer m.mu.Unlock()
102 return m.lastBody
103}
104
105// magicLinkPattern finds the emailed link inside the sign-in mail body.
106// Anchored to this app's own callback path so it cannot mistake some
107// other URL the body might one day carry for the sign-in link itself.
108var magicLinkPattern = regexp.MustCompile(`https?://\S+/auth/verify\?token=\S+`)
109
110// normalizeAddress puts an address into the one form the allowlist
111// both stores and compares: trimmed, lowercased. Shared by
112// resolveAllowlist and allowlist.allows so the two can never drift
113// into comparing differently-normalised forms of the same address.
114func normalizeAddress(address string) string {
115 return strings.ToLower(strings.TrimSpace(address))
116}
117
118// allowlist is Config.AllowedAddresses, parsed and normalised.
119//
120// addrs == nil means "admit every address" — resolveAllowlist's
121// development-only default, spelled out rather than left as an
122// accidental nil. addrs != nil means "admit nothing but exactly this
123// set". resolveAllowlist returns a non-nil-but-empty map only in team
124// mode (admit nobody locally: the roster decides, and Home signs people
125// in), since an empty parse outside development is otherwise a startup
126// refusal.
127type allowlist struct {
128 addrs map[string]struct{}
129}
130
131func (a allowlist) allows(address string) bool {
132 if a.addrs == nil {
133 return true
134 }
135 _, ok := a.addrs[normalizeAddress(address)]
136 return ok
137}
138
139// resolveAllowlist applies Config.AllowedAddresses' fail-closed rule.
140//
141// Refusal, not "admit nobody" — a deliberate choice. An instance that
142// silently admitted nobody would boot looking entirely healthy:
143// /signin renders, POST /signin answers its ordinary 303 ?sent=1 on
144// every submission (gateBegin's whole point is that a refused
145// submission and a genuine one are byte-identical), and nothing would
146// surface the mistake short of somebody noticing that no link ever
147// arrives. A startup refusal is loud instead: the process does not
148// come up and whoever is deploying it sees that immediately. The
149// honest cost is that a misconfigured instance is down rather than
150// merely closed — accepted here because "down" gets fixed the same
151// day, while "quietly admits nobody" on a public hostname could sit
152// unnoticed indefinitely.
153func resolveAllowlist(cfg Config) (allowlist, error) {
154 addrs := make(map[string]struct{})
155 for _, addr := range strings.Split(cfg.AllowedAddresses, ",") {
156 addr = normalizeAddress(addr)
157 if addr == "" {
158 continue
159 }
160 // Every entry must look like an address, because the separator
161 // is the one thing nobody checks. Split on "," alone turns
162 // "a@x.com;b@y.com" — or a space- or newline-separated list —
163 // into ONE entry that is nobody's address, len(addrs) > 0, and
164 // a boot that succeeds into precisely the "quietly admits
165 // nobody" state the refusal below exists to prevent. The
166 // instance then looks entirely healthy and no link ever
167 // arrives, which is the failure this app has already had once.
168 //
169 // Refusing at boot rather than dropping the bad entry: dropping
170 // it would admit whoever parsed cleanly and silently lock out
171 // the rest, which is a worse shape of the same bug.
172 if !strings.Contains(addr, "@") {
173 return allowlist{}, fmt.Errorf(
174 "calendar: $CALENDAR_ALLOWED_ADDRESSES has an entry with no %q in it — the list is comma-separated, and a %q or a space is not a separator; refusing to start rather than admit nobody",
175 "@", ";")
176 }
177 addrs[addr] = struct{}{}
178 }
179 if len(addrs) > 0 {
180 return allowlist{addrs: addrs}, nil
181 }
182 if cfg.Team != nil {
183 // Team mode: the roster decides standing, and the list is only
184 // local sign-in's admission. Empty admits nobody locally, in
185 // every Env: a team instance never takes the development
186 // default that admits everyone.
187 return allowlist{addrs: addrs}, nil
188 }
189 if cfg.Env == "development" {
190 return allowlist{}, nil // addrs stays nil: admit everyone
191 }
192 return allowlist{}, fmt.Errorf("calendar: $CALENDAR_ALLOWED_ADDRESSES is empty and Env is %q, not %q — refusing to start with no allowlist configured; set it to this instance's address(es)", cfg.Env, "development")
193}
194
195// newAuthPlugin builds the one *rauth.Auth this process shares. One per
196// process, never one per request: the underlying flow carries its
197// rate-limiter budget on the value, so a plugin per request would get a
198// fresh empty budget every time — no rate limiting at all, silently.
199//
200// Authorize is list.allows as well as mailQueue. The two defend
201// different things: mailQueue stops the mail going out, Authorize
202// stops a session being minted for a non-permitted address, whether
203// Keymail verified it or a link was somehow minted for it (mailed
204// before the allowlist changed, say).
205//
206// door supplies the two pages auth asks the app for: the door a verified
207// but refused address is shown (App.refused) and the door an emailed link
208// opens on (App.renderConfirm).
209func newAuthPlugin(origin string, writer *sql.DB, instanceKey string, mailer mail.Sender, list allowlist, logger *slog.Logger, homeEnabled bool, door authPages) (*rauth.Auth, error) {
210 signedIn := "/"
211 if homeEnabled {
212 signedIn = connect.LocalCompletePath
213 }
214 return rauth.New(rauth.Config{
215 DB: writer,
216 // The smart door (Home spec 2026-11-19-smart-door.md): rastrillo's
217 // screen, one way in per page. Every outcome, chooser link and
218 // Forget lands on /signin, which with Home configured is connect's
219 // SigninDoor, offering Continue with Oficina ID (home/connect
220 // MIGRATING.md, step 6). It was /signin/local with Home on, which
221 // would send every outcome to the email-only door.
222 SigninScreen: true,
223 SigninOneWay: true,
224 SigninPath: connect.SigninPath,
225 ForgetPath: signinForgetPath,
226 SignedInPath: signedIn,
227 Origin: origin,
228 InstanceKey: instanceKey,
229 Mailer: mailer,
230 Authorize: list.allows,
231 // A verified address the allowlist does not hold gets the door,
232 // with the refusal on it, in auth's own 403 (App.refused).
233 Refused: door.refused,
234 // GET /auth/verify spends nothing: it opens the door with one
235 // Sign in button that POSTs the link back, so a mail scanner's
236 // fetch cannot spend it (App.renderConfirm).
237 RenderConfirm: door.confirm,
238 // No proof-of-work on the sign-in form. Calendar never had one:
239 // Begin's rate budgets and mailQueue's allowlist check are what
240 // stand between a stranger and the mailer. ProofOff keeps
241 // today's behaviour; wiring a pow.Guard is a decision of its own
242 // (schema, assets, a form that needs JavaScript).
243 ProofOff: true,
244 Subject: chrome.EmailSubject("Calendar"),
245 // nil in every deployment: rastrillo's default, any server an
246 // address's own _keymail delegation names, dialed only at a
247 // public address. Only tests list servers (keymailTestServers).
248 KeymailServers: keymailTestServers,
249 Logger: logger,
250 })
251}
252
253// keymailTestServers is rauth.Config.KeymailServers, and nil outside
254// tests. From rastrillo v0.45.0 an unlisted Keymail server is dialed only
255// at a public address, by a client cloned from http.DefaultTransport;
256// the tests' in-process Keymail fixtures (keymailtest) answer behind a
257// wrapped DefaultTransport at a name nothing resolves, so the test mains
258// list their host (SetKeymailServersForTest) and auth reaches them
259// through its listed-servers guard instead.
260var keymailTestServers []string
261
262// authPages are the two pages auth asks the app for (newAuthPlugin).
263type authPages struct {
264 refused func(http.ResponseWriter, *http.Request, rauth.Identity)
265 confirm func(http.ResponseWriter, *http.Request, rauth.ConfirmPageData)
266}
267
268// linkPath extracts the request-target — path plus query, no scheme or
269// host — from an emailed magic link. It exists so the test harness does
270// not have to know the emailed link is absolute.
271func linkPath(link string) (string, error) {
272 u, err := url.Parse(link)
273 if err != nil {
274 return "", fmt.Errorf("calendar: parse magic link %q: %w", link, err)
275 }
276 return u.RequestURI(), nil
277}
278