dodot-lib 4.0.0

Core library for dodot dotfiles manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Scheme registry — dispatches a secret reference to the right
//! [`SecretProvider`] based on the URI scheme prefix.
//!
//! Reference shapes the registry recognises:
//!
//! - `op://Vault/Item/Field` — full URI form, `://` separator
//! - `pass:path/to/secret`   — single colon, no slashes
//! - `sops:file.yaml#k.path` — single colon, fragment optional
//! - `bw:Folder/Item`        — single colon
//!
//! Rule: split at the first colon, take everything to its left as the
//! scheme. The provider's `resolve()` sees what's after the colon
//! verbatim — it doesn't need to re-parse the scheme prefix.
//!
//! See `secrets.lex` §3.1 for the user-facing reference syntax and
//! §5.5 for the registry's role in adding new providers (no central
//! plumbing change required).

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::secret::provider::{ProbeResult, SecretProvider};
use crate::secret::secret_string::SecretString;
use crate::{DodotError, Result};

/// Owned set of registered providers, keyed by scheme.
///
/// Constructed once per `dodot up` invocation by the secrets layer in
/// `commands::up`, populated from the `[secret.providers.*]` config,
/// and threaded into the `secret()` MiniJinja function. `Arc<dyn>`
/// because providers are held behind a trait object and the registry
/// is shared with the template engine across rendering passes.
///
/// Resolved values are cached in `cache` so a reference that appears
/// in N templates only fires the underlying provider once. The cache
/// is shared between [`Clone`]s of the registry (it lives behind an
/// `Arc<Mutex>`); two registries built from the same config but via
/// independent constructor calls have independent caches. This
/// satisfies `secrets.lex` §7.4's "user authenticates once per run"
/// for the common case of a single registry threaded through every
/// pack rendered in one `dodot up` invocation.
///
/// Cache values are stored as `Arc<SecretString>` so the cached
/// bytes are zeroized when the registry (and its last Arc holder)
/// drops. Callers that need a plain `&str` go through
/// [`SecretString::expose`] at the substitution boundary; the cache
/// itself never holds an unsealed `String` copy.
#[derive(Default, Clone)]
pub struct SecretRegistry {
    providers: HashMap<String, Arc<dyn SecretProvider>>,
    cache: Arc<Mutex<HashMap<String, Arc<SecretString>>>>,
}

impl SecretRegistry {
    /// Empty registry — no providers registered yet. The `secret()`
    /// function against an empty registry always errors with
    /// "unknown scheme"; callers that want a user-friendly
    /// "secrets disabled" message should check the registry shape
    /// before rendering.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a provider. Replacing an existing entry for the same
    /// scheme is intentionally allowed (it's how tests substitute
    /// the mock for the real provider) but is logged at `debug` to
    /// catch unintentional overrides during normal config loading.
    pub fn register(&mut self, provider: Arc<dyn SecretProvider>) {
        let scheme = provider.scheme().to_string();
        if self.providers.contains_key(&scheme) {
            tracing::debug!(scheme = %scheme, "secret provider replaced");
        }
        self.providers.insert(scheme, provider);
    }

    /// True iff a provider is registered for the given scheme.
    pub fn has(&self, scheme: &str) -> bool {
        self.providers.contains_key(scheme)
    }

    /// All registered scheme names. Stable iteration order is NOT
    /// guaranteed; callers that want a deterministic listing should
    /// `collect::<Vec<_>>()` and sort.
    pub fn schemes(&self) -> impl Iterator<Item = &str> {
        self.providers.keys().map(String::as_str)
    }

    /// Borrow the provider for a scheme, if any.
    pub fn get(&self, scheme: &str) -> Option<&Arc<dyn SecretProvider>> {
        self.providers.get(scheme)
    }

    /// Resolve a full reference (with scheme prefix) by dispatching
    /// to the right provider. **Bypasses the within-run cache** —
    /// every call shells out to the provider. Most callers want the
    /// [`Self::cache_get`] / [`Self::cache_put`] surface (used by
    /// the `secret()` MiniJinja function); this entry point exists
    /// for tests that want to count provider invocations and for
    /// `dodot secret probe` paths that intentionally hit the wire.
    ///
    /// Returns `DodotError::Other` with an actionable message when:
    ///
    /// - The reference doesn't contain `:` (malformed input).
    /// - No provider is registered for the parsed scheme.
    /// - The provider's `resolve()` itself fails (error propagated
    ///   verbatim — provider impls are responsible for stripping
    ///   secret bytes from any error string).
    ///
    /// Mode gating is NOT this function's job. The `secret()`
    /// MiniJinja function checks `PreprocessMode` before calling
    /// `resolve()` per the §7.4 contract; the registry just routes.
    pub fn resolve(&self, full_reference: &str) -> Result<SecretString> {
        let (scheme, suffix) = split_scheme(full_reference)?;
        let provider = self.get(scheme).ok_or_else(|| {
            let config_key = scheme_to_config_key(scheme);
            DodotError::Other(format!(
                "no secret provider registered for scheme `{scheme}`. \
                 Configured schemes: [{}]. \
                 Add a `[secret.providers.{config_key}] enabled = true` block \
                 to your config, or check the reference for typos.",
                self.sorted_schemes_for_display()
            ))
        })?;
        provider.resolve(suffix)
    }

    /// Look up a previously-resolved reference in the within-run
    /// cache. Returns `None` on cache miss; the caller (the
    /// `secret()` MiniJinja function) is expected to call
    /// [`Self::resolve`] and then [`Self::cache_put`] to populate
    /// the cache for future calls.
    ///
    /// Returns `Arc<SecretString>` so the cached bytes stay zeroize-
    /// on-drop — callers go through `SecretString::expose` at the
    /// substitution boundary, never an unsealed `String` copy in
    /// the cache itself. Cloning the Arc is a cheap pointer bump;
    /// the inner buffer is dropped (and zeroized) when the last
    /// holder is gone.
    ///
    /// Splitting cache access from resolution lets the caller
    /// validate values (multi-line refusal, UTF-8) with rich error
    /// messages co-located with the rendering surface, while still
    /// avoiding repeat shell-outs for the cache-hit path.
    pub fn cache_get(&self, full_reference: &str) -> Option<Arc<SecretString>> {
        self.cache.lock().unwrap().get(full_reference).cloned()
    }

    /// Store a resolved (and validated) value in the within-run
    /// cache. Takes `Arc<SecretString>` directly so the caller
    /// keeps the same handle for the substitution path —
    /// constructing a fresh `SecretString` here would lose the
    /// zeroize lineage on the original. The caller is responsible
    /// for ensuring the value is genuine (no markers, no UTF-8
    /// violations, not a multi-line value); the cache is dumb
    /// storage.
    pub fn cache_put(&self, full_reference: &str, value: Arc<SecretString>) {
        self.cache
            .lock()
            .unwrap()
            .insert(full_reference.to_string(), value);
    }

    /// Number of entries currently held in the within-run cache.
    /// Useful for batching assertions in tests; not a public surface
    /// for production code, which has no reason to inspect cache
    /// size at runtime.
    #[cfg(test)]
    pub fn cache_len(&self) -> usize {
        self.cache.lock().unwrap().len()
    }

    /// Drop every entry from the within-run cache. Tests use this to
    /// re-exercise the provider path; production code should never
    /// need to call it (the cache is per-registry-instance and the
    /// instance is per-run).
    #[cfg(test)]
    pub fn clear_cache(&self) {
        self.cache.lock().unwrap().clear();
    }

    /// Probe every registered provider. Used by `dodot secret probe`
    /// to give the user a one-shot view of what's working.
    pub fn probe_all(&self) -> Vec<(String, ProbeResult)> {
        let mut out: Vec<(String, ProbeResult)> = self
            .providers
            .iter()
            .map(|(scheme, p)| (scheme.clone(), p.probe()))
            .collect();
        out.sort_by(|a, b| a.0.cmp(&b.0));
        out
    }

    fn sorted_schemes_for_display(&self) -> String {
        let mut s: Vec<&str> = self.providers.keys().map(String::as_str).collect();
        s.sort_unstable();
        s.join(", ")
    }
}

/// Map a scheme name (as it appears in a `secret(...)` reference)
/// to the TOML config key under `[secret.providers.<key>]`.
///
/// Most schemes match their config key 1:1. The `secret-tool`
/// scheme is the lone exception: the TOML field is named
/// `secret_tool` (underscore) because confique's `Config` derive
/// generates the TOML key from the Rust field identifier, and
/// Rust identifiers can't contain hyphens. We keep the hyphenated
/// scheme prefix (matching the binary name `secret-tool` and
/// `secrets.lex` §S4) and translate at the user-facing edges.
///
/// Used by error messages that point users at the corresponding
/// config block, so a "no provider for scheme `secret-tool`" hint
/// suggests `[secret.providers.secret_tool]` (which actually
/// maps to a struct field) rather than the syntactically-valid-
/// but-non-loading `[secret.providers.secret-tool]`.
pub fn scheme_to_config_key(scheme: &str) -> &str {
    match scheme {
        "secret-tool" => "secret_tool",
        other => other,
    }
}

/// Split a full reference into `(scheme, suffix)` at the first `:`.
///
/// `op://Vault/Item/Field` → `("op", "//Vault/Item/Field")`
/// `pass:path/to/x`         → `("pass", "path/to/x")`
/// `sops:f.yaml#k.path`     → `("sops", "f.yaml#k.path")`
///
/// Empty schemes (`":foo"`) and missing colons (`"plain-string"`)
/// produce an actionable error pointing the user at the reference
/// syntax.
pub fn split_scheme(reference: &str) -> Result<(&str, &str)> {
    let (scheme, suffix) = reference.split_once(':').ok_or_else(|| {
        DodotError::Other(format!(
            "secret reference `{reference}` is missing a scheme prefix. \
             Expected `<scheme>:<provider-specific-reference>` — for example \
             `op://Vault/Item/Field` or `pass:path/to/secret`."
        ))
    })?;
    if scheme.is_empty() {
        return Err(DodotError::Other(format!(
            "secret reference `{reference}` has an empty scheme prefix. \
             Expected `<scheme>:<provider-specific-reference>`."
        )));
    }
    Ok((scheme, suffix))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::secret::test_support::MockSecretProvider;

    #[test]
    fn scheme_to_config_key_maps_only_secret_tool() {
        // The hyphen-vs-underscore wart only exists for
        // `secret-tool`. Every other scheme name is a valid Rust
        // identifier and round-trips identically. Pin the
        // contract so a future provider that adds another
        // hyphenated scheme has to update both sides at once.
        assert_eq!(scheme_to_config_key("secret-tool"), "secret_tool");
        assert_eq!(scheme_to_config_key("pass"), "pass");
        assert_eq!(scheme_to_config_key("op"), "op");
        assert_eq!(scheme_to_config_key("bw"), "bw");
        assert_eq!(scheme_to_config_key("sops"), "sops");
        assert_eq!(scheme_to_config_key("keychain"), "keychain");
    }

    #[test]
    fn missing_provider_error_uses_underscore_key_for_secret_tool() {
        // The user-facing "no provider for scheme `secret-tool`"
        // error must point at `[secret.providers.secret_tool]`
        // (the actual TOML key that maps to a struct field), not
        // `[secret.providers.secret-tool]` (which would be valid
        // TOML but wouldn't load — Rust field names can't
        // contain hyphens).
        let mut reg = SecretRegistry::new();
        reg.register(Arc::new(MockSecretProvider::new("pass")));
        let err = reg.resolve("secret-tool:GitHub").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("no secret provider registered for scheme `secret-tool`"));
        assert!(
            msg.contains("[secret.providers.secret_tool]"),
            "expected underscore form, got: {msg}"
        );
        assert!(
            !msg.contains("[secret.providers.secret-tool]"),
            "hyphen form must not leak through: {msg}"
        );
    }

    #[test]
    fn split_scheme_handles_op_uri_form() {
        let (scheme, suffix) = split_scheme("op://Vault/Item/Field").unwrap();
        assert_eq!(scheme, "op");
        // Note: the `//` stays — providers see exactly what came
        // after the first colon. The `op` provider re-parses
        // `//Vault/Item/Field` itself.
        assert_eq!(suffix, "//Vault/Item/Field");
    }

    #[test]
    fn split_scheme_handles_pass_single_colon() {
        let (scheme, suffix) = split_scheme("pass:path/to/secret").unwrap();
        assert_eq!(scheme, "pass");
        assert_eq!(suffix, "path/to/secret");
    }

    #[test]
    fn split_scheme_handles_sops_with_fragment() {
        let (scheme, suffix) = split_scheme("sops:secrets.yaml#database.password").unwrap();
        assert_eq!(scheme, "sops");
        assert_eq!(suffix, "secrets.yaml#database.password");
    }

    #[test]
    fn split_scheme_rejects_no_colon_with_actionable_message() {
        let err = split_scheme("plain-string").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("missing a scheme prefix"));
        assert!(msg.contains("`<scheme>:<provider-specific-reference>`"));
        // Examples in the message help the user reach for the right shape.
        assert!(msg.contains("op://"));
        assert!(msg.contains("pass:"));
    }

    #[test]
    fn split_scheme_rejects_empty_scheme() {
        let err = split_scheme(":nothing").unwrap_err();
        assert!(err.to_string().contains("empty scheme prefix"));
    }

    #[test]
    fn registry_dispatches_to_correct_provider() {
        let mut reg = SecretRegistry::new();
        reg.register(Arc::new(
            MockSecretProvider::new("pass")
                .with("path/to/db", "hunter2")
                .with("path/to/api", "tok-abc"),
        ));
        reg.register(Arc::new(
            MockSecretProvider::new("op").with("//V/Item/password", "op-value"),
        ));

        let v = reg.resolve("pass:path/to/db").unwrap();
        assert_eq!(v.expose().unwrap(), "hunter2");

        let v = reg.resolve("op://V/Item/password").unwrap();
        assert_eq!(v.expose().unwrap(), "op-value");
    }

    #[test]
    fn registry_unknown_scheme_lists_configured_schemes_in_error() {
        let mut reg = SecretRegistry::new();
        reg.register(Arc::new(MockSecretProvider::new("pass")));
        reg.register(Arc::new(MockSecretProvider::new("op")));

        let err = reg.resolve("sops:foo.yaml#x").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("no secret provider registered for scheme `sops`"));
        // Configured schemes appear sorted so the message is stable.
        assert!(msg.contains("op, pass"));
    }

    #[test]
    fn registry_register_replaces_same_scheme() {
        let mut reg = SecretRegistry::new();
        reg.register(Arc::new(MockSecretProvider::new("pass").with("k", "first")));
        // Replace with a fresh provider for the same scheme.
        reg.register(Arc::new(
            MockSecretProvider::new("pass").with("k", "second"),
        ));
        assert_eq!(reg.resolve("pass:k").unwrap().expose().unwrap(), "second");
    }

    fn put(reg: &SecretRegistry, reference: &str, value: &str) {
        reg.cache_put(reference, Arc::new(SecretString::new(value.to_string())));
    }

    #[test]
    fn cache_get_returns_none_until_cache_put_populates_it() {
        let reg = SecretRegistry::new();
        assert!(reg.cache_get("op://V/I/F").is_none());
        put(&reg, "op://V/I/F", "secret-value");
        let hit = reg.cache_get("op://V/I/F").unwrap();
        assert_eq!(hit.expose().unwrap(), "secret-value");
    }

    #[test]
    fn cache_is_shared_between_clones_of_the_same_registry() {
        // Clone semantics: the cache lives behind an Arc<Mutex>, so
        // two clones of one registry observe the same cache. This
        // is what lets `commands::up` build the registry once and
        // pass it to N pack-rendering passes that all share auth.
        let reg = SecretRegistry::new();
        let clone = reg.clone();
        put(&clone, "pass:k", "v");
        let hit = reg.cache_get("pass:k").unwrap();
        assert_eq!(hit.expose().unwrap(), "v");
    }

    #[test]
    fn cache_is_independent_between_separate_registry_constructions() {
        // Two `SecretRegistry::new()` calls produce independent
        // caches even when the same providers are registered. This
        // pins the "per-instance, not process-global" contract — a
        // later refactor that changes the cache to a static
        // singleton would silently break the test isolation
        // contract every other test in this module relies on.
        let a = SecretRegistry::new();
        let b = SecretRegistry::new();
        put(&a, "pass:k", "from-a");
        assert!(b.cache_get("pass:k").is_none());
    }

    #[test]
    fn registry_resolve_does_not_consult_or_populate_cache() {
        // resolve() bypasses the cache by design — it's the
        // wire-hitting entry point that callers use to count
        // provider invocations. cache_get and cache_put are the
        // cache-aware surface. Pin the contract.
        let mut reg = SecretRegistry::new();
        reg.register(Arc::new(MockSecretProvider::new("pass").with("k", "v")));
        let _ = reg.resolve("pass:k").unwrap();
        assert_eq!(reg.cache_len(), 0, "resolve() must not populate the cache");
        assert!(
            reg.cache_get("pass:k").is_none(),
            "cache_get must miss when only resolve() ran"
        );
    }

    #[test]
    fn registry_has_and_schemes_reflect_registered_providers() {
        let mut reg = SecretRegistry::new();
        assert!(!reg.has("pass"));
        reg.register(Arc::new(MockSecretProvider::new("pass")));
        reg.register(Arc::new(MockSecretProvider::new("op")));
        assert!(reg.has("pass"));
        assert!(reg.has("op"));
        assert!(!reg.has("sops"));

        let mut schemes: Vec<&str> = reg.schemes().collect();
        schemes.sort_unstable();
        assert_eq!(schemes, vec!["op", "pass"]);
    }
}