Skip to main content

cls_eedi/engine/device/
commissioning.rs

1//! Bind SHIP state readback to a complete trust replacement and its equipment outcome.
2use super::*;
3use crate::wire::Pairing;
4
5/// Equipment evidence for one distinct DER certificate in a trust replacement.
6///
7/// After verifying and installing the certificate, supply its original hex-encoded
8/// DER and the SKI observed by the SHIP implementation. The adapter performs the
9/// X.509 and key checks. The engine binds this result to the submitted DER bytes.
10#[derive(Clone, PartialEq, Eq)]
11pub struct InstalledCertificate {
12    pub certificate: String,
13    pub ski: String,
14}
15
16impl std::fmt::Debug for InstalledCertificate {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        f.write_str("InstalledCertificate { [redacted] }")
19    }
20}
21
22pub(super) fn confirmed_trust(
23    requested: &[TrustEntry],
24    certificates: Vec<InstalledCertificate>,
25) -> Result<Vec<TrustEntry>, EngineError> {
26    let mut by_der: BTreeMap<_, Option<String>> = requested
27        .iter()
28        .filter_map(|entry| {
29            entry
30                .certificate
31                .as_deref()
32                .map(|der| (der.to_ascii_lowercase(), None))
33        })
34        .collect();
35    if certificates.len() != by_der.len() {
36        return Err(EngineError::TrustReadback);
37    }
38    for cert in certificates {
39        if cert.certificate.len() > crate::wire::MAX_MESSAGE_BYTES
40            || cert.ski.len() != 40
41            || !cert.ski.bytes().all(|b| b.is_ascii_hexdigit())
42        {
43            return Err(EngineError::TrustReadback);
44        }
45        let slot = by_der
46            .get_mut(&cert.certificate.to_ascii_lowercase())
47            .ok_or(EngineError::TrustReadback)?;
48        if slot.replace(cert.ski).is_some() {
49            return Err(EngineError::TrustReadback);
50        }
51    }
52    requested
53        .iter()
54        .map(|entry| {
55            if let Some(der) = &entry.certificate {
56                let ski = by_der
57                    .get(&der.to_ascii_lowercase())
58                    .and_then(Option::as_ref)
59                    .ok_or(EngineError::TrustReadback)?;
60                Ok(TrustEntry {
61                    ski: Some(ski.clone()),
62                    ..Default::default()
63                })
64            } else {
65                Ok(entry.clone())
66            }
67        })
68        .collect()
69}
70
71impl LocalDevice {
72    /// Import a previously commissioned equipment inventory once on a fresh local
73    /// route. Later changes use a confirmed replacement or [Self::pairing_established].
74    pub fn initialize_trust(&mut self, trust: Vec<TrustEntry>) -> Result<(), EngineError> {
75        if self.journal.provisioning.subsequent || self.journal.trust_revision != 0 {
76            return Err(EngineError::Unexpected);
77        }
78        if self.pending().any(|(_, c)| c.trust.is_some()) {
79            return Err(EngineError::ReconciliationRequired);
80        }
81        self.update_observations(|state| state.trust = Some(trust))?;
82        self.journal.trust_revision = 1;
83        Ok(())
84    }
85
86    /// Revision of the active local trust replacement. Capture this value when starting
87    /// asynchronous SHIP pairing. Each newly accepted replacement advances the revision,
88    /// including a successful clear. A replayed control returns its saved outcome and
89    /// leaves the revision unchanged. Device checkpoints preserve it on restart.
90    pub fn trust_revision(&self) -> Option<u64> {
91        (self.journal.trust_revision != 0).then_some(self.journal.trust_revision)
92    }
93
94    /// Record the authenticated SHIP peer's SKI in its original pairing entry.
95    /// Returns true for a new observation and false for an identical duplicate.
96    /// The revision, case-sensitive SHIP ID and certificate fingerprint must match.
97    /// A pending replacement requires reconciliation before reporting a result.
98    /// On success, checkpoint the updated inventory before publishing its readback. The
99    /// original pairing ID, fingerprint and secret remain in the authorized state response.
100    /// [KEO 1.2.0 state trust semantics](https://github.com/KEO-cls-eedi/specification/blob/1.2.0/doc/clseedi.md#trust-statetrust)
101    pub fn pairing_established(
102        &mut self,
103        revision: u64,
104        for_id: &str,
105        for_par: &str,
106        ski: &str,
107    ) -> Result<bool, EngineError> {
108        if self.trust_revision() != Some(revision) || self.journal.provisioning.subsequent {
109            return Err(EngineError::PairingMismatch);
110        }
111        if self.pending().any(|(_, c)| c.trust.is_some()) {
112            return Err(EngineError::ReconciliationRequired);
113        }
114        let mut peers = self
115            .journal
116            .state
117            .trust
118            .iter()
119            .flatten()
120            .enumerate()
121            .filter_map(|(i, entry)| {
122                let pairing = entry.ship_pairing_service.as_ref()?;
123                (pairing.for_id == for_id && pairing.for_par.eq_ignore_ascii_case(for_par))
124                    .then_some((i, pairing))
125            });
126        let (index, peer) = peers.next().ok_or(EngineError::PairingMismatch)?;
127        if peers.next().is_some() || ski.len() != 40 || !ski.bytes().all(|b| b.is_ascii_hexdigit())
128        {
129            return Err(EngineError::PairingMismatch);
130        }
131        if let Some(known) = &peer.ski {
132            return if known.eq_ignore_ascii_case(ski) {
133                Ok(false)
134            } else {
135                Err(EngineError::PairingMismatch)
136            };
137        }
138        let updated = Pairing {
139            ski: Some(ski.to_owned()),
140            ..peer.clone()
141        };
142        self.update_observations(move |state| {
143            // This index was selected in the same inventory before the candidate clone.
144            state.trust.as_mut().expect("existing inventory")[index].ship_pairing_service =
145                Some(updated);
146        })?;
147        Ok(true)
148    }
149}