anvilsign in

collin/anvil

1//! Server configuration: loaded from a TOML file with sensible defaults.
2
3use std::path::{
4 Path,
5 PathBuf,
6};
7
8use serde::{
9 Deserialize,
10 Serialize,
11};
12
13use crate::error::{
14 Error,
15 Result,
16};
17
18/// Top-level anvil configuration.
19///
20/// Load with [`Config::load`] (from a TOML file) or [`Config::default`].
21#[derive(Clone, Debug, Deserialize, Serialize)]
22#[serde(default)]
23pub struct Config {
24 /// Root directory holding all server state (database + repositories).
25 pub data_dir: PathBuf,
26 /// HTTP server settings.
27 pub http: HttpConfig,
28 /// SSH server settings.
29 pub ssh: SshConfig,
30 /// Continuous-deployment settings (the single-repo redeploy webhook).
31 pub ci: CiConfig,
32}
33
34/// CI configuration: job sandbox limits and the single-repo redeploy webhook.
35///
36/// On a successful CI run of [`deploy_branch`](CiConfig::deploy_branch) in the
37/// single repository named by [`deploy_repo`](CiConfig::deploy_repo), anvil
38/// POSTs to [`deploy_webhook`](CiConfig::deploy_webhook). This is deliberately
39/// scoped to **one** repository — no other repo can trigger the deploy, even
40/// with its own passing CI.
41#[derive(Clone, Debug, Deserialize, Serialize)]
42#[serde(default)]
43pub struct CiConfig {
44 /// The one repository (`owner/name`) permitted to trigger the deploy
45 /// webhook. Empty disables deploys entirely.
46 pub deploy_repo: String,
47 /// URL POSTed to when `deploy_repo`'s `deploy_branch` goes green. Should be
48 /// a host-local plaintext HTTP endpoint (a small deploy-script receiver);
49 /// HTTPS is intentionally unsupported to keep the build TLS-free.
50 pub deploy_webhook: String,
51 /// Shared secret sent as the `X-Anvil-Deploy-Secret` header so the receiver
52 /// can authenticate the call. Empty sends no header.
53 pub deploy_secret: String,
54 /// Branch whose successful run triggers a deploy. Defaults to `main`.
55 pub deploy_branch: String,
56 /// Images a pipeline may run in. Empty allows any image. An entry without a
57 /// tag (e.g. `rust`) allows every tag of that image; an entry with a tag
58 /// (e.g. `rust:1.95-bookworm`) allows exactly that image.
59 pub allowed_images: Vec<String>,
60 /// Memory cap for a job container, in MiB (swap is capped to the same
61 /// value). `0` means unlimited. Defaults to 2048.
62 pub memory_mb: i64,
63 /// CPU cap for a job container, in (possibly fractional) CPUs. `0` means
64 /// unlimited. Defaults to 2.
65 pub cpus: f64,
66 /// Process-count cap inside a job container. `0` means unlimited.
67 /// Defaults to 512.
68 pub pids_limit: i64,
69 /// Wall-clock timeout for a job, in seconds; on expiry the container is
70 /// force-removed and the run errors. `0` disables the timeout. Defaults to
71 /// 1800 (30 minutes).
72 pub timeout_secs: u64,
73 /// Whether job containers get network access (the default Docker network).
74 /// Most builds need it to fetch dependencies; disable for stricter
75 /// isolation. Defaults to `true`.
76 pub network: bool,
77 /// User to run the job as inside the container (`uid[:gid]` or a name known
78 /// to the image). Empty keeps the image's default user. Note many base
79 /// images assume root for e.g. `apt-get`.
80 pub run_as: String,
81 /// Size cap for a single artifact, in MiB; larger artifacts are skipped
82 /// (with a log note), never failing the run. `0` means unlimited.
83 /// Defaults to 256.
84 pub artifact_max_mb: i64,
85 /// Combined size cap for one run's artifacts, in MiB. Artifacts that would
86 /// push the run over it are skipped. `0` means unlimited. Defaults to 512.
87 pub artifact_run_max_mb: i64,
88 /// Combined artifact budget per repository, in MiB. After each run, oldest
89 /// commits' artifacts are deleted until the repo fits (branch-head commits
90 /// are pinned). `0` means unlimited. Defaults to 4096.
91 pub artifact_quota_mb: i64,
92}
93
94#[derive(Clone, Debug, Deserialize, Serialize)]
95#[serde(default)]
96pub struct HttpConfig {
97 /// Address the HTTP server binds to, e.g. `127.0.0.1:3000`.
98 pub listen: String,
99 /// Externally visible base URL, used when constructing clone URLs.
100 pub base_url: String,
101 /// Memory budget, in MiB, for the cache of syntax-highlighted file views
102 /// (rendered HTML keyed by blob oid). Highlighting large files is the most
103 /// CPU-expensive page render, so repeat views are served from this cache.
104 /// `0` disables it — lowest memory, every view re-highlights. Defaults
105 /// to 16.
106 pub highlight_cache_mb: usize,
107 /// Maximum size, in MiB, of a single uploaded attachment (e.g. an image
108 /// pasted into the file editor). Uploads over this are rejected. Defaults
109 /// to 16.
110 pub attachment_max_mb: usize,
111 /// Per-repository cap, in MiB, on total stored attachments. A new upload
112 /// that would push a repo over this is rejected (re-uploading existing,
113 /// deduped content is always free). `0` means unlimited. Defaults to 0.
114 pub attachment_quota_mb: usize,
115}
116
117#[derive(Clone, Debug, Deserialize, Serialize)]
118#[serde(default)]
119pub struct SshConfig {
120 /// Whether the SSH git transport is enabled.
121 pub enabled: bool,
122 /// Address the SSH server binds to internally, e.g. `0.0.0.0:2222`. Under
123 /// Docker this is the in-container bind, which may differ from the
124 /// externally forwarded port — see the `clone_*` fields below.
125 pub listen: String,
126 /// Hostname shown in SSH clone URLs (what users actually connect to).
127 pub clone_host: String,
128 /// Port shown in SSH clone URLs. Set this to the *externally forwarded*
129 /// port when it differs from the internal bind (e.g. Docker `-p 2200:2222`).
130 pub clone_port: u16,
131 /// Username shown in SSH clone URLs (conventionally `git`).
132 pub clone_user: String,
133}
134
135impl Default for Config {
136 fn default() -> Self {
137 Self {
138 data_dir: PathBuf::from("data"),
139 http: HttpConfig::default(),
140 ssh: SshConfig::default(),
141 ci: CiConfig::default(),
142 }
143 }
144}
145
146impl Default for CiConfig {
147 fn default() -> Self {
148 Self {
149 deploy_repo: String::new(),
150 deploy_webhook: String::new(),
151 deploy_secret: String::new(),
152 deploy_branch: "main".to_string(),
153 allowed_images: Vec::new(),
154 memory_mb: 2048,
155 cpus: 2.0,
156 pids_limit: 512,
157 timeout_secs: 1800,
158 network: true,
159 run_as: String::new(),
160 artifact_max_mb: 256,
161 artifact_run_max_mb: 512,
162 artifact_quota_mb: 4096,
163 }
164 }
165}
166
167impl CiConfig {
168 /// Whether `owner/name` on `branch` is the configured deploy target.
169 pub fn is_deploy_target(&self, owner: &str, name: &str, branch: &str) -> bool {
170 !self.deploy_repo.is_empty()
171 && !self.deploy_webhook.is_empty()
172 && self.deploy_repo == format!("{owner}/{name}")
173 && self.deploy_branch == branch
174 }
175
176 /// Whether `image` passes [`allowed_images`](CiConfig::allowed_images).
177 /// An empty allowlist permits any image; a tagless entry permits every tag
178 /// of that image; a tagged entry permits exactly itself.
179 pub fn image_allowed(&self, image: &str) -> bool {
180 self.allowed_images.is_empty()
181 || self.allowed_images.iter().any(|allowed| {
182 image == allowed
183 || (!allowed.contains(':')
184 && image
185 .strip_prefix(allowed.as_str())
186 .is_some_and(|rest| rest.starts_with(':')))
187 })
188 }
189}
190
191impl Default for HttpConfig {
192 fn default() -> Self {
193 Self {
194 listen: "127.0.0.1:3000".to_string(),
195 base_url: "http://localhost:3000".to_string(),
196 highlight_cache_mb: 16,
197 attachment_max_mb: 16,
198 attachment_quota_mb: 0,
199 }
200 }
201}
202
203impl Default for SshConfig {
204 fn default() -> Self {
205 Self {
206 enabled: false,
207 listen: "127.0.0.1:2222".to_string(),
208 clone_host: "localhost".to_string(),
209 clone_port: 2222,
210 clone_user: "git".to_string(),
211 }
212 }
213}
214
215impl Config {
216 /// Load configuration from a TOML file. Missing fields fall back to defaults.
217 pub fn load(path: impl AsRef<Path>) -> Result<Self> {
218 let path = path.as_ref();
219 let text = std::fs::read_to_string(path)
220 .map_err(|e| Error::Config(format!("reading {}: {e}", path.display())))?;
221 toml::from_str(&text).map_err(|e| Error::Config(format!("parsing {}: {e}", path.display())))
222 }
223
224 /// Load from `path` if it exists, otherwise return defaults.
225 pub fn load_or_default(path: impl AsRef<Path>) -> Result<Self> {
226 let path = path.as_ref();
227 if path.exists() {
228 Self::load(path)
229 } else {
230 Ok(Self::default())
231 }
232 }
233
234 /// Filesystem path to the SQLite database file.
235 pub fn database_path(&self) -> PathBuf {
236 self.data_dir.join("anvil.db")
237 }
238
239 /// Root directory under which bare repositories are stored.
240 pub fn repositories_dir(&self) -> PathBuf {
241 self.data_dir.join("repositories")
242 }
243
244 /// Root directory under which CI artifacts are stored
245 /// (`artifacts/{repo_id}/{commit}/…` — see `docs/ci-artifacts.md`).
246 pub fn artifacts_dir(&self) -> PathBuf {
247 self.data_dir.join("artifacts")
248 }
249
250 /// Root directory under which uploaded attachments are stored
251 /// (`attachments/{repo_id}/{hash}`). Kept out of `repositories/` so the
252 /// files are never git objects.
253 pub fn attachments_dir(&self) -> PathBuf {
254 self.data_dir.join("attachments")
255 }
256
257 /// Whether session cookies should carry the `Secure` attribute (HTTPS-only).
258 /// Derived from the public base URL's scheme, so local plaintext dev still
259 /// works while production behind TLS gets `Secure` automatically.
260 pub fn secure_cookies(&self) -> bool {
261 self.http.base_url.starts_with("https://")
262 }
263
264 /// The HTTP clone URL for `<owner>/<name>`, e.g.
265 /// `http://localhost:3000/alice/hello.git`.
266 pub fn http_clone_url(&self, owner: &str, name: &str) -> String {
267 format!(
268 "{}/{owner}/{name}.git",
269 self.http.base_url.trim_end_matches('/')
270 )
271 }
272
273 /// The SSH clone URL for `<owner>/<name>`, using the externally advertised
274 /// host/port/user (which may differ from the internal bind under Docker).
275 /// The port is omitted when it is the SSH default (22).
276 pub fn ssh_clone_url(&self, owner: &str, name: &str) -> String {
277 let ssh = &self.ssh;
278 if ssh.clone_port == 22 {
279 format!(
280 "ssh://{}@{}/{owner}/{name}.git",
281 ssh.clone_user, ssh.clone_host
282 )
283 } else {
284 format!(
285 "ssh://{}@{}:{}/{owner}/{name}.git",
286 ssh.clone_user, ssh.clone_host, ssh.clone_port
287 )
288 }
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 #[test]
297 fn image_allowlist_semantics() {
298 let mut ci = CiConfig::default();
299 assert!(ci.image_allowed("anything:latest"), "empty list allows all");
300
301 ci.allowed_images = vec!["rust".to_string(), "alpine:3.20".to_string()];
302 assert!(ci.image_allowed("rust"), "tagless entry, tagless image");
303 assert!(
304 ci.image_allowed("rust:1.95-bookworm"),
305 "tagless entry allows any tag"
306 );
307 assert!(ci.image_allowed("alpine:3.20"), "tagged entry, exact match");
308 assert!(!ci.image_allowed("alpine:3.21"), "tagged entry, other tag");
309 assert!(!ci.image_allowed("alpine"), "tagged entry, tagless image");
310 assert!(
311 !ci.image_allowed("rustlang/rust:nightly"),
312 "no prefix bleed"
313 );
314 assert!(!ci.image_allowed("rusty:latest"), "no name-prefix bleed");
315 }
316}