| 1 | //! Core domain model, persistence, and on-disk repository storage for anvil. |
| 2 | //! |
| 3 | //! This crate is transport-agnostic: it knows about users, repositories, the |
| 4 | //! SQLite database, and bare git repositories on disk, but nothing about HTTP, |
| 5 | //! SSH, or the git wire protocol. Higher layers (`anvil-web`, `anvil-ssh`, |
| 6 | //! `anvil-git`) build on top of it. |
| 7 | |
| 8 | pub mod access; |
| 9 | pub mod admin_cache; |
| 10 | pub mod api_tokens; |
| 11 | pub mod attachments; |
| 12 | pub mod ci; |
| 13 | pub mod config; |
| 14 | pub mod db; |
| 15 | pub mod error; |
| 16 | pub mod issues; |
| 17 | pub mod language; |
| 18 | pub mod models; |
| 19 | pub mod passkeys; |
| 20 | pub mod periodic; |
| 21 | pub mod preview_images; |
| 22 | pub mod repos; |
| 23 | pub mod secrets; |
| 24 | pub mod sessions; |
| 25 | pub mod ssh_keys; |
| 26 | pub mod storage; |
| 27 | pub mod usage; |
| 28 | pub mod users; |
| 29 | |
| 30 | pub use config::Config; |
| 31 | pub use error::{ |
| 32 | Error, |
| 33 | Result, |
| 34 | }; |
| 35 | pub use models::{ |
| 36 | ApiToken, |
| 37 | Attachment, |
| 38 | CiArtifact, |
| 39 | CiRun, |
| 40 | Issue, |
| 41 | IssueComment, |
| 42 | Passkey, |
| 43 | RepoSecret, |
| 44 | Repository, |
| 45 | Session, |
| 46 | SshKey, |
| 47 | User, |
| 48 | }; |
| 49 | |
| 50 | /// Current Unix time in seconds, for `created_at` columns. |
| 51 | pub(crate) fn now() -> i64 { |
| 52 | std::time::SystemTime::now() |
| 53 | .duration_since(std::time::UNIX_EPOCH) |
| 54 | .map(|d| d.as_secs() as i64) |
| 55 | .unwrap_or(0) |
| 56 | } |
| 57 | |
| 58 | /// Shared application state: configuration plus a database handle. |
| 59 | /// |
| 60 | /// Cloneable and cheap to pass around — `toasty::Db` is internally reference |
| 61 | /// counted and backed by a connection pool. |
| 62 | #[derive(Clone)] |
| 63 | pub struct App { |
| 64 | pub config: Config, |
| 65 | pub db: toasty::Db, |
| 66 | /// Notifies the CI runner of newly-enqueued run ids. `None` until the runner |
| 67 | /// is started (e.g. CLI commands don't run CI). Use [`App::notify_ci`]. |
| 68 | pub ci_tx: Option<tokio::sync::mpsc::UnboundedSender<i64>>, |
| 69 | /// Plaintext repo secrets for CI, held in memory only and lost on |
| 70 | /// restart — see [`secrets::Vault`]. |
| 71 | pub vault: secrets::Vault, |
| 72 | /// WebAuthn challenges awaiting an answer — see [`passkeys::Ceremonies`]. |
| 73 | pub ceremonies: passkeys::Ceremonies, |
| 74 | /// Server-wide secret keying CSRF tokens. Persisted in the data dir so |
| 75 | /// tokens survive restarts. Wrapped in `Arc` to keep `App: Clone` cheap. |
| 76 | csrf_secret: std::sync::Arc<[u8; 32]>, |
| 77 | } |
| 78 | |
| 79 | impl App { |
| 80 | /// Initialize application state from a config: ensure the data directories |
| 81 | /// exist, then open the database and create the schema. |
| 82 | pub async fn bootstrap(config: Config) -> Result<Self> { |
| 83 | std::fs::create_dir_all(&config.data_dir)?; |
| 84 | std::fs::create_dir_all(config.repositories_dir())?; |
| 85 | |
| 86 | let db = db::connect(config.database_path()).await?; |
| 87 | let csrf_secret = std::sync::Arc::new(load_or_create_csrf_secret(&config.data_dir)?); |
| 88 | |
| 89 | Ok(Self { |
| 90 | config, |
| 91 | db, |
| 92 | ci_tx: None, |
| 93 | vault: secrets::Vault::default(), |
| 94 | ceremonies: passkeys::Ceremonies::default(), |
| 95 | csrf_secret, |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | /// Notify the CI runner that `run_id` is queued (no-op if no runner). |
| 100 | pub fn notify_ci(&self, run_id: i64) { |
| 101 | if let Some(tx) = &self.ci_tx { |
| 102 | let _ = tx.send(run_id); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// The CSRF token bound to a given session token: `HMAC-SHA256(secret, |
| 107 | /// session)`, hex-encoded. Stable for a session's lifetime, unguessable |
| 108 | /// without the server secret, and requires no extra storage. |
| 109 | pub fn csrf_token(&self, session_token: &str) -> String { |
| 110 | use hmac::{ |
| 111 | Hmac, |
| 112 | Mac, |
| 113 | }; |
| 114 | let mut mac = Hmac::<sha2::Sha256>::new_from_slice(self.csrf_secret.as_slice()) |
| 115 | .expect("HMAC accepts any key length"); |
| 116 | mac.update(session_token.as_bytes()); |
| 117 | mac.finalize() |
| 118 | .into_bytes() |
| 119 | .iter() |
| 120 | .map(|b| format!("{b:02x}")) |
| 121 | .collect() |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /// Load the persistent CSRF secret, generating and saving it on first run. |
| 126 | fn load_or_create_csrf_secret(data_dir: &std::path::Path) -> Result<[u8; 32]> { |
| 127 | use argon2::password_hash::rand_core::{ |
| 128 | OsRng, |
| 129 | RngCore, |
| 130 | }; |
| 131 | |
| 132 | let path = data_dir.join("csrf_secret"); |
| 133 | if path.exists() { |
| 134 | let bytes = std::fs::read(&path)?; |
| 135 | if let Ok(secret) = <[u8; 32]>::try_from(bytes.as_slice()) { |
| 136 | return Ok(secret); |
| 137 | } |
| 138 | // Malformed (truncated/extended) — regenerate rather than run weak. |
| 139 | } |
| 140 | let mut secret = [0u8; 32]; |
| 141 | OsRng.fill_bytes(&mut secret); |
| 142 | std::fs::write(&path, secret)?; |
| 143 | #[cfg(unix)] |
| 144 | { |
| 145 | use std::os::unix::fs::PermissionsExt; |
| 146 | let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); |
| 147 | } |
| 148 | Ok(secret) |
| 149 | } |