steid

@jamesgill /

steid/src/main.rs
Rust5.3 KBCode·Blame·History·Raw
1use steid::{
2 application::{AppConfig, is_claimed, sweep_interrupted_imports},
3 domain::SetupToken,
4 infrastructure::{
5 self,
6 repository::{SqliteRepoRepo, SqliteUserRepo},
7 web::{
8 context::SetupState, rate_limit::RateLimiter, session_cookie::InsecureCookieTokenStore,
9 },
10 },
11};
12use topcoat::{
13 asset::{AssetBundle, RouterBuilderAssetExt},
14 cookie::RouterBuilderCookieExt,
15 router::{Router, RouterBuilderDiscoverExt},
16 session::{RouterBuilderSessionExt, SessionConfig},
17};
18
19#[tokio::main]
20async fn main() -> Result<(), Box<dyn std::error::Error>> {
21 dotenvy::dotenv().ok();
22
23 let mut config = AppConfig::from_env()?;
24 let pool = infrastructure::database::connect(&config.database_url).await?;
25
26 // Before a single request is served, and before anything is spawned. An import runs
27 // in a background task, so every one that was running when this process's
28 // predecessor stopped is dead and its row still says otherwise. Sweeping here is
29 // safe precisely because of the timing: there is no live import to mark as failed.
30 match sweep_interrupted_imports(&SqliteRepoRepo::new(pool.clone())).await {
31 Ok(0) => {}
32 Ok(swept) => println!("steid: {swept} interrupted import(s) marked as failed"),
33 // Not fatal. A stuck row is a repository showing the wrong panel, which is worse
34 // than this line and much better than refusing to boot.
35 Err(error) => eprintln!("steid: interrupted imports could not be swept: {error}"),
36 }
37
38 // Taken out of the config before it reaches the app context, so the only copy the
39 // running application holds is the `SetupToken` in `SetupState` — which is
40 // redacted in `Debug` and dropped entirely once the instance is claimed.
41 let configured_token = config.setup_token.take();
42
43 let mut builder = Router::builder()
44 .assets(AssetBundle::load()?)
45 .cookies()
46 .sessions(session_config(config.insecure_cookies))
47 .discover()
48 .app_context(config)
49 .app_context(pool.clone())
50 // One limiter for the process, shared by every request. Constructing it per
51 // request would count each attempt against an empty window and limit nothing.
52 .app_context(RateLimiter::default());
53
54 // The setup token exists only while the instance is unclaimed, so a claimed
55 // installation has no token in context for a claim attempt to match against.
56 if !is_claimed(&SqliteUserRepo::new(pool)).await? {
57 let token = match &configured_token {
58 // Fails startup rather than serving a claim page guarded by a weak
59 // secret. This is the one moment an operator is watching the output.
60 Some(supplied) => {
61 let token = SetupToken::from_operator(supplied.expose()).map_err(|error| {
62 eprintln!();
63 eprintln!(" !! STEID_SETUP_TOKEN is not usable: {error}");
64 eprintln!(" !! Unset it to have one generated, or supply a stronger value.");
65 eprintln!();
66 error
67 })?;
68 announce_configured_setup();
69 token
70 }
71 None => {
72 let token = SetupToken::generate();
73 announce_setup(&token);
74 token
75 }
76 };
77
78 builder = builder.app_context(SetupState(token));
79 }
80
81 // Graceful shutdown needs no wiring: `topcoat::start` serves until Ctrl+C or
82 // SIGTERM, then stops accepting, lets in-flight requests finish within the
83 // service's shutdown timeout, and returns. A `systemctl restart` therefore does
84 // not cut a clone mid-pack.
85 topcoat::start(builder.build()).await?;
86
87 println!("steid: shut down");
88
89 Ok(())
90}
91
92/// Builds the session configuration.
93///
94/// The hardened default requires a trustworthy origin for its `Secure` cookie;
95/// browsers disagree about whether plain-HTTP localhost qualifies, and where it
96/// doesn't the cookie is dropped silently and every page renders signed out.
97fn session_config(insecure_cookies: bool) -> SessionConfig {
98 if insecure_cookies {
99 eprintln!();
100 eprintln!(" !! STEID_INSECURE_COOKIES is on: the session cookie has no Secure");
101 eprintln!(" !! flag and travels unencrypted. Local development only.");
102 eprintln!();
103
104 SessionConfig::builder()
105 .token_store(InsecureCookieTokenStore::new())
106 .build()
107 } else {
108 SessionConfig::default()
109 }
110}
111
112/// Prints the claim instructions when the operator supplied the token themselves.
113///
114/// Says that a token is in force without repeating it: they already have it, and
115/// printing it would copy a secret they chose into the journal.
116fn announce_configured_setup() {
117 println!();
118 println!(" This steid has no owner yet. Claim it at /auth/setup with the token");
119 println!(" from STEID_SETUP_TOKEN.");
120 println!();
121}
122
123/// Prints the claim instructions. The only time the token is ever revealed.
124fn announce_setup(token: &SetupToken) {
125 println!();
126 println!(" This steid has no owner yet. Claim it at /auth/setup with:");
127 println!();
128 println!(" {}", token.reveal());
129 println!();
130 println!(" The token is held in memory only — restarting issues a new one.");
131 println!();
132}