lenso-service 0.1.24

Public contracts for Lenso Providers and Autonomous Services.
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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
use std::collections::{BTreeMap, BTreeSet};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use utoipa::ToSchema;

use crate::extraction_input_digest;

use super::{DeliveryEffects, DeliveryIssue, DeliveryIssueCode, issue};

pub const CONFIG_CONTRACT_PROTOCOL: &str = "lenso.config-contract.v1";
pub const CONFIG_REVISION_PROTOCOL: &str = "lenso.config-revision.v1";
pub const CONFIG_ACTIVATION_PLAN_PROTOCOL: &str = "lenso.config-activation-plan.v1";
pub const CONFIG_ACTIVATION_RECEIPT_PROTOCOL: &str = "lenso.config-activation-receipt.v1";

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ConfigValueType {
    String,
    Integer,
    Number,
    Boolean,
    Object,
    Array,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ConfigFieldSensitivity {
    Public,
    Sensitive,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ConfigFieldScope {
    Service,
    Workload,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ConfigFieldActivation {
    Hot,
    Restart,
}

#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct ConfigField {
    pub path: String,
    pub value_type: ConfigValueType,
    pub required: bool,
    pub sensitivity: ConfigFieldSensitivity,
    pub scope: ConfigFieldScope,
    pub activation: ConfigFieldActivation,
    pub mutable: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigContractDefinition {
    pub protocol: String,
    pub reference: String,
    pub digest: String,
    pub fields: Vec<ConfigField>,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum SecretReferenceStatus {
    Resolved,
    Unresolved,
    Expired,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SecretReference {
    pub reference_id: String,
    pub provider: String,
    pub purpose: String,
    pub scope: String,
    pub status: SecretReferenceStatus,
    #[serde(default)]
    pub metadata: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SecretReferenceObservation {
    pub status: SecretReferenceStatus,
    #[serde(default)]
    pub metadata: BTreeMap<String, String>,
}

/// Replaceable boundary for observing an opaque reference without reading its value.
pub trait SecretProvider: std::fmt::Debug + Send + Sync {
    fn provider_name(&self) -> &str;

    fn observe_reference(&self, reference_id: &str) -> Option<SecretReferenceObservation>;
}

#[derive(Debug, Clone, Default)]
pub struct DeterministicSecretProvider {
    provider_name: String,
    observations: BTreeMap<String, SecretReferenceObservation>,
}

impl DeterministicSecretProvider {
    #[must_use]
    pub fn new(
        provider_name: impl Into<String>,
        observations: impl IntoIterator<Item = (String, SecretReferenceObservation)>,
    ) -> Self {
        Self {
            provider_name: provider_name.into(),
            observations: observations.into_iter().collect(),
        }
    }
}

impl SecretProvider for DeterministicSecretProvider {
    fn provider_name(&self) -> &str {
        &self.provider_name
    }

    fn observe_reference(&self, reference_id: &str) -> Option<SecretReferenceObservation> {
        self.observations.get(reference_id).cloned()
    }
}

#[must_use]
pub fn observe_secret_reference(
    provider: &dyn SecretProvider,
    reference_id: impl Into<String>,
    purpose: impl Into<String>,
    scope: impl Into<String>,
) -> SecretReference {
    let reference_id = reference_id.into();
    let observation = provider
        .observe_reference(&reference_id)
        .filter(|observation| secret_metadata_is_safe(&observation.metadata))
        .unwrap_or(SecretReferenceObservation {
            status: SecretReferenceStatus::Unresolved,
            metadata: BTreeMap::new(),
        });
    SecretReference {
        reference_id,
        provider: provider.provider_name().to_owned(),
        purpose: purpose.into(),
        scope: scope.into(),
        status: observation.status,
        metadata: observation.metadata,
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigImpact {
    pub path: String,
    pub scope: ConfigFieldScope,
    pub activation: ConfigFieldActivation,
    pub mutable: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigRevision {
    pub protocol: String,
    pub revision_id: String,
    pub revision_digest: String,
    pub service_id: String,
    pub contract_reference: String,
    pub contract_digest: String,
    pub values: BTreeMap<String, Value>,
    pub secret_references: Vec<SecretReference>,
    pub impacts: Vec<ConfigImpact>,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ConfigOperation {
    Stage,
    Activate,
    Rollback,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ConfigRevisionActivation {
    Staged,
    Active,
    RolledBack,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigActivationPlan {
    pub protocol: String,
    pub plan_id: String,
    pub plan_digest: String,
    pub environment: String,
    pub expected_environment_revision: u64,
    pub operation: ConfigOperation,
    pub target_revision_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_revision_id: Option<String>,
    pub contract_digest: String,
    pub effects: DeliveryEffects,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigActivationReceipt {
    pub protocol: String,
    pub receipt_id: String,
    pub plan_id: String,
    pub environment: String,
    pub environment_revision_before: u64,
    pub environment_revision_after: u64,
    pub target_revision_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_revision_id: Option<String>,
    pub activation: ConfigRevisionActivation,
    pub effects: DeliveryEffects,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigState {
    pub environment: String,
    pub environment_revision: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub staged_revision_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_revision_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_revision_id: Option<String>,
    #[serde(default)]
    pub history: Vec<ConfigActivationReceipt>,
}

impl ConfigState {
    #[must_use]
    pub fn new(environment: impl Into<String>, environment_revision: u64) -> Self {
        Self {
            environment: environment.into(),
            environment_revision,
            staged_revision_id: None,
            active_revision_id: None,
            previous_revision_id: None,
            history: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConfigApplyRejection {
    pub issues: Vec<DeliveryIssue>,
    pub effects: DeliveryEffects,
}

pub fn build_config_contract(
    reference: impl Into<String>,
    mut fields: Vec<ConfigField>,
) -> Result<ConfigContractDefinition, Vec<DeliveryIssue>> {
    let reference = reference.into();
    fields.sort();
    let mut issues = Vec::new();
    if reference.trim().is_empty() || fields.is_empty() {
        issues.push(issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "A Config Contract requires a stable reference and at least one field.",
            "Declare the exact configuration surface consumed by the Service Release.",
            "Correct the Config Contract and build it again.",
        ));
    }
    let unique_paths = fields
        .iter()
        .map(|field| field.path.as_str())
        .collect::<BTreeSet<_>>();
    if unique_paths.len() != fields.len() || unique_paths.contains("") {
        issues.push(issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "Config Contract field paths must be non-empty and unique.",
            "Assign one stable path to every configuration field.",
            "Correct duplicate or empty paths and build the contract again.",
        ));
    }
    if !issues.is_empty() {
        return Err(issues);
    }
    let digest = digest_json(&(
        CONFIG_CONTRACT_PROTOCOL,
        reference.as_str(),
        fields.as_slice(),
    ));
    Ok(ConfigContractDefinition {
        protocol: CONFIG_CONTRACT_PROTOCOL.to_owned(),
        reference,
        digest,
        fields,
    })
}

pub fn build_config_revision(
    service_id: impl Into<String>,
    contract: &ConfigContractDefinition,
    values: BTreeMap<String, Value>,
    mut secret_references: Vec<SecretReference>,
    secret_provider: &dyn SecretProvider,
) -> Result<ConfigRevision, Vec<DeliveryIssue>> {
    let service_id = service_id.into();
    let mut issues = Vec::new();
    if !config_contract_integrity_is_valid(contract) {
        issues.push(issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "The Config Contract content does not match its digest.",
            "Use the exact Config Contract bound to the Service Release.",
            "Regenerate the Config Contract and Config Revision.",
        ));
    }

    let fields = contract
        .fields
        .iter()
        .map(|field| (field.path.as_str(), field))
        .collect::<BTreeMap<_, _>>();
    for (path, value) in &values {
        let Some(field) = fields.get(path.as_str()) else {
            issues.push(issue(
                DeliveryIssueCode::ConfigContractMismatch,
                format!("Configuration field `{path}` is not declared by the Config Contract."),
                "Remove unknown values or update the Config Contract before building a revision.",
                "Correct the values and build the Config Revision again.",
            ));
            continue;
        };
        if field.sensitivity == ConfigFieldSensitivity::Sensitive {
            issues.push(issue(
                DeliveryIssueCode::PlaintextSecretDetected,
                format!("Sensitive field `{path}` was supplied as configuration data."),
                "Replace the value with an opaque Secret Reference.",
                "Remove the plaintext value and bind a Secret Reference.",
            ));
        } else if !value_matches(field.value_type, value) {
            issues.push(issue(
                DeliveryIssueCode::ConfigContractMismatch,
                format!("Configuration field `{path}` has the wrong JSON value type."),
                "Supply a value matching the Config Contract field type.",
                "Correct the value and build the Config Revision again.",
            ));
        }
    }

    secret_references.sort_by(|left, right| {
        (&left.purpose, &left.reference_id).cmp(&(&right.purpose, &right.reference_id))
    });
    let unique_reference_ids = secret_references
        .iter()
        .map(|reference| reference.reference_id.as_str())
        .collect::<BTreeSet<_>>();
    let unique_purposes = secret_references
        .iter()
        .map(|reference| reference.purpose.as_str())
        .collect::<BTreeSet<_>>();
    if unique_reference_ids.len() != secret_references.len()
        || unique_purposes.len() != secret_references.len()
    {
        issues.push(issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "Secret References must bind one unique opaque reference to each sensitive field.",
            "Keep exactly one resolved Secret Reference per declared sensitive purpose.",
            "Remove duplicate Secret References and build the Config Revision again.",
        ));
    }
    for reference in &secret_references {
        let observed = secret_provider.observe_reference(&reference.reference_id);
        if reference.reference_id.trim().is_empty()
            || reference.provider.trim().is_empty()
            || reference.purpose.trim().is_empty()
            || reference.scope.trim().is_empty()
            || !secret_metadata_is_safe(&reference.metadata)
        {
            issues.push(issue(
                DeliveryIssueCode::PlaintextSecretDetected,
                "A Secret Reference contains unsafe or value-shaped metadata.",
                "Keep only opaque provider identity, purpose, scope, and non-sensitive status metadata.",
                "Remove sensitive metadata and build the Config Revision again.",
            ));
        }
        if reference.provider != secret_provider.provider_name()
            || observed.as_ref().is_none_or(|observed| {
                observed.status != reference.status || observed.metadata != reference.metadata
            })
        {
            issues.push(issue(
                DeliveryIssueCode::SecretReferenceUnresolved,
                format!(
                    "Secret Reference `{}` is not attested by the selected Secret Provider.",
                    reference.reference_id
                ),
                "Observe the opaque reference through the configured provider boundary.",
                "Refresh the provider observation and build the Config Revision again.",
            ));
        }
        if reference.status != SecretReferenceStatus::Resolved {
            issues.push(issue(
                DeliveryIssueCode::SecretReferenceUnresolved,
                format!(
                    "Secret Reference `{}` is not resolved.",
                    reference.reference_id
                ),
                "Resolve the opaque reference through the selected Secret Provider.",
                "Refresh Secret Reference status before activation.",
            ));
        }
        if !fields
            .get(reference.purpose.as_str())
            .is_some_and(|field| field.sensitivity == ConfigFieldSensitivity::Sensitive)
        {
            issues.push(issue(
                DeliveryIssueCode::ConfigContractMismatch,
                format!(
                    "Secret Reference `{}` does not bind a declared sensitive Config field.",
                    reference.reference_id
                ),
                "Bind opaque references only to sensitive fields in the exact Config Contract.",
                "Correct the Secret Reference purpose and build the Config Revision again.",
            ));
        }
    }

    for field in &contract.fields {
        if !field.required {
            continue;
        }
        let present = match field.sensitivity {
            ConfigFieldSensitivity::Public => values.contains_key(&field.path),
            ConfigFieldSensitivity::Sensitive => secret_references
                .iter()
                .any(|reference| reference.purpose == field.path),
        };
        if !present {
            issues.push(issue(
                if field.sensitivity == ConfigFieldSensitivity::Sensitive {
                    DeliveryIssueCode::SecretReferenceUnresolved
                } else {
                    DeliveryIssueCode::ConfigContractMismatch
                },
                format!("Required configuration field `{}` is missing.", field.path),
                "Supply the required non-secret value or opaque Secret Reference.",
                "Complete the Config Revision and validate it again.",
            ));
        }
    }
    if !issues.is_empty() {
        return Err(issues);
    }

    let impacts = contract
        .fields
        .iter()
        .filter(|field| {
            values.contains_key(&field.path)
                || secret_references
                    .iter()
                    .any(|reference| reference.purpose == field.path)
        })
        .map(|field| ConfigImpact {
            path: field.path.clone(),
            scope: field.scope,
            activation: field.activation,
            mutable: field.mutable,
        })
        .collect::<Vec<_>>();
    let revision_digest = digest_json(&(
        CONFIG_REVISION_PROTOCOL,
        service_id.as_str(),
        contract.reference.as_str(),
        contract.digest.as_str(),
        &values,
        &secret_references,
        &impacts,
    ));
    Ok(ConfigRevision {
        protocol: CONFIG_REVISION_PROTOCOL.to_owned(),
        revision_id: format!("config-revision:{revision_digest}"),
        revision_digest,
        service_id,
        contract_reference: contract.reference.clone(),
        contract_digest: contract.digest.clone(),
        values,
        secret_references,
        impacts,
    })
}

fn secret_metadata_is_safe(metadata: &BTreeMap<String, String>) -> bool {
    metadata.iter().all(|(key, value)| match key.as_str() {
        "leaseExpiresAt" | "lastResolvedAt" => timestamp_metadata_is_safe(value),
        "rotationRevision" | "providerRevision" => {
            !value.is_empty()
                && value.len() <= 20
                && value.bytes().all(|byte| byte.is_ascii_digit())
        }
        "rotationStatus" => matches!(
            value.as_str(),
            "current" | "due" | "rotating" | "stale" | "revoked"
        ),
        _ => false,
    })
}

/// Return whether a Secret Reference contains only the bounded, non-value metadata
/// accepted by the production delivery contract.
#[must_use]
pub fn secret_reference_metadata_is_safe(reference: &SecretReference) -> bool {
    secret_metadata_is_safe(&reference.metadata)
}

fn timestamp_metadata_is_safe(value: &str) -> bool {
    value.len() >= 20
        && value.len() <= 40
        && value.as_bytes().get(4) == Some(&b'-')
        && value.as_bytes().get(7) == Some(&b'-')
        && value.as_bytes().get(10) == Some(&b'T')
        && (value.ends_with('Z')
            || value
                .as_bytes()
                .iter()
                .rev()
                .take(6)
                .any(|byte| *byte == b'+'))
        && value.bytes().all(|byte| {
            byte.is_ascii_digit() || matches!(byte, b'-' | b':' | b'T' | b'.' | b'Z' | b'+')
        })
}

pub fn plan_config_activation(
    state: &ConfigState,
    contract: &ConfigContractDefinition,
    revision: &ConfigRevision,
    secret_provider: &dyn SecretProvider,
    operation: ConfigOperation,
) -> Result<ConfigActivationPlan, Vec<DeliveryIssue>> {
    if state.environment.trim().is_empty()
        || !config_revision_matches_contract(revision, contract, secret_provider)
    {
        return Err(vec![issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "Config activation requires an integrity-valid Config Revision and environment identity.",
            "Regenerate the Config Revision from its exact Config Contract.",
            "Correct the input and plan activation again.",
        )]);
    }
    if operation == ConfigOperation::Activate
        && state.staged_revision_id.as_deref() != Some(revision.revision_id.as_str())
        && state.active_revision_id.as_deref() != Some(revision.revision_id.as_str())
    {
        return Err(vec![issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "The Config Revision must be staged before activation.",
            "Stage and validate the exact revision before making it active.",
            "Plan and apply the stage operation first.",
        )]);
    }
    if operation == ConfigOperation::Rollback
        && state.previous_revision_id.as_deref() != Some(revision.revision_id.as_str())
    {
        return Err(vec![issue(
            DeliveryIssueCode::ConfigContractMismatch,
            "Config rollback must target the environment's explicit previous Config Revision.",
            "Select the exact previous revision recorded by the active environment state.",
            "Refresh Config state and plan rollback to its previous revision.",
        )]);
    }
    let previous_revision_id = state.active_revision_id.clone();
    let effects = DeliveryEffects::default();
    let plan_digest = digest_json(&(
        CONFIG_ACTIVATION_PLAN_PROTOCOL,
        state.environment.as_str(),
        state.environment_revision,
        operation,
        revision.revision_id.as_str(),
        previous_revision_id.as_deref(),
        revision.contract_digest.as_str(),
        &effects,
    ));
    Ok(ConfigActivationPlan {
        protocol: CONFIG_ACTIVATION_PLAN_PROTOCOL.to_owned(),
        plan_id: format!("config-activation-plan:{plan_digest}"),
        plan_digest,
        environment: state.environment.clone(),
        expected_environment_revision: state.environment_revision,
        operation,
        target_revision_id: revision.revision_id.clone(),
        previous_revision_id,
        contract_digest: revision.contract_digest.clone(),
        effects,
    })
}

pub fn apply_config_activation(
    state: &mut ConfigState,
    plan: &ConfigActivationPlan,
) -> Result<ConfigActivationReceipt, ConfigApplyRejection> {
    if !config_activation_plan_integrity_is_valid(plan) {
        return Err(ConfigApplyRejection {
            issues: vec![issue(
                DeliveryIssueCode::StaleInput,
                "Config activation inputs changed after the plan was generated.",
                "Generate a new plan from the current environment and Config Revision state.",
                "Refresh state and plan the configuration operation again.",
            )],
            effects: DeliveryEffects::default(),
        });
    }
    if let Some(existing) = state
        .history
        .iter()
        .find(|item| item.plan_id == plan.plan_id)
    {
        return config_activation_receipt_integrity_is_valid(existing, plan)
            .then(|| existing.clone())
            .ok_or_else(|| ConfigApplyRejection {
                issues: vec![issue(
                    DeliveryIssueCode::StaleInput,
                    "The completed Config activation receipt no longer matches the exact plan.",
                    "Preserve the immutable plan and append-only receipt together.",
                    "Restore the original receipt or create a new Config activation plan.",
                )],
                effects: DeliveryEffects::default(),
            });
    }
    if state.environment != plan.environment
        || state.environment_revision != plan.expected_environment_revision
    {
        return Err(ConfigApplyRejection {
            issues: vec![issue(
                DeliveryIssueCode::StaleInput,
                "Config activation inputs changed after the plan was generated.",
                "Generate a new plan from the current environment and Config Revision state.",
                "Refresh state and plan the configuration operation again.",
            )],
            effects: DeliveryEffects::default(),
        });
    }

    let activation = match plan.operation {
        ConfigOperation::Stage => {
            state.staged_revision_id = Some(plan.target_revision_id.clone());
            ConfigRevisionActivation::Staged
        }
        ConfigOperation::Activate => {
            if state.staged_revision_id.as_deref() != Some(plan.target_revision_id.as_str())
                && state.active_revision_id.as_deref() != Some(plan.target_revision_id.as_str())
            {
                return Err(ConfigApplyRejection {
                    issues: vec![issue(
                        DeliveryIssueCode::StaleInput,
                        "The staged Config Revision changed before activation.",
                        "Regenerate the plan from the current staged revision.",
                        "Restage or replan activation.",
                    )],
                    effects: DeliveryEffects::default(),
                });
            }
            state.previous_revision_id = state.active_revision_id.clone();
            state.active_revision_id = Some(plan.target_revision_id.clone());
            state.staged_revision_id = None;
            ConfigRevisionActivation::Active
        }
        ConfigOperation::Rollback => {
            if state.previous_revision_id.as_deref() != Some(plan.target_revision_id.as_str())
                || state.active_revision_id != plan.previous_revision_id
            {
                return Err(ConfigApplyRejection {
                    issues: vec![issue(
                        DeliveryIssueCode::StaleInput,
                        "The previous Config Revision changed before rollback.",
                        "Regenerate rollback from the current active and previous revision pair.",
                        "Refresh state and replan the rollback.",
                    )],
                    effects: DeliveryEffects::default(),
                });
            }
            state.previous_revision_id = state.active_revision_id.clone();
            state.active_revision_id = Some(plan.target_revision_id.clone());
            state.staged_revision_id = None;
            ConfigRevisionActivation::RolledBack
        }
    };
    let revision_before = state.environment_revision;
    state.environment_revision += 1;
    let effects = DeliveryEffects {
        mutates_configuration: true,
        appends_ledger: true,
        ..DeliveryEffects::default()
    };
    let receipt_id = format!(
        "config-activation-receipt:{}",
        digest_json(&(
            plan.plan_id.as_str(),
            revision_before,
            state.environment_revision,
            activation,
        ))
    );
    let receipt = ConfigActivationReceipt {
        protocol: CONFIG_ACTIVATION_RECEIPT_PROTOCOL.to_owned(),
        receipt_id,
        plan_id: plan.plan_id.clone(),
        environment: state.environment.clone(),
        environment_revision_before: revision_before,
        environment_revision_after: state.environment_revision,
        target_revision_id: plan.target_revision_id.clone(),
        previous_revision_id: plan.previous_revision_id.clone(),
        activation,
        effects,
    };
    state.history.push(receipt.clone());
    Ok(receipt)
}

#[must_use]
pub fn config_contract_integrity_is_valid(contract: &ConfigContractDefinition) -> bool {
    let mut canonical_fields = contract.fields.clone();
    canonical_fields.sort();
    let unique_paths = contract
        .fields
        .iter()
        .map(|field| field.path.as_str())
        .collect::<BTreeSet<_>>();
    contract.protocol == CONFIG_CONTRACT_PROTOCOL
        && !contract.reference.trim().is_empty()
        && !contract.fields.is_empty()
        && contract.fields == canonical_fields
        && unique_paths.len() == contract.fields.len()
        && !unique_paths.contains("")
        && digest_json(&(
            contract.protocol.as_str(),
            contract.reference.as_str(),
            contract.fields.as_slice(),
        )) == contract.digest
}

#[must_use]
pub fn config_revision_integrity_is_valid(revision: &ConfigRevision) -> bool {
    revision.protocol == CONFIG_REVISION_PROTOCOL
        && revision.revision_id == format!("config-revision:{}", revision.revision_digest)
        && digest_json(&(
            revision.protocol.as_str(),
            revision.service_id.as_str(),
            revision.contract_reference.as_str(),
            revision.contract_digest.as_str(),
            &revision.values,
            &revision.secret_references,
            &revision.impacts,
        )) == revision.revision_digest
}

#[must_use]
pub fn config_revision_matches_contract(
    revision: &ConfigRevision,
    contract: &ConfigContractDefinition,
    secret_provider: &dyn SecretProvider,
) -> bool {
    if !config_contract_integrity_is_valid(contract)
        || !config_revision_integrity_is_valid(revision)
        || revision.contract_reference != contract.reference
        || revision.contract_digest != contract.digest
    {
        return false;
    }
    build_config_revision(
        revision.service_id.clone(),
        contract,
        revision.values.clone(),
        revision.secret_references.clone(),
        secret_provider,
    )
    .is_ok_and(|expected| expected == *revision)
}

#[must_use]
pub fn config_activation_plan_integrity_is_valid(plan: &ConfigActivationPlan) -> bool {
    plan.protocol == CONFIG_ACTIVATION_PLAN_PROTOCOL
        && plan.plan_id == format!("config-activation-plan:{}", plan.plan_digest)
        && digest_json(&(
            plan.protocol.as_str(),
            plan.environment.as_str(),
            plan.expected_environment_revision,
            plan.operation,
            plan.target_revision_id.as_str(),
            plan.previous_revision_id.as_deref(),
            plan.contract_digest.as_str(),
            &plan.effects,
        )) == plan.plan_digest
}

#[must_use]
pub fn config_activation_receipt_integrity_is_valid(
    receipt: &ConfigActivationReceipt,
    plan: &ConfigActivationPlan,
) -> bool {
    let activation = match plan.operation {
        ConfigOperation::Stage => ConfigRevisionActivation::Staged,
        ConfigOperation::Activate => ConfigRevisionActivation::Active,
        ConfigOperation::Rollback => ConfigRevisionActivation::RolledBack,
    };
    let effects = DeliveryEffects {
        mutates_configuration: true,
        appends_ledger: true,
        ..DeliveryEffects::default()
    };
    receipt.protocol == CONFIG_ACTIVATION_RECEIPT_PROTOCOL
        && config_activation_plan_integrity_is_valid(plan)
        && receipt.plan_id == plan.plan_id
        && receipt.environment == plan.environment
        && receipt.environment_revision_before == plan.expected_environment_revision
        && receipt.environment_revision_after == receipt.environment_revision_before + 1
        && receipt.target_revision_id == plan.target_revision_id
        && receipt.previous_revision_id == plan.previous_revision_id
        && receipt.activation == activation
        && receipt.effects == effects
        && receipt.receipt_id
            == format!(
                "config-activation-receipt:{}",
                digest_json(&(
                    plan.plan_id.as_str(),
                    receipt.environment_revision_before,
                    receipt.environment_revision_after,
                    activation,
                ))
            )
}

fn value_matches(expected: ConfigValueType, value: &Value) -> bool {
    match expected {
        ConfigValueType::String => value.is_string(),
        ConfigValueType::Integer => value.as_i64().is_some() || value.as_u64().is_some(),
        ConfigValueType::Number => value.is_number(),
        ConfigValueType::Boolean => value.is_boolean(),
        ConfigValueType::Object => value.is_object(),
        ConfigValueType::Array => value.is_array(),
    }
}

fn digest_json(value: &impl Serialize) -> String {
    extraction_input_digest(serde_json::to_vec(value).expect("delivery values must serialize"))
}