| 1 | // Instance-local sign-in uses Keymail OAuth when detected and email otherwise. |
| 2 | // Credentials remain at Keymail; Docs never enrolls a per-instance passkey. |
| 3 | package docs |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "database/sql" |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "regexp" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | |
| 16 | "amadan.net/oficina/estilo.git/brand" |
| 17 | "amadan.net/oficina/estilo.git/chrome" |
| 18 | "amadan.net/oficina/estilo.git/sky" |
| 19 | "amadan.net/oficina/home/connect" |
| 20 | rauth "amadan.net/rastrillo/rastrillo/auth" |
| 21 | "amadan.net/rastrillo/rastrillo/lastsignin" |
| 22 | "amadan.net/rastrillo/rastrillo/mail" |
| 23 | "amadan.net/rastrillo/rastrillo/sessions" |
| 24 | |
| 25 | "amadan.net/rastrillo/rastrillo" |
| 26 | ) |
| 27 | |
| 28 | // authSchema aliases rauth.Schema — auth's own migrations, merged into |
| 29 | // BootSchema (app.go) ahead of this app's own Schema and after |
| 30 | // sessions.Schema, per rauth's own doc comment: its backfill migration |
| 31 | // reads the sessions table, so sessions.Schema must apply first. |
| 32 | var authSchema = rauth.Schema |
| 33 | |
| 34 | // devInstanceKey is resolveInstanceKey's fallback, used only when Env |
| 35 | // is "development" and Config.InstanceKey is empty (NewForTest's |
| 36 | // case). It is not a secret: it is a fixed, public string, exactly as |
| 37 | // dangerous — and exactly as acceptable — as rastrillo/auth's own |
| 38 | // empty-key value would be, except spelled out here instead of left |
| 39 | // implicit, and it never seals anything outside a throwaway |
| 40 | // development database. resolveInstanceKey refuses to fall back to it |
| 41 | // for any other Env. |
| 42 | const devInstanceKey = "docs-development-instance-key-not-a-secret" |
| 43 | |
| 44 | // resolveInstanceKey applies Config.InstanceKey's own fail-closed |
| 45 | // rule (see its doc comment on Config): non-empty always wins; empty |
| 46 | // is fine only in development, where it defaults to devInstanceKey; |
| 47 | // anywhere else it is a startup refusal, the same shape New already |
| 48 | // uses for Origin. |
| 49 | func resolveInstanceKey(cfg Config) (string, error) { |
| 50 | key := strings.TrimSpace(cfg.InstanceKey) |
| 51 | if key != "" { |
| 52 | return key, nil |
| 53 | } |
| 54 | if cfg.Env == "development" { |
| 55 | return devInstanceKey, nil |
| 56 | } |
| 57 | return "", fmt.Errorf("docs: 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 $DOCS_INSTANCE_KEY", cfg.Env, "development") |
| 58 | } |
| 59 | |
| 60 | // buildMailer applies Config.Mailer's fail-closed rule (see its own |
| 61 | // doc comment): an explicit Mailer always wins; nil is fine only in |
| 62 | // development, where it falls back to rastrillo/mail's logging |
| 63 | // sender; anywhere else nil is a startup refusal — a sign-in that |
| 64 | // cannot send its link is not sign-in, so this is the same fail-closed |
| 65 | // shape New already uses for Origin, not merely a warning. |
| 66 | // |
| 67 | // In development the chosen sender is always wrapped in a |
| 68 | // *recordingMailer, whether or not Config.Mailer was already set: |
| 69 | // that is what lets TestSignIn (testing.go) read back the last |
| 70 | // mailed link without a real mail server, keeping |
| 71 | // scripts/run-dev.sh a one-command affair. The returned |
| 72 | // *recordingMailer is nil outside development — nothing there needs |
| 73 | // it, and it holds the plaintext of the last link sent in memory, |
| 74 | // which a real deployment has no reason to carry. |
| 75 | func buildMailer(cfg Config, logger *slog.Logger) (mail.Sender, *recordingMailer, error) { |
| 76 | sender := cfg.Mailer |
| 77 | if sender == nil { |
| 78 | if cfg.Env != "development" { |
| 79 | return nil, nil, fmt.Errorf("docs: mail is not configured (CARLOS mail submission sets $CARLOS_MAIL=submit; otherwise set $DOCS_SMTP_HOST and $DOCS_SMTP_FROM) and Env is %q, not %q — refusing to start: a sign-in that cannot send its link is not sign-in", cfg.Env, "development") |
| 80 | } |
| 81 | // Loudly labelled by mail.Logged itself on every send — see |
| 82 | // its own doc comment; this is the dev/test-only fallback, |
| 83 | // never reached outside Env == "development". |
| 84 | sender = mail.Logged(logger) |
| 85 | } |
| 86 | if cfg.Env != "development" { |
| 87 | return sender, nil, nil |
| 88 | } |
| 89 | rec := &recordingMailer{next: sender} |
| 90 | return rec, rec, nil |
| 91 | } |
| 92 | |
| 93 | // recordingMailer wraps a mail.Sender, remembering the most recently |
| 94 | // sent message's body so TestSignIn (testing.go) can read the magic |
| 95 | // link back out of it — the development/test convenience buildMailer |
| 96 | // installs, never wired outside Env == "development". It still |
| 97 | // forwards every Send to the wrapped sender, so the ordinary |
| 98 | // dev-mode behavior (the link lands in the log, clearly marked) is |
| 99 | // unchanged; this only adds a second, in-memory place to find it. |
| 100 | type recordingMailer struct { |
| 101 | mu sync.Mutex |
| 102 | next mail.Sender |
| 103 | // lastTo is recorded alongside lastBody, and it is not decoration. |
| 104 | // The mail queue leaves a refused address with exactly the 303 ?sent=1 a |
| 105 | // real one gets — deliberately, so the endpoint is not a membership |
| 106 | // oracle — so a caller that reads only lastBody cannot tell "a link |
| 107 | // was mailed to this address" from "somebody else's link is still |
| 108 | // sitting here". TestSignIn used to make that mistake and reported |
| 109 | // success for an address the allowlist had refused. |
| 110 | lastTo string |
| 111 | lastBody string |
| 112 | // sends counts mails, and it is the field that makes the recipient |
| 113 | // check above actually work. Comparing only lastTo answers "was the |
| 114 | // most recent mail addressed here", which stays true for every later |
| 115 | // REFUSAL of the same address — the recorder simply keeps the earlier |
| 116 | // success. A caller has to know a NEW mail was sent, not that an old |
| 117 | // one is still lying there. |
| 118 | sends int |
| 119 | } |
| 120 | |
| 121 | func (m *recordingMailer) Send(ctx context.Context, to, subject, body string) error { |
| 122 | m.mu.Lock() |
| 123 | m.lastTo, m.lastBody, m.sends = to, body, m.sends+1 |
| 124 | m.mu.Unlock() |
| 125 | return m.next.Send(ctx, to, subject, body) |
| 126 | } |
| 127 | |
| 128 | // magicLinkPattern finds the emailed link inside signin's default mail |
| 129 | // body ("Open this link to sign in:\n\n<link>\n\n..." — |
| 130 | // keymaildev/signin's flow.go). Anchored to the app's own callback |
| 131 | // path so it cannot mistake some other URL the body might someday |
| 132 | // carry for the sign-in link itself. |
| 133 | var magicLinkPattern = regexp.MustCompile(`https?://\S+/auth/verify\?token=\S+`) |
| 134 | |
| 135 | // normalizeAddress puts address into the one form allowlist compares |
| 136 | // and stores: trimmed of surrounding whitespace, lowercased. Shared |
| 137 | // by resolveAllowlist (building the set) and allowlist.allows |
| 138 | // (checking against it) so the two can never drift into comparing |
| 139 | // differently-normalized forms of the same address. |
| 140 | func normalizeAddress(address string) string { |
| 141 | return strings.ToLower(strings.TrimSpace(address)) |
| 142 | } |
| 143 | |
| 144 | // allowlist is Config.AllowedAddresses ($DOCS_ALLOWED_ADDRESSES), |
| 145 | // parsed and normalized — see that field's own doc comment on Config |
| 146 | // for what it gates and why it is wired into two different places. |
| 147 | // |
| 148 | // addrs == nil means "admit every address" — resolveAllowlist's |
| 149 | // development-only default (the same shape devInstanceKey uses for |
| 150 | // InstanceKey: spelled out here rather than left as an accidental |
| 151 | // nil, and refused everywhere else). addrs != nil means "admit |
| 152 | // nothing but exactly this set"; resolveAllowlist never returns a |
| 153 | // non-nil-but-empty map outside development, since an empty parse |
| 154 | // there is a startup refusal, not a value this type carries. |
| 155 | type allowlist struct { |
| 156 | addrs map[string]struct{} |
| 157 | |
| 158 | // granted widens admission to anybody holding a grant on a document |
| 159 | // here, and is nil when nothing has wired the store in (every test of |
| 160 | // the allowlist alone, and any construction before the store exists). |
| 161 | // |
| 162 | // It exists because $DOCS_ALLOWED_ADDRESSES gates who may receive a |
| 163 | // magic link at all, and suppressed delivery answers identically for |
| 164 | // a refused address so this endpoint is not a membership oracle. |
| 165 | // Without this clause, sharing a document to somebody outside the list |
| 166 | // produces a grant that can never be redeemed: the sharer sees success, |
| 167 | // the recipient gets a link that silently does nothing, and neither is |
| 168 | // told why. That is the worst available failure shape, because it looks |
| 169 | // like it worked. |
| 170 | // |
| 171 | // Deliberately one clause in allows(). Sharing widening who may sign in |
| 172 | // is a real decision about this instance's front door, and reversing it |
| 173 | // should be deleting two lines rather than unpicking a design. |
| 174 | granted func(address string) (bool, error) |
| 175 | } |
| 176 | |
| 177 | // configured reports whether address is a MEMBER of this instance — on |
| 178 | // $DOCS_ALLOWED_ADDRESSES, rather than admitted by a grant. |
| 179 | // |
| 180 | // The distinction the branch review found missing (finding 1). Suite §1 |
| 181 | // ruling 1 and Docs §8.2 both say an outside guest is a *guest* member; |
| 182 | // the branch had no guest kind, so a grant was a full membership and |
| 183 | // admission became transitive — Alice grants Bob, Bob creates and grants |
| 184 | // Mallory, and the operator's allowlist has quietly stopped being the |
| 185 | // membership list. |
| 186 | // |
| 187 | // A guest reads and writes what they were granted. Creating documents and |
| 188 | // changing who reaches one are member powers, and this is the predicate |
| 189 | // that says so. |
| 190 | // |
| 191 | // addrs == nil (development's admit-everyone) makes everybody a member, |
| 192 | // which is the same latitude allows() already gives and the same reason: |
| 193 | // a dev instance with no configuration should not need a membership list |
| 194 | // to be usable. |
| 195 | func (a allowlist) configured(address string) bool { |
| 196 | if a.addrs == nil { |
| 197 | return true |
| 198 | } |
| 199 | _, ok := a.addrs[normalizeAddress(address)] |
| 200 | return ok |
| 201 | } |
| 202 | |
| 203 | // allows reports whether address may sign in, and whether the question |
| 204 | // could be answered at all. |
| 205 | // |
| 206 | // The error is separate from the answer because the two demand different |
| 207 | // responses on a live request: a definite "no" ejects, an unanswerable |
| 208 | // question must not. See requireAdmission. |
| 209 | func (a allowlist) allows(address string) (bool, error) { |
| 210 | if a.addrs == nil { |
| 211 | return true, nil |
| 212 | } |
| 213 | normalized := normalizeAddress(address) |
| 214 | if _, ok := a.addrs[normalized]; ok { |
| 215 | return true, nil |
| 216 | } |
| 217 | // A grant admits its holder, and nobody else — as a guest, not as a |
| 218 | // member: see configured() above for the powers that stay behind the |
| 219 | // configured list, and requireAdmission for why this is now re-asked on |
| 220 | // every request rather than only at sign-in. |
| 221 | if a.granted == nil { |
| 222 | return false, nil |
| 223 | } |
| 224 | return a.granted(normalized) |
| 225 | } |
| 226 | |
| 227 | // admits is allows for callers that take a plain predicate — rauth's own |
| 228 | // Authorize hook, which has no way to say "could not tell". |
| 229 | // |
| 230 | // A failed check refuses, which is the right direction at sign-in: there |
| 231 | // is no unsaved work to lose, and a person who is genuinely admitted can |
| 232 | // try again. requireAdmission is the caller that must NOT do this, and it |
| 233 | // uses allows directly for exactly that reason. |
| 234 | func (a allowlist) admits(address string) bool { |
| 235 | ok, err := a.allows(address) |
| 236 | return err == nil && ok |
| 237 | } |
| 238 | |
| 239 | // resolveAllowlist applies Config.AllowedAddresses' own fail-closed |
| 240 | // rule (see its doc comment on Config): a non-empty, comma-separated |
| 241 | // list always wins, parsed and normalized; an empty one is fine only |
| 242 | // in development, where it defaults to "admit everyone" so TestSignIn |
| 243 | // and scripts/run-dev.sh need no setup of their own; anywhere else it |
| 244 | // is a startup refusal. |
| 245 | // |
| 246 | // Refusal, not "admit nobody" — a real choice, made deliberately, not |
| 247 | // the shape everything else in this file happens to use. An instance |
| 248 | // that silently admitted nobody would boot looking entirely healthy: |
| 249 | // /signin renders and email submissions answer 303 ?sent=1 whether |
| 250 | // delivery was permitted or suppressed. Nothing would |
| 251 | // ever surface the mistake short of a person noticing that no sign-in |
| 252 | // link ever arrives — on an app whose entire premise is one |
| 253 | // instance, one team, where "nobody configured" is exactly the state |
| 254 | // a fresh, not-yet-configured deployment starts in. A startup refusal |
| 255 | // is loud: the process does not come up, whoever is deploying it sees |
| 256 | // that immediately, and cannot ship it half-configured by accident. |
| 257 | // The honest cost is that a misconfigured instance is down rather |
| 258 | // than merely closed — weighed and accepted here because "down" gets |
| 259 | // fixed the same day, while "quietly admits nobody" on a public |
| 260 | // hostname could sit unnoticed indefinitely. This is the same |
| 261 | // tradeoff Origin, InstanceKey and Mailer already make in this file |
| 262 | // and app.go: a misconfigured instance refuses to start, never |
| 263 | // quietly does the wrong thing. |
| 264 | func resolveAllowlist(cfg Config) (allowlist, error) { |
| 265 | addrs := make(map[string]struct{}) |
| 266 | for _, addr := range strings.Split(cfg.AllowedAddresses, ",") { |
| 267 | addr = normalizeAddress(addr) |
| 268 | if addr == "" { |
| 269 | continue |
| 270 | } |
| 271 | addrs[addr] = struct{}{} |
| 272 | } |
| 273 | if len(addrs) > 0 || cfg.Team != nil { |
| 274 | return allowlist{addrs: addrs}, nil |
| 275 | } |
| 276 | if cfg.Env == "development" { |
| 277 | return allowlist{}, nil // addrs stays nil: admit everyone |
| 278 | } |
| 279 | return allowlist{}, fmt.Errorf("docs: $DOCS_ALLOWED_ADDRESSES is empty and Env is %q, not %q — refusing to start with no allowlist configured: an instance-per-team app admitting nobody would look identical to one working correctly (see resolveAllowlist's own doc comment), so this refuses rather than boots quietly wrong; set $DOCS_ALLOWED_ADDRESSES to this team's address(es)", cfg.Env, "development") |
| 280 | } |
| 281 | |
| 282 | // listAdmits is the sign-in mail queue's admission check (mailqueue.go): |
| 283 | // list.allows, with a failed grant lookup refusing, as a refusal always |
| 284 | // has here. It runs on the queue's worker, after the response: every |
| 285 | // address reaches classification, the same rate limits and the same |
| 286 | // enqueue, so neither POST /signin's answer nor its timing says who is |
| 287 | // admitted (Astra on oficina/slides #20: a send inside the request made |
| 288 | // a permitted address wait for SMTP, 252 ms against 0.35 ms). Callback |
| 289 | // admission remains authoritative, including for tokens minted before |
| 290 | // an address was removed; a token never delivered is never redeemed. |
| 291 | func listAdmits(list allowlist) func(string) bool { |
| 292 | return func(to string) bool { |
| 293 | admitted, err := list.allows(to) |
| 294 | return err == nil && admitted |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // requireAdmission re-asks the front-door question on every request, and |
| 299 | // answers a person who no longer passes it by ending them at /signin. |
| 300 | // |
| 301 | // It exists because allows() used to run only at sign-in. A session lasts |
| 302 | // 30 days (rastrillo/auth.DefaultSessionTTL), so revoking somebody's last |
| 303 | // grant took their document away and left them a working session for a |
| 304 | // month — during which, before the guest rule above, they went on creating |
| 305 | // documents and granting them to other people. "Stop sharing" was complete |
| 306 | // for the document and silent about the instance. (Branch review, finding |
| 307 | // 3.) |
| 308 | // |
| 309 | // Cheap for members: allows() checks the configured set first and returns |
| 310 | // before touching the database. Only a guest pays a query, and a guest is |
| 311 | // exactly who the answer can have changed for. |
| 312 | // |
| 313 | // It sits after RequireSession so it can rely on there being an identity; |
| 314 | // with no identity it does nothing and lets RequireSession's own redirect |
| 315 | // stand. |
| 316 | func requireAdmission(list allowlist, signinPath string) func(http.Handler) http.Handler { |
| 317 | admission := requireAdmissionOf(list, signinPath, func(r *http.Request) (string, bool) { |
| 318 | if id, ok := currentIdentity(r); ok { |
| 319 | if id.Actor.VerifiedAddress == nil { |
| 320 | return "", false |
| 321 | } |
| 322 | return *id.Actor.VerifiedAddress, true |
| 323 | } |
| 324 | s, ok := sessions.Current(r) |
| 325 | return s.Subject, ok && !connect.IsHomeDerived(s.Method) |
| 326 | }) |
| 327 | return func(next http.Handler) http.Handler { |
| 328 | allowed := admission(next) |
| 329 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 330 | // Missing adapter wiring fails closed even if an opaque subject happens |
| 331 | // to match an allowed address. It must not take the legacy fallback. |
| 332 | if s, ok := sessions.Current(r); ok && connect.IsHomeDerived(s.Method) { |
| 333 | if _, resolved := currentIdentity(r); !resolved { |
| 334 | refuseIdentity(w, r, signinPath, false) |
| 335 | return |
| 336 | } |
| 337 | } |
| 338 | allowed.ServeHTTP(w, r) |
| 339 | }) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | // requireAdmissionOf is requireAdmission with the identity lookup passed |
| 344 | // in, which is the only way this middleware can be tested at all: rauth |
| 345 | // stores the identity under an unexported context key, so a test cannot |
| 346 | // build a request that carries one. |
| 347 | // |
| 348 | // The seam is here rather than the test reaching through HTTP because an |
| 349 | // end-to-end version of the "database is down" case never reaches this |
| 350 | // code — rastrillo's own session layer refuses first, and the test would |
| 351 | // have asserted on its 403 while proving nothing about this middleware. |
| 352 | // That is the failure mode this branch has now produced four times. |
| 353 | func requireAdmissionOf(list allowlist, signinPath string, identity func(*http.Request) (string, bool)) func(http.Handler) http.Handler { |
| 354 | return func(next http.Handler) http.Handler { |
| 355 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 356 | address, ok := identity(r) |
| 357 | if !ok { |
| 358 | next.ServeHTTP(w, r) |
| 359 | return |
| 360 | } |
| 361 | admitted, err := list.allows(address) |
| 362 | if err != nil { |
| 363 | // The question could not be answered, which is not the |
| 364 | // same as "no". 503 rather than 403: save-queue.mjs |
| 365 | // retries a 5xx and permanently drops a 4xx, so folding a |
| 366 | // database stall into a refusal would cost a guest their |
| 367 | // paragraph. Retryable, and honest. |
| 368 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 369 | return |
| 370 | } |
| 371 | if admitted { |
| 372 | next.ServeHTTP(w, r) |
| 373 | return |
| 374 | } |
| 375 | |
| 376 | // A redirect answers "show me a page". It is never an answer |
| 377 | // to "store this". |
| 378 | // |
| 379 | // The first version of this middleware 303'd every method, |
| 380 | // which was the worst defect on this branch and was introduced |
| 381 | // by the fix for the previous one. fetch() follows redirects by |
| 382 | // default, so the editor's POST became a GET of the sign-in |
| 383 | // page, came back 200 with HTML, and save-queue.mjs read res.ok |
| 384 | // and reported the batch saved. A revoked writer typed into a |
| 385 | // page that told them everything was fine — strictly worse than |
| 386 | // the reader-editor bug, which at least lit "save failed". |
| 387 | // |
| 388 | // rastrillo's own refuseSession draws the line in exactly this |
| 389 | // place and for exactly this reason. (Re-review, finding 1.) |
| 390 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 391 | http.Redirect(w, r, signinPath, http.StatusSeeOther) |
| 392 | return |
| 393 | } |
| 394 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusForbidden) |
| 395 | }) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | // newAuthPlugin wires rastrillo/auth per its SKILL.md contract: one |
| 400 | // *Auth built at boot (New — SKILL.md's own warning against building |
| 401 | // a Flow per request, since the rate limiter's budget lives on the |
| 402 | // value), Origin as both the emailed link's base and the cookie |
| 403 | // decision, InstanceKey and Mailer already resolved and fail-closed |
| 404 | // by resolveInstanceKey/buildMailer above. Authorize is list.admits — |
| 405 | // the fail-closed predicate form, because rauth's hook has no way to |
| 406 | // say "could not tell" and refusing is the safe answer here. |
| 407 | // Delivery and callback admission are checked independently. No local passkey |
| 408 | // second factor is enrolled; Keymail verifies credentials at its own origin. |
| 409 | // |
| 410 | // door draws the two pages rastrillo hands back to the app: Refused, a |
| 411 | // verified address the allowlist does not hold, and RenderConfirm, the |
| 412 | // page an emailed link opens (GET /auth/verify), whose one Sign in button |
| 413 | // POSTs the token back to spend it. Both are the sign-in door. |
| 414 | // |
| 415 | // ProofOff: Docs has never put a proof-of-work front door on POST |
| 416 | // /signin. Its abuse controls are rastrillo's per-address and per-IP rate |
| 417 | // limits and the allowlist-gated mail queue, which never delivers to an |
| 418 | // address it does not hold. rastrillo now refuses to start without the |
| 419 | // choice being made, and this keeps today's behaviour. |
| 420 | func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.Sender, list allowlist, logger *slog.Logger, door signinDoor) (*rauth.Auth, error) { |
| 421 | // Both modes land on /auth/local/complete, which sends a person to |
| 422 | // the page they came from (signin_return.go), since Verify itself can |
| 423 | // only land on one fixed path. |
| 424 | return rauth.New(rauth.Config{ |
| 425 | // The smart door (Home spec 2026-11-19-smart-door.md): rastrillo's |
| 426 | // screen, one way in per page. Every outcome, chooser link and |
| 427 | // Forget lands on /signin, which with Home configured is connect's |
| 428 | // SigninDoor (home/connect MIGRATING.md, step 6). |
| 429 | SigninScreen: true, |
| 430 | SigninOneWay: true, |
| 431 | SigninPath: connect.SigninPath, |
| 432 | ForgetPath: signinForgetPath, |
| 433 | SignedInPath: localLinkCompletePath, |
| 434 | DB: writer, |
| 435 | Origin: cfg.Origin, |
| 436 | InstanceKey: instanceKey, |
| 437 | Mailer: mailer, // the sign-in mail queue (mailqueue.go) |
| 438 | Authorize: list.admits, |
| 439 | Logger: logger, |
| 440 | Subject: chrome.EmailSubject("Docs"), |
| 441 | ProofOff: true, |
| 442 | // nil in every deployment: rastrillo's default, any server an |
| 443 | // address's own _keymail delegation names, dialed only at a |
| 444 | // public address. Only the tests list one (keymailTestServers). |
| 445 | KeymailServers: keymailTestServers, |
| 446 | Refused: func(w http.ResponseWriter, r *http.Request, _ rauth.Identity) { |
| 447 | door.refused(w, r) |
| 448 | }, |
| 449 | RenderConfirm: func(w http.ResponseWriter, r *http.Request, d rauth.ConfirmPageData) { |
| 450 | door.confirm(w, r, d) |
| 451 | }, |
| 452 | }) |
| 453 | } |
| 454 | |
| 455 | // keymailTestServers is rauth.Config.KeymailServers, and nil outside |
| 456 | // this package's tests. From rastrillo v0.45.0 an unlisted Keymail |
| 457 | // server is dialed only at a public address, by a client cloned from |
| 458 | // http.DefaultTransport; TestKeymailOAuthActualIntegration answers its |
| 459 | // Keymail server in-process behind a replaced DefaultTransport, so it |
| 460 | // lists that host here and auth reaches it through its listed-servers |
| 461 | // guard instead. Only that test's child process sets it: every other |
| 462 | // test builds auth as a deployment does, with the list nil. |
| 463 | var keymailTestServers []string |
| 464 | |
| 465 | // signinForgetPath is where rastrillo auth's Forget is mounted (app.go): |
| 466 | // "Use a different email" on the door, and "Forget me on this device" on |
| 467 | // the signed-out page. It is auth's own default, named here because the |
| 468 | // signed-out page and connect's RoutesConfig.ForgetPath must agree with it. |
| 469 | const signinForgetPath = "/signin/forget" |
| 470 | |
| 471 | // oficinaChain is the hidden field the signed-out page's Forget form posts |
| 472 | // (chain=oficina) when Home is configured: after forgetting this browser |
| 473 | // here, Docs sends it on to Oficina ID's own Forget (forget, below). The |
| 474 | // door's "Use a different email" posts to the same Forget without it, and |
| 475 | // stays on the door. |
| 476 | const oficinaChain = "oficina" |
| 477 | |
| 478 | // oficinaIDName is the suite's sign-in service, the federated door's name. |
| 479 | const oficinaIDName = "Oficina ID" |
| 480 | |
| 481 | // signinPage is the view data of the sign-in door (views/signin.html): |
| 482 | // rastrillo's sign-in screen (its ui "signin" partial, fed by |
| 483 | // auth.SigninState) drawn inside estilo's door by estilo-signin-screen. |
| 484 | // Every state is that one template: the door, the chooser ("Other ways to |
| 485 | // sign in"), Sent, the Keymail continuation and the confirm step an |
| 486 | // emailed link opens. |
| 487 | type signinPage struct { |
| 488 | Frame Frame |
| 489 | Screen chrome.SignInScreen |
| 490 | } |
| 491 | |
| 492 | // signin is the sign-in door (the smart-door spec in Home, |
| 493 | // docs/superpowers/specs/2026-11-19-smart-door.md): GET /signin, and with |
| 494 | // Home configured GET /signin/local too (connect's SigninDoor and |
| 495 | // SigninLocal hand both here), the landing spot for every outcome |
| 496 | // rastrillo's handlers redirect back with, Config.RenderConfirm's confirm |
| 497 | // step, and Config.Refused's refusal. |
| 498 | // |
| 499 | // rastrillo decides what the door shows from the query and this browser's |
| 500 | // cookies (SigninState: the way in it used last, Sent, problems, the |
| 501 | // chooser), with SigninOneWay drawing one way in per page. Docs adds what |
| 502 | // only it knows: Oficina ID where connect says the door may offer it |
| 503 | // (OficinaHref is "" on /signin/local, on a step-up and anywhere else), |
| 504 | // and the refusal, which only someone who has just verified the address |
| 505 | // reaches (refusedHere), in the screen's app-problem slot with the email |
| 506 | // field. |
| 507 | func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| 508 | st := h.auth.SigninState(r) |
| 509 | if st.Unavailable { |
| 510 | // Under a base path or on a direct host the hub signs people in, |
| 511 | // estilo-signin-screen draws nothing, and every route rastrillo's |
| 512 | // door names answers 404 there. So does the door. |
| 513 | h.notFound(w, r) |
| 514 | return |
| 515 | } |
| 516 | if href := connect.OficinaHref(r); href != "" { |
| 517 | st.Federated = &rauth.FederatedDoor{ |
| 518 | Provider: lastsignin.ProviderOficina, |
| 519 | Href: href, |
| 520 | // A name, like the door's own "Docs": the same in every |
| 521 | // language, and rastrillo draws it as "Continue with {name}". |
| 522 | Label: oficinaIDName, |
| 523 | Icon: chrome.OficinaGlyph, |
| 524 | } |
| 525 | } |
| 526 | if refusedHere(r) { |
| 527 | // Keymail or a link verified the address and the allowlist does |
| 528 | // not hold it, in this very response (Config.Refused, |
| 529 | // auth_navigation.go's signinRefused). Never from the query. |
| 530 | st.AppProblem = &rauth.AppProblem{Text: rastrillo.T(r, "docs.signin.error.refused"), Ask: true} |
| 531 | } |
| 532 | h.rememberSigninReturn(w, r, &st) |
| 533 | h.auth.PrepareSigninResponse(w, st) |
| 534 | data := signinPage{Screen: chrome.SignInScreen{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host), State: st}} |
| 535 | title, err := h.render.signinTitle(data.Screen) |
| 536 | if err != nil { |
| 537 | h.logger.Error("docs: render signin title", "err", err) |
| 538 | h.fail(w, r, http.StatusInternalServerError, failStatus) |
| 539 | return |
| 540 | } |
| 541 | data.Frame = h.frame(r, frameOptions{title: title, signinPage: true}) |
| 542 | if err := h.render.page(w, r, "signin", data); err != nil { |
| 543 | h.logger.Error("docs: render signin", "err", err) |
| 544 | h.fail(w, r, http.StatusInternalServerError, failStatus) |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | // rememberSigninReturn keeps the page a sign-in began from in Docs' own |
| 549 | // sealed return memory (home_return.go), read at /auth/local/complete, |
| 550 | // when the door is opened afresh: a plain GET of /signin or /signin/local |
| 551 | // that is not one of the email flow's outcomes. A plain /signin remembers |
| 552 | // the list, so a page remembered by an earlier, abandoned attempt never |
| 553 | // wins over the one being made now. A plain /signin/local does not: connect |
| 554 | // sends people there (failed, unknown, "Connect my existing account") |
| 555 | // without return_to, mid-way through a sign-in that already remembered its |
| 556 | // page, so the door carries that page on its forms instead (st.ReturnTo), |
| 557 | // and the post remembers it again (beginSignin). The chooser's links carry |
| 558 | // return_to, so moving between ways keeps it. The confirm step and a |
| 559 | // refusal are drawn on /auth/*, and remember nothing. |
| 560 | func (h *handlers) rememberSigninReturn(w http.ResponseWriter, r *http.Request, st *rauth.SigninState) { |
| 561 | if h.rememberReturn == nil || r.Method != http.MethodGet || signinOutcome(r) || |
| 562 | (r.URL.Path != connect.SigninPath && r.URL.Path != connect.SigninLocalPath) { |
| 563 | return |
| 564 | } |
| 565 | path, ok := requestedReturn(r) |
| 566 | switch { |
| 567 | case ok: |
| 568 | h.rememberReturn(w, path) |
| 569 | case r.URL.Path == connect.SigninPath: |
| 570 | h.rememberReturn(w, "/") |
| 571 | case h.returnPath != nil && st.ReturnTo == "": |
| 572 | if kept := h.returnPath(r); kept != "/" { |
| 573 | st.ReturnTo = kept |
| 574 | } |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | // forget is POST /signin/forget, rastrillo auth's Forget: "Use a |
| 579 | // different email" on the door, and "Forget me on this device" on the |
| 580 | // signed-out page. Each host remembers for itself, so with Home configured |
| 581 | // the signed-out page's form (chain=oficina) goes on to Oficina ID's own |
| 582 | // Forget once this one has answered, with Docs' signed-out page as the way |
| 583 | // back: {issuer}/forget?return=<origin>/signed-out. id.oficina.works asks |
| 584 | // "Forget me on Oficina ID too?" and returns only to a registered |
| 585 | // consumer's exact /signed-out. Anything but Forget's own redirect (a |
| 586 | // cross-origin refusal, a wrong method) is passed on as it is. |
| 587 | func (h *handlers) forget(forget http.HandlerFunc) http.HandlerFunc { |
| 588 | return func(w http.ResponseWriter, r *http.Request) { |
| 589 | if h.homeIssuer == "" { |
| 590 | forget(w, r) |
| 591 | return |
| 592 | } |
| 593 | result := &signinResponse{header: make(http.Header)} |
| 594 | forget(result, r) |
| 595 | if result.status == http.StatusSeeOther && r.PostFormValue("chain") == oficinaChain { |
| 596 | result.header.Set("Location", oficinaForgetURL(h.homeIssuer, h.origin)) |
| 597 | } |
| 598 | result.replay(w) |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | // oficinaForgetURL is Oficina ID's Forget, returning to this origin's |
| 603 | // signed-out page (Home's internal/home/door.go, forgetChainReturn). |
| 604 | func oficinaForgetURL(issuer, origin string) string { |
| 605 | back := strings.TrimSuffix(origin, "/") + "/signed-out" |
| 606 | return strings.TrimSuffix(issuer, "/") + "/forget?" + url.Values{"return": {back}}.Encode() |
| 607 | } |
| 608 | |
| 609 | // signedOut is GET /signed-out without Home, where Sign out lands: "You’re |
| 610 | // signed out", a Sign in button and "Forget me on this device" (spec |
| 611 | // §9.2; the smart-door spec's "Signed out"). With Home configured the page |
| 612 | // is connect's SignedOut, drawn by the same renderer (home_render.go). |
| 613 | func (h *handlers) signedOut(w http.ResponseWriter, r *http.Request) { |
| 614 | h.render.homeLink(w, r, "signedout", "", http.StatusOK) |
| 615 | } |
| 616 | |
| 617 | // linkPath extracts the request-target (path plus query, no |
| 618 | // scheme/host) from an emailed magic link — what |
| 619 | // httptest.NewRequest, and a real browser following a same-origin |
| 620 | // link, both just need. It exists so TestSignIn (testing.go) does not |
| 621 | // have to know the emailed link is absolute. |
| 622 | func linkPath(link string) (string, error) { |
| 623 | u, err := url.Parse(link) |
| 624 | if err != nil { |
| 625 | return "", fmt.Errorf("docs: parse magic link %q: %w", link, err) |
| 626 | } |
| 627 | return u.RequestURI(), nil |
| 628 | } |
| 629 | |