Skip to main content

qualia_core_db/q42/app_registry/
registry.rs

1//! Cold, bounded in-memory installed-app registry.
2
3use super::compat::{engine_too_new, engine_too_old};
4use super::error::AppRegistryError;
5use super::fixture::{poet_fixture_manifest, POET_APP_ID};
6use super::probe::probe_identity;
7use super::record::{AppInspectView, AppRecordState, InstalledAppRecord, PermissionIntentSummary};
8use crate::q42::app_manifest::{PermissionIntent, PortableAppManifest};
9
10/// Maximum installed / quarantined slots retained in memory.
11pub const MAX_INSTALLED_APPS: usize = 32;
12
13/// Default engine version string used for compatibility checks.
14///
15/// Keep in sync with the workspace release line when bumping; comparison is
16/// the simple dotted numeric helper in `super::compat`.
17pub const DEFAULT_ENGINE_VERSION: &str = "0.0.40";
18
19/// Internal slot payload (record + inspect snapshot).
20#[derive(Debug, Clone)]
21struct Slot {
22    record: InstalledAppRecord,
23    author_name: String,
24    author_did: String,
25    permission_intents: Vec<PermissionIntent>,
26    entry_ids: Vec<String>,
27    min_engine_version: String,
28    max_engine_version: String,
29    required_features: Vec<String>,
30}
31
32/// Bounded installed-app registry (cold construction / inspection only).
33///
34/// # Security
35///
36/// - Does **not** execute, launch, or load application code.
37/// - `inspect` / `get` / `list` are read-only and do not mutate state.
38/// - Malformed packages are quarantined when identity is recoverable; otherwise rejected.
39pub struct AppRegistry {
40    slots: Vec<Option<Slot>>,
41    engine_version: String,
42}
43
44impl Default for AppRegistry {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl AppRegistry {
51    /// Empty registry with [`DEFAULT_ENGINE_VERSION`].
52    pub fn new() -> Self {
53        Self::with_engine_version(DEFAULT_ENGINE_VERSION)
54    }
55
56    /// Empty registry with an explicit engine version for compatibility checks.
57    pub fn with_engine_version(engine_version: impl Into<String>) -> Self {
58        Self {
59            slots: (0..MAX_INSTALLED_APPS).map(|_| None).collect(),
60            engine_version: engine_version.into(),
61        }
62    }
63
64    /// Seed a registry that already contains the bundled POET fixture as Active.
65    ///
66    /// Fixture is in-memory only — not a claim that package bytes exist on disk.
67    pub fn with_bundled_poet_fixture() -> Self {
68        let mut reg = Self::new();
69        let manifest = poet_fixture_manifest();
70        reg.register_manifest(&manifest)
71            .expect("poet fixture must register");
72        debug_assert_eq!(
73            reg.get(POET_APP_ID).map(|r| r.app_id.as_str()),
74            Some(POET_APP_ID)
75        );
76        reg
77    }
78
79    /// Registered engine version.
80    pub fn engine_version(&self) -> &str {
81        &self.engine_version
82    }
83
84    /// Maximum capacity.
85    pub fn capacity(&self) -> usize {
86        MAX_INSTALLED_APPS
87    }
88
89    /// Number of elements.
90    pub fn len(&self) -> usize {
91        self.slots.iter().filter(|s| s.is_some()).count()
92    }
93
94    /// `true` when empty.
95    pub fn is_empty(&self) -> bool {
96        self.len() == 0
97    }
98
99    /// Register a decoded/validated manifest (no external package digest check).
100    ///
101    /// Integrity is treated as ok unless compatibility marks the slot incompatible.
102    pub fn register_manifest(
103        &mut self,
104        manifest: &PortableAppManifest,
105    ) -> Result<&InstalledAppRecord, AppRegistryError> {
106        manifest.validate()?;
107        let integrity_ok = true;
108        let state = self.admission_state(manifest, integrity_ok, None);
109        self.insert_from_manifest(manifest, integrity_ok, state)
110    }
111
112    /// Decode bytes, optionally verify `package_digest` against the integrity block.
113    ///
114    /// - Decode/validate failure → quarantine when identity recoverable, else reject.
115    /// - Digest mismatch → quarantine (identity from decoded or probed fields).
116    pub fn register_manifest_bytes(
117        &mut self,
118        bytes: &[u8],
119        package_digest: Option<&[u8; 32]>,
120    ) -> Result<&InstalledAppRecord, AppRegistryError> {
121        match PortableAppManifest::decode(bytes) {
122            Ok(manifest) => {
123                let mut integrity_ok = true;
124                let mut quarantine_reason: Option<String> = None;
125                if let Some(digest) = package_digest {
126                    if manifest.verify_package_digest(digest).is_err() {
127                        integrity_ok = false;
128                        quarantine_reason =
129                            Some("package digest mismatch vs Integrity.package_sha256".into());
130                    }
131                }
132                let state = self.admission_state(&manifest, integrity_ok, quarantine_reason);
133                self.insert_from_manifest(&manifest, integrity_ok, state)
134            }
135            Err(err) => self.quarantine_or_reject(bytes, &err.to_string()),
136        }
137    }
138
139    /// Read-only list of records in slot order (occupied slots only).
140    pub fn list(&self) -> Vec<&InstalledAppRecord> {
141        self.slots
142            .iter()
143            .filter_map(|s| s.as_ref().map(|slot| &slot.record))
144            .collect()
145    }
146
147    /// Look up by `app_id` (exact match).
148    pub fn get(&self, app_id: &str) -> Option<&InstalledAppRecord> {
149        self.find_slot(app_id)
150            .map(|i| &self.slots[i].as_ref().unwrap().record)
151    }
152
153    /// Read-only inspect view. Does not mutate the registry and does not launch.
154    pub fn inspect(&self, app_id: &str) -> Option<AppInspectView> {
155        let idx = self.find_slot(app_id)?;
156        let slot = self.slots[idx].as_ref()?;
157        Some(AppInspectView {
158            app_id: slot.record.app_id.clone(),
159            version: slot.record.version.clone(),
160            author_name: slot.author_name.clone(),
161            author_did: slot.author_did.clone(),
162            digest: slot.record.digest,
163            integrity_ok: slot.record.integrity_ok,
164            state: slot.record.state.clone(),
165            permission_intents: slot.permission_intents.clone(),
166            permission_summary: slot.record.permission_intents.clone(),
167            entry_ids: slot.entry_ids.clone(),
168            min_engine_version: slot.min_engine_version.clone(),
169            max_engine_version: slot.max_engine_version.clone(),
170            required_features: slot.required_features.clone(),
171        })
172    }
173
174    fn admission_state(
175        &self,
176        manifest: &PortableAppManifest,
177        integrity_ok: bool,
178        quarantine_reason: Option<String>,
179    ) -> AppRecordState {
180        if let Some(reason) = quarantine_reason {
181            return AppRecordState::Quarantined { reason };
182        }
183        if !integrity_ok {
184            return AppRecordState::Quarantined {
185                reason: "integrity check failed".into(),
186            };
187        }
188        let min = &manifest.compatibility.min_engine_version;
189        let max = &manifest.compatibility.max_engine_version;
190        if engine_too_old(min, &self.engine_version) || engine_too_new(max, &self.engine_version) {
191            return AppRecordState::Incompatible;
192        }
193        AppRecordState::Active
194    }
195
196    fn insert_from_manifest(
197        &mut self,
198        manifest: &PortableAppManifest,
199        integrity_ok: bool,
200        state: AppRecordState,
201    ) -> Result<&InstalledAppRecord, AppRegistryError> {
202        let app_id = manifest.identity.app_id.trim();
203        if app_id.is_empty() {
204            return Err(AppRegistryError::MissingAppId);
205        }
206        let record = InstalledAppRecord {
207            app_id: manifest.identity.app_id.clone(),
208            version: manifest.identity.version.clone(),
209            digest: manifest.integrity.package_sha256,
210            permission_intents: PermissionIntentSummary::from_intents(&manifest.permission_intents),
211            integrity_ok,
212            state,
213        };
214        let slot = Slot {
215            record,
216            author_name: manifest.identity.author.name.clone(),
217            author_did: manifest.identity.author.did.clone(),
218            permission_intents: manifest.permission_intents.clone(),
219            entry_ids: manifest
220                .entries
221                .iter()
222                .map(|e| e.entry_id.clone())
223                .collect(),
224            min_engine_version: manifest.compatibility.min_engine_version.clone(),
225            max_engine_version: manifest.compatibility.max_engine_version.clone(),
226            required_features: manifest.compatibility.required_features.clone(),
227        };
228        self.upsert(slot)
229    }
230
231    fn quarantine_or_reject(
232        &mut self,
233        bytes: &[u8],
234        reason: &str,
235    ) -> Result<&InstalledAppRecord, AppRegistryError> {
236        let Some(recovered) = probe_identity(bytes) else {
237            return Err(AppRegistryError::RejectedMalformed);
238        };
239        let record = InstalledAppRecord {
240            app_id: recovered.app_id.clone(),
241            version: recovered.version.clone(),
242            digest: [0u8; 32],
243            permission_intents: PermissionIntentSummary::default(),
244            integrity_ok: false,
245            state: AppRecordState::Quarantined {
246                reason: reason.to_string(),
247            },
248        };
249        let slot = Slot {
250            record,
251            author_name: String::new(),
252            author_did: String::new(),
253            permission_intents: Vec::new(),
254            entry_ids: Vec::new(),
255            min_engine_version: String::new(),
256            max_engine_version: String::new(),
257            required_features: Vec::new(),
258        };
259        self.upsert(slot)
260    }
261
262    fn upsert(&mut self, slot: Slot) -> Result<&InstalledAppRecord, AppRegistryError> {
263        if let Some(idx) = self.find_slot(&slot.record.app_id) {
264            self.slots[idx] = Some(slot);
265            return Ok(&self.slots[idx].as_ref().unwrap().record);
266        }
267        let free = self
268            .slots
269            .iter()
270            .position(|s| s.is_none())
271            .ok_or(AppRegistryError::RegistryFull)?;
272        self.slots[free] = Some(slot);
273        Ok(&self.slots[free].as_ref().unwrap().record)
274    }
275
276    fn find_slot(&self, app_id: &str) -> Option<usize> {
277        self.slots.iter().position(|s| {
278            s.as_ref()
279                .map(|slot| slot.record.app_id == app_id)
280                .unwrap_or(false)
281        })
282    }
283}