steid

@jamesgill /

steid/src/main.rs
Rust8.6 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, mode } => finish(run_restore(&config, &archive, mode).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 // Before the claim token is minted, because seeding an owner is what makes this
68 // instance claimed — and a claimed instance has no token to mint. An operator who
69 // asked for an owner and did not get one must not end up serving a setup page, so
70 // every way this can fail stops the boot, exactly like the mail check above. And
71 // every boot after it: the seed is checked whole before anything is written, so a
72 // refusal leaves the instance unclaimed and systemd's restart meets the same one.
73 match infrastructure::app::seed_owner_on_boot(&config, &pool).await {
74 Ok(Some(owner)) => {
75 println!(
76 "steid: owner {} <{}> created at boot; sign in with: steid reset-password {}",
77 owner.handle, owner.email, owner.handle
78 );
79 if let Some(organisation) = &owner.organisation {
80 println!(
81 "steid: organisation {} created and set as the home page",
82 organisation.handle
83 );
84 }
85 }
86 // Nothing configured, or already claimed. Both say nothing: the variables stay
87 // in the environment file for the life of the instance and must be inert.
88 Ok(None) => {}
89 Err(error) => {
90 eprintln!();
91 eprintln!(" !! the configured owner could not be created: {error}");
92 eprintln!(" !! STEID_OWNER_EMAIL and STEID_OWNER_HANDLE are read together and");
93 eprintln!(" !! must both be usable, as must STEID_OWNER_ORG where it is set.");
94 eprintln!(" !! Unset them to start unclaimed and claim at /auth/setup instead.");
95 eprintln!();
96 std::process::exit(4);
97 }
98 }
99
100 // Both are settings that make the instance less safe and leave no other trace, so
101 // the one moment an operator is reading the output is the moment to say so. They are
102 // printed here rather than from the builder so that a test booting the router does
103 // not print them on every run.
104 if config.allow_private_webhooks {
105 eprintln!();
106 eprintln!(" !! STEID_ALLOW_PRIVATE_WEBHOOKS is on: a webhook may point inside");
107 eprintln!(" !! this machine's own network. Local development only.");
108 eprintln!();
109 }
110
111 if config.insecure_cookies {
112 eprintln!();
113 eprintln!(" !! STEID_INSECURE_COOKIES is on: the session cookie has no Secure");
114 eprintln!(" !! flag and travels unencrypted. Local development only.");
115 eprintln!();
116 }
117
118 // Taken out of the config before it reaches the builder, so the only copy the running
119 // application holds is the `SetupToken` in `SetupState` — which is redacted in
120 // `Debug` and dropped entirely once the instance is claimed.
121 let configured_token = config.setup_token.take();
122
123 // The setup token exists only while the instance is unclaimed, so a claimed
124 // installation has no token in context for a claim attempt to match against.
125 let setup = if is_claimed(&SqliteUserRepo::new(pool.clone())).await? {
126 None
127 } else {
128 Some(claim_token(configured_token.as_ref())?)
129 };
130
131 let router = infrastructure::app::build(config, pool, AssetBundle::load()?, setup)
132 .await
133 .build();
134
135 // Graceful shutdown needs no wiring: `topcoat::start` serves until Ctrl+C or
136 // SIGTERM, then stops accepting, lets in-flight requests finish within the
137 // service's shutdown timeout, and returns. A `systemctl restart` therefore does
138 // not cut a clone mid-pack.
139 topcoat::start(router).await?;
140
141 println!("steid: shut down");
142
143 Ok(())
144}
145
146/// The token an unclaimed instance is claimed with, announced as it is chosen.
147///
148/// An operator-supplied value that will not validate fails startup rather than serving a
149/// claim page guarded by a weak secret. This is the one moment they are watching the
150/// output.
151fn claim_token(
152 configured: Option<&steid::application::Secret>,
153) -> Result<SetupToken, Box<dyn std::error::Error>> {
154 match configured {
155 Some(supplied) => {
156 let token = SetupToken::from_operator(supplied.expose()).map_err(|error| {
157 eprintln!();
158 eprintln!(" !! STEID_SETUP_TOKEN is not usable: {error}");
159 eprintln!(" !! Unset it to have one generated, or supply a stronger value.");
160 eprintln!();
161 error
162 })?;
163 announce_configured_setup();
164 Ok(token)
165 }
166 None => {
167 let token = SetupToken::generate();
168 announce_setup(&token);
169 Ok(token)
170 }
171 }
172}
173
174/// Prints the claim instructions when the operator supplied the token themselves.
175///
176/// Says that a token is in force without repeating it: they already have it, and
177/// printing it would copy a secret they chose into the journal.
178fn announce_configured_setup() {
179 println!();
180 println!(" This steid has no owner yet. Claim it at /auth/setup with the token");
181 println!(" from STEID_SETUP_TOKEN.");
182 println!();
183}
184
185/// Prints the claim instructions. The only time the token is ever revealed.
186fn announce_setup(token: &SetupToken) {
187 println!();
188 println!(" This steid has no owner yet. Claim it at /auth/setup with:");
189 println!();
190 println!(" {}", token.reveal());
191 println!();
192 println!(" The token is held in memory only — restarting issues a new one.");
193 println!();
194}
195
196/// Ends the process on the result of a subcommand.
197///
198/// The message is the error's `Display`. Returning it from `main` instead would print
199/// `Box<dyn Error>`'s `Debug` — `Domain(Unavailable { entity: "instance", .. })` — at
200/// somebody who asked for a sentence.
201fn finish(outcome: Result<(), Box<dyn std::error::Error>>) -> ! {
202 match outcome {
203 Ok(()) => std::process::exit(0),
204 Err(error) => {
205 eprintln!("steid: {error}");
206 std::process::exit(1);
207 }
208 }
209}