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