capsule_core/validation/structural.rs
1//! The key-less structural envelope checks a server runs before persisting any write
2//! (SSoT: [Threat Model — Server-Side Validation Invariants]). The server holds no keys,
3//! so it cannot verify signatures — but it validates *structure* refuse-by-default. These
4//! are pure predicates over the manifest core and server-known state; the client mirrors
5//! them via [`verify_asset`](crate::crypto::verify_asset::verify_asset).
6//!
7//! [Threat Model — Server-Side Validation Invariants]: https://docs/design/threat-model/validation/#server-side-validation-invariants
8
9use crate::crypto::encryption::blob_ciphertext_hash;
10use crate::crypto::hash::Hash32;
11use crate::crypto::primitives::SuiteId;
12use crate::crypto::provenance::ManifestCore;
13
14/// Invariant 3: the declared content hash length matches the digest size for the suite.
15/// (Type-level true for [`Hash32`], but checked explicitly for wire-decoded lengths.)
16pub fn hash_length_ok(suite_id: u16, hash_len: usize) -> bool {
17 SuiteId::from_u16(suite_id).is_some_and(|s| s.hash_len() == hash_len)
18}
19
20/// Invariant 4: declared size is in `(0, max_file_size]`.
21pub fn size_in_bounds(size: u64, max_file_size: u64) -> bool {
22 size > 0 && size <= max_file_size
23}
24
25/// Invariant 5: `content_type` is in the closed allow-list for this protocol version.
26pub fn content_type_allowed(content_type: &str, allowed: &[&str]) -> bool {
27 allowed.contains(&content_type)
28}
29
30/// Part of invariant 6: the album's pinned `protocol_version` equals the request's.
31pub fn album_pin_matches(request_protocol: &str, album_pin: &str) -> bool {
32 request_protocol == album_pin
33}
34
35/// Invariant 7 (time half): the device's directory `added_at` precedes the manifest
36/// `timestamp`. `None` on an unparseable timestamp (the caller rejects with `400`).
37pub fn device_added_before(added_at: &str, timestamp: &str) -> Option<bool> {
38 let a = added_at.parse::<jiff::Timestamp>().ok()?;
39 let t = timestamp.parse::<jiff::Timestamp>().ok()?;
40 Some(a <= t)
41}
42
43/// Invariant 8: the self-asserted `timestamp` is within `±drift_days` of the server clock.
44/// A non-security gross-drift guard. `None` on an unparseable timestamp.
45pub fn timestamp_within_drift(
46 timestamp: &str,
47 server_clock: &str,
48 drift_days: i64,
49) -> Option<bool> {
50 let t = timestamp.parse::<jiff::Timestamp>().ok()?;
51 let now = server_clock.parse::<jiff::Timestamp>().ok()?;
52 // Absolute-time days: 24 h, matching the drift guard's UTC semantics.
53 let delta = (t.as_second() - now.as_second()).abs() / 86_400;
54 Some(delta <= drift_days)
55}
56
57/// Invariant 17: `prior_provenance_hash` equals the last accepted manifest's hash for this
58/// asset. `stored_head` is `None` for a never-seen asset (only a `create` is valid then).
59pub fn prior_hash_matches(
60 prior: Option<Hash32>,
61 stored_head: Option<Hash32>,
62 is_create: bool,
63) -> bool {
64 if is_create {
65 prior.is_none() && stored_head.is_none()
66 } else {
67 prior.is_some() && prior == stored_head
68 }
69}
70
71/// Invariant 18: `amk_version` never regresses for an album (server's structural backstop;
72/// MLS is the authority on the ceiling — see [`verify_asset`](crate::crypto::verify_asset::verify_asset)).
73pub fn amk_version_monotonic(new: u32, stored: Option<u32>) -> bool {
74 match stored {
75 None => true,
76 Some(prev) => new >= prev,
77 }
78}
79
80/// Invariant 25 (key-free): the metadata blob in the bundle has a content hash equal to the
81/// manifest's committed `metadata_blob_hash`. The server holds no key, but it hashes the
82/// ciphertext object it stores and compares it against the signed manifest field, so a client
83/// cannot present a metadata blob different from the one its manifest is signed over. `false`
84/// when the manifest commits to no hash — a bundle carrying a blob must be committed to.
85///
86/// This is the value half of the client-side round-trip check
87/// ([`verify_metadata_binding`](crate::crypto::verify_asset::verify_metadata_binding)); the server never
88/// decrypts, so it checks only the content address.
89pub fn metadata_blob_hash_matches(committed: Option<Hash32>, metadata_blob: &[u8]) -> bool {
90 committed.is_some_and(|h| blob_ciphertext_hash(metadata_blob) == h)
91}
92
93/// A keyless envelope decision over a manifest core plus the server-known context.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum EnvelopeReject {
96 /// `crypto_suite_id` unknown (invariant 2).
97 UnknownSuite,
98 /// Album pin mismatch (invariant 6).
99 AlbumPinMismatch,
100 /// Device `added_at` postdates the manifest timestamp (invariant 7).
101 DeviceAddedAfter,
102 /// Timestamp unparseable or beyond the drift bound (invariant 8).
103 TimestampUnsane,
104 /// `prior_provenance_hash` does not match the stored chain head (invariant 17).
105 StaleChain,
106 /// `amk_version` regressed (invariant 18).
107 AmkRegressed,
108 /// The bundled metadata blob's content hash does not match the manifest's committed
109 /// `metadata_blob_hash` (invariant 25).
110 MetadataBlobHashMismatch,
111}
112
113/// Context a key-less server holds when validating a non-upload lifecycle manifest.
114pub struct EnvelopeContext<'a> {
115 /// The album's immutable protocol pin.
116 pub album_pin: &'a str,
117 /// The device's `added_at` from the published directory.
118 pub device_added_at: &'a str,
119 /// The server's trusted clock (RFC3339).
120 pub server_clock: &'a str,
121 /// Allowed timestamp drift in days.
122 pub drift_days: i64,
123 /// The last accepted provenance head for this asset.
124 pub stored_chain_head: Option<Hash32>,
125 /// The last accepted `amk_version` for this album.
126 pub stored_amk_version: Option<u32>,
127}
128
129/// Run the keyless envelope checks (2, 6, 7, 8, 17, 18) over a lifecycle manifest core.
130/// Returns the first invariant violated, or `Ok(())`.
131pub fn check_manifest_envelope(
132 core: &ManifestCore,
133 ctx: &EnvelopeContext<'_>,
134) -> Result<(), EnvelopeReject> {
135 if SuiteId::from_u16(core.crypto_suite_id).is_none() {
136 return Err(EnvelopeReject::UnknownSuite);
137 }
138 if !album_pin_matches(&core.protocol_version, ctx.album_pin) {
139 return Err(EnvelopeReject::AlbumPinMismatch);
140 }
141 match device_added_before(ctx.device_added_at, &core.timestamp) {
142 None => return Err(EnvelopeReject::TimestampUnsane),
143 Some(false) => return Err(EnvelopeReject::DeviceAddedAfter),
144 Some(true) => {}
145 }
146 match timestamp_within_drift(&core.timestamp, ctx.server_clock, ctx.drift_days) {
147 None | Some(false) => return Err(EnvelopeReject::TimestampUnsane),
148 Some(true) => {}
149 }
150 if !prior_hash_matches(
151 core.prior_provenance_hash,
152 ctx.stored_chain_head,
153 core.action.is_create(),
154 ) {
155 return Err(EnvelopeReject::StaleChain);
156 }
157 if !amk_version_monotonic(core.amk_version.0, ctx.stored_amk_version) {
158 return Err(EnvelopeReject::AmkRegressed);
159 }
160 Ok(())
161}
162
163/// Invariant 25 as a refuse-by-default decision: run on any write whose bundle carries a
164/// metadata blob (a `create` bundle, at finalization, or a non-upload `metadata-update`). The
165/// blob's content hash must equal the manifest's committed `metadata_blob_hash`. Key-free — the
166/// server never decrypts (SSoT: [Threat Model — invariant 25], [Metadata — Local and Server
167/// Metadata Equivalence]).
168///
169/// [Threat Model — invariant 25]: https://docs/design/threat-model/validation/#server-side-validation-invariants
170/// [Metadata — Local and Server Metadata Equivalence]: https://docs/design/metadata/#local-and-server-metadata-equivalence
171pub fn check_metadata_blob_envelope(
172 core: &ManifestCore,
173 metadata_blob: &[u8],
174) -> Result<(), EnvelopeReject> {
175 if metadata_blob_hash_matches(core.metadata_blob_hash, metadata_blob) {
176 Ok(())
177 } else {
178 Err(EnvelopeReject::MetadataBlobHashMismatch)
179 }
180}
181
182#[cfg(test)]
183mod tests;