oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// config.go is everything cmd/slides/main.go reads out of the
2// environment and hands to New, plus the rules that decide whether a
3// given combination is safe to start.
4//
5// One rule runs through all of it: exactly one Env value —
6// "development" — may ever take a default, and cmd/slides/main.go's
7// chooseEnv makes sure only an explicit -env flag can select it.
8// Anywhere else, a setting that decides whether sign-in is safe is a
9// startup refusal when it is missing, never a silent fallback. A
10// misconfigured instance is down, which gets fixed the same day; an
11// instance that quietly did the wrong thing looks healthy for as long
12// as nobody checks.
13package slides
14
15import (
16 "fmt"
17 "log/slog"
18 "net/http"
19 "net/url"
20 "strings"
21
22 "amadan.net/oficina/home/connect"
23 "amadan.net/oficina/home/roster"
24 "amadan.net/oficina/home/teammode"
25 "amadan.net/rastrillo/rastrillo/blobs"
26 "amadan.net/rastrillo/rastrillo/mail"
27)
28
29// EnvDevelopment is the one Env value that unlocks a default. Spelled
30// once, so the several places that compare against it cannot drift.
31const EnvDevelopment = "development"
32
33// EnvProduction is Env's default when nothing sets it — deliberately
34// the closed one, so forgetting to set $SLIDES_ENV never opens
35// anything.
36const EnvProduction = "production"
37
38// DefaultOrigin is Config.Origin's fallback, reachable only in
39// development. Exported so a caller that needs to know which origin a
40// development app is protecting itself against does not duplicate the
41// literal.
42const DefaultOrigin = "http://localhost:8091"
43
44// Config is what New needs to build the app. cmd/slides/main.go fills
45// it from the environment; the test harness fills it directly.
46type Config struct {
47 AgentIssuer string
48 AgentTeam string
49 Home *connect.Credentials
50
51 // Team is roster team mode's configuration (teammode.ConfigFromEnv
52 // with prefix SLIDES: the five SLIDES_TEAM_* variables, all or none),
53 // nil with team mode off. It exists only beside Home, and in team
54 // mode AllowedAddresses is optional: if set, it only admits local
55 // sign-in, and gives nobody team standing (team_config.go).
56 Team *teammode.Config
57 // teamTransport and teamClock are for tests: a directory that
58 // answers in memory and a clock a test can step (teammodetest).
59 // Production leaves both nil.
60 teamTransport http.RoundTripper
61 teamClock roster.Clock
62 // Origin is this instance's external origin, scheme included —
63 // "https://slides.oficina.works". It is three things at once:
64 // csrf.Protect's yardstick for the legacy Origin/Referer fallback
65 // (a modern browser is decided by Sec-Fetch-Site before this
66 // string is read), the base of every emailed magic link, and what
67 // decides Secure/__Host- cookie names.
68 //
69 // Empty is allowed only in development, where it falls back to
70 // DefaultOrigin. Anywhere else it is a startup refusal: on the
71 // platform's socket/LISTEN_FDS activation path there is no -addr
72 // to derive an origin from, so a silent placeholder would mean
73 // mailing sign-in links to a hostname nobody can reach.
74 Origin string
75
76 // Env is EnvDevelopment or anything else (empty means
77 // EnvProduction). It gates the defaults below and nothing else.
78 // cmd/slides/main.go sources it from an explicit -env flag;
79 // $SLIDES_ENV is consulted too, but never for "development"
80 // itself — see chooseEnv there for why an env var must not be able
81 // to select it.
82 Env string
83
84 // InstanceKey seals rastrillo/auth's pending-link blob (an HMAC
85 // key). An empty one hashes to a single fixed, publicly computable
86 // value, identical across every deployment that made the same
87 // mistake — see auth.Config.InstanceKey's own doc comment. Empty
88 // is allowed only in development, where it falls back to
89 // devInstanceKey (auth.go); anywhere else it is a startup refusal.
90 InstanceKey string
91
92 // Mailer delivers the magic link. Nil is allowed only in
93 // development, where mail.Logged puts the link in the log, clearly
94 // marked. Outside development nil is a startup refusal: a sign-in
95 // that cannot send its link is not sign-in, and quietly logging a
96 // live credential in a real deployment's log is the mistake that
97 // fallback exists to flag, not to absorb.
98 //
99 // cmd/slides/main.go builds it (newMailer): CARLOS mail submission
100 // through rastrillo's mail.FromCarlos when the agent set
101 // $CARLOS_MAIL=submit, else SMTP from $SLIDES_SMTP_{HOST,PORT,USER,
102 // PASS,FROM}, falling back per variable to the $CARLOS_SMTP_*
103 // equivalent that `carlos email enable` delivers — see smtpSetting
104 // there for why the fallback is per variable rather than per set.
105 Mailer mail.Sender
106
107 // AllowedAddresses is the only set of addresses this instance ever
108 // mails a link to or admits a session for. Compared
109 // case-insensitively, each entry trimmed (auth.go's
110 // normalizeAddress).
111 //
112 // It is wired to two places on purpose: rauth.Config.Authorize
113 // gates admission, after Keymail or a link has verified the
114 // address, and mailQueue (mailqueue.go) drops the mail for an
115 // address not on it. The second is what keeps this instance's
116 // sending identity from being an open relay for any address a
117 // stranger types into the form, since Authorize fires only after
118 // a link has been mailed and clicked. Neither changes what POST
119 // /signin answers (auth.go's note on POST /signin).
120 //
121 // Empty is allowed only in development, where it means "admit
122 // everyone" so the dev script and the suite need no setup.
123 // Anywhere else it is a startup refusal rather than "admit
124 // nobody": an instance admitting nobody boots looking perfectly
125 // healthy — /signin renders, POST /signin answers as it would for
126 // anyone, because an answer that does not depend on the list is
127 // the whole point of POST /signin — and the only symptom is that no
128 // link ever arrives.
129 AllowedAddresses []string
130
131 // Blobs is where uploaded bytes live — the object store, never the
132 // instance's own filesystem, which is ephemeral and hibernates.
133 // cmd/slides/main.go binds the platform's bucket with
134 // blobs.S3FromEnv and falls back to blobs.Dir in development.
135 // Nothing in this task reads it yet; deck assets do.
136 Blobs blobs.Store
137
138 // ClipCache is a directory for clips' videos read from a store that
139 // cannot seek (clipcache.go). Empty, the app makes one of its own
140 // under the system's temporary directory and removes it on Close.
141 ClipCache string
142
143 // Logger defaults to slog.Default().
144 Logger *slog.Logger
145
146 // KeymailServers is rastrillo/auth's Config.KeymailServers, and nil
147 // in every deployment (cmd/slides never sets it): any server an
148 // address's own _keymail delegation names, dialed only at a public
149 // address by a client auth clones from http.DefaultTransport
150 // (rastrillo v0.45.0). The tests list their in-process Keymail
151 // fixtures here (keymailtest), which answer behind a replaced
152 // DefaultTransport that clone cannot be made from; listed, auth
153 // reaches a server through its guard over DefaultTransport instead.
154 KeymailServers []string
155
156 // AI is the editor assistant's configuration (config_ai.go):
157 // SLIDES_AI, SLIDES_TENSORX_API_KEY, SLIDES_AI_MODELS and the
158 // development-only SLIDES_AI_DEV_BASE_URL. The zero value is off.
159 AI AIConfig
160}
161
162// development reports whether cfg is in the one Env that may default.
163func (cfg Config) development() bool { return cfg.Env == EnvDevelopment }
164
165// resolve turns the config a caller supplied into the config the app
166// actually runs on: Env, Logger, Origin, InstanceKey and Mailer each
167// either filled in or refused, plus the parsed allowlist. Every
168// fail-closed rule in this file is applied here, once, before anything
169// opens.
170//
171// It returns a Config rather than five values because what New stores
172// on the app must be the RESOLVED one. Storing the caller's raw Config
173// was a real bug: in development a.cfg.Origin was "" while the app was
174// protecting http://localhost:8091, and a.cfg.Mailer was nil while mail
175// was going to the log — so any later code reading its own config would
176// have read a description of the app that was not true.
177func resolve(cfg Config) (Config, allowlist, error) {
178 if cfg.Env == "" {
179 cfg.Env = EnvProduction
180 }
181 if cfg.Logger == nil {
182 cfg.Logger = slog.Default()
183 }
184
185 origin, err := resolveOrigin(cfg)
186 if err != nil {
187 return Config{}, allowlist{}, err
188 }
189 cfg.Origin = origin
190
191 instanceKey, err := resolveInstanceKey(cfg)
192 if err != nil {
193 return Config{}, allowlist{}, err
194 }
195 cfg.InstanceKey = instanceKey
196
197 mailer, err := resolveMailer(cfg, cfg.Logger)
198 if err != nil {
199 return Config{}, allowlist{}, err
200 }
201 cfg.Mailer = mailer
202
203 // AllowedAddresses is deliberately NOT rewritten onto cfg: the
204 // parsed, normalized form is the allowlist type, and leaving the
205 // raw slice in place keeps one obvious answer to "what was
206 // configured" beside the derived answer to "what is admitted".
207 list, err := resolveAllowlist(cfg)
208 if err != nil {
209 return Config{}, allowlist{}, err
210 }
211
212 ai, err := resolveAI(cfg)
213 if err != nil {
214 return Config{}, allowlist{}, err
215 }
216 cfg.AI = ai
217 return cfg, list, nil
218}
219
220// resolveOrigin applies Config.Origin's own rule: a non-empty value is
221// trimmed and validated, an empty one falls back to DefaultOrigin in
222// development and is refused anywhere else.
223//
224// Trimmed before the emptiness test on purpose: $SLIDES_ORIGIN=" " is
225// not empty by a bare == "" check, so it would sail past the guard and
226// only surface later, at request time, on whichever legacy client
227// still exercises csrf.Protect's Origin/Referer fallback.
228func resolveOrigin(cfg Config) (string, error) {
229 origin := strings.TrimSpace(cfg.Origin)
230 if origin == "" {
231 if cfg.development() {
232 return DefaultOrigin, nil
233 }
234 return "", fmt.Errorf("slides: Config.Origin is empty and Env is %q, not %q — refusing to start with an unset origin; set $SLIDES_ORIGIN to this instance's real origin", cfg.Env, EnvDevelopment)
235 }
236 if err := validateOrigin(origin); err != nil {
237 return "", fmt.Errorf("slides: Config.Origin is invalid: %w", err)
238 }
239 return origin, nil
240}
241
242// validateOrigin reports whether origin is something csrf.Protect and
243// an emailed link can both actually use: an absolute http(s) URL naming
244// a scheme and a host and nothing else.
245//
246// "Nothing else" is checked deliberately. url.Parse happily accepts a
247// bare path, a value carrying a query string, or one with embedded
248// userinfo, none of which could ever equal a browser's Origin header,
249// and none of which belongs at the front of a magic link. Hostname()
250// rather than Host: "http://:8091" — what a bare -addr :8091 would
251// derive — has a non-empty Host and no host at all.
252func validateOrigin(origin string) error {
253 u, err := url.Parse(origin)
254 if err != nil {
255 return fmt.Errorf("origin %q does not parse as a URL: %w", origin, err)
256 }
257 if u.Scheme != "http" && u.Scheme != "https" {
258 return fmt.Errorf("origin %q must have an http or https scheme", origin)
259 }
260 if u.Hostname() == "" {
261 return fmt.Errorf("origin %q has no host", origin)
262 }
263 if u.Path != "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
264 return fmt.Errorf("origin %q must be scheme://host[:port] only, with no path, query, fragment or userinfo", origin)
265 }
266 return nil
267}
268