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