Skip to main content

hoike_core/
admission.rs

1//! Shared bundle integrity, seal trust, and scope authorization policy.
2//!
3//! Admission is read-only. Freshness, rollback checks, and installation belong
4//! to the caller.
5
6use ahu::{Bundle, BundleType, CompressionAlgorithm, SealVerification};
7use der::{Decode, DecodePem, Encode};
8use tracing::{info, warn};
9
10use crate::config::StorageConfig;
11use crate::error::{CoreError, Result};
12
13#[derive(Debug, PartialEq, Eq)]
14pub enum AdmissionTrust {
15    Authenticated { signer_sha256: String },
16    UnauthenticatedDemo,
17}
18
19/// Verify structure, digests, the CMS seal, and configured scope restrictions.
20///
21/// Decoded manifest fields must match the encoded manifest used for CMS
22/// verification; structural verification binds them before policy checks.
23///
24/// Requires explicit signer pins or CA anchors, even when demo admission is
25/// enabled. Certificate validity is checked at `now` (Unix seconds). Empty scope
26/// authorizations impose no additional restriction on trusted signers.
27pub fn authenticate_bundle(
28    bundle: &Bundle,
29    storage: &StorageConfig,
30    now: u64,
31) -> Result<SealVerification> {
32    verify_structure(bundle)?;
33    let has_trust_anchors = storage
34        .seal_trust_anchors
35        .as_ref()
36        .is_some_and(|v| !v.is_empty());
37    let has_pins = !storage.seal_signer_pins.is_empty();
38    if !has_trust_anchors && !has_pins {
39        return Err(CoreError::Config(
40            if storage.seal_authorizations.is_empty() {
41                "bundle authentication requires seal_signer_pins or seal_trust_anchors".into()
42            } else {
43                "seal_authorizations requires trust anchors or explicit signer pins".into()
44            },
45        ));
46    }
47    if bundle.seal_bytes.is_empty() {
48        return Err(CoreError::Config(
49            "seal trust configured but bundle has no seal".into(),
50        ));
51    }
52
53    let read_certs = |paths: &[std::path::PathBuf]| -> Result<Vec<Vec<u8>>> {
54        let mut anchors = Vec::new();
55        for path in paths {
56            let bytes = std::fs::read(path).map_err(|e| {
57                CoreError::Config(format!(
58                    "cannot read seal trust anchor {}: {e}",
59                    path.display()
60                ))
61            })?;
62            let cert = if bytes.starts_with(b"-----BEGIN") {
63                x509_cert::Certificate::from_pem(&bytes)
64            } else {
65                x509_cert::Certificate::from_der(&bytes)
66            }
67            .map_err(|e| {
68                CoreError::Config(format!("invalid seal trust anchor {}: {e}", path.display()))
69            })?;
70            anchors.push(
71                cert.to_der()
72                    .map_err(|e| CoreError::Config(e.to_string()))?,
73            );
74        }
75        Ok(anchors)
76    };
77    let anchors = read_certs(storage.seal_trust_anchors.as_deref().unwrap_or(&[]))?;
78    let pins = read_certs(&storage.seal_signer_pins)?;
79    let verification = if has_pins {
80        ahu::verify_seal_with_pins(&bundle.manifest_bytes, &bundle.seal_bytes, &pins, now).or_else(
81            |pin_error| {
82                if has_trust_anchors {
83                    ahu::verify_seal_with_anchors(
84                        &bundle.manifest_bytes,
85                        &bundle.seal_bytes,
86                        &anchors,
87                        now,
88                    )
89                } else {
90                    Err(pin_error)
91                }
92            },
93        )
94    } else {
95        ahu::verify_seal_with_anchors(&bundle.manifest_bytes, &bundle.seal_bytes, &anchors, now)
96    }
97    .map_err(|e| CoreError::Config(format!("seal verification failed: {e}")))?;
98    if !storage.seal_authorizations.is_empty() {
99        for scope in &bundle.manifest.ca_scopes {
100            if !storage.seal_authorizations.iter().any(|auth| {
101                auth.producer_id == bundle.manifest.producer_id
102                    && auth
103                        .issuer_key_hash
104                        .eq_ignore_ascii_case(&hex::encode(&scope.issuer_key_hash))
105                    && auth
106                        .signer_sha256
107                        .eq_ignore_ascii_case(&verification.signer_sha256)
108            }) {
109                return Err(CoreError::Config(
110                    "seal signer is not authorized for producer/CA scope".into(),
111                ));
112            }
113        }
114    }
115    info!(signer = %verification.signer_sha256, "CMS seal authenticated against configured trust policy");
116    Ok(verification)
117}
118
119/// Validate that a bundle matches the serving profile this responder
120/// supports: a full, uncompressed bundle (design §S3).
121///
122/// The ahu *format* can represent delta bundles, tombstones, Zstd
123/// compression, and delta-chain metadata; this responder implements none of
124/// the runtime machinery those require (no delta overlays, no decompression,
125/// no chain tracking). Admission therefore rejects them before any durable
126/// state changes. A valid seal does not change this: use
127/// [`authenticate_bundle`] to inspect an authenticated delta, and
128/// materialize deltas into a full, uncompressed bundle (`ahu apply`) before
129/// serving them.
130pub fn validate_serving_profile(bundle: &Bundle) -> Result<()> {
131    let reject = |reason: &str| {
132        Err(CoreError::Config(format!(
133            "unsupported serving profile: {reason}"
134        )))
135    };
136    if bundle.manifest.bundle_type != BundleType::Full {
137        return reject("delta bundle; materialize it into a full bundle before serving");
138    }
139    match &bundle.manifest.compression {
140        None => {}
141        Some(compression) => {
142            if compression.algorithm != CompressionAlgorithm::None {
143                return reject("compressed bundle; serve an uncompressed bundle instead");
144            }
145            if compression.dictionary_digest.is_some() {
146                return reject("compression dictionary; serve an uncompressed bundle instead");
147            }
148        }
149    }
150    if bundle.index.iter().any(|record| record.is_tombstone()) {
151        return reject("tombstone in a full bundle; tombstones only apply to deltas");
152    }
153    if bundle.manifest.continuity.base_manifest_digest.is_some() {
154        return reject("full bundle naming a base manifest");
155    }
156    if bundle.manifest.continuity.chain_length != 0 {
157        return reject("full bundle with nonzero chain_length");
158    }
159    Ok(())
160}
161
162/// Admit a bundle under the configured trust policy, or for explicitly enabled
163/// unauthenticated demo serving. Configured trust always takes precedence.
164///
165/// Admission also enforces the supported serving profile regardless of trust
166/// mode: a correctly sealed delta or compressed bundle is inspectable but not
167/// servable.
168pub fn admit_bundle(bundle: &Bundle, storage: &StorageConfig, now: u64) -> Result<AdmissionTrust> {
169    validate_serving_profile(bundle)?;
170    if storage.allow_unauthenticated_bundles
171        && storage.seal_signer_pins.is_empty()
172        && storage
173            .seal_trust_anchors
174            .as_ref()
175            .is_none_or(|v| v.is_empty())
176        && storage.seal_authorizations.is_empty()
177    {
178        verify_structure(bundle)?;
179        warn!(
180            target: "audit",
181            event = "bundle_admission",
182            trust = "unauthenticated_demo",
183            producer = %bundle.manifest.producer_id,
184            "UNAUTHENTICATED DEMO bundle admitted; CMS seal not verified"
185        );
186        return Ok(AdmissionTrust::UnauthenticatedDemo);
187    }
188
189    let verification = authenticate_bundle(bundle, storage, now)?;
190    Ok(AdmissionTrust::Authenticated {
191        signer_sha256: verification.signer_sha256,
192    })
193}
194
195fn verify_structure(bundle: &Bundle) -> Result<()> {
196    let result = ahu::verify_structure(bundle)?;
197    for warning in &result.warnings {
198        warn!(warning, "bundle verification warning");
199    }
200    Ok(())
201}