steid

@jamesgill /

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