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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
/// Errors produced by secret resolution.
#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic)]
pub enum Error {
/// Secret could not be resolved. The source error is preserved for
/// diagnostics. `Arc` provides `Clone` without requiring the inner
/// error to be `Clone`.
#[error("secret resolution failed")]
Resolve(#[source] Arc<dyn std::error::Error + Send + Sync>),
#[error("unknown secret: {0:?}")]
UnknownSecret(String),
}
pub type Result<T> = std::result::Result<T, Error>;
/// A string value that deserializes from either a plain literal or a file path.
///
/// Fennel config can provide a secret as:
/// - A plain string: `"s3cret"`
/// - A file reference: `{:file "/run/secrets/my_token"}`
///
/// File contents are resolved lazily on first access to [`SecretString::reveal`]
/// and cached for the lifetime of the instance. Trailing newlines are stripped
/// from file contents (Docker secrets convention).
///
/// The [`std::fmt::Debug`] impl redacts the value.
#[derive(Clone)]
pub struct SecretString(SecretSource);
enum SecretSource {
Plain(String),
File {
path: PathBuf,
resolved: OnceLock<std::result::Result<String, Arc<dyn std::error::Error + Send + Sync>>>,
},
}
impl Clone for SecretSource {
fn clone(&self) -> Self {
match self {
Self::Plain(s) => Self::Plain(s.clone()),
// File clones get a fresh OnceLock — they re-read from disk on next reveal.
Self::File { path, .. } => Self::File {
path: path.clone(),
resolved: OnceLock::new(),
},
}
}
}
impl SecretString {
/// The resolved secret value.
///
/// For the file variant, reads from disk on first call and caches the
/// result. Errors are also cached — subsequent calls return the same error.
pub fn reveal(&self) -> Result<&str> {
match &self.0 {
SecretSource::Plain(s) => Ok(s.as_str()),
SecretSource::File { path, resolved } => resolved
.get_or_init(|| {
fs_err::read_to_string(path)
.map(|s| s.strip_suffix('\n').unwrap_or(&s).to_string())
.map_err(|e| Arc::new(e) as Arc<dyn std::error::Error + Send + Sync>)
})
.as_ref()
.map(|s| s.as_str())
.map_err(|arc| Error::Resolve(Arc::clone(arc))),
}
}
}
impl std::fmt::Debug for SecretString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("SecretString").field(&"<redacted>").finish()
}
}
impl std::fmt::Display for SecretString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[secret]")
}
}
impl From<String> for SecretString {
fn from(value: String) -> Self {
Self(SecretSource::Plain(value))
}
}
impl From<&str> for SecretString {
fn from(value: &str) -> Self {
Self(SecretSource::Plain(value.to_string()))
}
}
impl From<PathBuf> for SecretString {
/// Build from a file path. Contents are read lazily on first [`reveal`].
///
/// [`reveal`]: SecretString::reveal
fn from(path: PathBuf) -> Self {
Self(SecretSource::File {
path,
resolved: OnceLock::new(),
})
}
}
impl<'de> serde::Deserialize<'de> for SecretString {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum Raw {
Plain(String),
File { file: PathBuf },
}
let raw = Raw::deserialize(deserializer)?;
let source = match raw {
Raw::Plain(s) => SecretSource::Plain(s),
Raw::File { file } => SecretSource::File {
path: file,
resolved: OnceLock::new(),
},
};
Ok(Self(source))
}
}
// ── Secret registry and redaction ───────────────────────────────
/// Opaque wrapper for a revealed secret value. No Debug impl.
struct Revealed(String);
impl Revealed {
fn new(value: String) -> Self {
Self(value)
}
fn as_str(&self) -> &str {
&self.0
}
}
// Explicitly no Debug impl — revealed values must never be printed.
/// Signature for a secret fallback fetcher: given a name, return the
/// revealed value or an error.
type SecretFetcher = Box<dyn Fn(&str) -> Result<String>>;
/// Per-run secret store. Resolves secret names to values via a fetcher
/// closure, caching each result so the fetcher is called at most once
/// per name. Revealed values are registered for redaction.
///
/// The normal construction path installs an API fetcher and starts with
/// an empty cache. The filesystem source pre-warms the cache via
/// [`SecretRegistry::seed`] so no fetches are needed at run time.
///
/// Lifetime is bounded to a single CI run. Do not carry a registry
/// across runs — revealed values from previous runs would contaminate
/// redaction of unrelated output.
pub struct SecretRegistry {
/// Pull-through cache: name → secret. Pre-seeded for the filesystem
/// source; populated lazily for the API source.
cache: HashMap<String, SecretString>,
/// name → revealed value (opaque). Populated on first `(secret :name)` call.
revealed: HashMap<String, Revealed>,
/// Called when a name is absent from the cache. Always present — the
/// normal case is an API fetcher; tests and the filesystem source use
/// a closure that returns [`Error::UnknownSecret`].
fetcher: SecretFetcher,
}
impl std::fmt::Debug for SecretRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SecretRegistry")
.field("cache", &self.cache.keys().collect::<Vec<_>>())
.field("revealed", &self.revealed.keys().collect::<Vec<_>>())
.field("fetcher", &"<fn>")
.finish()
}
}
fn not_found_fetcher(name: &str) -> Result<String> {
Err(Error::UnknownSecret(name.to_string()))
}
impl From<HashMap<String, SecretString>> for SecretRegistry {
fn from(secrets: HashMap<String, SecretString>) -> Self {
Self::new(not_found_fetcher).seed(secrets)
}
}
impl From<Vec<(String, SecretString)>> for SecretRegistry {
fn from(pairs: Vec<(String, SecretString)>) -> Self {
Self::from(pairs.into_iter().collect::<HashMap<_, _>>())
}
}
impl From<Vec<(&str, &str)>> for SecretRegistry {
fn from(pairs: Vec<(&str, &str)>) -> Self {
let cache: HashMap<String, SecretString> = pairs
.into_iter()
.map(|(k, v)| (k.to_string(), SecretString::from(v)))
.collect();
Self::from(cache)
}
}
impl SecretRegistry {
/// Create a registry backed by `fetcher`. The cache starts empty;
/// use [`SecretRegistry::seed`] to pre-warm it.
///
/// `fetcher` is called at most once per name — results are cached
/// back into the registry so subsequent lookups are local. Values
/// fetched through either path are registered for redaction.
pub fn new<F>(fetcher: F) -> Self
where
F: Fn(&str) -> Result<String> + 'static,
{
Self {
cache: HashMap::new(),
revealed: HashMap::new(),
fetcher: Box::new(fetcher),
}
}
/// Pre-warm the cache with an existing set of secrets. Intended for
/// the filesystem source, which receives all secrets up-front in the
/// bootstrap file. Pre-seeded names are served from the cache without
/// invoking the fetcher.
pub fn seed(mut self, secrets: HashMap<String, SecretString>) -> Self {
self.cache = secrets;
self
}
/// Resolve a secret by name, caching the revealed value for
/// redaction. Checks the cache first; on a miss, calls the fetcher
/// and stores the result. Returns `Err` if the name is unknown or
/// the source can't be read.
///
/// Values shorter than 8 characters are returned to the caller
/// but not registered for redaction — the false-positive rate on
/// common short strings like "true" or "yes" is too high. A warn
/// is emitted so an operator can see why a short token is showing
/// up unredacted in CI output.
///
/// The returned `String` is the plain, revealed value. Do not pass
/// it to `tracing` or any other log sink — the global tracing
/// subscriber has no redaction layer, so a leaked value would
/// reach stderr and Sentry. Route it into a surface that goes
/// through [`redact`] (e.g. `sh` command args, ShOutput) or wrap
/// it in a type whose `Debug`/`Display` impl redacts.
pub fn resolve(&mut self, name: &str) -> Result<String> {
let value = if let Some(secret) = self.cache.get(name) {
secret.reveal()?.to_string()
} else {
let fetched = (self.fetcher)(name)?;
self.cache
.insert(name.to_string(), SecretString::from(fetched.clone()));
fetched
};
if value.len() >= 8 {
self.revealed
.insert(name.to_string(), Revealed::new(value.clone()));
} else {
tracing::warn!(
secret = %name,
length = value.len(),
"secret value is shorter than the 8-byte minimum and will not be redacted from CI output"
);
}
Ok(value)
}
/// Return revealed (name, value) pairs sorted by value length
/// descending so longest matches are replaced first (prevents
/// partial replacement of overlapping secrets). Equal-length
/// values tiebreak on name, so two names that map to the same
/// value redact deterministically.
fn entries(&self) -> Vec<(&str, &str)> {
let mut entries: Vec<_> = self
.revealed
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
entries.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(b.0)));
entries
}
pub fn has_redactions(&self) -> bool {
!self.revealed.is_empty()
}
}
/// Replace any revealed secret value in `text` with `{{ name }}`.
///
/// Longest values are replaced first to prevent partial matches.
/// Returns the input unchanged when no secrets have been revealed.
pub fn redact(text: &str, registry: &SecretRegistry) -> String {
if !registry.has_redactions() {
return text.to_string();
}
let mut result = text.to_string();
for (name, value) in registry.entries() {
let replacement = format!("{{{{ {} }}}}", name);
result = result.replace(value, &replacement);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fennel::Fennel;
#[test]
fn debug_redacts_value() {
let secret = SecretString::from("super_secret_password");
let debug_output = format!("{secret:?}");
assert_eq!(debug_output, "SecretString(\"<redacted>\")");
assert!(
!debug_output.contains("super_secret_password"),
"Debug must not leak the secret value"
);
}
#[test]
fn registry_debug_does_not_leak_revealed_values() {
let mut registry: SecretRegistry =
vec![("github_token", "abcdefghijklmnop_long_enough")].into();
let _ = registry.resolve("github_token").unwrap();
let debug_output = format!("{registry:?}");
assert!(
!debug_output.contains("abcdefghijklmnop_long_enough"),
"SecretRegistry Debug must not leak revealed values: {debug_output}"
);
assert!(
debug_output.contains("github_token"),
"SecretRegistry Debug should still surface cached names: {debug_output}"
);
}
#[test]
fn reveal_returns_plain_value() {
let secret = SecretString::from("plain_value");
assert_eq!(secret.reveal().unwrap(), "plain_value");
}
#[test]
fn clone_preserves_plain_value() {
let secret = SecretString::from("clonable");
let cloned = secret.clone();
assert_eq!(cloned.reveal().unwrap(), "clonable");
}
#[test]
fn reveal_caches_file_value() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("token");
fs_err::write(&path, "initial\n").expect("write");
let secret = SecretString::from(path.clone());
assert_eq!(secret.reveal().unwrap(), "initial");
// Overwrite the file — cached value should not change.
fs_err::write(&path, "changed\n").expect("overwrite");
assert_eq!(secret.reveal().unwrap(), "initial");
}
#[test]
fn reveal_strips_trailing_newline() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("secret");
fs_err::write(&path, "line1\nline2\n").expect("write");
let secret = SecretString::from(path.clone());
assert_eq!(secret.reveal().unwrap(), "line1\nline2");
}
#[test]
fn reveal_strips_only_one_trailing_newline() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("secret");
// Docker secrets convention: strip exactly one trailing newline.
// Any additional trailing newlines are part of the secret.
fs_err::write(&path, "value\n\n\n").expect("write");
let secret = SecretString::from(path.clone());
assert_eq!(secret.reveal().unwrap(), "value\n\n");
}
#[test]
fn reveal_errors_on_missing_file() {
let secret = SecretString::from(PathBuf::from("/no/such/file/ever"));
let err = secret.reveal().unwrap_err();
assert!(
matches!(err, Error::Resolve(_)),
"expected Resolve error, got {err:?}"
);
}
#[test]
fn clone_resets_cache_and_rereads_from_disk() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("pw");
fs_err::write(&path, "initial\n").expect("write");
let original = SecretString::from(path.clone());
assert_eq!(original.reveal().unwrap(), "initial");
// Overwrite after the original cached "initial". The clone gets a fresh
// OnceLock, so it re-reads the current file contents.
fs_err::write(&path, "changed\n").expect("overwrite");
let cloned = original.clone();
assert_eq!(cloned.reveal().unwrap(), "changed");
// Original's cache is untouched.
assert_eq!(original.reveal().unwrap(), "initial");
}
#[test]
fn deserialize_plain_string() {
#[derive(serde::Deserialize)]
struct Wrapper {
token: SecretString,
}
let json = r#"{"token": "s3cret"}"#;
let w: Wrapper = serde_json::from_str(json).expect("deserialize plain string");
assert_eq!(w.token.reveal().unwrap(), "s3cret");
}
#[test]
fn deserialize_file_does_not_touch_disk() {
#[derive(serde::Deserialize)]
struct Wrapper {
token: SecretString,
}
let json = r#"{"token": {"file": "/no/such/file/ever"}}"#;
let w: Wrapper = serde_json::from_str(json).expect("deserialize should not read file");
// Deserialization succeeded without touching disk.
assert!(w.token.reveal().is_err());
}
#[test]
fn deserialize_file_resolves_on_reveal() {
#[derive(serde::Deserialize)]
struct Wrapper {
token: SecretString,
}
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("token");
fs_err::write(&path, "from_file\n").expect("write");
let json = serde_json::json!({
"token": {"file": path.display().to_string()}
});
let w: Wrapper = serde_json::from_value(json).expect("deserialize");
assert_eq!(w.token.reveal().unwrap(), "from_file");
}
#[test]
fn fetcher_result_is_cached() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let call_count = Arc::new(AtomicUsize::new(0));
let counter = call_count.clone();
let mut registry = SecretRegistry::new(move |name| {
counter.fetch_add(1, Ordering::SeqCst);
Ok(format!("fetched_{name}_abcdefgh"))
});
let first = registry.resolve("token").unwrap();
let second = registry.resolve("token").unwrap();
assert_eq!(first, "fetched_token_abcdefgh");
assert_eq!(second, "fetched_token_abcdefgh");
assert_eq!(
call_count.load(Ordering::SeqCst),
1,
"fallback should be called exactly once"
);
}
#[test]
fn fennel_round_trip_plain_string() {
#[derive(serde::Deserialize)]
struct Config {
token: SecretString,
}
let fennel = Fennel::new().expect("fennel");
let config: Config = fennel
.load_string(r#"{:token "hunter2"}"#, "test.fnl", |_| {})
.expect("deserialize from fennel");
assert_eq!(config.token.reveal().unwrap(), "hunter2");
}
#[test]
fn fennel_round_trip_file_ref() {
#[derive(serde::Deserialize)]
struct Config {
token: SecretString,
}
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("pw");
fs_err::write(&path, "secret_from_file\n").expect("write");
let fennel = Fennel::new().expect("fennel");
// Fennel table syntax: {:token {:file "/path"}}
let source = format!("{{:token {{:file \"{}\"}}}}", path.display(),);
let config: Config = fennel
.load_string(&source, "test.fnl", |_| {})
.expect("deserialize file ref from fennel");
assert_eq!(config.token.reveal().unwrap(), "secret_from_file");
}
}