steid

@jamesgill /

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