hyprstream_rpc/service/body.rs
1//! The one bounded decode of a signed request body (v16 §5.2).
2//!
3//! `DecodedRequestBody` is produced exactly once per request by the service's
4//! **generated** decoder ([`crate::service::RequestService::decode_request_body`])
5//! and then feeds every consumer of the request's method identity and content:
6//!
7//! - the generated per-method signature policy (`proof::policy`) resolves its
8//! row with [`DecodedRequestBody::leaf_path`];
9//! - the dispatch MAC PEP receives the same leaf path as its object
10//! coordinate; and
11//! - the handler dispatch reads the request from the same decoded message via
12//! [`DecodedRequestBody::root`] — there is no second
13//! `capnp::serialize::read_message` anywhere between admission and handler.
14//!
15//! The leaf path is the chain of Cap'n Proto union discriminants from the
16//! service root request union down to the executed leaf (v16 §5.1): nested
17//! scope unions contribute their discriminants, so a nested method selects a
18//! distinct policy row rather than collapsing onto its parent. Human-readable
19//! names are review metadata; the numeric discriminants are wire identity.
20
21use capnp::message::ReaderOptions;
22use capnp::serialize::OwnedSegments;
23
24/// Reviewed decode caps for the single signed-body decode (v16 §5.2).
25///
26/// Cap'n Proto's pointer-traversal amplification is bounded by the traversal
27/// limit (in 8-byte words); nesting depth bounds recursion. These are
28/// deliberately far below `ReaderOptions::default()`'s 64 MiB traversal
29/// allowance: an RPC request body is transport-size-capped well below this,
30/// so the caps bound decode work without constraining any legitimate request.
31pub const BODY_TRAVERSAL_LIMIT_WORDS: u64 = 2 * 1024 * 1024; // 16 MiB of traversal
32/// Maximum pointer nesting depth for the signed-body decode.
33pub const BODY_NESTING_LIMIT: i32 = 64;
34
35/// The bounded reader options every generated signed-body decoder uses.
36pub fn bounded_reader_options() -> ReaderOptions {
37 let mut opts = ReaderOptions::new();
38 opts.traversal_limit_in_words(Some(BODY_TRAVERSAL_LIMIT_WORDS as usize));
39 opts.nesting_limit(BODY_NESTING_LIMIT);
40 opts
41}
42
43/// A request body decoded exactly once, with its derived full method leaf.
44///
45/// Constructed by generated service decoders via [`DecodedRequestBody::from_message`],
46/// or — only for services with no Cap'n Proto request schema (test echo
47/// services, byte-oriented bridges) — via [`DecodedRequestBody::opaque`].
48pub struct DecodedRequestBody {
49 /// The exact signed body bytes (what the request proof signs).
50 bytes: Vec<u8>,
51 /// The one decoded message. `None` only for [`DecodedRequestBody::opaque`]
52 /// bodies, which cannot serve generated dispatch.
53 message: Option<capnp::message::Reader<OwnedSegments>>,
54 /// Full union-discriminant chain from the root request union to the
55 /// executed leaf. Empty only for opaque bodies.
56 leaf_path: Vec<u16>,
57}
58
59impl DecodedRequestBody {
60 /// Wrap the one decoded message and its derived leaf path.
61 ///
62 /// Generated decoders call this after the single bounded
63 /// `read_message` + leaf traversal. The leaf path must be non-empty: a
64 /// request whose root union arm is unknown never reaches this
65 /// constructor (the generated decoder returns an error instead).
66 pub fn from_message(
67 bytes: Vec<u8>,
68 message: capnp::message::Reader<OwnedSegments>,
69 leaf_path: Vec<u16>,
70 ) -> anyhow::Result<Self> {
71 anyhow::ensure!(
72 !leaf_path.is_empty(),
73 "decoded request body derived an empty method leaf path"
74 );
75 Ok(Self {
76 bytes,
77 message: Some(message),
78 leaf_path,
79 })
80 }
81
82 /// A body for a service with **no** Cap'n Proto request schema.
83 ///
84 /// The body carries raw bytes only: there is no decoded message and no
85 /// derivable method leaf, so a proof-bearing request to such a service
86 /// denies at leaf derivation (v16 §5.2) and generated dispatch cannot be
87 /// served from it. This exists for byte-oriented test/bridge services and
88 /// is an affirmative per-service choice, never a default.
89 pub fn opaque(bytes: Vec<u8>) -> Self {
90 Self {
91 bytes,
92 message: None,
93 leaf_path: Vec::new(),
94 }
95 }
96
97 /// The exact signed body bytes.
98 pub fn bytes(&self) -> &[u8] {
99 &self.bytes
100 }
101
102 /// The full numeric method leaf path, or `None` for an opaque body.
103 pub fn leaf_path(&self) -> Option<&[u16]> {
104 if self.leaf_path.is_empty() {
105 None
106 } else {
107 Some(&self.leaf_path)
108 }
109 }
110
111 /// The leaf path in the dotted form generated policy rows are keyed by.
112 pub fn leaf_path_string(&self) -> Option<String> {
113 self.leaf_path().map(|path| {
114 path.iter()
115 .map(u16::to_string)
116 .collect::<Vec<_>>()
117 .join(".")
118 })
119 }
120
121 /// Read the typed root of the one decoded message.
122 ///
123 /// Generated dispatch reads the request through this — pointer traversal
124 /// over the already-decoded message, never a second decode of the bytes.
125 pub fn root<'a, T: capnp::traits::FromPointerReader<'a>>(&'a self) -> anyhow::Result<T> {
126 let message = self.message.as_ref().ok_or_else(|| {
127 anyhow::anyhow!("opaque request body has no decoded message to dispatch from")
128 })?;
129 message.get_root::<T>().map_err(Into::into)
130 }
131}
132
133impl std::fmt::Debug for DecodedRequestBody {
134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 f.debug_struct("DecodedRequestBody")
136 .field("bytes_len", &self.bytes.len())
137 .field("decoded", &self.message.is_some())
138 .field("leaf_path", &self.leaf_path)
139 .finish()
140 }
141}