Skip to main content

cortexkit_claustrum_client/
fleet_epoch.rs

1//! Fleet epoch records use the caller domain attested by the vault route.
2
3use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
4use serde::Deserialize;
5use serde_json::value::RawValue;
6
7use crate::{CredentialErrorClass, CredentialResolverError, Secret};
8
9const MAX_BATCH_ITEMS: usize = 256;
10
11/// Bytes to seal under the current fleet epoch. The plaintext remains caller-owned.
12#[derive(Debug, Clone, Copy)]
13pub struct FleetEpochSealRequest<'a> {
14    pub aad: &'a [u8],
15    pub plaintext: &'a Secret<Vec<u8>>,
16}
17
18/// A sealed record and the exact associated data used to seal it.
19#[derive(Debug, Clone, Copy)]
20pub struct FleetEpochOpenRequest<'a> {
21    pub epoch: u32,
22    pub nonce: &'a [u8],
23    pub ciphertext: &'a [u8],
24    pub aad: &'a [u8],
25}
26
27/// Fleet epoch record to persist alongside its associated data.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct FleetEpochSeal {
30    pub epoch: u32,
31    pub nonce: [u8; 24],
32    pub ciphertext: Vec<u8>,
33}
34
35/// One ordered slot of a successful open batch. The refusal's code and class
36/// are those returned by the vault for that item.
37pub type FleetEpochOpenResult = Result<Secret<Vec<u8>>, CredentialResolverError>;
38
39#[derive(Deserialize)]
40struct Reply<'a> {
41    #[serde(borrow)]
42    result: &'a RawValue,
43}
44
45#[derive(Deserialize)]
46struct MaybeRefusal<'a> {
47    #[serde(borrow)]
48    error: Option<&'a RawValue>,
49}
50
51#[derive(Deserialize)]
52#[serde(deny_unknown_fields)]
53struct Refusal<'a> {
54    #[serde(borrow)]
55    error: &'a RawValue,
56}
57
58#[derive(Deserialize)]
59#[serde(deny_unknown_fields)]
60struct WireError<'a> {
61    code: &'a str,
62    class: &'a str,
63}
64
65#[derive(Deserialize)]
66#[serde(deny_unknown_fields)]
67struct Sealed<'a> {
68    epoch: std::num::NonZeroU32,
69    nonce: &'a str,
70    ciphertext: &'a str,
71}
72
73#[derive(Deserialize)]
74#[serde(deny_unknown_fields)]
75struct Opened<'a> {
76    #[serde(borrow)]
77    plaintext: &'a RawValue,
78}
79
80#[derive(Deserialize)]
81#[serde(deny_unknown_fields)]
82struct BatchReply<'a> {
83    #[serde(borrow)]
84    items: Vec<&'a RawValue>,
85}
86
87fn invalid_reply() -> CredentialResolverError {
88    CredentialResolverError::new(
89        CredentialErrorClass::InvalidResponse,
90        "invalid fleet epoch reply",
91    )
92}
93
94fn object<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, CredentialResolverError> {
95    if bytes.iter().find(|b| !b.is_ascii_whitespace()) != Some(&b'{') {
96        return Err(invalid_reply());
97    }
98    serde_json::from_slice(bytes).map_err(|_| invalid_reply())
99}
100
101fn result_body(bytes: &[u8]) -> Result<&RawValue, CredentialResolverError> {
102    Ok(object::<Reply<'_>>(bytes)?.result)
103}
104
105fn refusal(body: &RawValue) -> Result<Option<CredentialResolverError>, CredentialResolverError> {
106    if object::<MaybeRefusal<'_>>(body.get().as_bytes())?
107        .error
108        .is_none()
109    {
110        return Ok(None);
111    }
112    let refusal: Refusal<'_> = object(body.get().as_bytes())?;
113    let error: WireError<'_> = object(refusal.error.get().as_bytes())?;
114    let class = match error.class {
115        "permanent" => CredentialErrorClass::Permanent,
116        "transient" => CredentialErrorClass::Transient,
117        _ => return Err(invalid_reply()),
118    };
119    // Fleet not_found is a permanent admission refusal, not an absent credential.
120    Ok(Some(CredentialResolverError {
121        class,
122        code: error.code.to_owned(),
123        safe_message: "vault refused the fleet epoch operation".to_owned(),
124        established_route_dead: false,
125        sdk_route_credit_exhausted: false,
126    }))
127}
128
129fn success_body(bytes: &[u8]) -> Result<&RawValue, CredentialResolverError> {
130    let body = result_body(bytes)?;
131    match refusal(body)? {
132        Some(error) => Err(error),
133        None => Ok(body),
134    }
135}
136
137fn decode_sealed(body: &RawValue) -> Result<FleetEpochSeal, CredentialResolverError> {
138    let sealed: Sealed<'_> = object(body.get().as_bytes())?;
139    let mut nonce = [0; 24];
140    let len = URL_SAFE_NO_PAD
141        .decode_slice(sealed.nonce, &mut nonce)
142        .map_err(|_| invalid_reply())?;
143    if len != nonce.len() {
144        return Err(invalid_reply());
145    }
146    Ok(FleetEpochSeal {
147        epoch: sealed.epoch.get(),
148        nonce,
149        ciphertext: URL_SAFE_NO_PAD
150            .decode(sealed.ciphertext)
151            .map_err(|_| invalid_reply())?,
152    })
153}
154
155fn decode_opened(body: &RawValue) -> Result<Secret<Vec<u8>>, CredentialResolverError> {
156    let opened: Opened<'_> = object(body.get().as_bytes())?;
157    // Canonical base64url needs no JSON escapes. Borrow the string's raw bytes
158    // so even a malformed escaped value cannot leave a parser-owned copy.
159    let encoded = opened
160        .plaintext
161        .get()
162        .as_bytes()
163        .strip_prefix(b"\"")
164        .and_then(|value| value.strip_suffix(b"\""))
165        .ok_or_else(invalid_reply)?;
166    let mut plaintext = Secret::new(vec![0; base64::decoded_len_estimate(encoded.len())]);
167    let len = URL_SAFE_NO_PAD
168        .decode_slice(encoded, plaintext.expose_mut())
169        .map_err(|_| invalid_reply())?;
170    plaintext.expose_mut().truncate(len);
171    Ok(plaintext)
172}
173
174fn valid_batch_size(count: usize) -> bool {
175    (1..=MAX_BATCH_ITEMS).contains(&count)
176}
177
178fn batch_reply(bytes: &[u8]) -> Result<Vec<&RawValue>, CredentialResolverError> {
179    let body: BatchReply<'_> = object(success_body(bytes)?.get().as_bytes())?;
180    if !valid_batch_size(body.items.len()) {
181        return Err(invalid_reply());
182    }
183    Ok(body.items)
184}
185
186/// Decodes the JSON body of a fleet seal Response frame (including a vault refusal).
187/// Decode Error frames on the route separately with [`crate::decode_established_route_wire_error`].
188pub fn decode_fleet_epoch_seal_reply(
189    bytes: &[u8],
190) -> Result<FleetEpochSeal, CredentialResolverError> {
191    decode_sealed(success_body(bytes)?)
192}
193
194/// Decodes the JSON body of a fleet open Response frame (including a vault refusal).
195/// The input may hold encoded plaintext; keep it in zeroizing storage too.
196pub fn decode_fleet_epoch_open_reply(bytes: &[u8]) -> FleetEpochOpenResult {
197    decode_opened(success_body(bytes)?)
198}
199
200/// Decodes a fleet batch seal Response frame body, in wire order, or fails the whole reply.
201pub fn decode_fleet_epoch_seal_batch_reply(
202    bytes: &[u8],
203) -> Result<Vec<FleetEpochSeal>, CredentialResolverError> {
204    batch_reply(bytes)?.into_iter().map(decode_sealed).collect()
205}
206
207/// Decodes a fleet batch open Response frame body. An outer error is a whole-call
208/// refusal or invalid reply; item refusals preserve their slots in a successful batch.
209/// The input may hold encoded plaintext; keep it in zeroizing storage too.
210pub fn decode_fleet_epoch_open_batch_reply(
211    bytes: &[u8],
212) -> Result<Vec<FleetEpochOpenResult>, CredentialResolverError> {
213    batch_reply(bytes)?
214        .into_iter()
215        .map(|item| match refusal(item)? {
216            Some(error) => Ok(Err(error)),
217            None => decode_opened(item).map(Ok),
218        })
219        .collect()
220}
221
222#[cfg(any(feature = "transport", test))]
223mod request;
224
225#[cfg(test)]
226mod tests;