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