Skip to main content

qualia_core_db/q42/app_manifest/
project.rs

1//! Projection adapters (APP-03).
2//!
3//! Resolve one [`PortableAppManifest`] into host-neutral descriptors for Poet
4//! manifold, Poet container, focused mini-app, and Webizen Desktop launch —
5//! without a projection-specific private database or divergent permission model.
6//!
7//! # Invariants
8//!
9//! - Authorization is evaluated once via [`check_permission_intents`].
10//! - App / capability / asset / state-schema IDs and authorized permission kinds
11//!   are identical across every emitted descriptor.
12//! - Presentation hints copy as display data only; they never alter the grant.
13
14use super::error::AppManifestError;
15use super::manifest::{
16    PortableAppManifest, ProjectionKind, RequiredAsset, RequiredCapability, StateSchema,
17};
18use super::permissions::{
19    check_permission_intents, PermissionGrant, PermissionKind, PresentationHint,
20};
21
22/// Shared identity + authorization outcome for every projection of one manifest.
23///
24/// This is the single authority snapshot; descriptors may copy fields for
25/// host convenience but must not invent a second grant or private store.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct SharedProjectionIds {
28    pub app_id: String,
29    pub version: String,
30    pub author_name: String,
31    pub author_did: String,
32    pub capability_ids: Vec<String>,
33    pub asset_ids: Vec<String>,
34    pub state_schema: StateSchema,
35    /// Permission kinds that satisfied required intents under the host grant.
36    pub permission_kinds: Vec<PermissionKind>,
37    /// Display-only presentation hints (never authority).
38    pub presentation_hints: Vec<PresentationHint>,
39}
40
41/// Poet manifold entry projection (host-neutral; not a live `ManifoldSeed`).
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct PoetManifoldProjection {
44    pub entry_id: String,
45    pub app_id: String,
46    pub version: String,
47    pub relative_path: String,
48    pub capability_ids: Vec<String>,
49    pub asset_ids: Vec<String>,
50    pub state_schema: StateSchema,
51    pub permission_kinds: Vec<PermissionKind>,
52    pub presentation_hints: Vec<PresentationHint>,
53}
54
55/// Poet container placement / tool projection.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct PoetContainerProjection {
58    pub entry_id: String,
59    pub app_id: String,
60    pub version: String,
61    pub relative_path: String,
62    pub capability_ids: Vec<String>,
63    pub asset_ids: Vec<String>,
64    pub state_schema: StateSchema,
65    pub permission_kinds: Vec<PermissionKind>,
66    pub presentation_hints: Vec<PresentationHint>,
67}
68
69/// Focused mini-app entry projection.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct FocusedMiniAppProjection {
72    pub entry_id: String,
73    pub app_id: String,
74    pub version: String,
75    pub relative_path: String,
76    pub capability_ids: Vec<String>,
77    pub asset_ids: Vec<String>,
78    pub state_schema: StateSchema,
79    pub permission_kinds: Vec<PermissionKind>,
80    pub presentation_hints: Vec<PresentationHint>,
81}
82
83/// Webizen Desktop Apps launch / inspect descriptor (no lifecycle execution).
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct DesktopLaunchDescriptor {
86    pub entry_id: String,
87    pub app_id: String,
88    pub version: String,
89    pub relative_path: String,
90    pub capability_ids: Vec<String>,
91    pub asset_ids: Vec<String>,
92    pub state_schema: StateSchema,
93    pub permission_kinds: Vec<PermissionKind>,
94    pub presentation_hints: Vec<PresentationHint>,
95}
96
97/// Full cold projection of one portable app under a host grant.
98///
99/// Absent kinds are honest empty (`None` / empty). No projection owns private
100/// state or a separate permission table.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct ProjectedApp {
103    pub shared: SharedProjectionIds,
104    pub manifold: Option<PoetManifoldProjection>,
105    pub container: Option<PoetContainerProjection>,
106    pub focused_mini_app: Option<FocusedMiniAppProjection>,
107    pub desktop_launch: Option<DesktopLaunchDescriptor>,
108}
109
110impl ProjectedApp {
111    /// Number of concrete projection descriptors emitted.
112    pub fn descriptor_count(&self) -> usize {
113        usize::from(self.manifold.is_some())
114            + usize::from(self.container.is_some())
115            + usize::from(self.focused_mini_app.is_some())
116            + usize::from(self.desktop_launch.is_some())
117    }
118}
119
120/// Project every entry kind present on the manifest.
121pub fn project_manifest(
122    manifest: &PortableAppManifest,
123    grant: &PermissionGrant,
124) -> Result<ProjectedApp, AppManifestError> {
125    project_manifest_kinds(manifest, grant, None)
126}
127
128/// Project only the requested kinds (still authorize the full intent set).
129///
130/// When `kinds` is `None`, every matching entry kind is projected. Permission
131/// denial is identical regardless of which kinds are requested — escalation is
132/// checked before filtering.
133pub fn project_manifest_kinds(
134    manifest: &PortableAppManifest,
135    grant: &PermissionGrant,
136    kinds: Option<&[ProjectionKind]>,
137) -> Result<ProjectedApp, AppManifestError> {
138    manifest.validate()?;
139    // Fail closed before any descriptor is built — same result for any kind filter.
140    check_permission_intents(&manifest.permission_intents, grant)?;
141
142    let shared = build_shared(manifest, grant);
143    let want = |kind: ProjectionKind| kinds.map(|ks| ks.contains(&kind)).unwrap_or(true);
144
145    let mut manifold = None;
146    let mut container = None;
147    let mut focused_mini_app = None;
148    let mut desktop_launch = None;
149
150    for entry in &manifest.entries {
151        if !want(entry.projection) {
152            continue;
153        }
154        if entry.entry_id.trim().is_empty() || entry.relative_path.trim().is_empty() {
155            return Err(AppManifestError::InvalidProjection);
156        }
157        match entry.projection {
158            ProjectionKind::Manifold if manifold.is_none() => {
159                manifold = Some(PoetManifoldProjection {
160                    entry_id: entry.entry_id.clone(),
161                    app_id: shared.app_id.clone(),
162                    version: shared.version.clone(),
163                    relative_path: entry.relative_path.clone(),
164                    capability_ids: shared.capability_ids.clone(),
165                    asset_ids: shared.asset_ids.clone(),
166                    state_schema: shared.state_schema.clone(),
167                    permission_kinds: shared.permission_kinds.clone(),
168                    presentation_hints: shared.presentation_hints.clone(),
169                });
170            }
171            ProjectionKind::Container if container.is_none() => {
172                container = Some(PoetContainerProjection {
173                    entry_id: entry.entry_id.clone(),
174                    app_id: shared.app_id.clone(),
175                    version: shared.version.clone(),
176                    relative_path: entry.relative_path.clone(),
177                    capability_ids: shared.capability_ids.clone(),
178                    asset_ids: shared.asset_ids.clone(),
179                    state_schema: shared.state_schema.clone(),
180                    permission_kinds: shared.permission_kinds.clone(),
181                    presentation_hints: shared.presentation_hints.clone(),
182                });
183            }
184            ProjectionKind::FocusedMiniApp if focused_mini_app.is_none() => {
185                focused_mini_app = Some(FocusedMiniAppProjection {
186                    entry_id: entry.entry_id.clone(),
187                    app_id: shared.app_id.clone(),
188                    version: shared.version.clone(),
189                    relative_path: entry.relative_path.clone(),
190                    capability_ids: shared.capability_ids.clone(),
191                    asset_ids: shared.asset_ids.clone(),
192                    state_schema: shared.state_schema.clone(),
193                    permission_kinds: shared.permission_kinds.clone(),
194                    presentation_hints: shared.presentation_hints.clone(),
195                });
196            }
197            ProjectionKind::DesktopHost if desktop_launch.is_none() => {
198                desktop_launch = Some(DesktopLaunchDescriptor {
199                    entry_id: entry.entry_id.clone(),
200                    app_id: shared.app_id.clone(),
201                    version: shared.version.clone(),
202                    relative_path: entry.relative_path.clone(),
203                    capability_ids: shared.capability_ids.clone(),
204                    asset_ids: shared.asset_ids.clone(),
205                    state_schema: shared.state_schema.clone(),
206                    permission_kinds: shared.permission_kinds.clone(),
207                    presentation_hints: shared.presentation_hints.clone(),
208                });
209            }
210            // Duplicate kind: keep first; later entries of the same kind are ignored.
211            _ => {}
212        }
213    }
214
215    Ok(ProjectedApp {
216        shared,
217        manifold,
218        container,
219        focused_mini_app,
220        desktop_launch,
221    })
222}
223
224fn build_shared(manifest: &PortableAppManifest, grant: &PermissionGrant) -> SharedProjectionIds {
225    let capability_ids = manifest
226        .required_capabilities
227        .iter()
228        .map(|RequiredCapability { id, .. }| id.clone())
229        .collect();
230    let asset_ids = manifest
231        .required_assets
232        .iter()
233        .map(|RequiredAsset { asset_id, .. }| asset_id.clone())
234        .collect();
235    // Authorized kinds = required intents that the grant allows (optional intents
236    // included only when granted). Stable order follows manifest intent order.
237    let mut permission_kinds = Vec::new();
238    for intent in &manifest.permission_intents {
239        if grant.allows(intent.kind) && !permission_kinds.contains(&intent.kind) {
240            permission_kinds.push(intent.kind);
241        }
242    }
243
244    SharedProjectionIds {
245        app_id: manifest.identity.app_id.clone(),
246        version: manifest.identity.version.clone(),
247        author_name: manifest.identity.author.name.clone(),
248        author_did: manifest.identity.author.did.clone(),
249        capability_ids,
250        asset_ids,
251        state_schema: manifest.state_schema.clone(),
252        permission_kinds,
253        presentation_hints: manifest.presentation_hints.clone(),
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use crate::q42::app_manifest::manifest::{
261        sha256_of, AppAuthor, AppIdentity, Compatibility, EntryProjection, Integrity,
262        RequiredAsset, RequiredCapability, UpdateChannel,
263    };
264    use crate::q42::app_manifest::permissions::{
265        authority_from_presentation_hints, PermissionIntent,
266    };
267
268    fn sample_digest() -> [u8; 32] {
269        sha256_of(b"portable-app-package-fixture-v1")
270    }
271
272    fn base_manifest(entries: Vec<EntryProjection>) -> PortableAppManifest {
273        PortableAppManifest {
274            identity: AppIdentity {
275                app_id: "did:q42:app:health.proof".into(),
276                version: "1.0.0".into(),
277                author: AppAuthor {
278                    name: "Web Civics".into(),
279                    did: "did:q42:author:webcivics".into(),
280                },
281            },
282            entries,
283            required_capabilities: vec![RequiredCapability {
284                id: "qualia.graph.query".into(),
285                min_version: "0.0.40".into(),
286            }],
287            required_assets: vec![RequiredAsset {
288                asset_id: "did:q42:asset:chebi:261".into(),
289                expected_sha256: sha256_of(b"chebi-rel261"),
290            }],
291            state_schema: StateSchema {
292                schema_id: "q42:HealthAppStateShape".into(),
293                schema_version: "1".into(),
294            },
295            permission_intents: vec![
296                PermissionIntent {
297                    kind: PermissionKind::ReadLocalState,
298                    scope: "*".into(),
299                    optional: false,
300                },
301                PermissionIntent {
302                    kind: PermissionKind::ReadLocalAsset,
303                    scope: "did:q42:asset:chebi:261".into(),
304                    optional: false,
305                },
306            ],
307            presentation_hints: vec![PresentationHint {
308                key: "theme".into(),
309                value: "health-calm".into(),
310            }],
311            compatibility: Compatibility {
312                min_engine_version: "0.0.40".into(),
313                max_engine_version: String::new(),
314                required_features: vec!["q42-assets".into()],
315            },
316            integrity: Integrity {
317                package_sha256: sample_digest(),
318            },
319            update_channel: UpdateChannel {
320                channel_id: "stable".into(),
321                relative_feed: "update/channel.json".into(),
322            },
323        }
324    }
325
326    fn all_four_entries() -> Vec<EntryProjection> {
327        vec![
328            EntryProjection {
329                projection: ProjectionKind::Manifold,
330                entry_id: "health.overview".into(),
331                relative_path: "entries/overview.json".into(),
332            },
333            EntryProjection {
334                projection: ProjectionKind::Container,
335                entry_id: "health.measure".into(),
336                relative_path: "entries/measure.json".into(),
337            },
338            EntryProjection {
339                projection: ProjectionKind::FocusedMiniApp,
340                entry_id: "health.focused".into(),
341                relative_path: "entries/focused.json".into(),
342            },
343            EntryProjection {
344                projection: ProjectionKind::DesktopHost,
345                entry_id: "health.desktop".into(),
346                relative_path: "entries/desktop.json".into(),
347            },
348        ]
349    }
350
351    fn full_grant() -> PermissionGrant {
352        PermissionGrant {
353            allowed: vec![
354                PermissionKind::ReadLocalState,
355                PermissionKind::ReadLocalAsset,
356            ],
357        }
358    }
359
360    fn assert_shared_ids(shared: &SharedProjectionIds, app_id: &str, version: &str) {
361        assert_eq!(shared.app_id, app_id);
362        assert_eq!(shared.version, version);
363        assert_eq!(
364            shared.capability_ids,
365            vec!["qualia.graph.query".to_string()]
366        );
367        assert_eq!(
368            shared.asset_ids,
369            vec!["did:q42:asset:chebi:261".to_string()]
370        );
371        assert_eq!(shared.state_schema.schema_id, "q42:HealthAppStateShape");
372        assert_eq!(
373            shared.permission_kinds,
374            vec![
375                PermissionKind::ReadLocalState,
376                PermissionKind::ReadLocalAsset
377            ]
378        );
379    }
380
381    #[test]
382    fn conformance_all_four_kinds_share_ids() {
383        let manifest = base_manifest(all_four_entries());
384        let projected = project_manifest(&manifest, &full_grant()).unwrap();
385        assert_eq!(projected.descriptor_count(), 4);
386        assert_shared_ids(&projected.shared, "did:q42:app:health.proof", "1.0.0");
387
388        let m = projected.manifold.as_ref().unwrap();
389        let c = projected.container.as_ref().unwrap();
390        let f = projected.focused_mini_app.as_ref().unwrap();
391        let d = projected.desktop_launch.as_ref().unwrap();
392
393        assert_eq!(m.entry_id, "health.overview");
394        assert_eq!(c.entry_id, "health.measure");
395        assert_eq!(f.entry_id, "health.focused");
396        assert_eq!(d.entry_id, "health.desktop");
397
398        for (app_id, version, caps, assets, schema, perms) in [
399            (
400                &m.app_id,
401                &m.version,
402                &m.capability_ids,
403                &m.asset_ids,
404                &m.state_schema,
405                &m.permission_kinds,
406            ),
407            (
408                &c.app_id,
409                &c.version,
410                &c.capability_ids,
411                &c.asset_ids,
412                &c.state_schema,
413                &c.permission_kinds,
414            ),
415            (
416                &f.app_id,
417                &f.version,
418                &f.capability_ids,
419                &f.asset_ids,
420                &f.state_schema,
421                &f.permission_kinds,
422            ),
423            (
424                &d.app_id,
425                &d.version,
426                &d.capability_ids,
427                &d.asset_ids,
428                &d.state_schema,
429                &d.permission_kinds,
430            ),
431        ] {
432            assert_eq!(app_id, &projected.shared.app_id);
433            assert_eq!(version, &projected.shared.version);
434            assert_eq!(caps, &projected.shared.capability_ids);
435            assert_eq!(assets, &projected.shared.asset_ids);
436            assert_eq!(schema, &projected.shared.state_schema);
437            assert_eq!(perms, &projected.shared.permission_kinds);
438        }
439    }
440
441    #[test]
442    fn conformance_missing_kinds_are_honest_empty() {
443        let manifest = base_manifest(vec![
444            EntryProjection {
445                projection: ProjectionKind::Manifold,
446                entry_id: "only.manifold".into(),
447                relative_path: "entries/overview.json".into(),
448            },
449            EntryProjection {
450                projection: ProjectionKind::FocusedMiniApp,
451                entry_id: "only.focused".into(),
452                relative_path: "entries/focused.json".into(),
453            },
454        ]);
455        let projected = project_manifest(&manifest, &full_grant()).unwrap();
456        assert_eq!(projected.descriptor_count(), 2);
457        assert!(projected.manifold.is_some());
458        assert!(projected.container.is_none());
459        assert!(projected.focused_mini_app.is_some());
460        assert!(projected.desktop_launch.is_none());
461        assert_eq!(
462            projected.manifold.as_ref().unwrap().app_id,
463            projected.focused_mini_app.as_ref().unwrap().app_id
464        );
465    }
466
467    #[test]
468    fn conformance_permission_denial_identical_across_kind_filters() {
469        let manifest = base_manifest(all_four_entries());
470        let short = PermissionGrant {
471            allowed: vec![PermissionKind::ReadLocalState],
472        };
473        let deny_all = project_manifest(&manifest, &short);
474        let deny_manifold =
475            project_manifest_kinds(&manifest, &short, Some(&[ProjectionKind::Manifold]));
476        let deny_desktop =
477            project_manifest_kinds(&manifest, &short, Some(&[ProjectionKind::DesktopHost]));
478        let deny_focused =
479            project_manifest_kinds(&manifest, &short, Some(&[ProjectionKind::FocusedMiniApp]));
480        assert_eq!(deny_all, Err(AppManifestError::PermissionEscalation));
481        assert_eq!(deny_all, deny_manifold);
482        assert_eq!(deny_all, deny_desktop);
483        assert_eq!(deny_all, deny_focused);
484    }
485
486    #[test]
487    fn conformance_hints_cannot_escalate() {
488        let mut manifest = base_manifest(all_four_entries());
489        manifest.presentation_hints.push(PresentationHint {
490            key: "grant".into(),
491            value: "network_egress,admin".into(),
492        });
493        manifest.presentation_hints.push(PresentationHint {
494            key: "permission".into(),
495            value: PermissionKind::NetworkEgress.as_str().into(),
496        });
497
498        let from_hints = authority_from_presentation_hints(&manifest.presentation_hints);
499        assert!(from_hints.allowed.is_empty());
500        assert_eq!(
501            project_manifest(&manifest, &from_hints),
502            Err(AppManifestError::PermissionEscalation)
503        );
504
505        // With a real grant, hints appear as display data only — never as new kinds.
506        let projected = project_manifest(&manifest, &full_grant()).unwrap();
507        assert!(projected
508            .shared
509            .presentation_hints
510            .iter()
511            .any(|h| h.key == "grant"));
512        assert!(!projected
513            .shared
514            .permission_kinds
515            .contains(&PermissionKind::NetworkEgress));
516        assert_eq!(
517            projected.manifold.as_ref().unwrap().presentation_hints,
518            projected.shared.presentation_hints
519        );
520    }
521
522    #[test]
523    fn conformance_kind_filter_emits_subset_with_same_shared_ids() {
524        let manifest = base_manifest(all_four_entries());
525        let projected = project_manifest_kinds(
526            &manifest,
527            &full_grant(),
528            Some(&[ProjectionKind::Container, ProjectionKind::DesktopHost]),
529        )
530        .unwrap();
531        assert_eq!(projected.descriptor_count(), 2);
532        assert!(projected.manifold.is_none());
533        assert!(projected.focused_mini_app.is_none());
534        assert!(projected.container.is_some());
535        assert!(projected.desktop_launch.is_some());
536        assert_eq!(
537            projected.container.as_ref().unwrap().permission_kinds,
538            projected.desktop_launch.as_ref().unwrap().permission_kinds
539        );
540        assert_eq!(
541            projected.container.as_ref().unwrap().app_id,
542            projected.shared.app_id
543        );
544    }
545
546    #[test]
547    fn invalid_empty_entry_id_fails_closed_at_validate() {
548        let mut manifest = base_manifest(all_four_entries());
549        manifest.entries[0].entry_id.clear();
550        assert_eq!(
551            project_manifest(&manifest, &full_grant()),
552            Err(AppManifestError::EmptyEntries)
553        );
554    }
555
556    #[test]
557    fn unknown_projection_fails_at_decode() {
558        assert_eq!(
559            ProjectionKind::from_u8(0),
560            Err(AppManifestError::InvalidProjection)
561        );
562        assert_eq!(
563            ProjectionKind::from_u8(99),
564            Err(AppManifestError::InvalidProjection)
565        );
566    }
567}