| 1 | // Command docs runs the CARLOS Docs rastrillo app. |
| 2 | package main |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "os" |
| 9 | "os/signal" |
| 10 | "strings" |
| 11 | "syscall" |
| 12 | |
| 13 | "amadan.net/oficina/estilo.git/googleimport" |
| 14 | "amadan.net/oficina/home/teammode" |
| 15 | "amadan.net/oficina/suite/server" |
| 16 | "amadan.net/rastrillo/rastrillo" |
| 17 | "amadan.net/rastrillo/rastrillo/mail" |
| 18 | |
| 19 | "github.com/carlosframework/docs/internal/docs" |
| 20 | ) |
| 21 | |
| 22 | // devSeedAddress is docs.Seed's default owner when -seed is given |
| 23 | // with no $DOCS_SEED_ADDRESS override: a fixed, non-secret address to |
| 24 | // sign in with locally and see the sample documents land — the same |
| 25 | // "one fixed literal, never a real credential" shape devInstanceKey |
| 26 | // (internal/docs/auth.go) uses for the same reason. |
| 27 | const devSeedAddress = "dev@example.com" |
| 28 | |
| 29 | // extractEnvFlag pulls "-env value"/"-env=value" (or the "--env" |
| 30 | // spelling) out of args, returning the value (empty if absent) and |
| 31 | // everything else unchanged, order preserved. rastrillo.Resolve |
| 32 | // parses os.Args[1:] itself with its own flag.FlagSet, which knows |
| 33 | // only -socket/-addr/-db and errors on anything else, so any flag |
| 34 | // this binary defines on top of that has to be stripped out first — |
| 35 | // the same reason the now-deleted extractDevAuthFlag existed (fix |
| 36 | // round 1 on Task 1: -dev-auth's own identity had zero readers once |
| 37 | // real sign-in landed, and was removed rather than left as a trap; |
| 38 | // this flag replaces the one thing it was still secretly load-bearing |
| 39 | // for — see Env's own doc comment on docs.Config). |
| 40 | func extractEnvFlag(args []string) (env string, rest []string) { |
| 41 | for i := 0; i < len(args); i++ { |
| 42 | a := args[i] |
| 43 | switch { |
| 44 | case a == "-env" || a == "--env": |
| 45 | if i+1 < len(args) { |
| 46 | env = args[i+1] |
| 47 | i++ |
| 48 | } |
| 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 |
| 60 | } |
| 61 | |
| 62 | // extractSeedFlag pulls a bare "-seed"/"--seed" out of args, the same |
| 63 | // strip-before-rastrillo.Resolve shape extractEnvFlag uses just above |
| 64 | // and for the same reason (rastrillo.Resolve's own flag.FlagSet knows |
| 65 | // nothing about this flag and errors on it otherwise). Deliberately |
| 66 | // boolean, no "-seed=value" form: which address to seed is |
| 67 | // $DOCS_SEED_ADDRESS's job (devSeedAddress's own doc comment), the |
| 68 | // same env-var-for-configuration, flag-for-behaviour split Origin and |
| 69 | // -env already use — a flag that sometimes eats the next token and |
| 70 | // sometimes does not is exactly the ambiguity a bare boolean avoids |
| 71 | // (what would "-seed -addr :8099" mean if -seed could take a value?). |
| 72 | func extractSeedFlag(args []string) (seed bool, rest []string) { |
| 73 | for _, a := range args { |
| 74 | if a == "-seed" || a == "--seed" { |
| 75 | seed = true |
| 76 | continue |
| 77 | } |
| 78 | rest = append(rest, a) |
| 79 | } |
| 80 | return seed, rest |
| 81 | } |
| 82 | |
| 83 | // chooseEnv decides docs.Config.Env from -env's own extracted value |
| 84 | // (flagEnv, "" if the flag was absent or given with no value) and |
| 85 | // $DOCS_ENV (osEnv, "" if unset). "development" is honoured ONLY from |
| 86 | // flagEnv — fix round 2 on Task 1: the coordinator's own original |
| 87 | // instruction added a $DOCS_ENV fallback for this, and that reinstated |
| 88 | // exactly the trap the deleted -dev-auth flag existed to close. |
| 89 | // devauth_flag.go's own words, before it was deleted: "no config |
| 90 | // default, no env var, nothing a systemd unit's boilerplate could set |
| 91 | // without someone typing this literal flag." Platform instance |
| 92 | // configuration IS environment variables — $DOCS_ORIGIN, |
| 93 | // $DOCS_INSTANCE_KEY, $DOCS_SMTP_* — so a bare $DOCS_ENV=development |
| 94 | // sitting one line away from its neighbours in the same block is a |
| 95 | // production-reachable path to the public constant |
| 96 | // docs-development-instance-key-not-a-secret (internal/docs/auth.go) |
| 97 | // standing in for the HMAC key that seals auth's pending blob, and to |
| 98 | // every magic link — token included — landing in the instance's own |
| 99 | // log instead of being mailed. Verified live by the reviewer: |
| 100 | // $DOCS_ENV=development with a real origin booted a development app |
| 101 | // under the round-1 code. |
| 102 | // |
| 103 | // osEnv is still consulted for any OTHER value (a future "staging", |
| 104 | // say): every fail-closed check in docs.New reads as "== development" |
| 105 | // or "!= development", so any non-"development" string already |
| 106 | // behaves exactly like production, and there is nothing for $DOCS_ENV |
| 107 | // to unlock there. Only "development" itself is special-cased out. |
| 108 | func chooseEnv(flagEnv, osEnv string) string { |
| 109 | if flagEnv != "" { |
| 110 | return flagEnv |
| 111 | } |
| 112 | if osEnv != "" && osEnv != "development" { |
| 113 | return osEnv |
| 114 | } |
| 115 | return "production" |
| 116 | } |
| 117 | |
| 118 | // checkSeedGate is -seed's whole safety story, extracted to a single |
| 119 | // named predicate so main() and TestSeedGateRefusesWithoutDevelopment |
| 120 | // (main_test.go) call the exact same code — not a copy of its logic |
| 121 | // compared against itself. Fix round 1 on Task 3: the original test |
| 122 | // re-implemented this expression inline, inverted operand order and |
| 123 | // all, and so could not fail no matter how the real gate changed. |
| 124 | // |
| 125 | // chooseEnv above only ever returns "development" for the literal |
| 126 | // -env flag on this exact invocation — never $DOCS_ENV, never any |
| 127 | // default (chooseEnv's own doc comment, fix round 2's finding on Task |
| 128 | // 1) — so this one check is genuinely the only thing standing between |
| 129 | // -seed and a database that might hold real work: a systemd unit's |
| 130 | // argv that carelessly kept a -seed flag around, or a copy-pasted |
| 131 | // invocation run against a real deployment, must refuse here rather |
| 132 | // than writing six sample documents into it. A nil error means |
| 133 | // seeding may proceed. |
| 134 | func checkSeedGate(seed bool, env string) error { |
| 135 | if !seed || env == "development" { |
| 136 | return nil |
| 137 | } |
| 138 | return fmt.Errorf("-seed requires -env development; refusing to seed a database that might not be a throwaway one (env=%q)", env) |
| 139 | } |
| 140 | |
| 141 | // platformMailer builds the magic-link sender from what the platform |
| 142 | // configured, through rastrillo's mail.FromCarlos: CARLOS mail |
| 143 | // submission when the agent set $CARLOS_MAIL=submit (the From is |
| 144 | // $DOCS_MAIL_FROM, the control socket the agent's), else SMTP from |
| 145 | // $DOCS_SMTP_HOST/$DOCS_SMTP_FROM and their siblings. A half-configured |
| 146 | // channel is an error, so the process refuses to start rather than |
| 147 | // failing the first sign-in. |
| 148 | // |
| 149 | // With neither channel it returns nil, and the decision is docs.New's |
| 150 | // (Config.Mailer's own doc comment): rastrillo's logging sender in |
| 151 | // development, a startup refusal anywhere else. mail.FromEnv would |
| 152 | // instead fall back to logging a live credential silently. |
| 153 | // |
| 154 | // main calls it only on the serving path, never for docs-seal: a |
| 155 | // CARLOS seed or one-shot has no control socket and the agent strips |
| 156 | // $CARLOS_MAIL from it, so FromCarlos there would refuse a switched |
| 157 | // app. |
| 158 | func platformMailer(logger *slog.Logger) (mail.Sender, error) { |
| 159 | smtp := strings.TrimSpace(os.Getenv("DOCS_SMTP_HOST")) != "" && |
| 160 | strings.TrimSpace(os.Getenv("DOCS_SMTP_FROM")) != "" |
| 161 | if os.Getenv("CARLOS_MAIL") != "submit" && !smtp { |
| 162 | return nil, nil |
| 163 | } |
| 164 | return mail.FromCarlos("DOCS", logger) |
| 165 | } |
| 166 | |
| 167 | func main() { |
| 168 | logger := slog.Default() |
| 169 | if len(os.Args) > 1 && os.Args[1] == "docs-seal" { |
| 170 | if err := runContentMaintenance(context.Background(), os.Args[2:], os.Getenv, logger); err != nil { |
| 171 | logger.Error("docs: new", "err", err) |
| 172 | os.Exit(1) |
| 173 | } |
| 174 | return |
| 175 | } |
| 176 | |
| 177 | // -env (chooseEnv above; $DOCS_ENV is consulted too, but never for |
| 178 | // "development" — see chooseEnv's own doc comment, fix round 2) |
| 179 | // decides docs.Config.Env — deliberately the ONLY thing that |
| 180 | // does, independent of any identity flag. It used to be |
| 181 | // entangled with -dev-auth (whichever call set Env also turned |
| 182 | // the now-deleted development-only identity on); fix round 1 on |
| 183 | // Task 1 split them apart, because "log mail instead of sending |
| 184 | // it" and "who can sign in" were never the same decision, and a |
| 185 | // future deletion of an identity flag should never silently take |
| 186 | // the mail-logging fallback (and scripts/run-dev.sh) down with |
| 187 | // it. |
| 188 | envFlag, rest := extractEnvFlag(os.Args[1:]) |
| 189 | // -seed: extracted the same way, and for the same reason — |
| 190 | // see docs.Seed's own doc comment for what it does and this |
| 191 | // flag's gate on Env, just below, for why it can never reach a |
| 192 | // database that might be real. |
| 193 | seedFlag, rest := extractSeedFlag(rest) |
| 194 | os.Args = append(os.Args[:1], rest...) |
| 195 | |
| 196 | // Resolve applies the platform's activation argv (-socket/-addr/-db, |
| 197 | // or LISTEN_FDS/$STATE_DIRECTORY under the platform) — never |
| 198 | // hand-rolled, per SKILL.md §1. |
| 199 | opts, err := rastrillo.Resolve(rastrillo.Options{ |
| 200 | DBPath: "docs.db", |
| 201 | Logger: logger, |
| 202 | }) |
| 203 | if err != nil { |
| 204 | logger.Error("docs: resolve", "err", err) |
| 205 | os.Exit(1) |
| 206 | } |
| 207 | |
| 208 | // Origin feeds docs.Config.Origin — see its doc comment for what |
| 209 | // csrf.Protect actually does with it (fix round 3: Sec-Fetch-Site |
| 210 | // decides a modern browser's own traffic before this string is |
| 211 | // ever read; Origin only matters to the legacy Origin/Referer |
| 212 | // fallback path, and a wrong value there fails silently rather |
| 213 | // than visibly). An empty value here is not "no opinion", it is |
| 214 | // "New must refuse to start" once Env is anything but development. |
| 215 | // |
| 216 | // $DOCS_ORIGIN is the explicit, deploy-time override — the |
| 217 | // "<APP>_ORIGIN" convention rastrillo's own `new` scaffold uses |
| 218 | // (cmd/rastrillo/new.go's mainTemplate) — and always wins when set; |
| 219 | // that is where the platform's real per-instance origin (spec |
| 220 | // §9.2's <app>.<sqid>.oncarlos.com) belongs. Falling back to a TCP |
| 221 | // -addr only helps the local/dev path (scripts/run-dev.sh, or a |
| 222 | // person passing -addr by hand): that is exactly the host a |
| 223 | // browser loading this instance sends back as its own Origin |
| 224 | // header. The platform's real activation path is a unix socket or |
| 225 | // LISTEN_FDS — no -addr to derive anything from — so without |
| 226 | // $DOCS_ORIGIN set there, origin stays empty here and New refuses |
| 227 | // to start rather than silently falling back to docs.DefaultOrigin, |
| 228 | // a placeholder with no relationship to where this instance is |
| 229 | // actually reachable — that is exactly the trap this task closes, |
| 230 | // whether or not a given request would ever notice. |
| 231 | origin := os.Getenv("DOCS_ORIGIN") |
| 232 | if origin == "" && opts.Addr != "" { |
| 233 | origin = "http://" + opts.Addr |
| 234 | } |
| 235 | |
| 236 | // $DOCS_INSTANCE_KEY seals rastrillo/auth's pending-link blob — |
| 237 | // docs.Config.InstanceKey's own doc comment. Left empty here when |
| 238 | // unset: docs.New refuses to start on an empty one outside |
| 239 | // development, the same fail-closed shape as an empty Origin. |
| 240 | instanceKey := os.Getenv("DOCS_INSTANCE_KEY") |
| 241 | |
| 242 | // The sign-in sender (platformMailer below): CARLOS mail submission |
| 243 | // or $DOCS_SMTP_*, and nil with neither, which docs.New turns into |
| 244 | // a refusal outside development. |
| 245 | mailer, err := platformMailer(logger) |
| 246 | if err != nil { |
| 247 | logger.Error("docs: mail", "err", err) |
| 248 | os.Exit(1) |
| 249 | } |
| 250 | |
| 251 | // $DOCS_ALLOWED_ADDRESSES is the comma-separated allowlist |
| 252 | // docs.Config.AllowedAddresses' own doc comment describes — the |
| 253 | // only addresses this instance ever mails a sign-in link to or |
| 254 | // admits a session for. Left empty here when unset: docs.New |
| 255 | // (via resolveAllowlist, internal/docs/auth.go) refuses to start |
| 256 | // on an empty one outside development, the same fail-closed shape |
| 257 | // as InstanceKey and Mailer just above — never "admit everyone", |
| 258 | // which is what an unset allowlist reaching a public instance |
| 259 | // would otherwise silently mean. |
| 260 | allowedAddresses := os.Getenv("DOCS_ALLOWED_ADDRESSES") |
| 261 | // $DOCS_WARM_HANDLE: keep a replayed handle per document between update |
| 262 | // POSTs (the live-push spec's §3.5). on/off; unset is off. |
| 263 | warmHandle, err := docs.ParseWarmHandle(os.Getenv("DOCS_WARM_HANDLE")) |
| 264 | if err != nil { |
| 265 | logger.Error("docs: refusing to start", "err", err) |
| 266 | os.Exit(1) |
| 267 | } |
| 268 | // $DOCS_LIVE_PUSH: let push=1 streams carry update bytes (the live-push |
| 269 | // spec's slice 1b). on/off; unset is off. |
| 270 | livePush, err := docs.ParseLivePush(os.Getenv("DOCS_LIVE_PUSH")) |
| 271 | if err != nil { |
| 272 | logger.Error("docs: refusing to start", "err", err) |
| 273 | os.Exit(1) |
| 274 | } |
| 275 | |
| 276 | // $DOCS_SAMPLE_DOCUMENTS opts a deployed instance into |
| 277 | // docs.Config.SampleDocuments — see its own doc comment for the |
| 278 | // full reasoning (parsed permissively, default off, deliberately |
| 279 | // not fail-closed like the settings just above). This is the |
| 280 | // platform-reachable fix for the bug this branch exists to close: |
| 281 | // -seed below never runs on a deployed instance (gated to -env |
| 282 | // development, which activation argv never sets), so without this |
| 283 | // env var a real deployment's sample content stays exactly as |
| 284 | // unreachable as it was before. |
| 285 | sampleDocuments := os.Getenv("DOCS_SAMPLE_DOCUMENTS") |
| 286 | |
| 287 | // chooseEnv: -env wins; $DOCS_ENV wins next EXCEPT for |
| 288 | // "development" itself, which chooseEnv never honours from an env |
| 289 | // var (fix round 2 — see its own doc comment); the default with |
| 290 | // neither set, or with $DOCS_ENV=development and no flag, is |
| 291 | // "production". Nothing here ever defaults to "development" on its |
| 292 | // own; that always takes an explicit -env flag, on this binary or |
| 293 | // in run-dev.sh's own invocation. |
| 294 | env := chooseEnv(envFlag, os.Getenv("DOCS_ENV")) |
| 295 | |
| 296 | // checkSeedGate's own doc comment has the full reasoning; this |
| 297 | // call runs before docs.New even opens the database, so there is |
| 298 | // no window where a wrongly-seeded production process is already |
| 299 | // serving requests by the time this fires. |
| 300 | if err := checkSeedGate(seedFlag, env); err != nil { |
| 301 | logger.Error("docs: " + err.Error()) |
| 302 | os.Exit(1) |
| 303 | } |
| 304 | |
| 305 | // New opens its own database handle (SKILL.md §1's "app that opens |
| 306 | // its own database"), so opts.DBPath is blanked below before Serve |
| 307 | // — otherwise Serve would open a second connection to the file New |
| 308 | // already owns. |
| 309 | cfg := docs.Config{ |
| 310 | AgentIssuer: os.Getenv("DOCS_AGENT_ISSUER"), |
| 311 | AgentTeam: os.Getenv("DOCS_AGENT_TEAM"), |
| 312 | DBPath: opts.DBPath, |
| 313 | ContentKey: os.Getenv("DOCS_CONTENT_KEY"), |
| 314 | // The Google Drive chooser on the import page: all three public |
| 315 | // values or none (docs.Config.GoogleImport; estilo's googleimport |
| 316 | // README has the Google Cloud setup). |
| 317 | GoogleImport: googleimport.Config{ |
| 318 | ClientID: os.Getenv("DOCS_GOOGLE_CLIENT_ID"), |
| 319 | APIKey: os.Getenv("DOCS_GOOGLE_API_KEY"), |
| 320 | AppID: os.Getenv("DOCS_GOOGLE_APP_ID"), |
| 321 | }, |
| 322 | Env: env, |
| 323 | Origin: origin, |
| 324 | InstanceKey: instanceKey, |
| 325 | Mailer: mailer, |
| 326 | AllowedAddresses: allowedAddresses, |
| 327 | SampleDocuments: sampleDocuments, |
| 328 | WarmHandle: warmHandle, |
| 329 | LivePush: livePush, |
| 330 | Logger: logger, |
| 331 | // The hub directory the app switcher's "All apps" goes to. The |
| 332 | // same variable Home itself reads (home origins.go). |
| 333 | Directory: os.Getenv("HOME_DIRECTORY_ORIGIN"), |
| 334 | // The suite consumers (spec §8.2.2): $DOCS_SUITE_CONSUMERS, named by |
| 335 | // the contract's own suffix. Unset serves no suite routes; malformed |
| 336 | // is a refusal in docs.New. |
| 337 | SuiteConsumers: os.Getenv("DOCS" + server.EnvSuffix), |
| 338 | } |
| 339 | home := docs.HomeConfig{Issuer: os.Getenv("DOCS_HOME_ISSUER"), ConsumerID: os.Getenv("DOCS_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("DOCS_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("DOCS_HOME_DEK_BASE64")} |
| 340 | if home.Issuer != "" || home.ConsumerID != "" || home.KeysBase64 != "" || home.DEKBase64 != "" { |
| 341 | cfg.Home = &home |
| 342 | } |
| 343 | |
| 344 | // The five DOCS_TEAM_* variables, all or none: one set alone is a |
| 345 | // configuration docs.New refuses, never allowlist mode. |
| 346 | if team := teammode.ConfigFromEnv("DOCS"); team != nil { |
| 347 | cfg.Team = &docs.TeamConfig{TeamID: team.TeamID, DirectoryOrigin: team.DirectoryOrigin, ProvisioningBase64: team.ProvisioningBase64, OperatorKeysBase64: team.OperatorKeysBase64, RosterToken: team.RosterToken} |
| 348 | if seedFlag { |
| 349 | logger.Error("docs: seed unavailable in TeamMode") |
| 350 | os.Exit(1) |
| 351 | } |
| 352 | } |
| 353 | app, err := docs.New(cfg) |
| 354 | if err != nil { |
| 355 | logger.Error("docs: new", "err", err) |
| 356 | os.Exit(1) |
| 357 | } |
| 358 | defer app.Close() |
| 359 | |
| 360 | // Only reachable with both -seed and -env development (the check |
| 361 | // above) — after New, since both EnsurePerson and docs.Seed need a |
| 362 | // real app.Store() over an already-migrated database, and after |
| 363 | // the InstanceKey/Mailer checks above, so a database that cannot |
| 364 | // even send a real sign-in link never gets seeded either. |
| 365 | if seedFlag { |
| 366 | seedAddress := strings.TrimSpace(os.Getenv("DOCS_SEED_ADDRESS")) |
| 367 | if seedAddress == "" { |
| 368 | seedAddress = devSeedAddress |
| 369 | } |
| 370 | // EnsurePerson here runs with cfg.SampleDocuments as given on |
| 371 | // this invocation: if it's also truthy, EnsurePerson's own |
| 372 | // per-person seeding (store.go) already seeds seedAddress the |
| 373 | // moment its Person row is first created, before this call |
| 374 | // even returns — see its doc comment. The explicit docs.Seed |
| 375 | // call just below runs unconditionally regardless, exactly as |
| 376 | // it always has: -seed's whole point is "seed this address |
| 377 | // right now, guaranteed", not "seed it only if some other |
| 378 | // setting happens to agree." |
| 379 | owner, err := app.Store().EnsurePerson(context.Background(), seedAddress) |
| 380 | if err != nil { |
| 381 | logger.Error("docs: seed: resolve person", "address", seedAddress, "err", err) |
| 382 | os.Exit(1) |
| 383 | } |
| 384 | if err := docs.Seed(context.Background(), app.Store(), docs.Actor{PersonID: owner, VerifiedAddress: &seedAddress}); err != nil { |
| 385 | logger.Error("docs: seed", "address", seedAddress, "err", err) |
| 386 | os.Exit(1) |
| 387 | } |
| 388 | logger.Info("docs: seeded sample documents", "address", seedAddress) |
| 389 | } |
| 390 | |
| 391 | opts = docs.ServeOptions(opts, app) |
| 392 | |
| 393 | // rastrillo.Serve owns the signal and the graceful shutdown, and has |
| 394 | // no hook into it, so Docs listens for the same signals itself (every |
| 395 | // channel registered for a signal receives it) and ends its live |
| 396 | // streams the moment one arrives. Without this the shutdown waited |
| 397 | // its whole ten seconds on any open editor's stream and the process |
| 398 | // exited 1 (app.Drain). |
| 399 | stopping := make(chan os.Signal, 1) |
| 400 | signal.Notify(stopping, syscall.SIGTERM, syscall.SIGINT) |
| 401 | go func() { |
| 402 | <-stopping |
| 403 | app.Drain() |
| 404 | }() |
| 405 | |
| 406 | if err := rastrillo.Serve(opts); err != nil { |
| 407 | logger.Error("docs: serve", "err", err) |
| 408 | os.Exit(1) |
| 409 | } |
| 410 | } |
| 411 | |