Skip to main content

minco_config/
graph.rs

1use crate::{
2    ConfigDiagnostic, ConfigLayer, ConfigSourceKind, ConfigurationError, ConfigurationSchema,
3    ConfigurationValueKind, SecretReference, value_matches,
4};
5use serde::{Deserialize, Serialize, de::DeserializeOwned};
6use serde_json::{Map, Value};
7use sha2::{Digest, Sha256};
8use std::{
9    collections::{BTreeMap, BTreeSet},
10    fmt,
11};
12
13/// Fail-closed operational environment class.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum EnvironmentClass {
17    Local,
18    Test,
19    Development,
20    Staging,
21    Production,
22}
23
24/// Named environment and its operational class.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Environment {
27    pub name: String,
28    pub class: EnvironmentClass,
29}
30
31impl Environment {
32    pub fn new(name: impl Into<String>, class: EnvironmentClass) -> Self {
33        Self {
34            name: name.into(),
35            class,
36        }
37    }
38}
39
40/// Public provenance for one effective field. It contains no field value.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct ConfigProvenance {
43    pub source_kind: ConfigSourceKind,
44    pub source: String,
45    #[serde(default, skip_serializing_if = "Vec::is_empty")]
46    pub overrode: Vec<ConfigSource>,
47}
48
49/// One earlier source in an override chain.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct ConfigSource {
52    pub source_kind: ConfigSourceKind,
53    pub source: String,
54}
55
56/// Secret-safe explanation of one effective field.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct ConfigExplanation {
59    pub path: String,
60    pub kind: ConfigurationValueKind,
61    pub required: bool,
62    pub secret: bool,
63    pub redacted: bool,
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub value: Option<Value>,
66    pub provenance: ConfigProvenance,
67}
68
69/// Secret-safe deterministic difference between two effective graphs.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct ConfigDiff {
72    pub from: Environment,
73    pub to: Environment,
74    pub from_digest: String,
75    pub to_digest: String,
76    pub changes: Vec<ConfigDiffEntry>,
77}
78
79/// One changed effective field. Secret values and reference names are omitted.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct ConfigDiffEntry {
82    pub path: String,
83    pub secret: bool,
84    pub redacted: bool,
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub before: Option<Value>,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub after: Option<Value>,
89}
90
91#[derive(Clone, PartialEq, Eq)]
92struct EffectiveEntry {
93    value: Value,
94    provenance: ConfigProvenance,
95}
96
97/// Validated, typed and deterministically digested effective configuration.
98#[derive(Clone, PartialEq, Eq)]
99pub struct ConfigurationGraph {
100    environment: Environment,
101    schema: ConfigurationSchema,
102    entries: BTreeMap<String, EffectiveEntry>,
103    digest: String,
104}
105
106impl ConfigurationGraph {
107    pub fn compile(
108        schema: &ConfigurationSchema,
109        environment: Environment,
110        layers: impl IntoIterator<Item = ConfigLayer>,
111    ) -> Result<Self, ConfigurationError> {
112        let mut diagnostics = Vec::new();
113        if !valid_environment_name(&environment.name) {
114            diagnostics.push(ConfigDiagnostic::new(
115                "config.invalid_environment",
116                "environment name must be a bounded lowercase identifier",
117            ));
118        }
119
120        let mut layers: Vec<_> = layers.into_iter().collect();
121        layers.sort_by_key(|layer| layer.source_kind.precedence());
122        validate_layer_set(&environment, &layers, &mut diagnostics);
123
124        let mut entries = BTreeMap::new();
125        for (path, field) in schema.fields() {
126            if let Some(default) = &field.default {
127                entries.insert(
128                    path.to_owned(),
129                    EffectiveEntry {
130                        value: default.clone(),
131                        provenance: ConfigProvenance {
132                            source_kind: ConfigSourceKind::CompiledDefault,
133                            source: "compiled default".into(),
134                            overrode: Vec::new(),
135                        },
136                    },
137                );
138            }
139        }
140
141        for layer in &layers {
142            let flattened = flatten_layer(schema, layer, &mut diagnostics);
143            for (path, raw_value) in flattened {
144                let Some(field) = schema.field(&path) else {
145                    diagnostics.push(
146                        ConfigDiagnostic::new(
147                            "config.unknown_field",
148                            "field is not declared by the application or an enabled plugin",
149                        )
150                        .with_path(path)
151                        .with_source(&layer.source),
152                    );
153                    continue;
154                };
155                let value = if field.secret {
156                    let Some(reference) = raw_value.as_str() else {
157                        diagnostics.push(
158                            ConfigDiagnostic::new(
159                                "config.secret_reference_required",
160                                "secret fields accept only env:NAME or ssm:/absolute/name references",
161                            )
162                            .with_path(path)
163                            .with_source(&layer.source),
164                        );
165                        continue;
166                    };
167                    match SecretReference::parse(reference).and_then(|reference| {
168                        serde_json::to_value(reference)
169                            .map_err(|_| crate::SecretReferenceError::UnsupportedSyntax)
170                    }) {
171                        Ok(value) => value,
172                        Err(error) => {
173                            diagnostics.push(
174                                ConfigDiagnostic::new(
175                                    "config.invalid_secret_reference",
176                                    error.to_string(),
177                                )
178                                .with_path(path)
179                                .with_source(&layer.source),
180                            );
181                            continue;
182                        }
183                    }
184                } else if value_matches(field.kind, &raw_value) {
185                    raw_value
186                } else {
187                    diagnostics.push(
188                        ConfigDiagnostic::new(
189                            "config.type_mismatch",
190                            format!("value does not match {:?}", field.kind),
191                        )
192                        .with_path(path)
193                        .with_source(&layer.source),
194                    );
195                    continue;
196                };
197
198                let mut overrode = Vec::new();
199                if let Some(previous) = entries.get(&path) {
200                    overrode.extend(previous.provenance.overrode.clone());
201                    overrode.push(ConfigSource {
202                        source_kind: previous.provenance.source_kind,
203                        source: previous.provenance.source.clone(),
204                    });
205                }
206                entries.insert(
207                    path,
208                    EffectiveEntry {
209                        value,
210                        provenance: ConfigProvenance {
211                            source_kind: layer.source_kind,
212                            source: layer.source.clone(),
213                            overrode,
214                        },
215                    },
216                );
217            }
218        }
219
220        for (path, field) in schema.fields() {
221            if field.required && !entries.contains_key(path) {
222                diagnostics.push(
223                    ConfigDiagnostic::new(
224                        "config.required_field_missing",
225                        "required field has no effective value",
226                    )
227                    .with_path(path),
228                );
229            }
230        }
231        if !diagnostics.is_empty() {
232            return Err(ConfigurationError::new(diagnostics));
233        }
234
235        let digest = effective_digest(&environment, &entries).map_err(|_| {
236            ConfigurationError::new(vec![ConfigDiagnostic::new(
237                "config.digest_encoding",
238                "effective configuration could not be encoded deterministically",
239            )])
240        })?;
241        Ok(Self {
242            environment,
243            schema: schema.clone(),
244            entries,
245            digest,
246        })
247    }
248
249    pub const fn environment(&self) -> &Environment {
250        &self.environment
251    }
252
253    pub fn digest(&self) -> &str {
254        &self.digest
255    }
256
257    pub fn explain(&self, path: &str) -> Option<ConfigExplanation> {
258        let field = self.schema.field(path)?;
259        let entry = self.entries.get(path)?;
260        Some(ConfigExplanation {
261            path: path.into(),
262            kind: field.kind,
263            required: field.required,
264            secret: field.secret,
265            redacted: field.secret,
266            value: (!field.secret).then(|| entry.value.clone()),
267            provenance: entry.provenance.clone(),
268        })
269    }
270
271    pub fn explanations(&self) -> Vec<ConfigExplanation> {
272        self.schema
273            .fields()
274            .filter_map(|(path, _)| self.explain(path))
275            .collect()
276    }
277
278    pub fn diff(&self, other: &Self) -> ConfigDiff {
279        let paths = self
280            .entries
281            .keys()
282            .chain(other.entries.keys())
283            .map(String::as_str)
284            .collect::<BTreeSet<_>>();
285        let changes = paths
286            .into_iter()
287            .filter_map(|path| {
288                let before = self.entries.get(path);
289                let after = other.entries.get(path);
290                if before.map(|entry| &entry.value) == after.map(|entry| &entry.value) {
291                    return None;
292                }
293                let secret = self.schema.field(path).is_some_and(|field| field.secret)
294                    || other.schema.field(path).is_some_and(|field| field.secret);
295                Some(ConfigDiffEntry {
296                    path: path.into(),
297                    secret,
298                    redacted: secret,
299                    before: (!secret)
300                        .then(|| before.map(|entry| entry.value.clone()))
301                        .flatten(),
302                    after: (!secret)
303                        .then(|| after.map(|entry| entry.value.clone()))
304                        .flatten(),
305                })
306            })
307            .collect();
308        ConfigDiff {
309            from: self.environment.clone(),
310            to: other.environment.clone(),
311            from_digest: self.digest.clone(),
312            to_digest: other.digest.clone(),
313            changes,
314        }
315    }
316
317    /// Deserialize one namespace at the application composition boundary.
318    pub fn deserialize_namespace<T: DeserializeOwned>(
319        &self,
320        namespace: &str,
321    ) -> Result<T, ConfigurationError> {
322        let prefix = format!("{namespace}.");
323        let known = self.schema.field(namespace).is_some()
324            || self
325                .schema
326                .fields()
327                .any(|(path, _)| path.starts_with(&prefix));
328        let secret_bearing = self
329            .schema
330            .field(namespace)
331            .is_some_and(|field| field.secret)
332            || self
333                .schema
334                .fields()
335                .any(|(path, field)| path.starts_with(&prefix) && field.secret);
336        if !known {
337            return Err(ConfigurationError::new(vec![
338                ConfigDiagnostic::new(
339                    "config.unknown_namespace",
340                    "typed constructor requested an undeclared configuration namespace",
341                )
342                .with_path(namespace),
343            ]));
344        }
345        if let Some(entry) = self.entries.get(namespace) {
346            return deserialize_typed(namespace, entry.value.clone(), secret_bearing);
347        }
348        let mut root = Map::new();
349        for (path, entry) in &self.entries {
350            if let Some(relative) = path.strip_prefix(&prefix) {
351                insert_nested(&mut root, relative, entry.value.clone());
352            }
353        }
354        deserialize_typed(namespace, Value::Object(root), secret_bearing)
355    }
356
357    pub const fn schema(&self) -> &ConfigurationSchema {
358        &self.schema
359    }
360}
361
362impl fmt::Debug for ConfigurationGraph {
363    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
364        formatter
365            .debug_struct("ConfigurationGraph")
366            .field("environment", &self.environment)
367            .field("digest", &self.digest)
368            .field("field_count", &self.entries.len())
369            .finish_non_exhaustive()
370    }
371}
372
373fn valid_environment_name(value: &str) -> bool {
374    let mut bytes = value.bytes();
375    let Some(first) = bytes.next() else {
376        return false;
377    };
378    value.len() <= 64
379        && first.is_ascii_lowercase()
380        && bytes.all(|byte| {
381            byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-' || byte == b'_'
382        })
383}
384
385fn validate_layer_set(
386    environment: &Environment,
387    layers: &[ConfigLayer],
388    diagnostics: &mut Vec<ConfigDiagnostic>,
389) {
390    let mut kinds = BTreeSet::new();
391    for layer in layers {
392        if !kinds.insert(layer.source_kind) {
393            diagnostics.push(
394                ConfigDiagnostic::new(
395                    "config.duplicate_layer",
396                    "each precedence class may be supplied at most once",
397                )
398                .with_source(&layer.source),
399            );
400        }
401        match layer.source_kind {
402            ConfigSourceKind::CompiledDefault => diagnostics.push(
403                ConfigDiagnostic::new(
404                    "config.compiled_layer_forbidden",
405                    "compiled defaults are declared by the schema, not supplied as a layer",
406                )
407                .with_source(&layer.source),
408            ),
409            ConfigSourceKind::EnvironmentFile => match layer.environment_class {
410                None => diagnostics.push(
411                    ConfigDiagnostic::new(
412                        "config.environment_class_missing",
413                        "environment files must declare environment_class",
414                    )
415                    .with_source(&layer.source),
416                ),
417                Some(class) if class != environment.class => diagnostics.push(
418                    ConfigDiagnostic::new(
419                        "config.environment_class_mismatch",
420                        format!(
421                            "file declares {class:?} but selected environment is {:?}",
422                            environment.class
423                        ),
424                    )
425                    .with_source(&layer.source),
426                ),
427                Some(_) => {}
428            },
429            ConfigSourceKind::LocalOverride
430                if !matches!(
431                    environment.class,
432                    EnvironmentClass::Local | EnvironmentClass::Development
433                ) =>
434            {
435                diagnostics.push(
436                    ConfigDiagnostic::new(
437                        "config.local_override_forbidden",
438                        "local overrides are permitted only for local and development classes",
439                    )
440                    .with_source(&layer.source),
441                );
442            }
443            _ if layer.environment_class.is_some() => diagnostics.push(
444                ConfigDiagnostic::new(
445                    "config.environment_class_unexpected",
446                    "only an environment file may declare environment_class",
447                )
448                .with_source(&layer.source),
449            ),
450            _ => {}
451        }
452    }
453}
454
455fn flatten_layer(
456    schema: &ConfigurationSchema,
457    layer: &ConfigLayer,
458    diagnostics: &mut Vec<ConfigDiagnostic>,
459) -> BTreeMap<String, Value> {
460    let mut result = BTreeMap::new();
461    for (key, value) in &layer.values {
462        flatten_value(schema, key, value, &mut result, diagnostics, &layer.source);
463    }
464    result
465}
466
467fn flatten_value(
468    schema: &ConfigurationSchema,
469    path: &str,
470    value: &Value,
471    result: &mut BTreeMap<String, Value>,
472    diagnostics: &mut Vec<ConfigDiagnostic>,
473    source: &str,
474) {
475    if schema
476        .field(path)
477        .is_some_and(|field| field.kind == ConfigurationValueKind::Object && !field.secret)
478    {
479        insert_flattened(result, path, value, diagnostics, source);
480        return;
481    }
482    if let Some(object) = value.as_object() {
483        if object.is_empty() {
484            diagnostics.push(
485                ConfigDiagnostic::new(
486                    "config.empty_table",
487                    "empty configuration tables cannot select a typed field",
488                )
489                .with_path(path)
490                .with_source(source),
491            );
492            return;
493        }
494        for (key, nested) in object {
495            flatten_value(
496                schema,
497                &format!("{path}.{key}"),
498                nested,
499                result,
500                diagnostics,
501                source,
502            );
503        }
504    } else {
505        insert_flattened(result, path, value, diagnostics, source);
506    }
507}
508
509fn insert_flattened(
510    result: &mut BTreeMap<String, Value>,
511    path: &str,
512    value: &Value,
513    diagnostics: &mut Vec<ConfigDiagnostic>,
514    source: &str,
515) {
516    if result.insert(path.into(), value.clone()).is_some() {
517        diagnostics.push(
518            ConfigDiagnostic::new(
519                "config.duplicate_field",
520                "one configuration layer resolves multiple values to the same path",
521            )
522            .with_path(path)
523            .with_source(source),
524        );
525    }
526}
527
528fn effective_digest(
529    environment: &Environment,
530    entries: &BTreeMap<String, EffectiveEntry>,
531) -> Result<String, serde_json::Error> {
532    #[derive(Serialize)]
533    struct DigestMaterial<'a> {
534        schema: u32,
535        environment: &'a Environment,
536        values: BTreeMap<&'a str, &'a Value>,
537    }
538
539    let values = entries
540        .iter()
541        .map(|(path, entry)| (path.as_str(), &entry.value))
542        .collect();
543    let bytes = serde_json::to_vec(&DigestMaterial {
544        schema: ConfigurationSchema::SCHEMA_VERSION,
545        environment,
546        values,
547    })?;
548    Ok(hex::encode(Sha256::digest(bytes)))
549}
550
551fn deserialize_typed<T: DeserializeOwned>(
552    namespace: &str,
553    value: Value,
554    secret_bearing: bool,
555) -> Result<T, ConfigurationError> {
556    serde_json::from_value(value).map_err(|error| {
557        let message = if secret_bearing {
558            "typed constructor rejected a secret-bearing namespace".into()
559        } else {
560            format!("typed constructor rejected namespace: {error}")
561        };
562        ConfigurationError::new(vec![
563            ConfigDiagnostic::new("config.typed_deserialization", message).with_path(namespace),
564        ])
565    })
566}
567
568fn insert_nested(root: &mut Map<String, Value>, path: &str, value: Value) {
569    let mut segments = path.split('.').peekable();
570    let mut current = root;
571    while let Some(segment) = segments.next() {
572        if segments.peek().is_none() {
573            current.insert(segment.into(), value);
574            return;
575        }
576        let entry = current
577            .entry(segment)
578            .or_insert_with(|| Value::Object(Map::new()));
579        current = entry
580            .as_object_mut()
581            .expect("schema paths cannot overlap scalar and object fields");
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588    use crate::{ConfigurationField, ConfigurationValueKind};
589    use serde_json::json;
590
591    #[derive(Debug)]
592    struct EchoesInputOnFailure;
593
594    impl<'de> Deserialize<'de> for EchoesInputOnFailure {
595        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
596        where
597            D: serde::Deserializer<'de>,
598        {
599            let value = Value::deserialize(deserializer)?;
600            Err(serde::de::Error::custom(format!(
601                "typed constructor rejected {value}"
602            )))
603        }
604    }
605
606    #[test]
607    fn caller_layer_order_does_not_change_precedence() {
608        let schema = ConfigurationSchema::try_from_fields([ConfigurationField {
609            key: "application.name".into(),
610            kind: ConfigurationValueKind::String,
611            required: true,
612            secret: false,
613            description: "Name".into(),
614            default: Some(json!("compiled")),
615        }])
616        .unwrap();
617        let environment = Environment::new("dev", EnvironmentClass::Development);
618        let cli = ConfigLayer::from_pairs(
619            ConfigSourceKind::CliOverride,
620            "cli",
621            [("application.name", json!("cli"))],
622        )
623        .unwrap();
624        let file = ConfigLayer::from_pairs(
625            ConfigSourceKind::DefaultFile,
626            "default",
627            [("application.name", json!("file"))],
628        )
629        .unwrap();
630        let graph =
631            ConfigurationGraph::compile(&schema, environment, [cli, file]).expect("valid graph");
632        assert_eq!(
633            graph.explain("application.name").unwrap().value,
634            Some(json!("cli"))
635        );
636    }
637
638    #[test]
639    fn one_layer_cannot_repeat_a_path_with_nested_and_dotted_keys() {
640        let schema = ConfigurationSchema::try_from_fields([ConfigurationField {
641            key: "application.name".into(),
642            kind: ConfigurationValueKind::String,
643            required: true,
644            secret: false,
645            description: "Name".into(),
646            default: None,
647        }])
648        .unwrap();
649        let layer = ConfigLayer::from_pairs(
650            ConfigSourceKind::DefaultFile,
651            "default",
652            [
653                ("application", json!({ "name": "nested" })),
654                ("application.name", json!("dotted")),
655            ],
656        )
657        .unwrap();
658
659        let error = ConfigurationGraph::compile(
660            &schema,
661            Environment::new("dev", EnvironmentClass::Development),
662            [layer],
663        )
664        .unwrap_err();
665        assert_eq!(error.diagnostics()[0].code, "config.duplicate_field");
666    }
667
668    #[test]
669    fn local_override_policy_is_environment_class_specific() {
670        let schema = ConfigurationSchema::try_from_fields([ConfigurationField {
671            key: "application.name".into(),
672            kind: ConfigurationValueKind::String,
673            required: true,
674            secret: false,
675            description: "Name".into(),
676            default: Some(json!("compiled")),
677        }])
678        .unwrap();
679        for class in [
680            EnvironmentClass::Test,
681            EnvironmentClass::Staging,
682            EnvironmentClass::Production,
683        ] {
684            let layer = ConfigLayer::from_pairs(
685                ConfigSourceKind::LocalOverride,
686                ".local.toml",
687                [("application.name", json!("local"))],
688            )
689            .unwrap();
690            let error =
691                ConfigurationGraph::compile(&schema, Environment::new("protected", class), [layer])
692                    .unwrap_err();
693            assert_eq!(
694                error.diagnostics()[0].code,
695                "config.local_override_forbidden"
696            );
697        }
698        for class in [EnvironmentClass::Local, EnvironmentClass::Development] {
699            let layer = ConfigLayer::from_pairs(
700                ConfigSourceKind::LocalOverride,
701                ".local.toml",
702                [("application.name", json!("local"))],
703            )
704            .unwrap();
705            assert!(
706                ConfigurationGraph::compile(&schema, Environment::new("mutable", class), [layer])
707                    .is_ok()
708            );
709        }
710    }
711
712    #[test]
713    fn diff_redacts_when_either_schema_marks_a_field_secret() {
714        let public_schema = ConfigurationSchema::try_from_fields([ConfigurationField {
715            key: "integration.token".into(),
716            kind: ConfigurationValueKind::String,
717            required: true,
718            secret: false,
719            description: "Legacy public field".into(),
720            default: Some(json!("PUBLIC_TOKEN_SHOULD_NOT_LEAK")),
721        }])
722        .unwrap();
723        let secret_schema = ConfigurationSchema::try_from_fields([ConfigurationField {
724            key: "integration.token".into(),
725            kind: ConfigurationValueKind::String,
726            required: true,
727            secret: true,
728            description: "Secret reference".into(),
729            default: None,
730        }])
731        .unwrap();
732        let before = ConfigurationGraph::compile(
733            &public_schema,
734            Environment::new("development", EnvironmentClass::Development),
735            [],
736        )
737        .unwrap();
738        let after = ConfigurationGraph::compile(
739            &secret_schema,
740            Environment::new("after", EnvironmentClass::Production),
741            [ConfigLayer::from_pairs(
742                ConfigSourceKind::EnvironmentVariables,
743                "environment",
744                [("integration.token", json!("env:INTEGRATION_TOKEN"))],
745            )
746            .unwrap()],
747        )
748        .unwrap();
749
750        let rendered = serde_json::to_string(&before.diff(&after)).unwrap();
751        assert!(!rendered.contains("PUBLIC_TOKEN_SHOULD_NOT_LEAK"));
752        assert!(!rendered.contains("INTEGRATION_TOKEN"));
753    }
754
755    #[test]
756    fn typed_constructor_rejects_unknown_namespaces() {
757        let schema = ConfigurationSchema::try_from_fields([ConfigurationField {
758            key: "application.name".into(),
759            kind: ConfigurationValueKind::String,
760            required: true,
761            secret: false,
762            description: "Name".into(),
763            default: Some(json!("orders")),
764        }])
765        .unwrap();
766        let graph = ConfigurationGraph::compile(
767            &schema,
768            Environment::new("test", EnvironmentClass::Test),
769            [],
770        )
771        .unwrap();
772        let error = graph
773            .deserialize_namespace::<serde_json::Value>("applicaiton")
774            .unwrap_err();
775        assert_eq!(error.diagnostics()[0].code, "config.unknown_namespace");
776    }
777
778    #[test]
779    fn typed_constructor_errors_redact_secret_bearing_namespaces() {
780        let schema = ConfigurationSchema::try_from_fields([ConfigurationField {
781            key: "database.url".into(),
782            kind: ConfigurationValueKind::String,
783            required: true,
784            secret: true,
785            description: "Database secret reference".into(),
786            default: None,
787        }])
788        .unwrap();
789        let graph = ConfigurationGraph::compile(
790            &schema,
791            Environment::new("test", EnvironmentClass::Test),
792            [ConfigLayer::from_pairs(
793                ConfigSourceKind::EnvironmentVariables,
794                "environment",
795                [("database.url", json!("env:DO_NOT_LEAK"))],
796            )
797            .unwrap()],
798        )
799        .unwrap();
800
801        let error = graph
802            .deserialize_namespace::<EchoesInputOnFailure>("database")
803            .unwrap_err();
804        let diagnostic = &error.diagnostics()[0];
805        assert_eq!(diagnostic.code, "config.typed_deserialization");
806        assert!(!diagnostic.message.contains("DO_NOT_LEAK"));
807        assert!(!format!("{diagnostic:?}").contains("DO_NOT_LEAK"));
808    }
809}