Skip to main content

aft_base/secret/
wire.rs

1//! The `secret.use` wire contract (wire-contract v1, §15 "Agent secrets").
2//!
3//! AFT is a **sender**: it calls `secret.use` for the agent scope it is serving
4//! and receives material only for a call a live grant covers. The request is
5//! `{name, coverage?, stamp, target}`, and the stamp is the daemon's own
6//! `ScopeStamp`, relayed exactly as subc delivered it. There is no agent-name
7//! parameter: AFT holds no trusted human-readable name for an agent, so the
8//! vault names the agent only by the stamp's `attributes.agent_id`.
9//!
10//! Every key set here is **closed**. A request missing a required key, or
11//! carrying any key not shown, is refused with `invalid_params`. These types
12//! exist so AFT's outbound request cannot carry an extra key by accident, and
13//! so a reply is parsed strictly: an unknown or missing reply key is a protocol
14//! error, not something to guess about.
15//!
16//! The three reply forms are pinned by the contract's golden examples, which
17//! `crates/aft/tests/fixtures/secret/secret-approval-v1.json` carries and the
18//! seam's tests check.
19
20use std::fmt;
21
22use base64::Engine;
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25use subc_protocol::scope::ScopeStamp;
26
27/// Coverage default: one approval covers the asking scope.
28pub const COVERAGE_SCOPE: &str = "scope";
29/// Coverage for a Head and its workers; offered only `permanent`.
30pub const COVERAGE_AGENT_AND_WORKERS: &str = "agent_and_workers";
31
32/// Which approval coverage a request asks for.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum Coverage {
36    /// One secret use for the asking scope (the default when omitted).
37    Scope,
38    /// The asking head and every worker under it.
39    AgentAndWorkers,
40}
41
42impl Coverage {
43    /// The wire spelling.
44    pub fn as_str(&self) -> &'static str {
45        match self {
46            Coverage::Scope => COVERAGE_SCOPE,
47            Coverage::AgentAndWorkers => COVERAGE_AGENT_AND_WORKERS,
48        }
49    }
50}
51
52/// The target an API key is asked for: `{scheme, host, port?, path}`.
53///
54/// Senders strip the query and fragment before calling, so a `?` or `#` in
55/// `path` is a grammar fault on the vault's side; AFT refuses to send one.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct ApiKeyTarget {
59    /// `https`, the only scheme the vault accepts.
60    pub scheme: String,
61    /// Lowercase ASCII host.
62    pub host: String,
63    /// The port; omitted on the wire when it is the default 443.
64    #[serde(
65        default,
66        skip_serializing_if = "Option::is_none",
67        deserialize_with = "present_option"
68    )]
69    pub port: Option<u16>,
70    /// The request path, starting with `/` and carrying no query or fragment.
71    pub path: String,
72}
73
74/// The target a login was asked for: `{origin}`, canonical `https://host`.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct LoginTarget {
78    /// The canonical origin, with port 443 omitted.
79    pub origin: String,
80}
81
82/// The `target` member of a `secret.use` request.
83#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
84#[serde(untagged)]
85pub enum Target {
86    /// An API key for one host, port and path.
87    ApiKey(ApiKeyTarget),
88    /// A site login, addressed by origin only.
89    Login(LoginTarget),
90}
91
92impl Serialize for Target {
93    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
94        match self {
95            Target::ApiKey(target) => target.serialize(serializer),
96            Target::Login(target) => target.serialize(serializer),
97        }
98    }
99}
100
101/// One `secret.use` request: `{name, coverage?, stamp, target}`.
102///
103/// The `stamp` is the daemon's `ScopeStamp` value, relayed byte for byte. AFT
104/// never rewrites it, because the vault trusts the sender to pass it through
105/// unchanged and takes the asking scope from nowhere else.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[serde(deny_unknown_fields)]
108pub struct SecretUseRequest {
109    /// The secret name (`[A-Za-z0-9][A-Za-z0-9._-]*`, 1–64 bytes).
110    pub name: String,
111    /// The coverage; `scope` when omitted.
112    #[serde(
113        default,
114        skip_serializing_if = "Option::is_none",
115        deserialize_with = "present_option"
116    )]
117    pub coverage: Option<Coverage>,
118    /// The asking call's daemon stamp, unchanged.
119    pub stamp: ScopeStamp,
120    /// What the key is being used for.
121    pub target: Target,
122}
123
124fn present_option<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
125    deserializer: D,
126) -> Result<Option<T>, D::Error> {
127    T::deserialize(deserializer).map(Some)
128}
129
130impl SecretUseRequest {
131    /// Build a request for the scope `stamp` names.
132    ///
133    /// The stamp is taken by value from the route identity, so a caller cannot
134    /// substitute a stamp it typed.
135    pub fn new(name: &str, stamp: &ScopeStamp, target: Target) -> Self {
136        Self {
137            name: name.to_string(),
138            coverage: None,
139            stamp: stamp.clone(),
140            target,
141        }
142    }
143
144    /// Ask for coverage other than the default.
145    pub fn with_coverage(mut self, coverage: Coverage) -> Self {
146        self.coverage = Some(coverage);
147        self
148    }
149
150    /// The request as the `params` object of a `secret.use` call.
151    pub fn to_params(&self) -> Value {
152        serde_json::to_value(self).expect("a secret.use request serializes")
153    }
154}
155
156/// Why a reply could not be read as one of the three documented forms.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum ReplyError {
159    /// The reply is not one of the documented shapes, or carries a key the
160    /// contract does not show.
161    Malformed {
162        /// Plain text naming the shape fault; never a value from the reply.
163        detail: String,
164    },
165    /// `key_b64url` was not strict unpadded base64url.
166    BadKeyEncoding,
167}
168
169impl fmt::Display for ReplyError {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            ReplyError::Malformed { detail } => write!(f, "malformed reply: {detail}"),
173            ReplyError::BadKeyEncoding => {
174                f.write_str("key_b64url is not strict unpadded base64url")
175            }
176        }
177    }
178}
179
180/// An API key the vault released to AFT for this call.
181pub struct ReleasedApiKey {
182    /// Where to put the key: `authorization_bearer`, `header:<name>`,
183    /// `query:<name>` or `json_pointer:<pointer>`.
184    pub location: String,
185    /// The key bytes, zeroizing.
186    bytes: crate::secret::vault::Material,
187}
188
189impl ReleasedApiKey {
190    pub fn new(location: String, bytes: crate::secret::vault::Material) -> Self {
191        Self { location, bytes }
192    }
193
194    pub fn into_parts(self) -> (String, crate::secret::vault::Material) {
195        (self.location, self.bytes)
196    }
197    /// The key bytes for the one request that may carry them.
198    pub fn material(&self) -> &[u8] {
199        self.bytes.expose()
200    }
201}
202
203impl fmt::Debug for ReleasedApiKey {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.debug_struct("ReleasedApiKey")
206            .field("location", &self.location)
207            .field("key_len", &self.bytes.len())
208            .finish()
209    }
210}
211
212/// A site login the vault released; only Cerebellum asks for one.
213pub struct ReleasedLogin {
214    /// The account name.
215    pub username: String,
216    /// The password.
217    pub(super) password: crate::secret::vault::Material,
218    /// The current TOTP code, when the record holds a seed. The seed itself
219    /// never leaves the vault.
220    pub totp: Option<zeroize::Zeroizing<String>>,
221}
222
223impl ReleasedLogin {
224    /// The password bytes.
225    pub fn password(&self) -> &[u8] {
226        self.password.expose()
227    }
228}
229
230impl fmt::Debug for ReleasedLogin {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        f.debug_struct("ReleasedLogin")
233            .field("username_len", &self.username.len())
234            .field("password_len", &self.password.len())
235            .field("totp", &self.totp.is_some())
236            .finish()
237    }
238}
239
240/// What `secret.use` answered, as one of the contract's three forms.
241#[derive(Debug)]
242pub enum SecretUseReply {
243    /// A live grant covered the call: substitute the key at `location`.
244    ReleasedApiKey(ReleasedApiKey),
245    /// A live grant released a login to Cerebellum.
246    ReleasedLogin(ReleasedLogin),
247    /// No live grant covers the call. The sender shows nothing from this to
248    /// the model: the statement goes to the approval card, and the call is
249    /// retried after the phone answers. `approval_required` does not mean a
250    /// phone can currently approve.
251    ApprovalRequired(ApprovalRequest),
252}
253
254/// The vault's pending approval (§15 "Signed statement and envelope").
255#[derive(Clone, PartialEq, Eq, Serialize)]
256pub struct ApprovalRequest {
257    /// The vault's identifier for the pending request, a 26-character ULID.
258    pub request_id: String,
259    /// The signed approval statement, unpadded base64url.
260    pub statement_b64url: String,
261    /// When the pending request lapses, in milliseconds since the epoch.
262    pub expires_at_ms: u64,
263}
264
265impl fmt::Debug for ApprovalRequest {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        f.debug_struct("ApprovalRequest")
268            .field("request_id", &self.request_id)
269            .field("statement_b64url_len", &self.statement_b64url.len())
270            .field("expires_at_ms", &self.expires_at_ms)
271            .finish()
272    }
273}
274
275/// A refusal the vault gave as a result error, `{code, class}`.
276#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct VaultError {
278    /// The contract's code: `not_found`, `limit_exceeded`, `secret_setup_incomplete`,
279    /// `pending_limit`, `store_error`, `approval_invalid`, and the rest of §15's table.
280    pub code: String,
281    /// `permanent`, `transient` or `context_overflow`, when the code has a class.
282    pub class: Option<String>,
283}
284
285impl VaultError {
286    /// Whether a retry can change the answer.
287    pub fn is_transient(&self) -> bool {
288        matches!(self.class.as_deref(), Some("transient"))
289    }
290}
291
292/// A refusal the vault gave as a transport error frame, `{code, message}`.
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct VaultTransportError {
295    /// `invalid_params` and the other transport codes.
296    pub code: String,
297    /// The vault's fixed message, which never echoes the request.
298    pub message: String,
299}
300
301/// The answer to one `secret.use` call.
302#[derive(Debug)]
303pub enum SecretUseAnswer {
304    /// One of the three success shapes.
305    Reply(SecretUseReply),
306    /// A result error frame.
307    Refused(VaultError),
308    /// A transport error frame.
309    Rejected(VaultTransportError),
310}
311
312/// Refusals in the sender contract's ordered checks. A `not_found` never
313/// distinguishes caller admission, scope mapping, record, kind, or target.
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315pub enum SecretUseRefusal {
316    NotFound,
317    InvalidParams,
318    LimitExceeded,
319    SetupIncomplete,
320    PendingLimit,
321    StoreError,
322}
323
324impl SecretUseAnswer {
325    /// Classify known sender refusals without discarding the original wire
326    /// code/class. Unknown future refusals remain refusals, not success.
327    pub fn refusal(&self) -> Option<SecretUseRefusal> {
328        use SecretUseRefusal::*;
329        match self {
330            Self::Rejected(error) if error.code == "invalid_params" => Some(InvalidParams),
331            Self::Refused(error) => match error.code.as_str() {
332                "not_found" => Some(NotFound),
333                "limit_exceeded" => Some(LimitExceeded),
334                "secret_setup_incomplete" => Some(SetupIncomplete),
335                "pending_limit" => Some(PendingLimit),
336                "store_error" => Some(StoreError),
337                _ => None,
338            },
339            _ => None,
340        }
341    }
342}
343
344impl Serialize for SecretUseReply {
345    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
346        use serde::ser::SerializeMap;
347        let mut map = serializer.serialize_map(None)?;
348        match self {
349            Self::ReleasedApiKey(key) => {
350                let encoded = zeroize::Zeroizing::new(b64url().encode(key.material()));
351                map.serialize_entry("status", "released")?;
352                map.serialize_entry("kind", "agent_api_key")?;
353                map.serialize_entry("key_b64url", encoded.as_str())?;
354                map.serialize_entry("location", &key.location)?;
355            }
356            Self::ReleasedLogin(login) => {
357                let password = std::str::from_utf8(login.password())
358                    .map_err(|_| serde::ser::Error::custom("login password is not UTF-8"))?;
359                map.serialize_entry("status", "released")?;
360                map.serialize_entry("kind", "site_login")?;
361                map.serialize_entry("username", &login.username)?;
362                map.serialize_entry("password", password)?;
363                if let Some(totp) = &login.totp {
364                    map.serialize_entry("totp", totp.as_str())?;
365                }
366            }
367            Self::ApprovalRequired(request) => {
368                map.serialize_entry("status", "approval_required")?;
369                map.serialize_entry("request_id", &request.request_id)?;
370                map.serialize_entry("statement_b64url", &request.statement_b64url)?;
371                map.serialize_entry("expires_at_ms", &request.expires_at_ms)?;
372            }
373        }
374        map.end()
375    }
376}
377
378/// The base64url engine the contract uses: strict and unpadded.
379fn b64url() -> base64::engine::general_purpose::GeneralPurpose {
380    base64::engine::general_purpose::URL_SAFE_NO_PAD
381}
382
383/// Read `key_b64url`, which is strict unpadded base64url (nonzero trailing
384/// bits included).
385pub(super) fn decode_key(text: &str) -> Result<Vec<u8>, ReplyError> {
386    let mut decoded = zeroize::Zeroizing::new(vec![0u8; base64::decoded_len_estimate(text.len())]);
387    let length = b64url()
388        .decode_slice(text, &mut decoded)
389        .map_err(|_| ReplyError::BadKeyEncoding)?;
390    crate::secret::vault::zeroize(&mut decoded[length..]);
391    decoded.truncate(length);
392    Ok(std::mem::take(&mut *decoded))
393}
394
395/// The canonical 26-character Crockford ULID the vault's ids use: 26 base32
396/// characters from the 32-symbol Crockford alphabet, uppercase, with no
397/// padding. The first character is bounded to `0..=7` because the leading
398/// 128-bit timestamp field may not overflow.
399pub(super) fn is_ulid(text: &str) -> bool {
400    const CROCKFORD: &[u8] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
401    let bytes = text.as_bytes();
402    bytes.len() == 26
403        && matches!(bytes[0], b'0'..=b'7')
404        && bytes.iter().all(|byte| CROCKFORD.contains(byte))
405}
406
407/// Read a reply value as one of the three documented forms.
408///
409/// Each form's key set is exactly what the contract shows. An unknown key, a
410/// missing key, or a `kind` the form does not carry is a protocol error rather
411/// than a guess, because a sender that guessed could substitute the wrong bytes
412/// at the wrong place.
413pub fn parse_reply(value: &Value) -> Result<SecretUseReply, ReplyError> {
414    let object = value.as_object().ok_or_else(|| ReplyError::Malformed {
415        detail: "the reply is not an object".into(),
416    })?;
417    let status = object
418        .get("status")
419        .and_then(Value::as_str)
420        .ok_or_else(|| ReplyError::Malformed {
421            detail: "the reply has no status".into(),
422        })?;
423    match status {
424        "released" => parse_released(object),
425        "approval_required" => {
426            expect_keys(
427                object,
428                &["status", "request_id", "statement_b64url", "expires_at_ms"],
429            )?;
430            let request_id = object
431                .get("request_id")
432                .and_then(Value::as_str)
433                .filter(|id| is_ulid(id))
434                .ok_or_else(|| ReplyError::Malformed {
435                    detail: "request_id is not a ULID".into(),
436                })?;
437            let statement_b64url = object
438                .get("statement_b64url")
439                .and_then(Value::as_str)
440                .ok_or_else(|| ReplyError::Malformed {
441                    detail: "statement_b64url is missing".into(),
442                })?;
443            // The statement is base64url, and decoding it here proves the
444            // envelope bytes the phone will sign are intact.
445            b64url()
446                .decode(statement_b64url)
447                .map_err(|_| ReplyError::Malformed {
448                    detail: "statement_b64url is not strict unpadded base64url".into(),
449                })?;
450            let expires_at_ms = object
451                .get("expires_at_ms")
452                .and_then(Value::as_u64)
453                .ok_or_else(|| ReplyError::Malformed {
454                    detail: "expires_at_ms is not an unsigned integer".into(),
455                })?;
456            Ok(SecretUseReply::ApprovalRequired(ApprovalRequest {
457                request_id: request_id.to_string(),
458                statement_b64url: statement_b64url.to_string(),
459                expires_at_ms,
460            }))
461        }
462        other => Err(ReplyError::Malformed {
463            detail: format!("unknown status {}", other.len()),
464        }),
465    }
466}
467
468/// Check that `object` carries exactly `keys`, so a contract change shows up as
469/// a refusal instead of silently dropped or extra data.
470fn expect_keys(object: &serde_json::Map<String, Value>, keys: &[&str]) -> Result<(), ReplyError> {
471    for key in keys {
472        if !object.contains_key(*key) {
473            return Err(ReplyError::Malformed {
474                detail: "a documented reply key is missing".into(),
475            });
476        }
477    }
478    if object.len() != keys.len() {
479        return Err(ReplyError::Malformed {
480            detail: "the reply carries a key the contract does not show".into(),
481        });
482    }
483    Ok(())
484}
485
486/// Distinguish the API-key form from the login form by their `kind`.
487fn parse_released(object: &serde_json::Map<String, Value>) -> Result<SecretUseReply, ReplyError> {
488    match object.get("kind").and_then(Value::as_str) {
489        Some("agent_api_key") => {
490            expect_keys(object, &["status", "kind", "key_b64url", "location"])?;
491            let location = object
492                .get("location")
493                .and_then(Value::as_str)
494                .ok_or_else(|| ReplyError::Malformed {
495                    detail: "location is missing".into(),
496                })?;
497            let key_b64url = object
498                .get("key_b64url")
499                .and_then(Value::as_str)
500                .ok_or_else(|| ReplyError::Malformed {
501                    detail: "key_b64url is missing".into(),
502                })?;
503            Ok(SecretUseReply::ReleasedApiKey(ReleasedApiKey {
504                location: location.to_string(),
505                bytes: crate::secret::vault::Material::new(decode_key(key_b64url)?),
506            }))
507        }
508        Some("site_login") => {
509            let totp = object.get("totp").cloned();
510            let keys: Vec<&str> = match &totp {
511                Some(_) => vec!["status", "kind", "username", "password", "totp"],
512                None => vec!["status", "kind", "username", "password"],
513            };
514            expect_keys(object, &keys)?;
515            let username = object
516                .get("username")
517                .and_then(Value::as_str)
518                .ok_or_else(|| ReplyError::Malformed {
519                    detail: "username is missing".into(),
520                })?;
521            let password = object
522                .get("password")
523                .and_then(Value::as_str)
524                .ok_or_else(|| ReplyError::Malformed {
525                    detail: "password is missing".into(),
526                })?;
527            let totp = match totp {
528                None | Some(Value::Null) => None,
529                Some(Value::String(code)) => Some(zeroize::Zeroizing::new(code)),
530                Some(_) => {
531                    return Err(ReplyError::Malformed {
532                        detail: "totp is not a string".into(),
533                    })
534                }
535            };
536            Ok(SecretUseReply::ReleasedLogin(ReleasedLogin {
537                username: username.to_string(),
538                password: crate::secret::vault::Material::new(password.as_bytes().to_vec()),
539                totp,
540            }))
541        }
542        Some(other) => Err(ReplyError::Malformed {
543            detail: format!("released reply kind {}", other.len()),
544        }),
545        None => Err(ReplyError::Malformed {
546            detail: "a released reply carries no kind".into(),
547        }),
548    }
549}
550
551/// A result error frame `{"error":{"code":…,"class":…}}`, as §15's code table
552/// spells it.
553#[derive(Debug, Deserialize)]
554struct ResultError {
555    error: ResultErrorBody,
556}
557
558#[derive(Debug, Deserialize)]
559struct ResultErrorBody {
560    code: String,
561    #[serde(default)]
562    class: Option<String>,
563}
564
565/// A transport error frame `{"code":…,"message":…}` with no class (§1a).
566#[derive(Debug, Deserialize)]
567struct TransportError {
568    code: String,
569    message: String,
570}
571
572/// Read a whole `secret.use` reply body (`{"result": …}` or an error object).
573///
574/// This is the one place the wire shapes are interpreted, so the client and the
575/// tests read replies by the same rules.
576pub fn parse_answer(body: &Value) -> Result<SecretUseAnswer, ReplyError> {
577    if let Some(result) = body.get("result") {
578        expect_keys(
579            body.as_object().ok_or_else(|| ReplyError::Malformed {
580                detail: "the reply is not an object".into(),
581            })?,
582            &["result"],
583        )?;
584        if result.get("error").is_some() {
585            let error: ResultError =
586                serde_json::from_value(result.clone()).map_err(|_| ReplyError::Malformed {
587                    detail: "the result error does not match the contract".into(),
588                })?;
589            return Ok(SecretUseAnswer::Refused(VaultError {
590                code: error.error.code,
591                class: error.error.class,
592            }));
593        }
594        return parse_reply(result).map(SecretUseAnswer::Reply);
595    }
596    if let Ok(error) = serde_json::from_value::<TransportError>(body.clone()) {
597        return Ok(SecretUseAnswer::Rejected(VaultTransportError {
598            code: error.code,
599            message: error.message,
600        }));
601    }
602    Err(ReplyError::Malformed {
603        detail: "the body is neither a result nor a transport error".into(),
604    })
605}