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