Skip to main content

subc_protocol/
claim.rs

1//! Single-use claims for connections belonging to a supervised spawn.
2//!
3//! These standalone bodies use channel 0, the connection's control lane. Merely
4//! defining them does not advertise daemon support for either operation.
5//! Success uses a RESPONSE; refusals use [`crate::ErrorBody`] and the codes in
6//! [`crate::error_codes`]. Claims grant nothing until the daemon consumes them.
7
8use std::{collections::BTreeMap, fmt};
9
10use serde::{de::Error as _, Deserialize, Deserializer, Serialize};
11use serde_json::Value;
12
13/// An opaque bearer claim. Debug output is always redacted, including when a
14/// containing request or reply is formatted. Never log the serialized body or
15/// exposed value, or put the claim in argv or an environment variable.
16#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(transparent)]
18pub struct Claim(String);
19
20impl Claim {
21    /// Wrap an opaque wire value. Only the daemon validates and consumes claims;
22    /// constructing this value does not establish a connection's identity.
23    pub fn new(value: impl Into<String>) -> Self {
24        Self(value.into())
25    }
26
27    /// Access the bearer value for an explicit handoff, never for logging.
28    pub fn expose_secret(&self) -> &str {
29        &self.0
30    }
31}
32
33impl fmt::Debug for Claim {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.write_str("Claim([REDACTED])")
36    }
37}
38
39/// The authority requested for one additional connection. Only a prefix claim
40/// carries a module id. The daemon checks its grammar and that the minting
41/// module owns the longest matching reserved prefix, excluding exact reserved
42/// or gated ids and prefixes without an owner.
43#[non_exhaustive]
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45#[serde(tag = "purpose")]
46pub enum ClaimPurpose {
47    #[serde(rename = "self")]
48    SelfConnection,
49    #[serde(rename = "helper")]
50    Helper,
51    #[serde(rename = "relay")]
52    Relay,
53    #[serde(rename = "prefix")]
54    Prefix { module_id: String },
55}
56
57impl<'de> Deserialize<'de> for ClaimPurpose {
58    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
59        #[derive(Deserialize)]
60        #[serde(rename_all = "snake_case")]
61        enum Purpose {
62            #[serde(rename = "self")]
63            SelfConnection,
64            Helper,
65            Relay,
66            Prefix,
67        }
68        #[derive(Deserialize)]
69        struct Wire {
70            purpose: Purpose,
71            #[serde(flatten)]
72            fields: BTreeMap<String, Value>,
73        }
74        let mut wire = Wire::deserialize(deserializer)?;
75        let module_id = wire.fields.remove("module_id");
76        match wire.purpose {
77            Purpose::Prefix => match module_id {
78                Some(Value::String(module_id)) => Ok(Self::Prefix { module_id }),
79                _ => Err(D::Error::custom("prefix claims require a string module_id")),
80            },
81            _ if module_id.is_some() => {
82                Err(D::Error::custom("module_id is only for prefix claims"))
83            }
84            Purpose::SelfConnection => Ok(Self::SelfConnection),
85            Purpose::Helper => Ok(Self::Helper),
86            Purpose::Relay => Ok(Self::Relay),
87        }
88    }
89}
90
91/// Mint only over the spawn's live primary registration channel. Claim-bound
92/// connections cannot mint. Refusals never permit falling back to direct.
93#[non_exhaustive]
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct ClaimMintRequest {
96    op: MintOp,
97    #[serde(flatten)]
98    pub purpose: ClaimPurpose,
99}
100
101impl ClaimMintRequest {
102    pub fn new(purpose: ClaimPurpose) -> Self {
103        Self {
104            op: MintOp::Op,
105            purpose,
106        }
107    }
108}
109
110/// One single-use 128-bit base64url claim, redeemable for 30 seconds on the
111/// daemon's monotonic clock. The wall-clock expiry is informational only;
112/// readers must not use it to decide that a claim is still valid.
113#[non_exhaustive]
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct ClaimMintReply {
116    op: MintOp,
117    pub claim: Claim,
118    pub expires_at_ms: u64,
119}
120
121impl ClaimMintReply {
122    pub fn new(claim: Claim, expires_at_ms: u64) -> Self {
123        Self {
124            op: MintOp::Op,
125            claim,
126            expires_at_ms,
127        }
128    }
129}
130
131/// The first frame after a new connection's handshake. Acceptance consumes the
132/// claim and binds the connection atomically while rechecking the live spawn.
133/// Any refused presentation closes the connection, including a retryable
134/// refusal; it never continues as direct.
135#[non_exhaustive]
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137pub struct ClaimPresentRequest {
138    op: PresentOp,
139    pub claim: Claim,
140}
141
142impl ClaimPresentRequest {
143    pub fn new(claim: Claim) -> Self {
144        Self {
145            op: PresentOp::Op,
146            claim,
147        }
148    }
149}
150
151/// Acceptance of a single-use claim. Refusals use an ERROR frame, never this ACK.
152#[non_exhaustive]
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct ClaimPresentReply {
155    op: PresentOp,
156}
157
158impl ClaimPresentReply {
159    pub fn new() -> Self {
160        Self { op: PresentOp::Op }
161    }
162}
163
164impl Default for ClaimPresentReply {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// Backoff carried in [`crate::ErrorBody::detail`] for `claim_rate_limited`.
171#[non_exhaustive]
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct ClaimRateLimitedDetail {
174    pub retry_after_ms: u64,
175}
176
177impl ClaimRateLimitedDetail {
178    pub fn new(retry_after_ms: u64) -> Self {
179        Self { retry_after_ms }
180    }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184enum MintOp {
185    #[serde(rename = "claim.mint")]
186    Op,
187}
188
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190enum PresentOp {
191    #[serde(rename = "claim.present")]
192    Op,
193}
194
195#[cfg(test)]
196mod claim_wire_tests {
197    use super::*;
198    use crate::{error_codes, manifest::ModuleManifest, ErrorBody};
199    use serde_json::json;
200
201    macro_rules! purpose_test {
202        ($name:ident, $purpose:expr, $body:expr) => {
203            #[test]
204            fn $name() {
205                let expected = $body;
206                let request = ClaimMintRequest::new($purpose);
207                assert_eq!(serde_json::to_value(&request).unwrap(), expected);
208                assert_eq!(
209                    serde_json::from_value::<ClaimMintRequest>(expected).unwrap(),
210                    request
211                );
212            }
213        };
214    }
215    purpose_test!(
216        mint_self,
217        ClaimPurpose::SelfConnection,
218        json!({"op":"claim.mint","purpose":"self"})
219    );
220    purpose_test!(
221        mint_helper,
222        ClaimPurpose::Helper,
223        json!({"op":"claim.mint","purpose":"helper"})
224    );
225    purpose_test!(
226        mint_relay,
227        ClaimPurpose::Relay,
228        json!({"op":"claim.mint","purpose":"relay"})
229    );
230    purpose_test!(
231        mint_prefix,
232        ClaimPurpose::Prefix {
233            module_id: "worker.child".into()
234        },
235        json!({"op":"claim.mint","purpose":"prefix","module_id":"worker.child"})
236    );
237
238    #[test]
239    fn module_id_only_for_prefix_and_required_op_tags() {
240        for purpose in ["self", "helper", "relay"] {
241            for module_id in [json!("child"), Value::Null] {
242                assert!(serde_json::from_value::<ClaimMintRequest>(json!({
243                    "op":"claim.mint", "purpose":purpose, "module_id":module_id
244                }))
245                .is_err());
246            }
247        }
248        for body in [
249            json!({"op":"claim.mint","purpose":"prefix"}),
250            json!({"op":"claim.mint","purpose":"prefix","module_id":5}),
251            json!({"op":"claim.mint","purpose":"future"}),
252            json!({"op":"claim.present","purpose":"self"}),
253            json!({"purpose":"self"}),
254        ] {
255            assert!(serde_json::from_value::<ClaimMintRequest>(body).is_err());
256        }
257        assert!(
258            serde_json::from_value::<ClaimPresentRequest>(json!({"op":"claim.present"})).is_err()
259        );
260        assert!(serde_json::from_value::<ClaimPresentReply>(json!({})).is_err());
261        assert!(serde_json::from_value::<ClaimPresentReply>(json!({"op":"claim.mint"})).is_err());
262        assert!(serde_json::from_value::<ClaimMintReply>(json!({"op":"claim.mint"})).is_err());
263    }
264
265    #[test]
266    fn replies_and_presentation_round_trip() {
267        let claim = Claim::new("AAAAAAAAAAAAAAAAAAAAAA");
268        let reply = ClaimMintReply::new(claim.clone(), 1_700_000_030_000);
269        let wire = json!({"op":"claim.mint","claim":claim,"expires_at_ms":1_700_000_030_000_u64});
270        assert!(serde_json::to_value(&reply).unwrap() == wire);
271        assert_eq!(
272            serde_json::from_value::<ClaimMintReply>(wire).unwrap(),
273            reply
274        );
275        let request = ClaimPresentRequest::new(claim.clone());
276        let wire = json!({"op":"claim.present","claim":claim});
277        assert!(serde_json::to_value(&request).unwrap() == wire);
278        assert_eq!(
279            serde_json::from_value::<ClaimPresentRequest>(wire).unwrap(),
280            request
281        );
282        let ack = ClaimPresentReply::new();
283        assert_eq!(
284            serde_json::to_value(&ack).unwrap(),
285            json!({"op":"claim.present"})
286        );
287        assert_eq!(
288            serde_json::from_str::<ClaimPresentReply>(r#"{"op":"claim.present"}"#).unwrap(),
289            ack
290        );
291    }
292
293    #[test]
294    fn debug_redacts_claim_and_containing_bodies() {
295        let secret = "BBBBBBBBBBBBBBBBBBBBBB";
296        let claim = Claim::new(secret);
297        let decoded: Claim = serde_json::from_value(json!(secret)).unwrap();
298        assert_eq!(decoded, claim);
299        assert!(decoded.expose_secret() == secret);
300        for debug in [
301            format!("{claim:?}"),
302            format!("{:?}", ClaimMintReply::new(claim.clone(), 0)),
303            format!("{:?}", ClaimPresentRequest::new(claim)),
304        ] {
305            assert!(!debug.contains(secret));
306            assert!(debug.contains("[REDACTED]"));
307        }
308    }
309
310    macro_rules! refusal_test {
311        ($name:ident, $code:ident, $spelling:literal, $retryable:expr) => {
312            #[test]
313            fn $name() {
314                assert_eq!(error_codes::$code, $spelling);
315                let wire = json!({"code":$spelling,"message":"claim refused"});
316                let error: ErrorBody = serde_json::from_value(wire.clone()).unwrap();
317                assert_eq!(serde_json::to_value(&error).unwrap(), wire);
318                assert_eq!(error_codes::is_retryable_claim(&error.code), $retryable);
319                assert!(!error_codes::is_retryable_route_open(&error.code));
320                let table: Value = serde_json::from_str(include_str!("../tests/golden/decision_tables.json")).unwrap();
321                assert_eq!(table["claim_retryable"][$spelling], if $retryable { "retryable" } else { "terminal" });
322            }
323        };
324    }
325    refusal_test!(
326        mint_not_allowed,
327        CLAIM_MINT_NOT_ALLOWED,
328        "claim_mint_not_allowed",
329        false
330    );
331    refusal_test!(
332        unredeemed_limit,
333        CLAIM_UNREDEEMED_LIMIT,
334        "claim_unredeemed_limit",
335        true
336    );
337    refusal_test!(rate_limited, CLAIM_RATE_LIMITED, "claim_rate_limited", true);
338    refusal_test!(
339        connection_limit,
340        CLAIM_CONNECTION_LIMIT,
341        "claim_connection_limit",
342        true
343    );
344    refusal_test!(invalid, CLAIM_INVALID, "claim_invalid", false);
345    refusal_test!(
346        present_not_first,
347        CLAIM_PRESENT_NOT_FIRST,
348        "claim_present_not_first",
349        false
350    );
351    refusal_test!(
352        prefix_refused,
353        CLAIM_PREFIX_REFUSED,
354        "claim_prefix_refused",
355        false
356    );
357
358    #[test]
359    fn rate_limit_backoff_detail_round_trip() {
360        let wire = json!({"code":"claim_rate_limited","message":"claim refused","detail":{"retry_after_ms":125}});
361        let error: ErrorBody = serde_json::from_value(wire.clone()).unwrap();
362        let detail: ClaimRateLimitedDetail =
363            serde_json::from_value(error.detail.clone().unwrap()).unwrap();
364        assert_eq!(detail, ClaimRateLimitedDetail::new(125));
365        let encoded = ErrorBody::new(error_codes::CLAIM_RATE_LIMITED, "claim refused")
366            .with_detail(serde_json::to_value(detail).unwrap());
367        assert_eq!(serde_json::to_value(encoded).unwrap(), wire);
368    }
369
370    #[test]
371    fn unknown_refusal_is_terminal() {
372        assert!(!error_codes::is_retryable_claim("a_code_nobody_declared"));
373    }
374
375    #[test]
376    fn manifest_registration_channel_is_optional_on_read() {
377        let legacy = ModuleManifest::builder("worker", "1.0.0").build();
378        let legacy_wire = serde_json::to_value(&legacy).unwrap();
379        assert!(legacy_wire.get("registration_channel").is_none());
380        let read: ModuleManifest = serde_json::from_value(legacy_wire.clone()).unwrap();
381        assert_eq!(read.registration_channel, None);
382        for supported in [true, false] {
383            let mut wire = legacy_wire.clone();
384            wire["registration_channel"] = json!(supported);
385            let read: ModuleManifest = serde_json::from_value(wire.clone()).unwrap();
386            assert_eq!(read.registration_channel, Some(supported));
387            assert_eq!(serde_json::to_value(&read).unwrap(), wire);
388            assert_eq!(
389                ModuleManifest::builder("worker", "1.0.0")
390                    .registration_channel(supported)
391                    .build(),
392                read
393            );
394        }
395    }
396}