hyprstream_rpc/_metadata.rs
1//! RPC schema introspection metadata types.
2//!
3//! These types represent metadata extracted from Cap'n Proto schema annotations
4//! (`$scope`/`$capability`, `$mcpDescription`, `$cliHidden`, `$paramDescription`).
5//! They are the shared source of truth used by both the `generate_rpc_service!`
6//! codegen macro and the runtime `ServiceFactory` inventory.
7
8/// Schema metadata for a single RPC method parameter.
9///
10/// Extracted from Cap'n Proto struct field definitions and `$paramDescription` annotations.
11#[derive(Debug, Clone)]
12pub struct ParamMeta {
13 pub name: &'static str,
14 pub type_name: &'static str,
15 pub required: bool,
16 pub description: &'static str,
17 /// Default value hint (empty = no default). For Bool fields this is "false".
18 pub default_value: &'static str,
19}
20
21/// Schema metadata for a single RPC method.
22///
23/// Extracted from Cap'n Proto union variants and schema annotations
24/// (`$scope`/`$capability`, `$mcpDescription`, `$cliHidden`).
25#[derive(Debug, Clone)]
26pub struct MethodMeta {
27 pub name: &'static str,
28 pub params: &'static [ParamMeta],
29 pub description: &'static str,
30 /// Required authorization scope action from `$scope`/`$capability` — one of the
31 /// `ScopeAction` enumerants (S3, #547). Mandatory: empty only for a method that
32 /// declared `$scopeExempt`. Maps 1:1 onto `hyprstream::auth::Operation`.
33 pub scope: &'static str,
34 pub is_streaming: bool,
35 pub is_scoped: bool,
36 pub scope_field: &'static str,
37 /// Whether to hide from auto-generated interfaces (from `$cliHidden`).
38 pub hidden: bool,
39 /// VFS usage example from `$docExample` annotation. Empty = no example.
40 pub doc_example: &'static str,
41}
42
43/// The 9P/VFS node kind a generated method projects to (epic #539).
44///
45/// Mirrors the `VfsNodeKind` capnp enum. `File`/`Dir`/`Query` are read-only
46/// (side-effect-free 9P reads); `Ctl` is a write-a-verb control file; `Stream`
47/// is a `/stream`-style pipe.
48#[derive(Copy, Clone, Debug, PartialEq, Eq)]
49pub enum VfsNodeKind {
50 /// Readable (maybe writable) leaf; `read` renders the method's response.
51 File,
52 /// Directory; `readdir` lists child entries (e.g. a `list` method).
53 Dir,
54 /// Write-a-verb control file; a `write` invokes the method.
55 Ctl,
56 /// `/stream`-style pipe (data/info/ctl) for a streaming method.
57 Stream,
58 /// Synthetic query file: write a spec, read the result.
59 Query,
60}
61
62impl VfsNodeKind {
63 /// Whether a `read` of this node must be side-effect-free (9P read invariant).
64 /// `File`/`Dir`/`Query` are read surfaces; `Ctl`/`Stream` mutate/produce.
65 pub fn is_read_only(self) -> bool {
66 matches!(self, Self::File | Self::Dir | Self::Query)
67 }
68}
69
70/// A single node in a service's generated 9P/VFS projection (epic #539, T2).
71///
72/// Built by codegen from each method's `MethodMeta` + `$vfs*` annotations. The
73/// runtime mount engine (T3) consumes these to serve `/srv/{service}` — `path`
74/// is mount-relative (fid-0 rooted, never absolute); `{braces}` in `path` are
75/// segments that bind the method's scalar argument.
76#[derive(Copy, Clone, Debug)]
77pub struct VfsNode {
78 /// The method this node projects (snake_case), used to dispatch on access.
79 pub method: &'static str,
80 /// Mount-relative path; `{name}` segments bind a scalar arg from the walk.
81 pub path: &'static str,
82 /// The projected node kind (inferred from scope+shape, or `$vfsKind`).
83 pub kind: VfsNodeKind,
84 /// Authorization scope action (from `MethodMeta::scope`).
85 pub scope: &'static str,
86 /// `$vfsBulk`: `read` returns raw mmap bytes, bypassing capnp (DMA path).
87 pub bulk: bool,
88 /// `$vfsMac` annotation text declaring this node's MAC security label
89 /// (#699 carrier (a)): the label is a property of the node's type, derived
90 /// at codegen. Decode with [`VfsNode::mac_label`]. Empty ⇒ the node is
91 /// unlabeled ⇒ deny ⇒ a genesis-coverage finding (no permissive default).
92 pub mac: &'static str,
93}
94
95impl VfsNode {
96 /// Decode this node's `$vfsMac` annotation into a [`SecurityLabel`].
97 ///
98 /// Returns `None` when the annotation is empty, malformed, or carries a
99 /// non-`pq-hybrid` assurance — the node is then **unlabeled**, which the MAC
100 /// model treats as **deny** (there is no permissive default; absence is
101 /// denial). Such nodes surface as gaps in the genesis coverage report rather
102 /// than being silently defaulted.
103 ///
104 /// Format: `"<level>:<assurance>[:<compBit>[,<compBit>...]]"` where `level`
105 /// is one of `public`/`internal`/`confidential`/`secret`, `assurance` is
106 /// **required** and must be exactly `pq-hybrid` (the internal non-interop
107 /// carrier rejects `unverified`/`classical`/omitted — #556), and each
108 /// `compBit` is a `u32` compartment bit index (the lattice vocabulary is S3's
109 /// job, #569).
110 pub fn mac_label(&self) -> Option<crate::auth::mac::SecurityLabel> {
111 parse_mac_annotation(self.mac)
112 }
113}
114
115/// Parse a `$vfsMac` annotation string into a [`SecurityLabel`].
116///
117/// `""` / unparseable / non-`pq-hybrid` ⇒ `None` (unlabeled ⇒ deny). See
118/// [`VfsNode::mac_label`].
119///
120/// **Assurance is mandatory and MUST be `pq-hybrid`** (#556, #1228): the
121/// generated 9P/VFS surface is an *internal, non-interop* carrier, and the
122/// operator ruling is PQ-hybrid required on all deployments. A level-only
123/// annotation, `unverified`, or `classical` would produce a label a classical
124/// subject dominates — the non-PQ path #556 was enacted to remove, reappearing
125/// as a silent default. Those forms are therefore **rejected** (⇒ unlabeled ⇒
126/// deny ⇒ a genesis-coverage finding), never silently downgraded.
127fn parse_mac_annotation(s: &str) -> Option<crate::auth::mac::SecurityLabel> {
128 use crate::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel};
129
130 let s = s.trim();
131 if s.is_empty() {
132 return None;
133 }
134 let mut parts = s.split(':');
135 let level = match parts.next()?.trim() {
136 "public" => Level::Public,
137 "internal" => Level::Internal,
138 "confidential" => Level::Confidential,
139 "secret" => Level::Secret,
140 _ => return None,
141 };
142 // Assurance is MANDATORY and must be exactly `pq-hybrid`. Omitted,
143 // `unverified`, and `classical` are all rejected ⇒ None ⇒ unlabeled ⇒ deny
144 // (this is the internal non-interop surface; #556 removes the classical
145 // floor, and this carrier must not silently reintroduce it).
146 let assurance = match parts.next().map(str::trim) {
147 Some("pq-hybrid") => Assurance::PqHybrid,
148 // Omitted, empty, unverified, classical, or unknown ⇒ reject.
149 None | Some("") | Some("unverified") | Some("classical") | Some(_) => return None,
150 };
151 let compartments = match parts.next().map(str::trim) {
152 None | Some("") => CompartmentSet::EMPTY,
153 Some(bits) => {
154 let mut set = CompartmentSet::EMPTY;
155 for b in bits.split(',') {
156 let b = b.trim();
157 if b.is_empty() {
158 continue;
159 }
160 let idx: u32 = b.parse().ok()?;
161 set = set.union(CompartmentSet::single(idx));
162 }
163 set
164 }
165 };
166 // A fourth field is not part of the grammar → malformed → deny.
167 if parts.next().is_some() {
168 return None;
169 }
170 Some(SecurityLabel::new(level, assurance, compartments))
171}
172
173/// Function type for a service's VFS node table.
174///
175/// Returns `(service_name, nodes)`.
176pub type VfsNodesFn = fn() -> (&'static str, &'static [VfsNode]);
177
178/// Inventory-registered generated VFS node table (#699 carrier (a) inventory).
179///
180/// Submitted by `generate_rpc_service!` for every schema that has request
181/// variants (i.e. every service that projects a `/srv/{name}` mount with
182/// generated nodes). The genesis coverage gate collects the union of these
183/// tables via [`inventory::iter::<VfsNodeTable>()`] so the startup gate covers
184/// every reachable generated object class — not just the ones a hand-built
185/// fixture happened to include.
186///
187/// The `nodes_fn` indirection keeps the table lazy (zero-cost until the gate
188/// walks it) and lets this crate stay free of a `hyprstream-service`
189/// dependency: the macro emits the `inventory::submit!` in whatever crate owns
190/// the generated client module, and the gate (in the daemon crate) iterates it.
191///
192/// On wasm32 (#1305) the link-time registration is compiled out (inventory's
193/// linker-section mechanism doesn't resolve there); the generated
194/// `vfs_nodes()` fn is the wasm-compatible path and stays directly callable.
195pub struct VfsNodeTable {
196 /// The `/srv/{name}` service this table belongs to.
197 pub name: &'static str,
198 /// `fn() -> (service_name, &[VfsNode])` — the generated `vfs_nodes()`.
199 pub nodes_fn: VfsNodesFn,
200}
201
202#[cfg(not(target_arch = "wasm32"))]
203inventory::collect!(VfsNodeTable);
204
205/// Function type for service schema metadata.
206///
207/// Returns `(service_name, methods)`.
208pub type SchemaMetadataFn = fn() -> (&'static str, &'static [MethodMeta]);
209
210/// Function type for scoped service schema metadata.
211///
212/// Returns `(service_name, scope_name, methods)`.
213pub type ScopedSchemaMetadataFn = fn() -> (&'static str, &'static str, &'static [MethodMeta]);
214
215/// Tree node describing a scoped client and its nested children.
216/// Generated by the proc macro, consumed by CLI/MCP for dynamic dispatch.
217#[derive(Copy, Clone, Debug)]
218pub struct ScopedClientTreeNode {
219 pub scope_name: &'static str,
220 pub scope_field: &'static str,
221 pub metadata_fn: ScopedSchemaMetadataFn,
222 pub nested: &'static [ScopedClientTreeNode],
223}
224
225#[cfg(test)]
226#[allow(clippy::unwrap_used)]
227mod tests {
228 use super::*;
229 use crate::auth::mac::{Assurance, Level};
230
231 fn node(mac: &'static str) -> VfsNode {
232 VfsNode {
233 method: "m",
234 path: "p",
235 kind: VfsNodeKind::File,
236 scope: "query",
237 bulk: false,
238 mac,
239 }
240 }
241
242 #[test]
243 fn mac_label_decodes_level_and_pq_hybrid_assurance() {
244 // The only accepted form: <level>:pq-hybrid. Assurance is mandatory.
245 let l = node("confidential:pq-hybrid").mac_label().unwrap();
246 assert_eq!(l.level, Level::Confidential);
247 assert_eq!(l.assurance, Assurance::PqHybrid);
248 assert!(l.compartments.is_empty());
249 }
250
251 #[test]
252 fn mac_label_decodes_level_and_assurance() {
253 let l = node("secret:pq-hybrid").mac_label().unwrap();
254 assert_eq!(l.level, Level::Secret);
255 assert_eq!(l.assurance, Assurance::PqHybrid);
256 }
257
258 #[test]
259 fn mac_label_decodes_compartments() {
260 // Compartments are the optional third field, after the mandatory
261 // `pq-hybrid` assurance.
262 let l = node("internal:pq-hybrid:0,3").mac_label().unwrap();
263 assert_eq!(l.level, Level::Internal);
264 assert_eq!(l.assurance, Assurance::PqHybrid);
265 assert!(l.compartments.contains(0));
266 assert!(l.compartments.contains(3));
267 assert!(!l.compartments.contains(1));
268 }
269
270 #[test]
271 fn mac_label_empty_is_unlabeled_deny() {
272 // No $vfsMac ⇒ unlabeled ⇒ None ⇒ deny. No permissive default.
273 assert!(node("").mac_label().is_none());
274 assert!(node(" ").mac_label().is_none());
275 }
276
277 #[test]
278 fn mac_label_level_only_is_denied_assurance_is_mandatory() {
279 // A level-only annotation (no assurance) is rejected ⇒ None ⇒ deny.
280 // Assurance is mandatory on this internal non-interop carrier; a
281 // level-only form would default to Unverified, the non-PQ path #556
282 // removed. Each level is rejected without an assurance.
283 for level in ["public", "internal", "confidential", "secret"] {
284 assert!(
285 node(level).mac_label().is_none(),
286 "level-only `{level}` must deny: assurance is mandatory"
287 );
288 }
289 }
290
291 #[test]
292 fn mac_label_unverified_assurance_is_denied() {
293 // `unverified` is the non-PQ floor ⇒ rejected on this internal carrier.
294 // Each form an operator might reach for that silently drops PQ is denied.
295 assert!(node("internal:unverified").mac_label().is_none());
296 assert!(node("public:unverified").mac_label().is_none());
297 }
298
299 #[test]
300 fn mac_label_classical_assurance_is_denied() {
301 // `classical` is the explicit non-PQ path #556 removes from internal VFS
302 // — a classical subject would dominate it. Rejected ⇒ None ⇒ deny.
303 assert!(node("internal:classical").mac_label().is_none());
304 assert!(node("secret:classical:0").mac_label().is_none());
305 }
306
307 #[test]
308 fn mac_label_malformed_is_unlabeled_deny() {
309 // An unknown level / assurance / a trailing field ⇒ None ⇒ deny
310 // (fail-closed, never a guessed label).
311 assert!(node("topsecret").mac_label().is_none());
312 assert!(node("secret:quantum").mac_label().is_none());
313 assert!(node("secret:pq-hybrid:0:extra").mac_label().is_none());
314 }
315
316 #[test]
317 fn mac_label_non_numeric_compartment_is_deny() {
318 assert!(node("secret:pq-hybrid:pii").mac_label().is_none());
319 }
320}