oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Command slides wires the app: resolve the platform's activation
2// argv, read the environment, open the database, build the app, serve.
3package main
4
5import (
6 "amadan.net/oficina/home/connect"
7 "amadan.net/oficina/home/teammode"
8 "fmt"
9 "log/slog"
10 "os"
11 "os/signal"
12 "path/filepath"
13 "strings"
14 "syscall"
15
16 "amadan.net/rastrillo/rastrillo"
17 "amadan.net/rastrillo/rastrillo/blobs"
18 "amadan.net/rastrillo/rastrillo/db"
19 "amadan.net/rastrillo/rastrillo/mail"
20
21 slides "amadan.net/oficina/slides/internal/slides"
22)
23
24// extractEnvFlag pulls "-env value"/"-env=value" (or the "--env"
25// spelling) out of args, returning the value ("" if absent) and
26// everything else unchanged, order preserved.
27//
28// It has to run before rastrillo.Resolve: Resolve parses os.Args[1:]
29// with its own flag.FlagSet, which knows only -socket/-addr/-db and
30// errors on anything else, so a flag this binary adds on top must be
31// stripped out first.
32//
33// A trailing "-env" with nothing after it is an error, not an empty
34// value. Silently reading as "" would make chooseEnv fall through to
35// $SLIDES_ENV and then to production — so `slides -env` (a typo for
36// `-env development`, or a truncated argv) would boot a production app
37// while its operator believed they had asked for a development one.
38// Refusing is the only answer that cannot be misread.
39func extractEnvFlag(args []string) (env string, rest []string, err error) {
40 for i := 0; i < len(args); i++ {
41 a := args[i]
42 switch {
43 case a == "-env" || a == "--env":
44 if i+1 >= len(args) {
45 return "", nil, fmt.Errorf("%s needs a value, for example: %s development", a, a)
46 }
47 env = args[i+1]
48 i++
49 continue
50 case strings.HasPrefix(a, "-env="):
51 env = strings.TrimPrefix(a, "-env=")
52 continue
53 case strings.HasPrefix(a, "--env="):
54 env = strings.TrimPrefix(a, "--env=")
55 continue
56 }
57 rest = append(rest, a)
58 }
59 return env, rest, nil
60}
61
62// chooseEnv decides slides.Config.Env from -env's extracted value
63// (flagEnv, "" when the flag was absent) and $SLIDES_ENV (osEnv).
64//
65// "development" is honoured ONLY from the flag. This is the rule Docs
66// arrived at the hard way, and it is the whole safety story for every
67// fail-closed default in config.go: platform instance configuration IS
68// environment variables — $SLIDES_ORIGIN, $SLIDES_INSTANCE_KEY,
69// $SLIDES_SMTP_* — so a bare $SLIDES_ENV=development sitting one line
70// away from its neighbours in the same block would be a
71// production-reachable path to the public constant standing in for the
72// HMAC key that seals auth's pending blob, to an allowlist that admits
73// everyone, and to every magic link — token included — landing in the
74// instance's own log instead of being mailed.
75//
76// osEnv is still consulted for any OTHER value (a future "staging",
77// say): every check in slides.New reads as "== development" or "!=
78// development", so any non-"development" string already behaves exactly
79// like production and there is nothing for $SLIDES_ENV to unlock.
80func chooseEnv(flagEnv, osEnv string) string {
81 if flagEnv != "" {
82 return flagEnv
83 }
84 if osEnv != "" && osEnv != slides.EnvDevelopment {
85 return osEnv
86 }
87 return slides.EnvProduction
88}
89
90// smtpSetting reads one SMTP setting, this app's own variable first and
91// the platform's as the fallback: $SLIDES_SMTP_HOST, else
92// $CARLOS_SMTP_HOST.
93//
94// Per variable, not per set. `carlos email enable` delivers
95// CARLOS_SMTP_{HOST,PORT,USER,PASS,FROM}, and the common case is
96// wanting every one of them except FROM — the address this app sends
97// as — which $SLIDES_SMTP_FROM then overrides on its own. An
98// all-or-nothing choice between the two prefixes would make that
99// ordinary case impossible to express without restating the platform's
100// own credentials in this app's variables, which is exactly the kind of
101// copy that goes stale after a credential rotation.
102//
103// Trimmed, because these five arrive from a deploy-time env block or a
104// secret store, where a trailing newline is a routine accident and a
105// leading space in a hostname is never meant.
106func smtpSetting(name string) string {
107 if v := strings.TrimSpace(os.Getenv("SLIDES_SMTP_" + name)); v != "" {
108 return v
109 }
110 return strings.TrimSpace(os.Getenv("CARLOS_SMTP_" + name))
111}
112
113// smtpSecret is smtpSetting for the two values that are credentials:
114// same per-variable fallback, no trimming. rastrillo/mail.FromEnv does
115// not trim these either, and for the same reason — a password's
116// surrounding whitespace may be part of the password, and silently
117// eating it would fail authentication with no way to see why.
118func smtpSecret(name string) string {
119 if v := os.Getenv("SLIDES_SMTP_" + name); v != "" {
120 return v
121 }
122 return os.Getenv("CARLOS_SMTP_" + name)
123}
124
125// newMailer builds the magic-link sender: CARLOS mail submission when
126// the agent turned it on, else SMTP from the settings above.
127//
128// Submission ($CARLOS_MAIL=submit, which only the CARLOS agent sets,
129// with its control socket) goes through rastrillo's mail.FromCarlos,
130// and the instance holds no mail credential. The From is
131// $CARLOS_MAIL_FROM, exactly what the platform delivers: it names the
132// variable from the app's declared prefix (CARLOS_SMTP for Slides, so
133// stem CARLOS). There is deliberately no SLIDES_ override here, unlike
134// the SMTP settings: the platform never delivers one, and the mail verb
135// sends only as the app's own sender. A submission missing
136// its socket, token or From is an error, so Slides refuses to start
137// rather than failing the first sign-in. main calls this only on the
138// serving path: a CARLOS seed or one-shot has no control socket, and
139// the agent strips $CARLOS_MAIL from it.
140//
141// SMTP is mail.SMTP directly rather than mail.FromEnv or FromCarlos,
142// because both read one prefix and this needs the per-variable
143// SLIDES-then-CARLOS fallback. FromEnv also falls back to a
144// warning-and-log sender when HOST or FROM is missing, which is the
145// wrong answer outside development: a nil return here is what lets
146// slides.New refuse to start rather than quietly logging live
147// credentials in a real deployment's log.
148//
149// HOST and FROM are the two values with no sane default, so either one
150// missing means this instance has no relay. PORT defaults to 587 inside
151// mail.SMTP; USER empty means anonymous submission.
152func newMailer(logger *slog.Logger) (mail.Sender, error) {
153 if os.Getenv("CARLOS_MAIL") == "submit" {
154 return mail.FromCarlos("CARLOS", logger)
155 }
156 host, from := smtpSetting("HOST"), smtpSetting("FROM")
157 if host == "" || from == "" {
158 return nil, nil
159 }
160 logger.Info("slides: SMTP configured", "host", host, "from", from)
161 return mail.SMTP(host, smtpSetting("PORT"), from, smtpSecret("USER"), smtpSecret("PASS")), nil
162}
163
164// newBlobs binds the object store: the platform's bucket when it
165// delivered one, a directory beside the database in development, and
166// nothing otherwise.
167//
168// S3FromEnv answers (nil, nil) — not an error — when the platform
169// delivered no bucket, and a typed nil assigned straight into the
170// blobs.Store interface would be a non-nil interface holding a nil
171// pointer, panicking on first use rather than reading as absent. Hence
172// the explicit nil check rather than `if err == nil { return s }`.
173func newBlobs(env, dbPath string, logger *slog.Logger) (blobs.Store, error) {
174 s3, err := blobs.S3FromEnv()
175 if err != nil {
176 return nil, err
177 }
178 if s3 != nil {
179 // Through the app, not presigned: the browser can reach neither
180 // the bucket's PUT nor its GET under this app's CSP, and the
181 // bucket has no CORS for it (slides.ThroughApp says why).
182 logger.Info("slides: object store bound, served through the app", "bucket", os.Getenv("CARLOS_STORE_BUCKET"))
183 return slides.ThroughApp(s3), nil
184 }
185 if env != slides.EnvDevelopment {
186 // No bucket outside development is not a refusal here: nothing
187 // in this slice stores bytes yet, and the screens that will do
188 // so are what should refuse. Said out loud so the silence is a
189 // decision rather than an oversight.
190 logger.Warn("slides: no object store bound (CARLOS_STORE_* unset)")
191 return nil, nil
192 }
193 root := filepath.Join(filepath.Dir(dbPath), "blobs")
194 return blobs.Dir(root)
195}
196
197func main() {
198 logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
199
200 // -env is stripped before Resolve sees argv (extractEnvFlag), and
201 // it is the only thing that can ever select "development"
202 // (chooseEnv).
203 envFlag, rest, err := extractEnvFlag(os.Args[1:])
204 if err != nil {
205 logger.Error("read flags", "err", err)
206 os.Exit(1)
207 }
208 os.Args = append(os.Args[:1], rest...)
209 env := chooseEnv(envFlag, os.Getenv("SLIDES_ENV"))
210
211 // Resolve, not Run: this app opens its own database handle via
212 // db.Open — a *gorm.DB with a split reader/writer pool, not the
213 // bare *sql.DB Options.Router would hand back — so Options.DBPath
214 // must be empty again by the Serve call below, or Serve would open
215 // a second, unused connection to the same file.
216 opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "slides.db", Logger: logger})
217 if err != nil {
218 logger.Error("resolve activation", "err", err)
219 os.Exit(1)
220 }
221
222 // $SLIDES_ORIGIN is the deploy-time origin — the platform's real
223 // per-instance hostname belongs here. Falling back to a TCP -addr
224 // helps only the local path (scripts/run-dev.sh, or a person
225 // passing -addr by hand); that is exactly the host a browser
226 // loading such an instance sends back as its own Origin. The
227 // platform's real activation path is a unix socket with no -addr to
228 // derive anything from, so with $SLIDES_ORIGIN unset there this
229 // stays empty and slides.New refuses to start — rather than mailing
230 // sign-in links pointing at a placeholder.
231 origin := os.Getenv("SLIDES_ORIGIN")
232 if origin == "" && opts.Addr != "" {
233 origin = "http://" + opts.Addr
234 }
235
236 var homeConfig *connect.Credentials
237 hc := connect.Credentials{Issuer: os.Getenv("SLIDES_HOME_ISSUER"), ConsumerID: os.Getenv("SLIDES_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("SLIDES_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("SLIDES_HOME_DEK_BASE64")}
238 if hc.Issuer != "" || hc.ConsumerID != "" || hc.KeysBase64 != "" || hc.DEKBase64 != "" {
239 // The hub directory the app switcher's "All apps" links to.
240 // Optional, and unprefixed: the same name and the same value
241 // Home itself reads (connect.CredentialsFromEnv reads it the
242 // same way; this app builds Credentials by hand). Checked by
243 // connect.DecodeCredentials, so a malformed value refuses boot.
244 hc.Directory = os.Getenv("HOME_DIRECTORY_ORIGIN")
245 homeConfig = &hc
246 }
247 if err := slides.ValidateAgentConfig(os.Getenv("SLIDES_AGENT_ISSUER"), os.Getenv("SLIDES_AGENT_TEAM"), origin, homeConfig); err != nil {
248 logger.Error("configure agent access", "err", err)
249 os.Exit(1)
250 }
251
252 // The editor's assistant: SLIDES_AI must be exactly "on" or unset,
253 // and a key alone turns nothing on (slides.AIConfigFromEnv).
254 ai, err := slides.AIConfigFromEnv(os.Getenv)
255 if err != nil {
256 logger.Error("configure the assistant", "err", err)
257 os.Exit(1)
258 }
259
260 store, err := newBlobs(env, opts.DBPath, logger)
261 if err != nil {
262 logger.Error("bind object store", "err", err)
263 os.Exit(1)
264 }
265
266 mailer, err := newMailer(logger)
267 if err != nil {
268 logger.Error("configure mail", "err", err)
269 os.Exit(1)
270 }
271
272 d, err := db.Open(opts.DBPath, logger)
273 if err != nil {
274 logger.Error("open database", "err", err)
275 os.Exit(1)
276 }
277 defer d.Close()
278
279 // Every empty value below is a startup refusal inside slides.New
280 // unless env is "development" — see config.go's package comment.
281
282 mux, a, err := slides.New(d, slides.Config{Home: homeConfig, AgentIssuer: os.Getenv("SLIDES_AGENT_ISSUER"), AgentTeam: os.Getenv("SLIDES_AGENT_TEAM"),
283 Team: teammode.ConfigFromEnv("SLIDES"),
284 Origin: origin,
285 Env: env,
286 InstanceKey: os.Getenv("SLIDES_INSTANCE_KEY"),
287 Mailer: mailer,
288 // Split here rather than inside New so Config carries a value
289 // that is already the shape it means: a list of addresses, not
290 // a string that happens to have commas in it.
291 AllowedAddresses: splitList(os.Getenv("SLIDES_ALLOWED_ADDRESSES")),
292 Blobs: store,
293 Logger: logger,
294 AI: ai,
295 })
296 if err != nil {
297 logger.Error("build app", "err", err)
298 os.Exit(1)
299 }
300 // Releases the compiled deck core's wazero runtime on the way out —
301 // after rastrillo.Serve returns (a signal, or a fatal error), same
302 // as d.Close() above.
303 defer a.Close()
304
305 // The router, the locales, the error page and the CSP
306 // (slides.ServeOptions, serving.go).
307 opts = a.ServeOptions(opts, mux)
308 opts.DBPath = ""
309 // rastrillo.Serve owns the signal and the graceful shutdown, and has
310 // no hook into it, so Slides listens for the same signals itself
311 // (every channel registered for a signal receives it) and ends its
312 // streams the moment one arrives. Without this the shutdown waited
313 // its whole ten seconds on any open editor or projector and the
314 // process exited 1 (drain.go, Docs #94).
315 stopping := make(chan os.Signal, 1)
316 signal.Notify(stopping, syscall.SIGTERM, syscall.SIGINT)
317 go func() {
318 <-stopping
319 a.Drain()
320 }()
321 if err := rastrillo.Serve(opts); err != nil {
322 logger.Error("serve failed", "err", err)
323 os.Exit(1)
324 }
325}
326
327// splitList parses a comma-separated environment value into the entries
328// it names, dropping empties so a trailing comma or a stray space is
329// not an entry. Normalization (case, surrounding whitespace) is
330// slides.Config's own job, so that a caller filling it directly gets
331// the same treatment.
332func splitList(raw string) []string {
333 var out []string
334 for _, part := range strings.Split(raw, ",") {
335 if part = strings.TrimSpace(part); part != "" {
336 out = append(out, part)
337 }
338 }
339 return out
340}
341