Skip to main content

capsula_config/
lib.rs

1use capsula_core::error::CapsulaError;
2use serde::{Deserialize, Deserializer};
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use thiserror::Error;
6use tracing::debug;
7
8#[derive(Error, Debug)]
9pub enum ConfigError {
10    #[error("Failed to parse TOML: {0}")]
11    TomlParse(#[from] toml::de::Error),
12
13    #[error("Configuration file not found: {path}")]
14    FileNotFound { path: PathBuf },
15
16    #[error("Invalid configuration: {message}")]
17    Invalid { message: String },
18
19    #[error("IO error: {0}")]
20    Io(#[from] std::io::Error),
21}
22
23pub type ConfigResult<T> = Result<T, ConfigError>;
24
25/// Convert `ConfigError` to `CapsulaError` for cross-crate compatibility
26impl From<ConfigError> for CapsulaError {
27    fn from(err: ConfigError) -> Self {
28        match err {
29            ConfigError::TomlParse(e) => Self::Configuration {
30                message: format!("Failed to parse TOML configuration: {e}"),
31            },
32            ConfigError::FileNotFound { path } => Self::Configuration {
33                message: format!(
34                    "Configuration file not found at '{}'. Create a 'capsula.toml' file or specify a custom path with --config",
35                    path.display()
36                ),
37            },
38            ConfigError::Invalid { message } => Self::Configuration { message },
39            ConfigError::Io(e) => Self::from(e),
40        }
41    }
42}
43
44#[derive(Deserialize, Debug, Clone)]
45#[serde(rename_all = "kebab-case")]
46pub struct CapsulaConfig {
47    pub vault: VaultConfig,
48    #[serde(default)]
49    pub dotenv: Option<PathBuf>,
50    #[serde(default)]
51    pub server: Option<ServerConfig>,
52    #[serde(default)]
53    pub pre_run: HookPhaseConfig,
54    #[serde(default)]
55    pub post_run: HookPhaseConfig,
56}
57
58/// Server connection settings.
59///
60/// Accepts either a plain URL string (`server = "https://..."`) or a table
61/// with a `url` and optional `headers` attached to every request:
62///
63/// ```toml
64/// [server]
65/// url = "https://capsula.example.com"
66///
67/// [server.headers]
68/// Authorization = { env = "CAPSULA_TOKEN", prefix = "Bearer " }
69/// ```
70#[derive(Debug, Clone)]
71pub struct ServerConfig {
72    pub url: String,
73    pub headers: BTreeMap<String, HeaderValueSource>,
74}
75
76impl<'de> Deserialize<'de> for ServerConfig {
77    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
78    where
79        D: Deserializer<'de>,
80    {
81        #[derive(Deserialize)]
82        #[serde(deny_unknown_fields)]
83        struct DetailedServerConfigHelper {
84            url: String,
85            #[serde(default)]
86            headers: BTreeMap<String, HeaderValueSource>,
87        }
88
89        #[derive(Deserialize)]
90        #[serde(untagged)]
91        enum ServerConfigHelper {
92            Url(String),
93            Detailed(DetailedServerConfigHelper),
94        }
95
96        Ok(match ServerConfigHelper::deserialize(deserializer)? {
97            ServerConfigHelper::Url(url) => Self {
98                url,
99                headers: BTreeMap::new(),
100            },
101            ServerConfigHelper::Detailed(detailed) => Self {
102                url: detailed.url,
103                headers: detailed.headers,
104            },
105        })
106    }
107}
108
109/// Source of an HTTP header value sent with server requests.
110#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
111#[serde(untagged)]
112pub enum HeaderValueSource {
113    /// The string is used as the header value verbatim.
114    Literal(String),
115    /// The value is read from an environment variable.
116    Env(EnvHeaderSource),
117    /// The value is the trimmed stdout of a command.
118    Command(CommandHeaderSource),
119}
120
121/// Header value read from an environment variable.
122#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
123#[serde(deny_unknown_fields)]
124pub struct EnvHeaderSource {
125    pub env: String,
126    /// Prepended to the variable's value (e.g. `"Bearer "`).
127    #[serde(default)]
128    pub prefix: Option<String>,
129}
130
131/// Header value produced by running a command and capturing its stdout.
132#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
133#[serde(deny_unknown_fields)]
134pub struct CommandHeaderSource {
135    pub command: String,
136}
137
138/// Directory holding the default location of every vault, relative to
139/// the project root.
140const DEFAULT_VAULT_ROOT: &str = ".capsula";
141
142/// Default directory of the vault named `name`, relative to the project
143/// root. Used when `[vault] path` is absent, and by commands that need a
144/// location for a vault other than the configured one.
145#[must_use]
146pub fn default_vault_path(name: &str) -> PathBuf {
147    Path::new(DEFAULT_VAULT_ROOT).join(name)
148}
149
150#[derive(Debug, Clone)]
151pub struct VaultConfig {
152    pub name: String,
153    pub path: PathBuf,
154}
155
156impl<'de> Deserialize<'de> for VaultConfig {
157    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
158    where
159        D: Deserializer<'de>,
160    {
161        #[derive(Deserialize)]
162        struct VaultConfigHelper {
163            name: String,
164            path: Option<PathBuf>,
165        }
166
167        let helper = VaultConfigHelper::deserialize(deserializer)?;
168        let path = helper
169            .path
170            .unwrap_or_else(|| default_vault_path(&helper.name));
171
172        Ok(Self {
173            name: helper.name,
174            path,
175        })
176    }
177}
178
179/// A phase configuration that contains hooks
180#[derive(Deserialize, Debug, Clone, Default)]
181pub struct HookPhaseConfig {
182    #[serde(default)]
183    pub hooks: Vec<HookEnvelope>,
184}
185
186#[derive(Deserialize, Debug, Clone)]
187pub struct HookEnvelope {
188    pub id: String,
189    #[serde(flatten)]
190    rest: serde_json::Value,
191}
192
193impl HookEnvelope {
194    /// The hook-specific configuration: every field except `id`.
195    #[must_use]
196    pub const fn config(&self) -> &serde_json::Value {
197        &self.rest
198    }
199}
200
201impl CapsulaConfig {
202    fn from_toml_str(content: &str) -> ConfigResult<Self> {
203        debug!("Parsing TOML configuration ({} bytes)", content.len());
204        let config = toml::from_str(content)?;
205        debug!("TOML configuration parsed successfully");
206        Ok(config)
207    }
208
209    pub fn from_file(path: impl AsRef<std::path::Path>) -> ConfigResult<Self> {
210        let path = path.as_ref();
211        debug!("Reading configuration file: {}", path.display());
212        let content = std::fs::read_to_string(path).map_err(|e| {
213            if e.kind() == std::io::ErrorKind::NotFound {
214                ConfigError::FileNotFound {
215                    path: path.to_path_buf(),
216                }
217            } else {
218                ConfigError::Io(e)
219            }
220        })?;
221        Self::from_toml_str(&content)
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn test_parse_example_config() {
231        let config_str = r#"
232[vault]
233name = "capsula"
234
235[[pre-run.hooks]]
236id = "capture-cwd"
237
238[[pre-run.hooks]]
239id = "capture-git-repo"
240path = "."
241
242[[pre-run.hooks]]
243id = "capture-file"
244glob = "capsula.toml"
245mode = "copy"
246hash = "sha256"
247
248[[pre-run.hooks]]
249id = "capture-file"
250glob = "Cargo.toml"
251hash = "sha256"
252
253[[post-run.hooks]]
254id = "capture-env"
255name = "PATH"
256"#;
257
258        let config = CapsulaConfig::from_toml_str(config_str).unwrap();
259
260        assert_eq!(config.vault.name, "capsula");
261        assert_eq!(config.vault.path, PathBuf::from(".capsula/capsula"));
262
263        assert_eq!(config.pre_run.hooks.len(), 4);
264        assert_eq!(config.pre_run.hooks[0].id, "capture-cwd");
265        assert_eq!(config.pre_run.hooks[1].id, "capture-git-repo");
266        assert_eq!(config.pre_run.hooks[2].id, "capture-file");
267        assert_eq!(config.pre_run.hooks[3].id, "capture-file");
268
269        assert_eq!(config.post_run.hooks.len(), 1);
270        assert_eq!(config.post_run.hooks[0].id, "capture-env");
271    }
272
273    #[test]
274    fn test_default_vault_path_is_under_dot_capsula() {
275        assert_eq!(
276            default_vault_path("my-vault"),
277            PathBuf::from(".capsula/my-vault")
278        );
279    }
280
281    #[test]
282    fn test_vault_config_with_explicit_path() {
283        let config_str = r#"
284[vault]
285name = "my_vault"
286path = "/custom/path/to/vault"
287
288[[pre-run.hooks]]
289id = "capture-cwd"
290"#;
291
292        let config = CapsulaConfig::from_toml_str(config_str).unwrap();
293
294        assert_eq!(config.vault.name, "my_vault");
295        assert_eq!(config.vault.path, PathBuf::from("/custom/path/to/vault"));
296    }
297
298    #[test]
299    fn parses_server_as_plain_url_string() {
300        let config_str = r#"
301server = "https://capsula.example.com"
302
303[vault]
304name = "v"
305"#;
306
307        let config = CapsulaConfig::from_toml_str(config_str).unwrap();
308
309        let server = config.server.unwrap();
310        assert_eq!(server.url, "https://capsula.example.com");
311        assert!(server.headers.is_empty());
312    }
313
314    #[test]
315    fn server_defaults_to_none_when_absent() {
316        let config_str = r#"
317[vault]
318name = "v"
319"#;
320
321        let config = CapsulaConfig::from_toml_str(config_str).unwrap();
322
323        assert!(config.server.is_none());
324    }
325
326    #[test]
327    fn parses_server_table_with_all_header_source_kinds() {
328        let config_str = r#"
329[vault]
330name = "v"
331
332[server]
333url = "https://capsula.example.com"
334
335[server.headers]
336x-literal = "fixed-value"
337Authorization = { env = "CAPSULA_TOKEN", prefix = "Bearer " }
338cf-access-token = { command = "cloudflared access token --app=https://capsula.example.com" }
339CF-Access-Client-Id = { env = "CF_ACCESS_CLIENT_ID" }
340"#;
341
342        let config = CapsulaConfig::from_toml_str(config_str).unwrap();
343
344        let server = config.server.unwrap();
345        assert_eq!(server.url, "https://capsula.example.com");
346        assert_eq!(
347            server.headers["x-literal"],
348            HeaderValueSource::Literal("fixed-value".to_string())
349        );
350        assert_eq!(
351            server.headers["Authorization"],
352            HeaderValueSource::Env(EnvHeaderSource {
353                env: "CAPSULA_TOKEN".to_string(),
354                prefix: Some("Bearer ".to_string()),
355            })
356        );
357        assert_eq!(
358            server.headers["cf-access-token"],
359            HeaderValueSource::Command(CommandHeaderSource {
360                command: "cloudflared access token --app=https://capsula.example.com".to_string(),
361            })
362        );
363        assert_eq!(
364            server.headers["CF-Access-Client-Id"],
365            HeaderValueSource::Env(EnvHeaderSource {
366                env: "CF_ACCESS_CLIENT_ID".to_string(),
367                prefix: None,
368            })
369        );
370    }
371
372    #[test]
373    fn rejects_header_source_mixing_env_and_command() {
374        let config_str = r#"
375[vault]
376name = "v"
377
378[server]
379url = "https://capsula.example.com"
380
381[server.headers]
382Authorization = { env = "CAPSULA_TOKEN", command = "echo x" }
383"#;
384
385        assert!(CapsulaConfig::from_toml_str(config_str).is_err());
386    }
387
388    #[test]
389    fn rejects_unknown_field_in_server_table() {
390        let config_str = r#"
391[vault]
392name = "v"
393
394[server]
395url = "https://capsula.example.com"
396
397[server.header]
398Authorization = "typo-should-fail"
399"#;
400
401        assert!(CapsulaConfig::from_toml_str(config_str).is_err());
402    }
403
404    #[test]
405    fn rejects_server_table_without_url() {
406        let config_str = r#"
407[vault]
408name = "v"
409
410[server]
411headers = {}
412"#;
413
414        assert!(CapsulaConfig::from_toml_str(config_str).is_err());
415    }
416
417    #[test]
418    fn test_vault_config_without_path() {
419        let config_str = r#"
420[vault]
421name = "test_vault"
422
423[[pre-run.hooks]]
424id = "capture-cwd"
425"#;
426
427        let config = CapsulaConfig::from_toml_str(config_str).unwrap();
428
429        assert_eq!(config.vault.name, "test_vault");
430        assert_eq!(config.vault.path, PathBuf::from(".capsula/test_vault"));
431    }
432}