steid

@jamesgill /

steid/src/main.rs
Rust6.9 KBCode·Blame·History·Raw
1//! The binary: parse the arguments, read the configuration, open the database, sweep,
2//! build the router, serve.
3//!
4//! Nothing here decides anything a test would want to assert, and what it does that is
5//! not a call is printing. The wiring and the boot sweeps are
6//! [`infrastructure::app`](steid::infrastructure::app) and the subcommands are
7//! [`steid::cli`], both in the library — see
8//! `plans/review-2026-09-10-organisation.md` §6 for why.
9
10use steid::{
11 application::{AppConfig, is_claimed, port::Mailer},
12 cli::{Command, print_reset_link, run_backup, run_restore},
13 domain::SetupToken,
14 infrastructure::{self, mail::LettreMailer, repository::SqliteUserRepo},
15};
16use topcoat::asset::AssetBundle;
17
18#[tokio::main]
19async fn main() -> Result<(), Box<dyn std::error::Error>> {
20 dotenvy::dotenv().ok();
21
22 // Decided before anything is opened: a subcommand must not spawn the server, and
23 // an unrecognised one must fail before it has touched the database.
24 let command = match Command::parse(std::env::args()) {
25 Ok(command) => command,
26 Err(message) => {
27 eprintln!("{message}");
28 std::process::exit(2);
29 }
30 };
31
32 let mut config = AppConfig::from_env()?;
33
34 match command {
35 Command::Serve => {}
36 // Each returns: a subcommand does one thing and exits, and none may fall
37 // through into the server.
38 Command::Backup { destination } => finish(run_backup(&config, &destination).await),
39 Command::Restore { archive } => finish(run_restore(&config, &archive).await),
40 Command::ResetPassword { handle } => {
41 let pool = infrastructure::database::connect(&config.database_url).await?;
42 print_reset_link(&handle, &config, &pool).await?;
43 return Ok(());
44 }
45 }
46
47 // Mail configuration is checked here, before anything is served, so that an operator
48 // who wrote a bad SMTP URL learns it at the one moment they are watching the output
49 // rather than the first time somebody forgets a password. An instance with no mail
50 // configured at all is not an error and says nothing.
51 match LettreMailer::from_config(&config) {
52 Ok(mailer) if mailer.configured() => println!("steid: outgoing mail is configured"),
53 Ok(_) => {}
54 Err(error) => {
55 eprintln!();
56 eprintln!(" !! the mail configuration is not usable: {error}");
57 eprintln!(" !! Unset STEID_SMTP_URL and STEID_MAIL_FROM to run without email.");
58 eprintln!();
59 std::process::exit(4);
60 }
61 }
62
63 let pool = infrastructure::database::connect(&config.database_url).await?;
64
65 infrastructure::app::sweep_on_boot(&config, &pool).await;
66
67 // Both are settings that make the instance less safe and leave no other trace, so
68 // the one moment an operator is reading the output is the moment to say so. They are
69 // printed here rather than from the builder so that a test booting the router does
70 // not print them on every run.
71 if config.allow_private_webhooks {
72 eprintln!();
73 eprintln!(" !! STEID_ALLOW_PRIVATE_WEBHOOKS is on: a webhook may point inside");
74 eprintln!(" !! this machine's own network. Local development only.");
75 eprintln!();
76 }
77
78 if config.insecure_cookies {
79 eprintln!();
80 eprintln!(" !! STEID_INSECURE_COOKIES is on: the session cookie has no Secure");
81 eprintln!(" !! flag and travels unencrypted. Local development only.");
82 eprintln!();
83 }
84
85 // Taken out of the config before it reaches the builder, so the only copy the running
86 // application holds is the `SetupToken` in `SetupState` — which is redacted in
87 // `Debug` and dropped entirely once the instance is claimed.
88 let configured_token = config.setup_token.take();
89
90 // The setup token exists only while the instance is unclaimed, so a claimed
91 // installation has no token in context for a claim attempt to match against.
92 let setup = if is_claimed(&SqliteUserRepo::new(pool.clone())).await? {
93 None
94 } else {
95 Some(claim_token(configured_token.as_ref())?)
96 };
97
98 let router = infrastructure::app::build(config, pool, AssetBundle::load()?, setup)
99 .await
100 .build();
101
102 // Graceful shutdown needs no wiring: `topcoat::start` serves until Ctrl+C or
103 // SIGTERM, then stops accepting, lets in-flight requests finish within the
104 // service's shutdown timeout, and returns. A `systemctl restart` therefore does
105 // not cut a clone mid-pack.
106 topcoat::start(router).await?;
107
108 println!("steid: shut down");
109
110 Ok(())
111}
112
113/// The token an unclaimed instance is claimed with, announced as it is chosen.
114///
115/// An operator-supplied value that will not validate fails startup rather than serving a
116/// claim page guarded by a weak secret. This is the one moment they are watching the
117/// output.
118fn claim_token(
119 configured: Option<&steid::application::Secret>,
120) -> Result<SetupToken, Box<dyn std::error::Error>> {
121 match configured {
122 Some(supplied) => {
123 let token = SetupToken::from_operator(supplied.expose()).map_err(|error| {
124 eprintln!();
125 eprintln!(" !! STEID_SETUP_TOKEN is not usable: {error}");
126 eprintln!(" !! Unset it to have one generated, or supply a stronger value.");
127 eprintln!();
128 error
129 })?;
130 announce_configured_setup();
131 Ok(token)
132 }
133 None => {
134 let token = SetupToken::generate();
135 announce_setup(&token);
136 Ok(token)
137 }
138 }
139}
140
141/// Prints the claim instructions when the operator supplied the token themselves.
142///
143/// Says that a token is in force without repeating it: they already have it, and
144/// printing it would copy a secret they chose into the journal.
145fn announce_configured_setup() {
146 println!();
147 println!(" This steid has no owner yet. Claim it at /auth/setup with the token");
148 println!(" from STEID_SETUP_TOKEN.");
149 println!();
150}
151
152/// Prints the claim instructions. The only time the token is ever revealed.
153fn announce_setup(token: &SetupToken) {
154 println!();
155 println!(" This steid has no owner yet. Claim it at /auth/setup with:");
156 println!();
157 println!(" {}", token.reveal());
158 println!();
159 println!(" The token is held in memory only — restarting issues a new one.");
160 println!();
161}
162
163/// Ends the process on the result of a subcommand.
164///
165/// The message is the error's `Display`. Returning it from `main` instead would print
166/// `Box<dyn Error>`'s `Debug` — `Domain(Unavailable { entity: "instance", .. })` — at
167/// somebody who asked for a sentence.
168fn finish(outcome: Result<(), Box<dyn std::error::Error>>) -> ! {
169 match outcome {
170 Ok(()) => std::process::exit(0),
171 Err(error) => {
172 eprintln!("steid: {error}");
173 std::process::exit(1);
174 }
175 }
176}