Skip to main content

laser_wire/
forward.rs

1// Frames the managed backend consumes on behalf of a client. The SDK never
2// sends these directly. They live here so the encoding has one definition and
3// the golden corpus pins them like every other frame.
4
5use serde::{Deserialize, Serialize};
6
7/// Who asked for a request the managed backend records, present only when a
8/// client asked. A record the backend or the streaming server issues on its own
9/// carries none.
10#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
11#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
12pub struct Caller {
13    /// The authenticated user. The root user is id zero.
14    pub user_id: u32,
15    /// The agent the caller's connection declared in its presence. A claim the
16    /// client makes, never verified.
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub agent: Option<crate::agent::AgentId>,
19    /// The end user an intermediary wrote for, as it named that user in
20    /// [`ON_BEHALF_OF_HEADER`](crate::http::ON_BEHALF_OF_HEADER). A claim the
21    /// backend records, never verified.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub on_behalf_of: Option<String>,
24}
25
26/// Trusted stream identity stamped by the server before forwarding a session request.
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
29pub struct ForwardedScope {
30    pub stream_id: u32,
31    pub stream: String,
32    pub stream_created_at_micros: u64,
33}
34
35/// A forwarded managed query. Carries the authenticated identity the SDK cannot
36/// set itself, plus the opaque request the SDK sent. CBOR-encoded, named fields.
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
39pub struct ForwardedQuery {
40    /// Authenticated identity. Audit today, per-user stream scoping later.
41    /// Trusted: set by the server, not the client.
42    pub user_id: u32,
43    /// Originating client id, for logging and audit only. Never zero for a
44    /// client, zero on a request the server issues itself.
45    pub client_id: u128,
46    /// `gen_ai.conversation.id` echoed for the audit log, never used to route.
47    pub correlation: Option<String>,
48    /// Opaque CBOR `QueryEnvelope` from the SDK, not decoded in transit.
49    #[cfg_attr(
50        feature = "schemars",
51        schemars(schema_with = "crate::encoding::bytes_schema")
52    )]
53    #[serde(with = "crate::encoding::bin_bytes")]
54    pub query_envelope: Vec<u8>,
55    /// The caller's effective capability grants, stamped by the server. Empty
56    /// (the default, skipped on the wire) when authorization is not in effect.
57    #[serde(default, skip_serializing_if = "Vec::is_empty")]
58    pub grants: Vec<crate::authz::Grant>,
59    /// The tenancy of the server's replicated authorization state. The
60    /// backend refuses a frame whose tenancy differs from its own.
61    #[serde(default, skip_serializing_if = "crate::authz::Tenancy::is_deployment")]
62    pub tenancy: crate::authz::Tenancy,
63    /// The stream of the queried index, stamped once the caller's native read
64    /// authority over it was checked. The backend refuses a query of a
65    /// stream-scoped index that arrives without this scope or with another.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub scope: Option<ForwardedScope>,
68}
69
70/// A forwarded keyed managed command (registry browse, key-value, forks). Unlike
71/// `ForwardedQuery`, several op kinds share one path, so the frame carries
72/// `command_code` and the backend dispatches on it. `payload` is the opaque
73/// CBOR request the SDK sent.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
76pub struct ForwardedCommand {
77    /// The client that asked, stamped by the server, so the SDK cannot set it.
78    /// The backend records it and authorizes with `grants`. Absent on a request
79    /// the server issues on its own.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub caller: Option<Caller>,
82    /// The caller's consensus client id, for logs and correlation only, never
83    /// identity.
84    pub client_id: u128,
85    /// `gen_ai.conversation.id` echoed for the audit log, never used to route.
86    pub correlation: Option<String>,
87    /// Stable identity minted by the originating SDK for a logical managed
88    /// mutation. Read-only commands leave it absent.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub operation_id: Option<u128>,
91    /// Vestigial. The server stamps `false`, the plane ignores it, and the
92    /// caller's grants govern access. It stays on the wire as the contract's
93    /// current structure, never as a widening flag.
94    #[serde(default)]
95    pub read_all: bool,
96    /// Server-stamped stream identity. A session command without it fails closed.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub scope: Option<ForwardedScope>,
99    /// The managed command code (browse, key-value, or fork block). The backend
100    /// dispatches on it.
101    pub command_code: u32,
102    /// Opaque CBOR request the SDK sent, not decoded in transit.
103    #[cfg_attr(
104        feature = "schemars",
105        schemars(schema_with = "crate::encoding::bytes_schema")
106    )]
107    #[serde(with = "crate::encoding::bin_bytes")]
108    pub payload: Vec<u8>,
109    /// The caller's effective capability grants, stamped by the server. Empty
110    /// (the default, skipped on the wire) when authorization is not in effect.
111    #[serde(default, skip_serializing_if = "Vec::is_empty")]
112    pub grants: Vec<crate::authz::Grant>,
113    /// Set by the server when the client wrapped this read in a
114    /// [`crate::mutation::ManagedReadEnvelope`]. The backend answers only once
115    /// its fold has reached the surface's mutation log head.
116    #[serde(default, skip_serializing_if = "is_false")]
117    pub read_barrier: bool,
118    /// Set by the server from [`crate::mutation::ManagedReadEnvelope`]: the
119    /// backend answers only once its fold for the read's surface has applied
120    /// this position.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub min_position: Option<crate::mutation::MutationPosition>,
123    /// Set by the server for a managed request an SDK client sent over the
124    /// binary protocol. The backend answers with a
125    /// [`crate::mutation::ManagedReplyEnvelope`] carrying its applied
126    /// frontier.
127    #[serde(default, skip_serializing_if = "is_false")]
128    pub positioned_reply: bool,
129    /// Set by the server from [`crate::mutation::ManagedReadEnvelope`]: the
130    /// session positions a session read must find applied.
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub min_sessions: Vec<crate::mutation::SessionPosition>,
133    /// The tenancy of the server's replicated authorization state. The
134    /// backend refuses a frame whose tenancy differs from its own.
135    #[serde(default, skip_serializing_if = "crate::authz::Tenancy::is_deployment")]
136    pub tenancy: crate::authz::Tenancy,
137}
138
139#[expect(clippy::trivially_copy_pass_by_ref, reason = "serde skip predicate")]
140fn is_false(value: &bool) -> bool {
141    !*value
142}
143
144#[cfg(all(test, feature = "cbor"))]
145mod tests {
146    use super::*;
147    use crate::framing::{decode_named, encode_named};
148
149    // A contiguous byte-string run inside the encoded frame proves the opaque
150    // field rode as a CBOR byte string (major type 2), not an array of ints.
151    // The values are all >= 0x18, which an array would have to widen to two
152    // bytes each, so the byte string is also strictly smaller.
153    fn contains_byte_string(frame: &[u8], len: u8, fill: u8) -> bool {
154        let head = 0x40 | len; // byte string, length in the low 5 bits
155        let mut want = vec![head];
156        want.extend(std::iter::repeat_n(fill, len as usize));
157        frame.windows(want.len()).any(|w| w == want.as_slice())
158    }
159
160    #[test]
161    fn given_forwarded_query_when_encoded_then_envelope_rides_as_a_byte_string() {
162        let frame = encode_named(&ForwardedQuery {
163            user_id: 7,
164            client_id: 42,
165            correlation: Some("conv-1".to_owned()),
166            query_envelope: vec![0x90; 5],
167            grants: Vec::new(),
168            tenancy: Default::default(),
169            scope: None,
170        })
171        .expect("encodes");
172        assert!(
173            contains_byte_string(&frame, 5, 0x90),
174            "query_envelope must encode as a CBOR byte string, got {frame:02x?}"
175        );
176    }
177
178    #[test]
179    fn given_forwarded_command_when_encoded_then_payload_rides_as_a_byte_string() {
180        let frame = encode_named(&ForwardedCommand {
181            read_barrier: false,
182            min_position: None,
183            positioned_reply: false,
184            min_sessions: Vec::new(),
185            tenancy: Default::default(),
186            caller: Some(Caller {
187                user_id: 7,
188                agent: None,
189                on_behalf_of: None,
190            }),
191            client_id: 42,
192            correlation: None,
193            operation_id: Some(17),
194            read_all: true,
195            scope: None,
196            command_code: 1_000_000,
197            payload: vec![0x90; 5],
198            grants: Vec::new(),
199        })
200        .expect("encodes");
201        assert!(
202            contains_byte_string(&frame, 5, 0x90),
203            "payload must encode as a CBOR byte string, got {frame:02x?}"
204        );
205    }
206
207    #[test]
208    fn given_forwarded_frames_when_round_tripped_then_should_preserve_fields() {
209        let query = ForwardedQuery {
210            user_id: 1,
211            client_id: u128::MAX,
212            correlation: Some("c".to_owned()),
213            query_envelope: vec![0xff, 0x00, 0x18, 0x7f],
214            grants: Vec::new(),
215            tenancy: Default::default(),
216            scope: Some(ForwardedScope {
217                stream_id: 3,
218                stream: "acme".to_owned(),
219                stream_created_at_micros: 9,
220            }),
221        };
222        let back: ForwardedQuery =
223            decode_named(&encode_named(&query).expect("encodes")).expect("decodes");
224        assert_eq!(back, query);
225
226        let command = ForwardedCommand {
227            read_barrier: false,
228            min_position: None,
229            positioned_reply: false,
230            min_sessions: Vec::new(),
231            tenancy: Default::default(),
232            caller: Some(Caller {
233                user_id: 2,
234                agent: Some("orbit-planner".parse().expect("agent id")),
235                on_behalf_of: Some("1793690355287073".to_owned()),
236            }),
237            client_id: 9,
238            correlation: None,
239            operation_id: Some(9),
240            read_all: false,
241            scope: None,
242            command_code: 42,
243            payload: vec![0xde, 0xad, 0xbe, 0xef],
244            grants: Vec::new(),
245        };
246        let back: ForwardedCommand =
247            decode_named(&encode_named(&command).expect("encodes")).expect("decodes");
248        assert_eq!(back, command);
249    }
250
251    #[test]
252    fn given_a_root_caller_with_an_agent_when_round_tripped_then_should_keep_both() {
253        let caller = Caller {
254            user_id: 0,
255            agent: Some("orbit-planner".parse().expect("agent id")),
256            on_behalf_of: None,
257        };
258
259        let back: Caller = decode_named(&encode_named(&caller).expect("encodes")).expect("decodes");
260
261        assert_eq!(back, caller);
262    }
263
264    #[test]
265    fn given_a_caller_written_for_an_end_user_when_round_tripped_then_should_keep_who_it_was_for() {
266        let caller = Caller {
267            user_id: 3,
268            agent: None,
269            on_behalf_of: Some("1793690355287073".to_owned()),
270        };
271
272        let back: Caller = decode_named(&encode_named(&caller).expect("encodes")).expect("decodes");
273
274        assert_eq!(back, caller);
275    }
276
277    #[test]
278    fn given_a_caller_with_an_empty_agent_when_decoded_then_should_be_refused() {
279        #[derive(serde::Serialize)]
280        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
281        struct Unchecked<'a> {
282            user_id: u32,
283            agent: &'a str,
284        }
285        let frame = encode_named(&Unchecked {
286            user_id: 3,
287            agent: "",
288        })
289        .expect("encodes");
290
291        assert!(decode_named::<Caller>(&frame).is_err());
292    }
293
294    #[test]
295    fn given_a_request_the_server_issues_on_its_own_when_encoded_then_should_carry_no_caller() {
296        let command = ForwardedCommand {
297            read_barrier: false,
298            min_position: None,
299            positioned_reply: false,
300            min_sessions: Vec::new(),
301            tenancy: Default::default(),
302            caller: None,
303            client_id: 0,
304            correlation: None,
305            operation_id: Some(9),
306            read_all: false,
307            scope: None,
308            command_code: 42,
309            payload: vec![1],
310            grants: Vec::new(),
311        };
312
313        let frame = encode_named(&command).expect("encodes");
314        let back: ForwardedCommand = decode_named(&frame).expect("decodes");
315
316        assert_eq!(back, command);
317        assert!(
318            !frame
319                .windows(b"caller".len())
320                .any(|window| window == b"caller"),
321            "an absent caller is omitted from the frame"
322        );
323    }
324}