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}
82
83#[derive(Clone, Debug, Deserialize, Serialize)]
84#[serde(default)]
85pub struct HttpConfig {
86 /// Address the HTTP server binds to, e.g. `127.0.0.1:3000`.
87 pub listen: String,
88 /// Externally visible base URL, used when constructing clone URLs.
89 pub base_url: String,
90 /// Memory budget, in MiB, for the cache of syntax-highlighted file views
91 /// (rendered HTML keyed by blob oid). Highlighting large files is the most
92 /// CPU-expensive page render, so repeat views are served from this cache.
93 /// `0` disables it — lowest memory, every view re-highlights. Defaults
94 /// to 16.
95 pub highlight_cache_mb: usize,
96}
97
98#[derive(Clone, Debug, Deserialize, Serialize)]
99#[serde(default)]
100pub struct SshConfig {
101 /// Whether the SSH git transport is enabled.
102 pub enabled: bool,
103 /// Address the SSH server binds to internally, e.g. `0.0.0.0:2222`. Under
104 /// Docker this is the in-container bind, which may differ from the
105 /// externally forwarded port — see the `clone_*` fields below.
106 pub listen: String,
107 /// Hostname shown in SSH clone URLs (what users actually connect to).
108 pub clone_host: String,
109 /// Port shown in SSH clone URLs. Set this to the *externally forwarded*
110 /// port when it differs from the internal bind (e.g. Docker `-p 2200:2222`).
111 pub clone_port: u16,
112 /// Username shown in SSH clone URLs (conventionally `git`).
113 pub clone_user: String,
114}
115
116impl Default for Config {
117 fn default() -> Self {
118 Self {
119 data_dir: PathBuf::from("data"),
120 http: HttpConfig::default(),
121 ssh: SshConfig::default(),
122 ci: CiConfig::default(),
123 }
124 }
125}
126
127impl Default for CiConfig {
128 fn default() -> Self {
129 Self {
130 deploy_repo: String::new(),
131 deploy_webhook: String::new(),
132 deploy_secret: String::new(),
133 deploy_branch: "main".to_string(),
134 allowed_images: Vec::new(),
135 memory_mb: 2048,
136 cpus: 2.0,
137 pids_limit: 512,
138 timeout_secs: 1800,
139 network: true,
140 run_as: String::new(),
141 }
142 }
143}
144
145impl CiConfig {
146 /// Whether `owner/name` on `branch` is the configured deploy target.
147 pub fn is_deploy_target(&self, owner: &str, name: &str, branch: &str) -> bool {
148 !self.deploy_repo.is_empty()
149 && !self.deploy_webhook.is_empty()
150 && self.deploy_repo == format!("{owner}/{name}")
151 && self.deploy_branch == branch
152 }
153
154 /// Whether `image` passes [`allowed_images`](CiConfig::allowed_images).
155 /// An empty allowlist permits any image; a tagless entry permits every tag
156 /// of that image; a tagged entry permits exactly itself.
157 pub fn image_allowed(&self, image: &str) -> bool {
158 self.allowed_images.is_empty()
159 || self.allowed_images.iter().any(|allowed| {
160 image == allowed
161 || (!allowed.contains(':')
162 && image
163 .strip_prefix(allowed.as_str())
164 .is_some_and(|rest| rest.starts_with(':')))
165 })
166 }
167}
168
169impl Default for HttpConfig {
170 fn default() -> Self {
171 Self {
172 listen: "127.0.0.1:3000".to_string(),
173 base_url: "http://localhost:3000".to_string(),
174 highlight_cache_mb: 16,
175 }
176 }
177}
178
179impl Default for SshConfig {
180 fn default() -> Self {
181 Self {
182 enabled: false,
183 listen: "127.0.0.1:2222".to_string(),
184 clone_host: "localhost".to_string(),
185 clone_port: 2222,
186 clone_user: "git".to_string(),
187 }
188 }
189}
190
191impl Config {
192 /// Load configuration from a TOML file. Missing fields fall back to defaults.
193 pub fn load(path: impl AsRef<Path>) -> Result<Self> {
194 let path = path.as_ref();
195 let text = std::fs::read_to_string(path)
196 .map_err(|e| Error::Config(format!("reading {}: {e}", path.display())))?;
197 toml::from_str(&text).map_err(|e| Error::Config(format!("parsing {}: {e}", path.display())))
198 }
199
200 /// Load from `path` if it exists, otherwise return defaults.
201 pub fn load_or_default(path: impl AsRef<Path>) -> Result<Self> {
202 let path = path.as_ref();
203 if path.exists() {
204 Self::load(path)
205 } else {
206 Ok(Self::default())
207 }
208 }
209
210 /// Filesystem path to the SQLite database file.
211 pub fn database_path(&self) -> PathBuf {
212 self.data_dir.join("anvil.db")
213 }
214
215 /// Root directory under which bare repositories are stored.
216 pub fn repositories_dir(&self) -> PathBuf {
217 self.data_dir.join("repositories")
218 }
219
220 /// Whether session cookies should carry the `Secure` attribute (HTTPS-only).
221 /// Derived from the public base URL's scheme, so local plaintext dev still
222 /// works while production behind TLS gets `Secure` automatically.
223 pub fn secure_cookies(&self) -> bool {
224 self.http.base_url.starts_with("https://")
225 }
226
227 /// The HTTP clone URL for `<owner>/<name>`, e.g.
228 /// `http://localhost:3000/alice/hello.git`.
229 pub fn http_clone_url(&self, owner: &str, name: &str) -> String {
230 format!(
231 "{}/{owner}/{name}.git",
232 self.http.base_url.trim_end_matches('/')
233 )
234 }
235
236 /// The SSH clone URL for `<owner>/<name>`, using the externally advertised
237 /// host/port/user (which may differ from the internal bind under Docker).
238 /// The port is omitted when it is the SSH default (22).
239 pub fn ssh_clone_url(&self, owner: &str, name: &str) -> String {
240 let ssh = &self.ssh;
241 if ssh.clone_port == 22 {
242 format!(
243 "ssh://{}@{}/{owner}/{name}.git",
244 ssh.clone_user, ssh.clone_host
245 )
246 } else {
247 format!(
248 "ssh://{}@{}:{}/{owner}/{name}.git",
249 ssh.clone_user, ssh.clone_host, ssh.clone_port
250 )
251 }
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn image_allowlist_semantics() {
261 let mut ci = CiConfig::default();
262 assert!(ci.image_allowed("anything:latest"), "empty list allows all");
263
264 ci.allowed_images = vec!["rust".to_string(), "alpine:3.20".to_string()];
265 assert!(ci.image_allowed("rust"), "tagless entry, tagless image");
266 assert!(
267 ci.image_allowed("rust:1.95-bookworm"),
268 "tagless entry allows any tag"
269 );
270 assert!(ci.image_allowed("alpine:3.20"), "tagged entry, exact match");
271 assert!(!ci.image_allowed("alpine:3.21"), "tagged entry, other tag");
272 assert!(!ci.image_allowed("alpine"), "tagged entry, tagless image");
273 assert!(
274 !ci.image_allowed("rustlang/rust:nightly"),
275 "no prefix bleed"
276 );
277 assert!(!ci.image_allowed("rusty:latest"), "no name-prefix bleed");
278 }
279}