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