steid

@jamesgill /

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