Skip to main content

keystate_core/verify/
manifest.rs

1//! The expected-configuration data shapes: [`EntityExpectation`],
2//! [`EntityPresence`], [`FieldExpectation`] and [`FieldManifest`].
3
4use std::collections::BTreeMap;
5
6use serde::{Deserialize, Serialize};
7
8use crate::model::EntityKind;
9use crate::{Error, Result, Version};
10
11/// Whether an entity *type* is expected to have at least one row.
12///
13/// A freshly created realm with zero users (or zero identity providers) is a
14/// valid, complete state — only [`Required`](EntityPresence::Required)
15/// entities must have rows.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum EntityPresence {
19    /// At least one row of this entity must exist.
20    Required,
21    /// Zero rows is a valid, complete state.
22    Optional,
23}
24
25/// A declaration about how many rows an entity type must have.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct EntityExpectation {
28    /// The entity kind this expectation covers.
29    pub entity: EntityKind,
30    /// Whether at least one row is required.
31    pub presence: EntityPresence,
32}
33
34impl EntityExpectation {
35    /// Declare that an entity type must (or must not) have rows.
36    pub fn new(entity: EntityKind, presence: EntityPresence) -> Self {
37        Self { entity, presence }
38    }
39}
40
41/// A single expected field, keyed to one entity kind.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct FieldExpectation {
44    /// The entity kind whose rows must carry this path.
45    pub entity: EntityKind,
46    /// Dotted path relative to the canonical row — e.g. `client_id`, or
47    /// `native.alternativeNames[]` for an array-valued native field. Array
48    /// segments end in `[]`.
49    pub path: String,
50    /// When `true`, every *existing* row of `entity` must carry `path`.
51    /// When `false`, the field is complete if at least one row carries it.
52    pub required: bool,
53    /// When `true`, the field is volatile — session/last-login style data
54    /// that changes between runs. It must be reported in the volatile
55    /// section, never in the config body, and never in the content hash.
56    pub volatile: bool,
57    /// The backend schema version that introduced the field, so a report can
58    /// say concretely "introduced in 26.x and absent here".
59    pub introduced_in: Version,
60}
61
62/// The complete expected configuration state for one backend version.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct FieldManifest {
65    /// Backend this manifest describes, e.g. `"keycloak"`.
66    pub backend: String,
67    /// The backend schema version these expectations were derived from.
68    pub for_version: Version,
69    /// Entity-type presence requirements.
70    pub entities: Vec<EntityExpectation>,
71    /// Field-level expectations, including volatility.
72    pub fields: Vec<FieldExpectation>,
73}
74
75impl FieldManifest {
76    /// An empty manifest for a backend version.
77    pub fn new(backend: impl Into<String>, for_version: Version) -> Self {
78        Self {
79            backend: backend.into(),
80            for_version,
81            entities: Vec::new(),
82            fields: Vec::new(),
83        }
84    }
85
86    /// Check internal consistency before trusting this manifest.
87    ///
88    /// Rejects duplicate `(entity, path)` field expectations, duplicate
89    /// entity expectations, empty paths, and contradictory Realm handling.
90    /// The engine refuses to verify against an invalid manifest, and the
91    /// contract suite calls this explicitly in adapters.
92    pub fn validate(&self) -> Result<()> {
93        if self.backend.trim().is_empty() {
94            return Err(Error::InvalidManifest(
95                "backend must be non-empty".to_string(),
96            ));
97        }
98        let mut seen: BTreeMap<EntityKind, BTreeMap<&str, ()>> = BTreeMap::new();
99        for fe in &self.fields {
100            if fe.path.trim().is_empty() {
101                return Err(Error::InvalidManifest(format!(
102                    "empty field path for entity {}",
103                    super::entity_label(fe.entity)
104                )));
105            }
106            if seen
107                .entry(fe.entity)
108                .or_default()
109                .insert(fe.path.as_str(), ())
110                .is_some()
111            {
112                return Err(Error::InvalidManifest(format!(
113                    "duplicate field expectation {} for entity {}",
114                    fe.path,
115                    super::entity_label(fe.entity)
116                )));
117            }
118        }
119        let mut entities = BTreeMap::new();
120        for ee in &self.entities {
121            if entities.insert(ee.entity, ee.presence).is_some() {
122                return Err(Error::InvalidManifest(format!(
123                    "duplicate entity expectation for {}",
124                    super::entity_label(ee.entity)
125                )));
126            }
127        }
128        if let Some(EntityPresence::Optional) = entities.get(&EntityKind::Realm) {
129            return Err(Error::InvalidManifest(
130                "Realm must always be present and cannot be declared optional".to_string(),
131            ));
132        }
133        Ok(())
134    }
135}
136
137use std::fmt;
138
139impl fmt::Display for FieldManifest {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        write!(
142            f,
143            "FieldManifest({} @ {}, {} entities, {} fields)",
144            self.backend,
145            self.for_version,
146            self.entities.len(),
147            self.fields.len()
148        )
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    fn manifest_for(backend: &str) -> FieldManifest {
157        FieldManifest::new(backend, Version::new(26, 0, 0))
158    }
159
160    #[test]
161    fn manifest_validate_rejects_duplicates() {
162        let mut manifest = manifest_for("stub");
163        let expectation = || FieldExpectation {
164            entity: EntityKind::Client,
165            path: "client_id".into(),
166            required: true,
167            volatile: false,
168            introduced_in: Version::new(1, 0, 0),
169        };
170        manifest.fields.push(expectation());
171        manifest.fields.push(expectation());
172        assert!(manifest.validate().is_err());
173    }
174
175    #[test]
176    fn manifest_validate_rejects_optional_realm() {
177        let mut manifest = manifest_for("stub");
178        manifest.entities.push(EntityExpectation::new(
179            EntityKind::Realm,
180            EntityPresence::Optional,
181        ));
182        assert!(manifest.validate().is_err());
183    }
184
185    #[test]
186    fn manifest_validate_rejects_empty_path() {
187        let mut manifest = manifest_for("stub");
188        manifest.fields.push(FieldExpectation {
189            entity: EntityKind::Realm,
190            path: "".into(),
191            required: true,
192            volatile: false,
193            introduced_in: Version::new(1, 0, 0),
194        });
195        assert!(manifest.validate().is_err());
196    }
197
198    #[test]
199    fn manifest_without_entities_is_valid() {
200        let manifest = manifest_for("stub");
201        assert!(manifest.validate().is_ok());
202    }
203}