| 1 | use steid::{ |
| 2 | application::{ |
| 3 | AppConfig, is_claimed, port::GitStorage, sweep_interrupted_imports, |
| 4 | sweep_orphan_directories, |
| 5 | }, |
| 6 | domain::SetupToken, |
| 7 | infrastructure::{ |
| 8 | self, |
| 9 | cat_file::CatFilePool, |
| 10 | git::{DiskGitStorage, GitFeatures}, |
| 11 | repository::{SqliteOrgRepo, SqliteRepoRepo, SqliteUserRepo}, |
| 12 | web::{ |
| 13 | context::SetupState, |
| 14 | import::ImportQueue, |
| 15 | rate_limit::{ArchiveLimiter, GitAuthLimiter, RateLimiter}, |
| 16 | session_cookie::InsecureCookieTokenStore, |
| 17 | }, |
| 18 | }, |
| 19 | }; |
| 20 | use topcoat::{ |
| 21 | asset::{AssetBundle, RouterBuilderAssetExt}, |
| 22 | cookie::RouterBuilderCookieExt, |
| 23 | router::{Router, RouterBuilderDiscoverExt}, |
| 24 | session::{RouterBuilderSessionExt, SessionConfig}, |
| 25 | }; |
| 26 | |
| 27 | #[tokio::main] |
| 28 | async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 29 | dotenvy::dotenv().ok(); |
| 30 | |
| 31 | let mut config = AppConfig::from_env()?; |
| 32 | let pool = infrastructure::database::connect(&config.database_url).await?; |
| 33 | |
| 34 | // Before a single request is served, and before anything is spawned. An import runs |
| 35 | // in a background task, so every one that was running when this process's |
| 36 | // predecessor stopped is dead and its row still says otherwise. Sweeping here is |
| 37 | // safe precisely because of the timing: there is no live import to mark as failed. |
| 38 | match sweep_interrupted_imports(&SqliteRepoRepo::new(pool.clone())).await { |
| 39 | Ok(0) => {} |
| 40 | Ok(swept) => println!("steid: {swept} interrupted import(s) marked as failed"), |
| 41 | // Not fatal. A stuck row is a repository showing the wrong panel, which is worse |
| 42 | // than this line and much better than refusing to boot. |
| 43 | Err(error) => eprintln!("steid: interrupted imports could not be swept: {error}"), |
| 44 | } |
| 45 | |
| 46 | // Beside the import sweep, and for the same kind of reason: a fact that lives outside |
| 47 | // the database and cannot be fixed by a migration. `git init --bare` leaves |
| 48 | // `core.logAllRefUpdates` off, so every repository created before Steid started |
| 49 | // setting it keeps no reflog, and the pusher it is served with has nowhere to land. |
| 50 | // |
| 51 | // Runs on **every** boot, which is cheap because it reads before it writes: one |
| 52 | // short-lived `git config --get` per repository on disk, and a write only for one |
| 53 | // that lacks the key. A hundred repositories is a hundred local file reads once at |
| 54 | // startup, so tracking "already swept" somewhere would cost more to get right than it |
| 55 | // saves. |
| 56 | match DiskGitStorage::new(config.data_dir.clone()) |
| 57 | .enable_reflogs() |
| 58 | .await |
| 59 | { |
| 60 | Ok(0) => {} |
| 61 | Ok(fixed) => println!("steid: reflog enabled on {fixed} bare repository/repositories"), |
| 62 | // Not fatal, exactly like the import sweep: a repository this could not fix is |
| 63 | // one whose pushes stay anonymous, which is not a reason to refuse to serve. |
| 64 | Err(error) => eprintln!("steid: reflogs could not be swept: {error}"), |
| 65 | } |
| 66 | |
| 67 | // Third of the boot sweeps, and the one that reconciles the two halves of a |
| 68 | // repository: a row and a directory cannot share a transaction, so a create, a rename |
| 69 | // or an import that died between them leaves a directory nothing claims. It is |
| 70 | // invisible until somebody tries to re-use the name, at which point `init_bare` |
| 71 | // refuses to adopt it and the refusal names nothing useful. |
| 72 | // |
| 73 | // **After** the import sweep, deliberately: that one only fails rows and leaves them |
| 74 | // in place, so an interrupted import's directory still has a row and is not an orphan. |
| 75 | // And before the first request, like the others, so nothing is half-written by a task |
| 76 | // that is still running. |
| 77 | match sweep_orphan_directories( |
| 78 | std::time::SystemTime::now(), |
| 79 | &SqliteOrgRepo::new(pool.clone()), |
| 80 | &SqliteRepoRepo::new(pool.clone()), |
| 81 | &DiskGitStorage::new(config.data_dir.clone()), |
| 82 | ) |
| 83 | .await |
| 84 | { |
| 85 | // Each one it moved has already logged its own path, which is the point: an |
| 86 | // orphan left no other trace. |
| 87 | Ok(_) => {} |
| 88 | // Not fatal, like the other two. A directory that could not be moved is a name |
| 89 | // that stays blocked, which is where it already was. |
| 90 | Err(error) => { |
| 91 | eprintln!("steid: orphaned repository directories could not be swept: {error}") |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Said at boot for the same reason `STEID_INSECURE_COOKIES` is: it is a setting that |
| 96 | // makes the instance less safe and leaves no other trace, so the one moment an |
| 97 | // operator is reading the output is the moment to say so. |
| 98 | if config.allow_private_webhooks { |
| 99 | eprintln!(); |
| 100 | eprintln!(" !! STEID_ALLOW_PRIVATE_WEBHOOKS is on: a webhook may point inside"); |
| 101 | eprintln!(" !! this machine's own network. Local development only."); |
| 102 | eprintln!(); |
| 103 | } |
| 104 | |
| 105 | // Taken out of the config before it reaches the app context, so the only copy the |
| 106 | // running application holds is the `SetupToken` in `SetupState` — which is |
| 107 | // redacted in `Debug` and dropped entirely once the instance is claimed. |
| 108 | let configured_token = config.setup_token.take(); |
| 109 | |
| 110 | let mut builder = Router::builder() |
| 111 | .assets(AssetBundle::load()?) |
| 112 | .cookies() |
| 113 | .sessions(session_config(config.insecure_cookies)) |
| 114 | .discover() |
| 115 | .app_context(config) |
| 116 | .app_context(pool.clone()) |
| 117 | // One limiter for the process, shared by every request. Constructing it per |
| 118 | // request would count each attempt against an empty window and limit nothing. |
| 119 | .app_context(RateLimiter::default()) |
| 120 | // A budget of its own for the git transport's Basic auth, so a clone cannot |
| 121 | // spend a person's sign-in allowance and a flood of clones cannot lock them |
| 122 | // out of the login form. |
| 123 | .app_context(GitAuthLimiter::default()) |
| 124 | // And one for archive downloads, the most expensive anonymous request there is. |
| 125 | .app_context(ArchiveLimiter::default()) |
| 126 | // Likewise one queue: a semaphore constructed per request would let every |
| 127 | // submission through and cap nothing. |
| 128 | .app_context(ImportQueue::default()) |
| 129 | // And one pool of `git cat-file` processes for the whole instance. This is the |
| 130 | // composition-root decision the Milestone 5 amendment to 0006 said had to be |
| 131 | // made before the first batch adapter existed: built per request, the pool |
| 132 | // would spawn and kill a pair of processes per request and pool nothing. |
| 133 | .app_context(std::sync::Arc::new(CatFilePool::new())) |
| 134 | // And one highlight cache, for the same reason: highlighting is tens of |
| 135 | // milliseconds of regex over a large file, and a cache built per request would |
| 136 | // remember nothing. `highlight::cache()` owns it so that the README renderer — |
| 137 | // a plain function with no request context — reaches the same one this puts in |
| 138 | // app context, rather than a second cache with its own budget. |
| 139 | .app_context(infrastructure::highlight::cache().clone()) |
| 140 | // And one merge cache. A pull request's page asks `git merge-tree` whether its |
| 141 | // branches still merge on every view, and `--write-tree` writes objects nothing |
| 142 | // references — so an unchanged pair of branches was paying a full three-way |
| 143 | // merge, and leaving a fresh set of garbage behind, per refresh. |
| 144 | .app_context(std::sync::Arc::new( |
| 145 | infrastructure::merge_cache::MergeCache::new(), |
| 146 | )) |
| 147 | // One `git --version`, once. Merging a pull request needs `git merge-tree |
| 148 | // --write-tree`, which arrived in git 2.38 — and before that the subcommand |
| 149 | // meant something else entirely, so an old git succeeds at the wrong thing |
| 150 | // rather than failing. Read here so the merge box can be absent rather than |
| 151 | // broken: a check that only fired at merge time is a check nobody sees until |
| 152 | // they have already written the pull request. |
| 153 | .app_context(GitFeatures::detect().await); |
| 154 | |
| 155 | // The setup token exists only while the instance is unclaimed, so a claimed |
| 156 | // installation has no token in context for a claim attempt to match against. |
| 157 | if !is_claimed(&SqliteUserRepo::new(pool)).await? { |
| 158 | let token = match &configured_token { |
| 159 | // Fails startup rather than serving a claim page guarded by a weak |
| 160 | // secret. This is the one moment an operator is watching the output. |
| 161 | Some(supplied) => { |
| 162 | let token = SetupToken::from_operator(supplied.expose()).map_err(|error| { |
| 163 | eprintln!(); |
| 164 | eprintln!(" !! STEID_SETUP_TOKEN is not usable: {error}"); |
| 165 | eprintln!(" !! Unset it to have one generated, or supply a stronger value."); |
| 166 | eprintln!(); |
| 167 | error |
| 168 | })?; |
| 169 | announce_configured_setup(); |
| 170 | token |
| 171 | } |
| 172 | None => { |
| 173 | let token = SetupToken::generate(); |
| 174 | announce_setup(&token); |
| 175 | token |
| 176 | } |
| 177 | }; |
| 178 | |
| 179 | builder = builder.app_context(SetupState(token)); |
| 180 | } |
| 181 | |
| 182 | // Graceful shutdown needs no wiring: `topcoat::start` serves until Ctrl+C or |
| 183 | // SIGTERM, then stops accepting, lets in-flight requests finish within the |
| 184 | // service's shutdown timeout, and returns. A `systemctl restart` therefore does |
| 185 | // not cut a clone mid-pack. |
| 186 | topcoat::start(builder.build()).await?; |
| 187 | |
| 188 | println!("steid: shut down"); |
| 189 | |
| 190 | Ok(()) |
| 191 | } |
| 192 | |
| 193 | /// Builds the session configuration. |
| 194 | /// |
| 195 | /// The hardened default requires a trustworthy origin for its `Secure` cookie; |
| 196 | /// browsers disagree about whether plain-HTTP localhost qualifies, and where it |
| 197 | /// doesn't the cookie is dropped silently and every page renders signed out. |
| 198 | fn session_config(insecure_cookies: bool) -> SessionConfig { |
| 199 | if insecure_cookies { |
| 200 | eprintln!(); |
| 201 | eprintln!(" !! STEID_INSECURE_COOKIES is on: the session cookie has no Secure"); |
| 202 | eprintln!(" !! flag and travels unencrypted. Local development only."); |
| 203 | eprintln!(); |
| 204 | |
| 205 | SessionConfig::builder() |
| 206 | .token_store(InsecureCookieTokenStore::new()) |
| 207 | .build() |
| 208 | } else { |
| 209 | SessionConfig::default() |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// Prints the claim instructions when the operator supplied the token themselves. |
| 214 | /// |
| 215 | /// Says that a token is in force without repeating it: they already have it, and |
| 216 | /// printing it would copy a secret they chose into the journal. |
| 217 | fn announce_configured_setup() { |
| 218 | println!(); |
| 219 | println!(" This steid has no owner yet. Claim it at /auth/setup with the token"); |
| 220 | println!(" from STEID_SETUP_TOKEN."); |
| 221 | println!(); |
| 222 | } |
| 223 | |
| 224 | /// Prints the claim instructions. The only time the token is ever revealed. |
| 225 | fn announce_setup(token: &SetupToken) { |
| 226 | println!(); |
| 227 | println!(" This steid has no owner yet. Claim it at /auth/setup with:"); |
| 228 | println!(); |
| 229 | println!(" {}", token.reveal()); |
| 230 | println!(); |
| 231 | println!(" The token is held in memory only — restarting issues a new one."); |
| 232 | println!(); |
| 233 | } |