anvilsign in

collin/anvil

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