Skip to main content

keystate_core/model/
envelope.rs

1//! The extracted envelope: what one extraction run produces, and what one
2//! selects.
3
4use std::collections::BTreeMap;
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9use crate::model::entities::{
10    AuthFlow, Client, ClientScope, Credential, Group, IdentityProvider, ProtocolMapper, Realm,
11    Role, User,
12};
13use crate::model::kind::EntityKind;
14use crate::version::Version;
15
16/// Metadata describing the backend and the schema version detected at the
17/// source. Rides inside the extracted envelope so manifests and reports are
18/// provably bound to a concrete version.
19#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
20pub struct BackendInfo {
21    /// Backend identifier, e.g. `"keycloak"` or `"ferriskey"`.
22    #[serde(default)]
23    pub backend: String,
24    /// The schema version detected at the source.
25    pub detected_version: Version,
26    /// Any backend-specific discovery detail the canonical model has not
27    /// formalized (e.g. distribution/edition). Opened but kept in the
28    /// envelope, not in entity rows.
29    #[serde(default)]
30    pub extra: BTreeMap<String, Value>,
31}
32
33/// Selects what one extraction run pulls.
34///
35/// Release one extracts exactly one realm per run.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct ExtractScope {
38    /// The realm to extract.
39    pub realm: String,
40}
41
42impl ExtractScope {
43    /// Construct a scope for a single realm.
44    pub fn new(realm: impl Into<String>) -> Self {
45        Self {
46            realm: realm.into(),
47        }
48    }
49}
50
51/// The volatile portion of an extraction.
52///
53/// Everything that changes on its own between runs with zero configuration
54/// drift — last-login timestamps, session-derived data — lives here, never in
55/// the config body. Fields are keyed by entity kind, row id, then their
56/// dotted path, so the completeness verifier can prove, for every existing
57/// row, that its volatile fields were captured.
58///
59/// The content hash covers only the config portion; this section never enters
60/// it, so volatile churn cannot pollute drift detection.
61#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
62pub struct VolatileSection(
63    /// `entity kind -> row id -> dotted path -> value`.
64    pub BTreeMap<EntityKind, BTreeMap<String, BTreeMap<String, Value>>>,
65);
66
67impl VolatileSection {
68    /// An empty volatile section.
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    /// Whether the section carries no data for any entity.
74    pub fn is_empty(&self) -> bool {
75        self.0.is_empty()
76    }
77
78    /// Record one volatile value for a row.
79    pub fn insert(
80        &mut self,
81        entity: EntityKind,
82        row_id: impl Into<String>,
83        path: impl Into<String>,
84        value: Value,
85    ) {
86        self.0
87            .entry(entity)
88            .or_default()
89            .entry(row_id.into())
90            .or_default()
91            .insert(path.into(), value);
92    }
93
94    /// Look up a recorded volatile value.
95    pub fn get(&self, entity: EntityKind, row_id: &str, path: &str) -> Option<&Value> {
96        self.0
97            .get(&entity)
98            .and_then(|by_id| by_id.get(row_id))
99            .and_then(|by_path| by_path.get(path))
100    }
101
102    /// All row ids recorded for an entity kind, in stable order.
103    pub fn row_ids<'a>(&'a self, entity: &'a EntityKind) -> impl Iterator<Item = &'a String> {
104        self.0.get(entity).into_iter().flat_map(|m| m.keys())
105    }
106}
107
108/// One canonical realm's worth of extracted state.
109///
110/// Collections are the adapter's responsibility to sort by a stable key
111/// before being placed here (see `ARCHITECTURE.md` §4); core serializes
112/// deterministically on top of that.
113#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
114pub struct CanonicalRealm {
115    /// Backend and schema version detected at the source.
116    #[serde(default)]
117    pub backend: BackendInfo,
118    /// The realm itself.
119    pub realm: Realm,
120    /// Clients.
121    #[serde(default)]
122    pub clients: Vec<Client>,
123    /// Reusable provider-configuration bundles.
124    #[serde(default)]
125    pub client_scopes: Vec<ClientScope>,
126    /// Groups.
127    #[serde(default)]
128    pub groups: Vec<Group>,
129    /// Roles.
130    #[serde(default)]
131    pub roles: Vec<Role>,
132    /// Users.
133    #[serde(default)]
134    pub users: Vec<User>,
135    /// Credential records.
136    #[serde(default)]
137    pub credentials: Vec<Credential>,
138    /// Protocol mappers.
139    #[serde(default)]
140    pub protocol_mappers: Vec<ProtocolMapper>,
141    /// Authentication flows.
142    #[serde(default)]
143    pub auth_flows: Vec<AuthFlow>,
144    /// External identity providers.
145    #[serde(default)]
146    pub identity_providers: Vec<IdentityProvider>,
147    /// Volatile, non-configuration data, keyed by entity/row/path.
148    #[serde(default)]
149    pub volatile: VolatileSection,
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn envelope_has_default_empty_state() {
158        let realm = CanonicalRealm::default();
159        assert!(realm.clients.is_empty());
160        assert!(realm.volatile.is_empty());
161    }
162
163    #[test]
164    fn volatile_section_roundtrips_and_is_ordered() {
165        let mut section = VolatileSection::new();
166        section.insert(
167            EntityKind::User,
168            "u1",
169            "native.last_login",
170            serde_json::json!("2026-01-01"),
171        );
172        section.insert(
173            EntityKind::User,
174            "u2",
175            "native.last_login",
176            serde_json::json!("2026-01-02"),
177        );
178        assert_eq!(
179            section
180                .get(EntityKind::User, "u1", "native.last_login")
181                .unwrap(),
182            &serde_json::json!("2026-01-01")
183        );
184        assert_eq!(
185            section.row_ids(&EntityKind::User).collect::<Vec<_>>(),
186            vec![&"u1".to_string(), &"u2".to_string()]
187        );
188
189        let json = serde_json::to_value(&section).unwrap();
190        assert!(json.is_object());
191        let back: VolatileSection = serde_json::from_value(json).unwrap();
192        assert_eq!(back, section);
193    }
194
195    #[test]
196    fn backend_info_defaults_to_unknown_backend() {
197        let info = BackendInfo::default();
198        assert_eq!(info.backend, "");
199        assert_eq!(info.detected_version, Version::default());
200    }
201}