anvilsign in

collin/anvil

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
8pub mod access;
9pub mod ci;
10pub mod config;
11pub mod db;
12pub mod error;
13pub mod models;
14pub mod repos;
15pub mod sessions;
16pub mod ssh_keys;
17pub mod storage;
18pub mod users;
19
20pub use config::Config;
21pub use error::{Error, Result};
22pub use models::{CiRun, Repository, Session, SshKey, User};
23
24/// Current Unix time in seconds, for `created_at` columns.
25pub(crate) fn now() -> i64 {
26 std::time::SystemTime::now()
27 .duration_since(std::time::UNIX_EPOCH)
28 .map(|d| d.as_secs() as i64)
29 .unwrap_or(0)
30}
31
32/// Shared application state: configuration plus a database handle.
33///
34/// Cloneable and cheap to pass around — `toasty::Db` is internally reference
35/// counted and backed by a connection pool.
36#[derive(Clone)]
37pub struct App {
38 pub config: Config,
39 pub db: toasty::Db,
40 /// Notifies the CI runner of newly-enqueued run ids. `None` until the runner
41 /// is started (e.g. CLI commands don't run CI). Use [`App::notify_ci`].
42 pub ci_tx: Option<tokio::sync::mpsc::UnboundedSender<i64>>,
43 /// Server-wide secret keying CSRF tokens. Persisted in the data dir so
44 /// tokens survive restarts. Wrapped in `Arc` to keep `App: Clone` cheap.
45 csrf_secret: std::sync::Arc<[u8; 32]>,
46}
47
48impl App {
49 /// Initialize application state from a config: ensure the data directories
50 /// exist, then open the database and create the schema.
51 pub async fn bootstrap(config: Config) -> Result<Self> {
52 std::fs::create_dir_all(&config.data_dir)?;
53 std::fs::create_dir_all(config.repositories_dir())?;
54
55 let db = db::connect(config.database_path()).await?;
56 let csrf_secret = std::sync::Arc::new(load_or_create_csrf_secret(&config.data_dir)?);
57
58 Ok(Self {
59 config,
60 db,
61 ci_tx: None,
62 csrf_secret,
63 })
64 }
65
66 /// Notify the CI runner that `run_id` is queued (no-op if no runner).
67 pub fn notify_ci(&self, run_id: i64) {
68 if let Some(tx) = &self.ci_tx {
69 let _ = tx.send(run_id);
70 }
71 }
72
73 /// The CSRF token bound to a given session token: `HMAC-SHA256(secret,
74 /// session)`, hex-encoded. Stable for a session's lifetime, unguessable
75 /// without the server secret, and requires no extra storage.
76 pub fn csrf_token(&self, session_token: &str) -> String {
77 use hmac::{Hmac, Mac};
78 let mut mac = Hmac::<sha2::Sha256>::new_from_slice(self.csrf_secret.as_slice())
79 .expect("HMAC accepts any key length");
80 mac.update(session_token.as_bytes());
81 mac.finalize()
82 .into_bytes()
83 .iter()
84 .map(|b| format!("{b:02x}"))
85 .collect()
86 }
87}
88
89/// Load the persistent CSRF secret, generating and saving it on first run.
90fn load_or_create_csrf_secret(data_dir: &std::path::Path) -> Result<[u8; 32]> {
91 use argon2::password_hash::rand_core::{OsRng, RngCore};
92
93 let path = data_dir.join("csrf_secret");
94 if path.exists() {
95 let bytes = std::fs::read(&path)?;
96 if let Ok(secret) = <[u8; 32]>::try_from(bytes.as_slice()) {
97 return Ok(secret);
98 }
99 // Malformed (truncated/extended) — regenerate rather than run weak.
100 }
101 let mut secret = [0u8; 32];
102 OsRng.fill_bytes(&mut secret);
103 std::fs::write(&path, secret)?;
104 #[cfg(unix)]
105 {
106 use std::os::unix::fs::PermissionsExt;
107 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
108 }
109 Ok(secret)
110}