Skip to main content

capsule_core/validation/
protocol.rs

1//! The universal, fail-closed protocol & capability handshake (SSoT: [Threat Model —
2//! Protocol and Capability Negotiation]). Every versioned surface runs this one-shot
3//! pre-flight before any state is written; a mismatch is a hard reject, never a degrade.
4//!
5//! [Threat Model — Protocol and Capability Negotiation]: https://docs/design/threat-model/validation/#protocol-and-capability-negotiation
6
7use crate::crypto::primitives::SuiteId;
8
9/// A handshake rejection. Each maps to a fail-closed rule and an HTTP status.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum HandshakeReject {
12    /// `X-Capsule-Protocol` outside the server's `[Min, Max]` window → `426 Upgrade Required`.
13    ProtocolOutOfRange,
14    /// `X-Capsule-Protocol` not a `YYYY-MM-DD` date → `400`.
15    ProtocolMalformed,
16    /// `crypto_suite_id` not in the inventory → `400`.
17    UnknownSuite,
18    /// `sidecar_schema` above the receiver's max known → `400`.
19    SidecarSchemaTooNew,
20}
21
22impl HandshakeReject {
23    /// The HTTP status code a server returns for this rejection.
24    pub fn http_status(self) -> u16 {
25        match self {
26            HandshakeReject::ProtocolOutOfRange => 426,
27            _ => 400,
28        }
29    }
30}
31
32/// True if `v` is a well-formed `YYYY-MM-DD` date (the only grammar `protocol_version`
33/// accepts). Lexicographic comparison of valid values equals chronological order.
34fn is_date(v: &str) -> bool {
35    let b = v.as_bytes();
36    b.len() == 10
37        && b[4] == b'-'
38        && b[7] == b'-'
39        && b[..4].iter().all(u8::is_ascii_digit)
40        && b[5..7].iter().all(u8::is_ascii_digit)
41        && b[8..].iter().all(u8::is_ascii_digit)
42}
43
44/// Gate a request's `protocol_version` against the server-advertised `[min, max]` window.
45/// Reads succeed for any past version (callers skip this on read paths); this is the write
46/// gate.
47pub fn protocol_gate(client: &str, min: &str, max: &str) -> Result<(), HandshakeReject> {
48    if !is_date(client) {
49        return Err(HandshakeReject::ProtocolMalformed);
50    }
51    // For YYYY-MM-DD, bytewise/lexicographic order is chronological order.
52    if client < min || client > max {
53        return Err(HandshakeReject::ProtocolOutOfRange);
54    }
55    Ok(())
56}
57
58/// Reject a `crypto_suite_id` the receiver does not implement (invariant 2).
59pub fn check_suite(suite_id: u16) -> Result<(), HandshakeReject> {
60    SuiteId::from_u16(suite_id)
61        .map(|_| ())
62        .ok_or(HandshakeReject::UnknownSuite)
63}
64
65/// Reject a `sidecar_schema` above the receiver's max known (Postel cross-version closure).
66pub fn check_sidecar_schema(schema: u16, max_known: u16) -> Result<(), HandshakeReject> {
67    if schema > max_known {
68        Err(HandshakeReject::SidecarSchemaTooNew)
69    } else {
70        Ok(())
71    }
72}
73
74#[cfg(test)]
75mod tests;