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