Skip to main content

qualia_core_db/q42/app_manifest/
mod.rs

1//! Portable application manifest v1 (APP-02) + projection adapters (APP-03).
2//!
3//! Cold-construction schema for app identity, entry projections, required
4//! capabilities/assets, state schema, permission intents, presentation hints,
5//! compatibility, integrity digests, and update channel.
6//!
7//! `project_manifest` resolves one manifest into host-neutral Poet manifold,
8//! Poet container, focused mini-app, and Desktop launch descriptors without a
9//! projection-specific private database or divergent permission model.
10//!
11//! # Security invariants
12//!
13//! - Unknown manifest versions fail closed.
14//! - Unknown permission wire values fail closed.
15//! - Permission intents that exceed a host grant ceiling fail closed.
16//! - Package path fields reject `..`, absolute escapes, and URL schemes.
17//! - **Presentation hints are inert for authority** — they never grant
18//!   permissions; see `authority_from_presentation_hints`.
19//! - Projection adapters authorize once and copy the same IDs / permission
20//!   outcome into every descriptor.
21
22mod codec;
23mod error;
24mod manifest;
25mod paths;
26mod permissions;
27mod project;
28
29pub use codec::APP_MANIFEST_MAGIC;
30pub use error::AppManifestError;
31pub use manifest::{
32    sha256_into, sha256_of, AppAuthor, AppIdentity, Compatibility, EntryProjection, Integrity,
33    PortableAppManifest, ProjectionKind, RequiredAsset, RequiredCapability, StateSchema,
34    UpdateChannel, APP_MANIFEST_VERSION, MAX_ASSETS, MAX_CAPABILITIES, MAX_ENTRIES, MAX_FEATURES,
35    MAX_HINTS, MAX_MANIFEST_BYTES, MAX_PERMISSIONS,
36};
37pub use paths::validate_package_relative_path;
38pub use permissions::{
39    authority_from_presentation_hints, check_permission_intents, PermissionGrant, PermissionIntent,
40    PermissionKind, PresentationHint,
41};
42pub use project::{
43    project_manifest, project_manifest_kinds, DesktopLaunchDescriptor, FocusedMiniAppProjection,
44    PoetContainerProjection, PoetManifoldProjection, ProjectedApp, SharedProjectionIds,
45};
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    fn sample_digest() -> [u8; 32] {
52        sha256_of(b"portable-app-package-fixture-v1")
53    }
54
55    fn sample_manifest() -> PortableAppManifest {
56        PortableAppManifest {
57            identity: AppIdentity {
58                app_id: "did:q42:app:health.proof".into(),
59                version: "1.0.0".into(),
60                author: AppAuthor {
61                    name: "Web Civics".into(),
62                    did: "did:q42:author:webcivics".into(),
63                },
64            },
65            entries: vec![
66                EntryProjection {
67                    projection: ProjectionKind::Manifold,
68                    entry_id: "health.overview".into(),
69                    relative_path: "entries/overview.json".into(),
70                },
71                EntryProjection {
72                    projection: ProjectionKind::FocusedMiniApp,
73                    entry_id: "health.focused".into(),
74                    relative_path: "entries/focused.json".into(),
75                },
76            ],
77            required_capabilities: vec![RequiredCapability {
78                id: "qualia.graph.query".into(),
79                min_version: "0.0.40".into(),
80            }],
81            required_assets: vec![RequiredAsset {
82                asset_id: "did:q42:asset:chebi:261".into(),
83                expected_sha256: sha256_of(b"chebi-rel261"),
84            }],
85            state_schema: StateSchema {
86                schema_id: "q42:HealthAppStateShape".into(),
87                schema_version: "1".into(),
88            },
89            permission_intents: vec![
90                PermissionIntent {
91                    kind: PermissionKind::ReadLocalState,
92                    scope: "*".into(),
93                    optional: false,
94                },
95                PermissionIntent {
96                    kind: PermissionKind::ReadLocalAsset,
97                    scope: "did:q42:asset:chebi:261".into(),
98                    optional: false,
99                },
100            ],
101            presentation_hints: vec![PresentationHint {
102                key: "theme".into(),
103                value: "health-calm".into(),
104            }],
105            compatibility: Compatibility {
106                min_engine_version: "0.0.40".into(),
107                max_engine_version: String::new(),
108                required_features: vec!["q42-assets".into()],
109            },
110            integrity: Integrity {
111                package_sha256: sample_digest(),
112            },
113            update_channel: UpdateChannel {
114                channel_id: "stable".into(),
115                relative_feed: "update/channel.json".into(),
116            },
117        }
118    }
119
120    #[test]
121    fn round_trip_preserves_manifest() {
122        let original = sample_manifest();
123        let bytes = original.encode().unwrap();
124        let decoded = PortableAppManifest::decode(&bytes).unwrap();
125        assert_eq!(decoded, original);
126    }
127
128    #[test]
129    fn deterministic_hash_is_stable() {
130        let a = sample_manifest().manifest_digest().unwrap();
131        let b = sample_manifest().manifest_digest().unwrap();
132        assert_eq!(a, b);
133        assert_ne!(a, [0u8; 32]);
134        // Re-encode yields identical bytes → identical digest.
135        let bytes_a = sample_manifest().encode().unwrap();
136        let bytes_b = sample_manifest().encode().unwrap();
137        assert_eq!(bytes_a, bytes_b);
138        assert_eq!(sha256_of(&bytes_a), a);
139    }
140
141    #[test]
142    fn malformed_magic_rejected() {
143        let mut bytes = sample_manifest().encode().unwrap();
144        bytes[0] = b'X';
145        assert_eq!(
146            PortableAppManifest::decode(&bytes),
147            Err(AppManifestError::InvalidMagic)
148        );
149    }
150
151    #[test]
152    fn truncated_bytes_rejected() {
153        let bytes = sample_manifest().encode().unwrap();
154        assert_eq!(
155            PortableAppManifest::decode(&bytes[..12]),
156            Err(AppManifestError::Truncated)
157        );
158    }
159
160    #[test]
161    fn unknown_version_fails_closed() {
162        let mut bytes = sample_manifest().encode().unwrap();
163        // version u16 LE at offset 8
164        bytes[8] = 99;
165        bytes[9] = 0;
166        assert_eq!(
167            PortableAppManifest::decode(&bytes),
168            Err(AppManifestError::UnsupportedVersion)
169        );
170    }
171
172    #[test]
173    fn unknown_permission_on_wire_fails_closed() {
174        let mut crafted = sample_manifest();
175        crafted.permission_intents = vec![PermissionIntent {
176            kind: PermissionKind::ReadLocalState,
177            scope: "*".into(),
178            optional: false,
179        }];
180        let wire = crafted.encode().unwrap();
181        // Patch the permission kind byte to 0xFF. Projection pads can look like
182        // kind=1/optional=0, so confirm by decode error kind.
183        let mut found = false;
184        for i in 0..wire.len().saturating_sub(1) {
185            if wire[i] == PermissionKind::ReadLocalState as u8 && wire[i + 1] == 0 {
186                let mut candidate = wire.clone();
187                candidate[i] = 0xFF;
188                if PortableAppManifest::decode(&candidate)
189                    == Err(AppManifestError::UnknownPermission)
190                {
191                    found = true;
192                    break;
193                }
194            }
195        }
196        assert!(found, "failed to locate permission kind byte");
197    }
198
199    #[test]
200    fn permission_escalation_fails_closed() {
201        let manifest = sample_manifest();
202        let grant = PermissionGrant {
203            allowed: vec![PermissionKind::ReadLocalState],
204        };
205        // Manifest also requires ReadLocalAsset → escalation.
206        assert_eq!(
207            check_permission_intents(&manifest.permission_intents, &grant),
208            Err(AppManifestError::PermissionEscalation)
209        );
210        let full = PermissionGrant {
211            allowed: vec![
212                PermissionKind::ReadLocalState,
213                PermissionKind::ReadLocalAsset,
214            ],
215        };
216        assert!(check_permission_intents(&manifest.permission_intents, &full).is_ok());
217
218        // NetworkEgress above a read-only grant.
219        let escalate = [PermissionIntent {
220            kind: PermissionKind::NetworkEgress,
221            scope: "*".into(),
222            optional: false,
223        }];
224        assert_eq!(
225            check_permission_intents(&escalate, &full),
226            Err(AppManifestError::PermissionEscalation)
227        );
228    }
229
230    #[test]
231    fn presentation_hints_are_inert_for_authority() {
232        let mut manifest = sample_manifest();
233        manifest.presentation_hints.push(PresentationHint {
234            key: "grant".into(),
235            value: "network_egress,admin,shell".into(),
236        });
237        manifest.presentation_hints.push(PresentationHint {
238            key: "permission".into(),
239            value: PermissionKind::NetworkEgress.as_str().into(),
240        });
241        let from_hints = authority_from_presentation_hints(&manifest.presentation_hints);
242        assert!(
243            from_hints.allowed.is_empty(),
244            "hints must never produce a grant"
245        );
246        // Even with malicious-looking hints, required intents still need a real grant.
247        assert_eq!(
248            check_permission_intents(&manifest.permission_intents, &from_hints),
249            Err(AppManifestError::PermissionEscalation)
250        );
251        // Round-trip still preserves hints as data only.
252        let decoded = PortableAppManifest::decode(&manifest.encode().unwrap()).unwrap();
253        assert_eq!(decoded.presentation_hints, manifest.presentation_hints);
254    }
255
256    #[test]
257    fn path_traversal_in_entry_fails() {
258        let mut manifest = sample_manifest();
259        manifest.entries[0].relative_path = "../escape.bin".into();
260        assert_eq!(manifest.validate(), Err(AppManifestError::PathTraversal));
261        assert_eq!(manifest.encode(), Err(AppManifestError::PathTraversal));
262    }
263
264    #[test]
265    fn absolute_update_feed_fails() {
266        let mut manifest = sample_manifest();
267        manifest.update_channel.relative_feed = "/etc/passwd".into();
268        assert_eq!(manifest.validate(), Err(AppManifestError::AbsolutePath));
269    }
270
271    #[test]
272    fn missing_identity_fails() {
273        let mut manifest = sample_manifest();
274        manifest.identity.app_id.clear();
275        assert_eq!(manifest.validate(), Err(AppManifestError::MissingAppId));
276    }
277}