steid

@jamesgill /

1//! The composition root: every dependency the running application has, wired once.
2//!
3//! It lived in `main.rs` until 2026-09-10, which meant it lived outside the library and
4//! nothing could boot the application but the binary. That is why fifteen HTTP-level
5//! facts — the security headers on a 404, the CSRF 403, `/metrics` answering 404 rather
6//! than 401 — were only ever asserted by hand in a browser. [`build`] is the whole of
7//! the fix: it returns the same builder `main` used to assemble inline, so a test can
8//! serve it on `127.0.0.1:0` and ask real questions of it. See `tests/http.rs`.
9//!
10//! **The `app_context` chain is append-only.** Everything a request can reach is on it,
11//! in one place, and the order does not matter — so a new dependency goes on the end
12//! with the sentence explaining why it is process-wide rather than per-request, and
13//! nothing above it moves.
14
15use sqlx::SqlitePool;
16use topcoat::{
17 asset::{AssetBundle, RouterBuilderAssetExt},
18 cookie::RouterBuilderCookieExt,
19 router::{Router, RouterBuilder, RouterBuilderDiscoverExt},
20 session::{RouterBuilderSessionExt, SessionConfig},
21};
22
23use crate::{
24 application::{
25 AppConfig, OwnerSeed, is_claimed, port::GitStorage, seed_owner, sweep_interrupted_imports,
26 sweep_orphan_directories,
27 },
28 domain::SetupToken,
29 infrastructure::{
30 self,
31 cat_file::CatFilePool,
32 git::{DiskGitStorage, GitFeatures},
33 password::Argon2Hasher,
34 repository::{SqliteMembershipRepo, SqliteOrgRepo, SqliteRepoRepo, SqliteUserRepo},
35 web::{
36 context::SetupState,
37 csrf::CsrfSecret,
38 import::ImportQueue,
39 instance::StartedAt,
40 rate_limit::{
41 ArchiveLimiter, BackupLimiter, GitAuthLimiter, InstanceLimiter, MetricsLimiter,
42 RateLimiter, ResetLimiter, SearchLimiter,
43 },
44 session_cookie::InsecureCookieTokenStore,
45 },
46 },
47};
48
49/// Assembles the router: routes discovered, assets served, and every process-wide
50/// value a handler can ask its `Cx` for.
51///
52/// `setup` is the claim token, and `Some` only while the instance is unclaimed — a
53/// claimed installation has no token in context for a claim attempt to match against.
54/// The decision of *which* token (generated, or the operator's) and the announcement
55/// that goes with it belong to the caller, because they are the only things here that
56/// print.
57///
58/// Returns the builder rather than a [`Router`] so a caller may append one more
59/// `app_context` — a test's clock, say — without this growing a parameter for it.
60pub async fn build(
61 mut config: AppConfig,
62 pool: SqlitePool,
63 assets: AssetBundle,
64 setup: Option<SetupToken>,
65) -> RouterBuilder {
66 // Defensively, and not only because `main` already took it: the only copy of the
67 // claim secret the running application holds must be the `SetupToken` in
68 // `SetupState`, which is redacted in `Debug` and absent entirely once claimed. The
69 // config goes into app context whole, one `dbg!` away from standard error.
70 config.setup_token = None;
71
72 let insecure_cookies = config.insecure_cookies;
73
74 let mut builder = Router::builder()
75 .assets(assets)
76 .cookies()
77 .sessions(session_config(insecure_cookies))
78 .discover()
79 .app_context(config)
80 .app_context(pool)
81 // One limiter for the process, shared by every request. Constructing it per
82 // request would count each attempt against an empty window and limit nothing.
83 .app_context(RateLimiter::default())
84 // A budget of its own for the git transport's Basic auth, so a clone cannot
85 // spend a person's sign-in allowance and a flood of clones cannot lock them
86 // out of the login form.
87 .app_context(GitAuthLimiter::default())
88 // And one for archive downloads, the most expensive anonymous request there is.
89 .app_context(ArchiveLimiter::default())
90 // And one for the unauthenticated `/api/instance` poll, so a provisioner
91 // watching a machine boot cannot spend the owner's sign-in allowance.
92 .app_context(InstanceLimiter::default())
93 // When this process started. Read per request it would report zero every time,
94 // which is why the operator surface's uptime is fixed here at the composition
95 // root rather than anywhere nearer the route.
96 .app_context(StartedAt::now())
97 // And one bounding how fast the operator token can be guessed at `/metrics`. Only
98 // requests that failed the bearer check count against it, so a flood cannot starve
99 // an authorized scraper.
100 .app_context(MetricsLimiter::default())
101 // And one for instance backups, which are more expensive again — a full copy of
102 // the database plus every repository — on their own hourly window.
103 .app_context(BackupLimiter::default())
104 // And one for `/auth/reset/{token}`, which is a page a person reloads: sharing
105 // the sign-in budget meant a few loads of a mailed link locked them out of the
106 // login form.
107 .app_context(ResetLimiter::default())
108 // And one for code search: one open-ended `git grep` per request, on its own
109 // budget so a crawler walking `?q=` cannot spend anyone's sign-in allowance.
110 .app_context(SearchLimiter::default())
111 // Likewise one queue: a semaphore constructed per request would let every
112 // submission through and cap nothing.
113 .app_context(ImportQueue::default())
114 // And one pool of `git cat-file` processes for the whole instance. This is the
115 // composition-root decision the Milestone 5 amendment to 0006 said had to be
116 // made before the first batch adapter existed: built per request, the pool
117 // would spawn and kill a pair of processes per request and pool nothing.
118 .app_context(std::sync::Arc::new(CatFilePool::new()))
119 // And one highlight cache, for the same reason: highlighting is tens of
120 // milliseconds of regex over a large file, and a cache built per request would
121 // remember nothing. `highlight::cache()` owns it so that the README renderer —
122 // a plain function with no request context — reaches the same one this puts in
123 // app context, rather than a second cache with its own budget.
124 .app_context(infrastructure::highlight::cache().clone())
125 // And one merge cache. A pull request's page asks `git merge-tree` whether its
126 // branches still merge on every view, and `--write-tree` writes objects nothing
127 // references — so an unchanged pair of branches was paying a full three-way
128 // merge, and leaving a fresh set of garbage behind, per refresh.
129 .app_context(std::sync::Arc::new(
130 infrastructure::merge_cache::MergeCache::new(),
131 ))
132 // And the counters, which every adapter already reaches through
133 // `metrics::metrics()`. This is the same `Arc`, put where `/metrics` can read it:
134 // the route asks its `Cx` like every other route rather than reaching for a
135 // process-wide value, so nothing but the module itself knows the global exists.
136 .app_context(infrastructure::metrics::metrics().clone())
137 // One `git --version`, once. Merging a pull request needs `git merge-tree
138 // --write-tree`, which arrived in git 2.38 — and before that the subcommand
139 // meant something else entirely, so an old git succeeds at the wrong thing
140 // rather than failing. Read here so the merge box can be absent rather than
141 // broken: a check that only fired at merge time is a check nobody sees until
142 // they have already written the pull request.
143 .app_context(GitFeatures::detect().await)
144 // And one CSRF secret, minted here for the life of the process. Built per
145 // request it would mint a different token on every page and verify nothing;
146 // there is no configured session secret to derive it from, so a restart
147 // invalidates whatever forms are already open. See `web::csrf`.
148 .app_context(CsrfSecret::generate());
149
150 if let Some(token) = setup {
151 builder = builder.app_context(SetupState(token));
152 }
153
154 builder
155}
156
157/// The three boot sweeps: run once, before a single request is served.
158///
159/// Together they reconcile facts that live outside the database's transactions — a row
160/// that outlived the task writing it, a repository created before Steid set a git
161/// option, a directory nothing claims. Each one is **not fatal**: a sweep that fails
162/// says so and boot continues, because every failure it can have is a worse page rather
163/// than a reason to refuse to serve.
164///
165/// It prints, which nothing else in this module does — but only when it actually did
166/// something, and it is `main` that calls it. [`build`] stays silent so a test that
167/// boots the router does not have to.
168pub async fn sweep_on_boot(config: &AppConfig, pool: &SqlitePool) {
169 // Before a single request is served, and before anything is spawned. An import runs
170 // in a background task, so every one that was running when this process's
171 // predecessor stopped is dead and its row still says otherwise. Sweeping here is
172 // safe precisely because of the timing: there is no live import to mark as failed.
173 match sweep_interrupted_imports(&SqliteRepoRepo::new(pool.clone())).await {
174 Ok(0) => {}
175 Ok(swept) => println!("steid: {swept} interrupted import(s) marked as failed"),
176 // Not fatal. A stuck row is a repository showing the wrong panel, which is worse
177 // than this line and much better than refusing to boot.
178 Err(error) => eprintln!("steid: interrupted imports could not be swept: {error}"),
179 }
180
181 // Beside the import sweep, and for the same kind of reason: a fact that lives outside
182 // the database and cannot be fixed by a migration. `git init --bare` leaves
183 // `core.logAllRefUpdates` off, so every repository created before Steid started
184 // setting it keeps no reflog, and the pusher it is served with has nowhere to land.
185 //
186 // Runs on **every** boot, which is cheap because it reads before it writes: one
187 // short-lived `git config --get` per repository on disk, and a write only for one
188 // that lacks the key. A hundred repositories is a hundred local file reads once at
189 // startup, so tracking "already swept" somewhere would cost more to get right than it
190 // saves.
191 match DiskGitStorage::new(config.data_dir.clone())
192 .enable_reflogs()
193 .await
194 {
195 Ok(0) => {}
196 Ok(fixed) => println!("steid: reflog enabled on {fixed} bare repository/repositories"),
197 // Not fatal, exactly like the import sweep: a repository this could not fix is
198 // one whose pushes stay anonymous, which is not a reason to refuse to serve.
199 Err(error) => eprintln!("steid: reflogs could not be swept: {error}"),
200 }
201
202 // Third of the boot sweeps, and the one that reconciles the two halves of a
203 // repository: a row and a directory cannot share a transaction, so a create, a rename
204 // or an import that died between them leaves a directory nothing claims. It is
205 // invisible until somebody tries to re-use the name, at which point `init_bare`
206 // refuses to adopt it and the refusal names nothing useful.
207 //
208 // **After** the import sweep, deliberately: that one only fails rows and leaves them
209 // in place, so an interrupted import's directory still has a row and is not an orphan.
210 // And before the first request, like the others, so nothing is half-written by a task
211 // that is still running.
212 match sweep_orphan_directories(
213 std::time::SystemTime::now(),
214 &SqliteOrgRepo::new(pool.clone()),
215 &SqliteRepoRepo::new(pool.clone()),
216 &DiskGitStorage::new(config.data_dir.clone()),
217 )
218 .await
219 {
220 // Each one it moved has already logged its own path, which is the point: an
221 // orphan left no other trace.
222 Ok(_) => {}
223 // Not fatal, like the other two. A directory that could not be moved is a name
224 // that stays blocked, which is where it already was.
225 Err(error) => {
226 eprintln!("steid: orphaned repository directories could not be swept: {error}")
227 }
228 }
229}
230
231/// Creates the configured owner, if this instance is unclaimed and one was configured.
232///
233/// The boot-time half of the claim: `STEID_OWNER_EMAIL` and `STEID_OWNER_HANDLE` make a
234/// scripted install come up **already owned**, so it is never an unclaimed instance with
235/// a setup page on the public internet. Returns the owner it created, for the caller to
236/// announce — `Ok(None)` covers both "nothing was configured" and "already claimed", the
237/// two cases that must say nothing at all.
238///
239/// **Silent on a claimed instance**, deliberately: the variables stay in the environment
240/// file across every restart and upgrade, and re-reading them must be inert exactly the
241/// way the setup token is once an owner exists. The refusal inside
242/// [`seed_owner`](crate::application::seed_owner) still stands behind this; it is the
243/// invariant, and this is the boot policy.
244///
245/// It lives here, beside [`build`] and [`sweep_on_boot`], rather than in `main`, for the
246/// reason the rest of this module exists: `tests/http.rs` can reach it and boot a
247/// claimed instance the same way the binary does.
248///
249/// # Errors
250///
251/// Half a configured owner, a reserved or malformed handle, a malformed email, or
252/// storage failing. Every one of them should stop the boot: an instance that was meant
253/// to be owned and is not is the state this exists to prevent.
254pub async fn seed_owner_on_boot(
255 config: &AppConfig,
256 pool: &SqlitePool,
257) -> Result<Option<OwnerSeed>, crate::application::Error> {
258 let Some(seed) = config.owner_seed()? else {
259 return Ok(None);
260 };
261
262 let users = SqliteUserRepo::new(pool.clone());
263 if is_claimed(&users).await? {
264 return Ok(None);
265 }
266
267 seed_owner(
268 &seed,
269 &users,
270 &SqliteOrgRepo::new(pool.clone()),
271 &SqliteMembershipRepo::new(pool.clone()),
272 &Argon2Hasher::new(),
273 )
274 .await?;
275
276 Ok(Some(seed))
277}
278
279/// Builds the session configuration.
280///
281/// The hardened default requires a trustworthy origin for its `Secure` cookie;
282/// browsers disagree about whether plain-HTTP localhost qualifies, and where it
283/// doesn't the cookie is dropped silently and every page renders signed out.
284///
285/// Says nothing: the warning that goes with the insecure store is `main`'s, printed
286/// beside the other boot-time warnings rather than from inside the builder — a test
287/// booting this on localhost would otherwise print it on every run.
288fn session_config(insecure_cookies: bool) -> SessionConfig {
289 if insecure_cookies {
290 SessionConfig::builder()
291 .token_store(InsecureCookieTokenStore::new())
292 .build()
293 } else {
294 SessionConfig::default()
295 }
296}