1pub mod registry;
7
8#[cfg(feature = "secrets-aws-sm")]
9mod aws_sm;
10#[cfg(feature = "secrets-azure-kv")]
11mod azure_kv;
12#[cfg(feature = "secrets-gcp-sm")]
13mod gcp_sm;
14#[cfg(feature = "secrets-vault")]
15mod vault;
16
17use crate::config::PipelineConfig;
18use crate::error::{CliError, CliResult};
19use crate::interpolate::{self, Directive};
20use async_trait::async_trait;
21use futures::stream::{self, StreamExt, TryStreamExt};
22use serde_json::Value;
23use std::collections::{BTreeSet, HashMap};
24use std::sync::Arc;
25
26pub const SECRET_SCHEMES: &[&str] = &["vault", "aws-sm", "gcp-sm", "azure-kv"];
28
29pub type SecretRef = (String, String);
31
32#[async_trait]
33pub trait SecretResolver: Send + Sync {
34 fn scheme(&self) -> &'static str;
36 async fn resolve(&self, reference: &str) -> CliResult<String>;
38}
39
40#[allow(dead_code)] pub(crate) fn split_field(reference: &str) -> (&str, Option<&str>) {
43 match reference.split_once('#') {
44 Some((path, field)) => (path, Some(field)),
45 None => (reference, None),
46 }
47}
48
49#[allow(dead_code)] pub(crate) fn extract_field(
53 scheme: &str,
54 reference: &str,
55 body: &str,
56 field: &str,
57) -> CliResult<String> {
58 let json: Value = serde_json::from_str(body).map_err(|_| CliError::SecretNotJson {
59 scheme: scheme.to_owned(),
60 reference: reference.to_owned(),
61 })?;
62 let obj = json.as_object().ok_or_else(|| CliError::SecretNotJson {
63 scheme: scheme.to_owned(),
64 reference: reference.to_owned(),
65 })?;
66 match obj.get(field) {
67 Some(Value::String(s)) => Ok(s.clone()),
68 Some(other) => Ok(other.to_string()),
69 None => Err(CliError::SecretFieldMissing {
70 scheme: scheme.to_owned(),
71 reference: reference.to_owned(),
72 field: field.to_owned(),
73 available: obj.keys().cloned().collect(),
74 }),
75 }
76}
77
78fn for_each_string<F: FnMut(&str)>(value: &Value, f: &mut F) {
80 match value {
81 Value::String(s) => f(s),
82 Value::Array(a) => a.iter().for_each(|v| for_each_string(v, f)),
83 Value::Object(m) => m.values().for_each(|v| for_each_string(v, f)),
84 _ => {}
85 }
86}
87
88fn for_each_string_mut<F: FnMut(&mut String) -> CliResult<()>>(
90 value: &mut Value,
91 f: &mut F,
92) -> CliResult<()> {
93 match value {
94 Value::String(s) => f(s),
95 Value::Array(a) => a.iter_mut().try_for_each(|v| for_each_string_mut(v, f)),
96 Value::Object(m) => m.values_mut().try_for_each(|v| for_each_string_mut(v, f)),
97 _ => Ok(()),
98 }
99}
100
101fn collect_refs_in_str(s: &str, out: &mut BTreeSet<SecretRef>) {
103 for (_token, dir) in interpolate::iter_directives(s) {
104 if let Directive::LoadTime { prefix, body } = dir
105 && SECRET_SCHEMES.contains(&prefix)
106 {
107 out.insert((prefix.to_owned(), body.to_owned()));
108 }
109 }
110}
111
112pub fn collect_refs(value: &Value, out: &mut BTreeSet<SecretRef>) {
114 for_each_string(value, &mut |s| collect_refs_in_str(s, out));
115}
116
117pub fn substitute(value: &mut Value, cache: &HashMap<SecretRef, String>) -> CliResult<()> {
120 for_each_string_mut(value, &mut |s| {
121 let new = interpolate::rewrite(s, |body| match interpolate::classify_directive(body) {
122 Directive::LoadTime { prefix, body: b } if SECRET_SCHEMES.contains(&prefix) => {
123 Ok(Some(
124 cache
125 .get(&(prefix.to_owned(), b.to_owned()))
126 .cloned()
127 .expect("scan collected every secret ref before fetch"),
128 ))
129 }
130 _ => Ok(None),
131 })?;
132 *s = new;
133 Ok(())
134 })
135}
136
137#[derive(Default, Clone)]
139pub struct ResolverSet {
140 resolvers: HashMap<&'static str, Arc<dyn SecretResolver>>,
141}
142
143impl ResolverSet {
144 pub fn insert(&mut self, resolver: Arc<dyn SecretResolver>) {
145 self.resolvers.insert(resolver.scheme(), resolver);
146 }
147 fn get(&self, scheme: &str) -> Option<&Arc<dyn SecretResolver>> {
148 self.resolvers.get(scheme)
149 }
150}
151
152fn make_resolver(scheme: &str) -> CliResult<Arc<dyn SecretResolver>> {
156 match scheme {
157 #[cfg(feature = "secrets-vault")]
158 "vault" => Ok(Arc::new(vault::VaultResolver::from_env()?)),
159 #[cfg(feature = "secrets-aws-sm")]
160 "aws-sm" => Ok(Arc::new(aws_sm::AwsSmResolver::new())),
161 #[cfg(feature = "secrets-gcp-sm")]
162 "gcp-sm" => Ok(Arc::new(gcp_sm::GcpSmResolver::new())),
163 #[cfg(feature = "secrets-azure-kv")]
164 "azure-kv" => Ok(Arc::new(azure_kv::AzureKvResolver::new())),
165 other => Err(CliError::SecretBackendDisabled {
166 scheme: other.to_owned(),
167 }),
168 }
169}
170
171fn visit_config_values<F: FnMut(&Value)>(cfg: &PipelineConfig, mut f: F) {
174 if let Some(auth) = cfg.auth.as_ref() {
178 for spec in auth.values() {
179 f(spec);
180 }
181 }
182 if let Some(vars) = cfg.vars.as_ref() {
183 for v in vars.values() {
184 f(v);
185 }
186 }
187 if let Some(r) = cfg.replication.as_ref() {
190 f(&r.snapshot.source.config);
191 }
192 for spec in cfg.pipeline.sources.values() {
193 f(&spec.config);
194 }
195 for spec in cfg.pipeline.sinks.values() {
196 f(&spec.config);
197 }
198 if let Some(spec) = cfg.pipeline.source.as_ref() {
199 f(&spec.config);
200 }
201 if let Some(spec) = cfg.pipeline.sink.as_ref() {
202 f(&spec.config);
203 }
204 for t in cfg.pipeline.transforms.iter() {
205 f(&t.config);
206 }
207 if let Some(s) = cfg.pipeline.state.as_ref() {
208 f(&s.config);
209 }
210 if let Some(d) = cfg.pipeline.dlq.as_ref() {
211 f(&d.sink.config);
212 }
213 for row in cfg.matrix.iter() {
214 if let Some(p) = row.source.as_ref()
215 && let Some(c) = p.config.as_ref()
216 {
217 f(c);
218 }
219 if let Some(p) = row.sink.as_ref()
220 && let Some(c) = p.config.as_ref()
221 {
222 f(c);
223 }
224 if let Some(ts) = row.transforms.as_ref() {
225 for t in ts.iter() {
226 f(&t.config);
227 }
228 }
229 if let Some(s) = row.state.as_ref() {
230 f(&s.config);
231 }
232 if let Some(Some(d)) = row.dlq.as_ref() {
233 f(&d.sink.config);
234 }
235 }
236}
237
238fn visit_config_values_mut<F: FnMut(&mut Value) -> CliResult<()>>(
240 cfg: &mut PipelineConfig,
241 mut f: F,
242) -> CliResult<()> {
243 if let Some(auth) = cfg.auth.as_mut() {
246 for spec in auth.values_mut() {
247 f(spec)?;
248 }
249 }
250 if let Some(vars) = cfg.vars.as_mut() {
251 for v in vars.values_mut() {
252 f(v)?;
253 }
254 }
255 if let Some(r) = cfg.replication.as_mut() {
258 f(&mut r.snapshot.source.config)?;
259 }
260 for spec in cfg.pipeline.sources.values_mut() {
261 f(&mut spec.config)?;
262 }
263 for spec in cfg.pipeline.sinks.values_mut() {
264 f(&mut spec.config)?;
265 }
266 if let Some(spec) = cfg.pipeline.source.as_mut() {
267 f(&mut spec.config)?;
268 }
269 if let Some(spec) = cfg.pipeline.sink.as_mut() {
270 f(&mut spec.config)?;
271 }
272 for t in cfg.pipeline.transforms.iter_mut() {
273 f(&mut t.config)?;
274 }
275 if let Some(s) = cfg.pipeline.state.as_mut() {
276 f(&mut s.config)?;
277 }
278 if let Some(d) = cfg.pipeline.dlq.as_mut() {
279 f(&mut d.sink.config)?;
280 }
281 for row in cfg.matrix.iter_mut() {
282 if let Some(p) = row.source.as_mut()
283 && let Some(c) = p.config.as_mut()
284 {
285 f(c)?;
286 }
287 if let Some(p) = row.sink.as_mut()
288 && let Some(c) = p.config.as_mut()
289 {
290 f(c)?;
291 }
292 if let Some(ts) = row.transforms.as_mut() {
293 for t in ts.iter_mut() {
294 f(&mut t.config)?;
295 }
296 }
297 if let Some(s) = row.state.as_mut() {
298 f(&mut s.config)?;
299 }
300 if let Some(Some(d)) = row.dlq.as_mut() {
301 f(&mut d.sink.config)?;
302 }
303 }
304 Ok(())
305}
306
307pub(crate) fn scan_config(cfg: &PipelineConfig) -> BTreeSet<SecretRef> {
309 let mut refs = BTreeSet::new();
310 visit_config_values(cfg, |v| collect_refs(v, &mut refs));
311 refs
312}
313
314pub fn scan_path_refs(
316 path: &std::path::Path,
317 profile: Option<&str>,
318) -> CliResult<BTreeSet<SecretRef>> {
319 let cfg = PipelineConfig::from_path_tolerating_secrets(path, profile)?;
320 Ok(scan_config(&cfg))
321}
322
323pub fn ensure_no_secret_directives(cfg: &PipelineConfig) -> CliResult<()> {
326 if scan_config(cfg).is_empty() {
327 Ok(())
328 } else {
329 Err(CliError::SecretsRequireAsyncLoad)
330 }
331}
332
333pub async fn resolve_secrets(cfg: &mut PipelineConfig) -> CliResult<()> {
336 let refs = scan_config(cfg);
337 if refs.is_empty() {
338 return Ok(());
339 }
340 let mut set = ResolverSet::default();
341 let schemes: BTreeSet<&str> = refs.iter().map(|(s, _)| s.as_str()).collect();
342 for scheme in schemes {
343 set.insert(make_resolver(scheme)?);
344 }
345 resolve_secrets_with(cfg, &set).await
346}
347
348pub async fn resolve_secrets_with(cfg: &mut PipelineConfig, set: &ResolverSet) -> CliResult<()> {
351 let refs = scan_config(cfg);
352 if refs.is_empty() {
353 return Ok(());
354 }
355 let cache = fetch_all(&refs, set).await?;
356 visit_config_values_mut(cfg, |v| substitute(v, &cache))
357}
358
359async fn fetch_all(
362 refs: &BTreeSet<SecretRef>,
363 set: &ResolverSet,
364) -> CliResult<HashMap<SecretRef, String>> {
365 const MAX_CONCURRENCY: usize = 8;
366 let pairs: Vec<(SecretRef, String)> =
367 stream::iter(refs.iter().cloned())
368 .map(|(scheme, reference)| async move {
369 let resolver = Arc::clone(set.get(&scheme).ok_or_else(|| {
372 CliError::SecretBackendDisabled {
373 scheme: scheme.clone(),
374 }
375 })?);
376 let value = resolver.resolve(&reference).await?;
377 registry::register(&value);
378 Ok::<(SecretRef, String), CliError>(((scheme, reference), value))
379 })
380 .buffer_unordered(MAX_CONCURRENCY)
381 .try_collect()
382 .await?;
383 Ok(pairs.into_iter().collect())
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use serde_json::json;
390
391 #[test]
392 fn collects_unique_refs_and_ignores_other_directives() {
393 let v = json!({
394 "a": "${vault:secret/data/app#token}",
395 "b": "${aws-sm:prod/db#password}",
396 "c": "${vault:secret/data/app#token}",
397 "d": "${users.id}",
398 "e": "${env:HOME}",
399 "nested": ["${gcp-sm:projects/p/secrets/s/versions/latest}"]
400 });
401 let mut refs = BTreeSet::new();
402 collect_refs(&v, &mut refs);
403 assert_eq!(refs.len(), 3);
404 assert!(refs.contains(&("vault".into(), "secret/data/app#token".into())));
405 assert!(refs.contains(&("aws-sm".into(), "prod/db#password".into())));
406 assert!(refs.contains(&(
407 "gcp-sm".into(),
408 "projects/p/secrets/s/versions/latest".into()
409 )));
410 }
411
412 #[test]
413 fn substitutes_from_cache_and_preserves_runtime_refs() {
414 let mut v = json!({
415 "token": "Bearer ${vault:secret/data/app#token}",
416 "path": "/v1/${users.id}"
417 });
418 let mut cache = HashMap::new();
419 cache.insert(
420 ("vault".into(), "secret/data/app#token".into()),
421 "abc123".into(),
422 );
423 substitute(&mut v, &cache).unwrap();
424 assert_eq!(v["token"], "Bearer abc123");
425 assert_eq!(v["path"], "/v1/${users.id}");
426 }
427
428 #[test]
429 fn extract_field_picks_key_or_errors_with_available() {
430 let body = r#"{"username":"u","password":"p"}"#;
431 assert_eq!(
432 extract_field("aws-sm", "ref", body, "password").unwrap(),
433 "p"
434 );
435 match extract_field("aws-sm", "ref", body, "missing").unwrap_err() {
436 CliError::SecretFieldMissing { available, .. } => {
437 assert!(available.contains(&"username".to_string()));
438 }
439 other => panic!("expected SecretFieldMissing, got {other:?}"),
440 }
441 match extract_field("aws-sm", "ref", "not json", "x").unwrap_err() {
442 CliError::SecretNotJson { .. } => {}
443 other => panic!("expected SecretNotJson, got {other:?}"),
444 }
445 }
446
447 struct FakeResolver {
448 scheme: &'static str,
449 value: String,
450 }
451 #[async_trait]
452 impl SecretResolver for FakeResolver {
453 fn scheme(&self) -> &'static str {
454 self.scheme
455 }
456 async fn resolve(&self, _reference: &str) -> CliResult<String> {
457 Ok(self.value.clone())
458 }
459 }
460
461 #[tokio::test]
462 async fn resolve_secrets_with_substitutes_via_injected_resolvers() {
463 let mut set = ResolverSet::default();
464 set.insert(Arc::new(FakeResolver {
465 scheme: "vault",
466 value: "RESOLVED".into(),
467 }));
468 let cfg_yaml = r#"
469version: 1
470pipeline:
471 source: { type: rest, config: { base_url: https://x, auth: { type: bearer, config: { token: "${vault:secret/data/app#token}" } } } }
472 sink: { type: jsonl, config: { path: ./o.jsonl } }
473"#;
474 let mut cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
475 resolve_secrets_with(&mut cfg, &set).await.unwrap();
476 let token = &cfg.pipeline.source.as_ref().unwrap().config["auth"]["config"]["token"];
477 assert_eq!(token, "RESOLVED");
478 }
479
480 #[tokio::test]
481 async fn resolve_secrets_resolves_auth_catalog_and_vars_block() {
482 let mut set = ResolverSet::default();
486 set.insert(Arc::new(FakeResolver {
487 scheme: "vault",
488 value: "RESOLVED".into(),
489 }));
490 let cfg_yaml = r#"
491version: 1
492vars:
493 shared_token: "${vault:secret/data/app#token}"
494auth:
495 idp: { type: static, config: { token: "${vault:secret/data/idp#token}" } }
496pipeline:
497 source: { type: rest, config: { base_url: https://x, auth: { ref: idp } } }
498 sink: { type: jsonl, config: { path: ./o.jsonl } }
499"#;
500 let mut cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
501 resolve_secrets_with(&mut cfg, &set).await.unwrap();
502
503 let auth_token = &cfg.auth.as_ref().unwrap()["idp"]["config"]["token"];
504 assert_eq!(auth_token, "RESOLVED", "auth-catalog secret should resolve");
505
506 let var_value = &cfg.vars.as_ref().unwrap()["shared_token"];
507 assert_eq!(var_value, "RESOLVED", "vars-block secret should resolve");
508 }
509
510 #[tokio::test]
511 async fn scan_config_collects_refs_from_auth_and_vars() {
512 let cfg_yaml = r#"
515version: 1
516vars:
517 v: "${aws-sm:prod/api#key}"
518auth:
519 idp: { type: static, config: { token: "${vault:secret/data/idp#token}" } }
520pipeline:
521 source: { type: rest, config: { base_url: https://x, auth: { ref: idp } } }
522 sink: { type: jsonl, config: { path: ./o.jsonl } }
523"#;
524 let cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
525 let refs = scan_config(&cfg);
526 assert!(refs.contains(&("vault".into(), "secret/data/idp#token".into())));
527 assert!(refs.contains(&("aws-sm".into(), "prod/api#key".into())));
528 }
529
530 #[tokio::test]
531 async fn resolve_secrets_errors_when_backend_not_built() {
532 let set = ResolverSet::default();
533 let cfg_yaml = r#"
534version: 1
535pipeline:
536 source: { type: rest, config: { url: "${vault:secret/x}" } }
537 sink: { type: jsonl, config: { path: ./o.jsonl } }
538"#;
539 let mut cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
540 match resolve_secrets_with(&mut cfg, &set).await.unwrap_err() {
541 CliError::SecretBackendDisabled { scheme } => assert_eq!(scheme, "vault"),
542 other => panic!("expected SecretBackendDisabled, got {other:?}"),
543 }
544 }
545
546 #[test]
547 fn make_resolver_rejects_unknown_scheme() {
548 match make_resolver("not-a-scheme") {
549 Err(CliError::SecretBackendDisabled { scheme }) => assert_eq!(scheme, "not-a-scheme"),
550 Err(other) => panic!("expected SecretBackendDisabled, got {other:?}"),
551 Ok(_) => panic!("expected SecretBackendDisabled for an unknown scheme"),
552 }
553 }
554
555 #[cfg(feature = "secrets-aws-sm")]
556 #[test]
557 fn make_resolver_builds_compiled_in_aws_backend() {
558 let r = make_resolver("aws-sm").unwrap();
561 assert_eq!(r.scheme(), "aws-sm");
562 }
563
564 #[tokio::test]
565 async fn resolve_secrets_walks_matrix_row_state_dlq_and_transforms() {
566 let mut set = ResolverSet::default();
569 set.insert(Arc::new(FakeResolver {
570 scheme: "vault",
571 value: "R".into(),
572 }));
573 let cfg_yaml = r#"
574version: 1
575pipeline:
576 source: { type: csv, config: { path: ./in.csv } }
577 sink: { type: jsonl, config: { path: ./o.jsonl } }
578matrix:
579 - id: row1
580 source: { config: { path: "${vault:secret/src}" } }
581 sink: { config: { path: "${vault:secret/sink}" } }
582 state: { type: file, config: { path: "${vault:secret/state}" } }
583 transforms:
584 - type: set
585 config: { field: tag, value: "${vault:secret/tf}" }
586 dlq:
587 sink: { type: jsonl, config: { path: "${vault:secret/dlq}" } }
588"#;
589 let mut cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
590 resolve_secrets_with(&mut cfg, &set).await.unwrap();
591
592 let row = &cfg.matrix[0];
593 assert_eq!(
594 row.source.as_ref().unwrap().config.as_ref().unwrap()["path"],
595 "R"
596 );
597 assert_eq!(
598 row.sink.as_ref().unwrap().config.as_ref().unwrap()["path"],
599 "R"
600 );
601 assert_eq!(row.state.as_ref().unwrap().config["path"], "R");
602 assert_eq!(row.transforms.as_ref().unwrap()[0].config["value"], "R");
603 let dlq = row.dlq.as_ref().unwrap().as_ref().unwrap();
604 assert_eq!(dlq.sink.config["path"], "R");
605 }
606
607 #[test]
608 fn scan_config_collects_refs_from_matrix_row_state_and_dlq() {
609 let cfg_yaml = r#"
611version: 1
612pipeline:
613 source: { type: csv, config: { path: ./in.csv } }
614 sink: { type: jsonl, config: { path: ./o.jsonl } }
615matrix:
616 - id: r
617 state: { type: file, config: { path: "${vault:secret/state}" } }
618 transforms:
619 - type: set
620 config: { field: t, value: "${aws-sm:tf/key}" }
621 dlq:
622 sink: { type: jsonl, config: { path: "${gcp-sm:projects/p/secrets/s/versions/1}" } }
623"#;
624 let cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
625 let refs = scan_config(&cfg);
626 assert!(refs.contains(&("vault".into(), "secret/state".into())));
627 assert!(refs.contains(&("aws-sm".into(), "tf/key".into())));
628 assert!(refs.contains(&("gcp-sm".into(), "projects/p/secrets/s/versions/1".into())));
629 }
630
631 #[test]
632 fn scan_config_collects_refs_from_replication_snapshot_source() {
633 let cfg_yaml = r#"
636version: 1
637pipeline:
638 source: { type: postgres-cdc, config: {} }
639 sink: { type: jsonl, config: { path: ./o.jsonl } }
640replication:
641 mode: snapshot_then_cdc
642 snapshot:
643 source:
644 type: postgres
645 config: { connection_url: "${vault:secret/data/db#url}", query: "SELECT 1" }
646"#;
647 let cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
648 let refs = scan_config(&cfg);
649 assert!(refs.contains(&("vault".into(), "secret/data/db#url".into())));
650 }
651
652 #[tokio::test]
653 async fn resolve_secrets_noop_when_no_directives() {
654 let cfg_yaml = r#"
657version: 1
658pipeline:
659 source: { type: csv, config: { path: ./in.csv } }
660 sink: { type: jsonl, config: { path: ./o.jsonl } }
661"#;
662 let mut cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
663 resolve_secrets(&mut cfg).await.unwrap();
664 }
665
666 #[test]
667 fn split_field_splits_on_hash() {
668 assert_eq!(split_field("a/b#c"), ("a/b", Some("c")));
669 assert_eq!(split_field("a/b"), ("a/b", None));
670 }
671
672 #[test]
673 fn ensure_no_secret_directives_passes_when_clean() {
674 let cfg_yaml = r#"
675version: 1
676pipeline:
677 source: { type: csv, config: { path: ./in.csv } }
678 sink: { type: jsonl, config: { path: ./o.jsonl } }
679"#;
680 let cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
681 assert!(ensure_no_secret_directives(&cfg).is_ok());
682 }
683
684 #[test]
685 fn ensure_no_secret_directives_flags_vault() {
686 let cfg_yaml = r#"
687version: 1
688pipeline:
689 source: { type: rest, config: { url: "${vault:secret/x}" } }
690 sink: { type: jsonl, config: { path: ./o.jsonl } }
691"#;
692 let cfg = PipelineConfig::from_text(cfg_yaml, std::path::Path::new("p.yaml")).unwrap();
693 assert!(matches!(
694 ensure_no_secret_directives(&cfg),
695 Err(CliError::SecretsRequireAsyncLoad)
696 ));
697 }
698}