| 1 | package sheets |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/estilo.git/chrome" |
| 5 | "amadan.net/oficina/home/connect" |
| 6 | "amadan.net/oficina/home/teammode" |
| 7 | "database/sql" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "log/slog" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "strings" |
| 14 | |
| 15 | "amadan.net/rastrillo/rastrillo/auth" |
| 16 | "amadan.net/rastrillo/rastrillo/mail" |
| 17 | ) |
| 18 | |
| 19 | // AuthEnv is everything sign-in needs from the environment, already |
| 20 | // validated. Building it is the only place these variable names appear. |
| 21 | type AuthEnv struct { |
| 22 | AgentIssuer string |
| 23 | AgentTeam string |
| 24 | Home *connect.Credentials |
| 25 | // Team is team mode's configuration (teammode.ConfigFromEnv), nil |
| 26 | // unless a SHEETS_TEAM_* variable is set. With it the roster is the |
| 27 | // team and SHEETS_OWNERS is optional: if set, it only admits local |
| 28 | // sign-in. TeamSettings verifies it. |
| 29 | Team *teammode.Config |
| 30 | // Origin is the instance's external origin, scheme included. It is |
| 31 | // the base of every emailed link and the CSRF origin check, which |
| 32 | // makes a WRONG value the dangerous case rather than a missing one: |
| 33 | // a missing origin refuses at boot, while a wrong one boots happily |
| 34 | // and mints links pointing at a host nobody serves. Set it only |
| 35 | // after the route exists and answers. |
| 36 | Origin string |
| 37 | |
| 38 | // InstanceKey seals auth's pending blob. auth.New refuses an empty |
| 39 | // one, but it refuses at the wiring call with a framework message; |
| 40 | // this refuses at boot naming the variable an operator has to set. |
| 41 | InstanceKey string |
| 42 | |
| 43 | // Owners is the admission allowlist: the addresses that may hold a |
| 44 | // session on this instance. |
| 45 | Owners []string |
| 46 | |
| 47 | // Mailer delivers the links. |
| 48 | Mailer mail.Sender |
| 49 | } |
| 50 | |
| 51 | // loopback reports whether origin is a local development origin. |
| 52 | // |
| 53 | // This is the ONLY thing that relaxes the mail requirement, and it is |
| 54 | // deliberately a fact rather than a switch. A deployed instance's origin |
| 55 | // is its public https host, so it cannot take this branch; there is no |
| 56 | // flag or variable that turns "development" on, so there is nothing to |
| 57 | // set by accident in production. And the failure mode of lying about it |
| 58 | // is loud rather than quiet — an instance claiming a loopback origin |
| 59 | // mints links pointing at localhost, which nobody can click. |
| 60 | // The host is compared after parsing, never by prefix. A prefix test on |
| 61 | // "http://127.0.0.1" also accepts "http://127.0.0.1.attacker.example", |
| 62 | // which is a real domain someone else can own — caught here by |
| 63 | // TestLoopbackIsNotPrefixSpoofable, which failed on exactly that string |
| 64 | // when this was written with strings.HasPrefix. |
| 65 | func loopback(origin string) bool { |
| 66 | u, err := url.Parse(origin) |
| 67 | if err != nil || u.Scheme != "http" { |
| 68 | return false |
| 69 | } |
| 70 | switch u.Hostname() { |
| 71 | case "localhost", "127.0.0.1", "::1": |
| 72 | return true |
| 73 | } |
| 74 | return false |
| 75 | } |
| 76 | |
| 77 | // LoadAuthEnv reads and validates sign-in configuration, refusing rather |
| 78 | // than degrading. |
| 79 | // |
| 80 | // Every refusal here is a case where continuing would produce an app |
| 81 | // that looks like it works. An instance with no mailer logs live |
| 82 | // credentials to platform-held storage instead of emailing them; an |
| 83 | // instance with an empty allowlist admits anyone who can receive mail at |
| 84 | // any address. Both serve pages and answer /healthz. |
| 85 | func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) { |
| 86 | env := AuthEnv{ |
| 87 | AgentIssuer: os.Getenv("SHEETS_AGENT_ISSUER"), |
| 88 | AgentTeam: os.Getenv("SHEETS_AGENT_TEAM"), |
| 89 | Home: connect.CredentialsFromEnv("SHEETS"), |
| 90 | Origin: strings.TrimSpace(os.Getenv("SHEETS_ORIGIN")), |
| 91 | InstanceKey: strings.TrimSpace(os.Getenv("SHEETS_INSTANCE_KEY")), |
| 92 | Owners: splitOwners(os.Getenv("SHEETS_OWNERS")), |
| 93 | Team: teammode.ConfigFromEnv("SHEETS"), |
| 94 | } |
| 95 | |
| 96 | var missing []string |
| 97 | if env.Origin == "" { |
| 98 | missing = append(missing, "SHEETS_ORIGIN") |
| 99 | } |
| 100 | if env.InstanceKey == "" { |
| 101 | missing = append(missing, "SHEETS_INSTANCE_KEY") |
| 102 | } |
| 103 | if len(env.Owners) == 0 && env.Team == nil { |
| 104 | missing = append(missing, "SHEETS_OWNERS") |
| 105 | } |
| 106 | if len(missing) > 0 { |
| 107 | return AuthEnv{}, fmt.Errorf("sign-in is not configured: %s not set", |
| 108 | strings.Join(missing, ", ")) |
| 109 | } |
| 110 | |
| 111 | // Mail is either channel rastrillo's mail.FromCarlos takes: |
| 112 | // CARLOS mail submission, which the agent turns on with |
| 113 | // CARLOS_MAIL=submit beside its control socket (the From is |
| 114 | // CARLOS_MAIL_FROM, the stem of Sheets' declared CARLOS_SMTP |
| 115 | // prefix), or CARLOS_SMTP_*. |
| 116 | // |
| 117 | // mail.FromEnv falls back to a logging sender with a warning when |
| 118 | // SMTP is absent. A warning is not enough: the emailed link is a |
| 119 | // live credential and the log is platform-held storage we cannot |
| 120 | // grep or redact. Detect the fallback ourselves and refuse. |
| 121 | submit := os.Getenv("CARLOS_MAIL") == "submit" |
| 122 | smtp := os.Getenv("CARLOS_SMTP_HOST") != "" && os.Getenv("CARLOS_SMTP_FROM") != "" |
| 123 | if !submit && !smtp { |
| 124 | if !loopback(env.Origin) { |
| 125 | return AuthEnv{}, errors.New( |
| 126 | "sign-in is not configured: neither CARLOS_MAIL=submit nor " + |
| 127 | "CARLOS_SMTP_HOST and CARLOS_SMTP_FROM are set, " + |
| 128 | "so magic links would be written to the log instead of emailed. " + |
| 129 | "Run `carlos email enable --app sheets`") |
| 130 | } |
| 131 | logger.Warn("sign-in: no SMTP configured and origin is loopback — " + |
| 132 | "magic links will be LOGGED, NOT SENT") |
| 133 | } |
| 134 | if _, err := connect.DecodeCredentials(env.Home, env.Origin); err != nil { |
| 135 | return AuthEnv{}, errHome |
| 136 | } |
| 137 | if err := validateAgentConfig(env.AgentIssuer, env.AgentTeam, env.Origin, env.Home); err != nil { |
| 138 | return AuthEnv{}, err |
| 139 | } |
| 140 | // Built here, on the serving path only (cmd/sheets main; the |
| 141 | // sheets-contract command never loads sign-in): a CARLOS seed or |
| 142 | // one-shot has no control socket and the agent strips CARLOS_MAIL |
| 143 | // from it, so FromCarlos there would refuse a switched app. |
| 144 | // FromCarlos never falls back to logged mail; that is only the |
| 145 | // loopback case above, with neither channel. |
| 146 | if submit || smtp { |
| 147 | mailer, err := mail.FromCarlos("CARLOS", logger) |
| 148 | if err != nil { |
| 149 | return AuthEnv{}, err |
| 150 | } |
| 151 | env.Mailer = mailer |
| 152 | } else { |
| 153 | env.Mailer = mail.FromEnv("CARLOS", logger) |
| 154 | } |
| 155 | |
| 156 | return env, nil |
| 157 | } |
| 158 | |
| 159 | // splitOwners parses the allowlist, lowercasing and dropping blanks so a |
| 160 | // trailing comma or stray space cannot admit or exclude anyone by |
| 161 | // accident. |
| 162 | func splitOwners(raw string) []string { |
| 163 | var out []string |
| 164 | for _, part := range strings.Split(raw, ",") { |
| 165 | if addr := strings.ToLower(strings.TrimSpace(part)); addr != "" { |
| 166 | out = append(out, addr) |
| 167 | } |
| 168 | } |
| 169 | return out |
| 170 | } |
| 171 | |
| 172 | // keymailTestServers is auth.Config.KeymailServers, and nil outside |
| 173 | // this package's tests. From rastrillo v0.45.0 an unlisted Keymail |
| 174 | // server is dialed only at a public address, by a client cloned from |
| 175 | // http.DefaultTransport; the tests' in-process Keymail fixtures |
| 176 | // (keymailtest) answer behind a wrapped DefaultTransport at a name |
| 177 | // nothing resolves, so TestMain lists their host here, and auth reaches |
| 178 | // them through its listed-servers guard instead. |
| 179 | var keymailTestServers []string |
| 180 | |
| 181 | // NewAuth wires the sign-in flow. Exactly one per process: auth's |
| 182 | // underlying flow carries rate-limiter state on the value, so one per |
| 183 | // request would get a fresh empty budget every time and rate-limit |
| 184 | // nothing, silently. |
| 185 | // |
| 186 | // app supplies the three things auth asks of the app at redemption: |
| 187 | // the admission gate (App.Admits), the door a verified but refused |
| 188 | // address is shown (App.refused), and the door an emailed link opens on |
| 189 | // (App.renderConfirm). Admission is the App's rather than |
| 190 | // Admits(env.Owners) because it is no longer a static list: a guest who |
| 191 | // has been granted a sheet must be able to sign in, and only the |
| 192 | // database knows who that is. |
| 193 | func NewAuth(db *sql.DB, env AuthEnv, logger *slog.Logger, app *App) (*auth.Auth, error) { |
| 194 | if app == nil { |
| 195 | // A nil Authorize admits every verified address, which on a |
| 196 | // public-hostname instance means anyone who can receive mail. |
| 197 | // Refusing here beats defaulting to the allowlist, because a |
| 198 | // caller that forgot to pass one has a bug either way and this |
| 199 | // is the version that says so. |
| 200 | return nil, errors.New("sign-in: refusing to wire auth with no admission gate") |
| 201 | } |
| 202 | authorize := app.Admits |
| 203 | queue := newMailQueue(env.Mailer, authorize, nil, logger) |
| 204 | if a, ok := env.Mailer.(queueAttacher); ok { |
| 205 | a.attachQueue(queue.wait) |
| 206 | } |
| 207 | signedInPath := "/sheets" |
| 208 | if env.Home != nil { |
| 209 | signedInPath = connect.LocalCompletePath |
| 210 | } |
| 211 | plugin, err := auth.New(auth.Config{ |
| 212 | DB: db, |
| 213 | Origin: env.Origin, |
| 214 | InstanceKey: env.InstanceKey, |
| 215 | // Begin runs for every address (handleBegin); the mail goes |
| 216 | // out after the response, and only to one authorize admits. |
| 217 | Mailer: queue, |
| 218 | Authorize: authorize, |
| 219 | // A verified address Authorize refuses gets the door, with the |
| 220 | // refusal on it, in auth's own 403 (App.refused). |
| 221 | Refused: app.refused, |
| 222 | // GET /auth/verify spends nothing: it opens the door with one |
| 223 | // Sign in button that POSTs the link back, so a mail scanner's |
| 224 | // fetch cannot spend it (App.renderConfirm). |
| 225 | RenderConfirm: app.renderConfirm, |
| 226 | // No proof-of-work on the sign-in form. Sheets never had one: |
| 227 | // handleBegin's rate budgets and mailQueue's admission check are |
| 228 | // what stand between a stranger and the mailer. ProofOff keeps |
| 229 | // today's behaviour; wiring a pow.Guard is a decision of its own |
| 230 | // (schema, assets, a form that needs JavaScript). |
| 231 | ProofOff: true, |
| 232 | // The smart door (Home spec 2026-11-19-smart-door.md): rastrillo's |
| 233 | // screen, one way in per page. Every outcome, chooser link and |
| 234 | // Forget lands on /signin, which with Home configured is connect's |
| 235 | // SigninDoor (home/connect MIGRATING.md, step 6). |
| 236 | SigninScreen: true, |
| 237 | SigninOneWay: true, |
| 238 | SigninPath: connect.SigninPath, |
| 239 | ForgetPath: signinForgetPath, |
| 240 | // Where a fresh session lands. auth defaults this to "/", |
| 241 | // which is the anonymous entry page — so without this line |
| 242 | // every magic-link click arrives on a page that exists to |
| 243 | // offer sign-in, and has to be told it worked. |
| 244 | SignedInPath: signedInPath, |
| 245 | Subject: chrome.EmailSubject("Sheets"), |
| 246 | // nil in every deployment: rastrillo's default, any server an |
| 247 | // address's own _keymail delegation names, dialed only at a |
| 248 | // public address. Only the tests list one (keymailTestServers). |
| 249 | KeymailServers: keymailTestServers, |
| 250 | Logger: logger, |
| 251 | }) |
| 252 | if err != nil { |
| 253 | queue.close() |
| 254 | return nil, err |
| 255 | } |
| 256 | signinQueuesMu.Lock() |
| 257 | signinQueues[plugin] = queue |
| 258 | signinQueuesMu.Unlock() |
| 259 | return plugin, nil |
| 260 | } |
| 261 | |
| 262 | // admits builds the admission gate. |
| 263 | // |
| 264 | // A nil Authorize admits every verified address, which on a |
| 265 | // public-hostname instance means anyone who can receive mail. The |
| 266 | // allowlist is a slice-one stand-in for a membership table: it is |
| 267 | // deliberately the smallest thing that is fail-closed, not the shape |
| 268 | // sharing will eventually need. |
| 269 | // |
| 270 | // Comparison is on the lowercased address. That is not full |
| 271 | // normalisation — addresses are case-sensitive before the @ per RFC |
| 272 | // 5321, and no mainstream provider honours that — so this matches what |
| 273 | // operators expect when they type an allowlist. |
| 274 | func Admits(owners []string) func(string) bool { |
| 275 | allowed := make(map[string]struct{}, len(owners)) |
| 276 | for _, o := range owners { |
| 277 | allowed[o] = struct{}{} |
| 278 | } |
| 279 | return func(address string) bool { |
| 280 | _, ok := allowed[strings.ToLower(strings.TrimSpace(address))] |
| 281 | return ok |
| 282 | } |
| 283 | } |
| 284 | |