Skip to main content

sew_e2ee/identity/
credential.rs

1//! The call credential: the MLS leaf's Basic credential is `TLS(SewCallIdentity)` version 2.
2//!
3//! ```text
4//! device_sig = ECDSA-P256-SHA256(device key,
5//!     "sew call leaf v2" ‖ TLS({ install_id<V>, member_id, device_id, scope<V>, leaf_signature_key<V> }))
6//! ```
7//!
8//! Every member validates every leaf (Welcome trees, Add proposals, commit update paths): the
9//! credential is Basic and decodes, version 2 and kind 1; its scope is non-empty and equals the
10//! call's; the certificate verifies; the serial is not revoked; `device_sig` verifies over the
11//! leaf's actual signature key. These repeat the server's checks on the client.
12
13use std::collections::BTreeSet;
14
15use openmls::prelude::{Credential, CredentialType};
16use sew_proto::e2ee::CallScope;
17use sew_proto::e2ee::tls::{
18    DeviceSigInput, IDENTITY_KIND_MEMBER, IDENTITY_VERSION, SewCallIdentity, TlsCodec,
19};
20
21use super::cert::{CertContext, check_device_cert, verify_device_sig};
22use crate::config::caps;
23use crate::ids::{Id, UnixMs, install_id_bytes};
24
25/// What a valid leaf credential says (member and device come from its certificate).
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct LeafIdentity {
28    /// The member.
29    pub member_id: Id,
30    /// The device.
31    pub device_id: Id,
32    /// The certificate serial.
33    pub serial: u64,
34    /// The platform code (1–5).
35    pub platform: u8,
36    /// The device label.
37    pub label: String,
38    /// The certificate's `not_after` (unix seconds).
39    pub cert_not_after_s: u64,
40}
41
42/// Why a leaf was refused. Carries no credential bytes.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
44#[non_exhaustive]
45pub enum LeafCheckError {
46    /// Not Basic, not `SewCallIdentity` v2, or `kind ≠ 1`.
47    #[error("credential: {0}")]
48    Credential(&'static str),
49    /// Empty, malformed or another call's scope (`report` kind `scope_invalid`).
50    #[error("scope: {0}")]
51    Scope(&'static str),
52    /// The certificate failed.
53    #[error("device certificate: {0}")]
54    Cert(&'static str),
55    /// The serial is revoked.
56    #[error("revoked")]
57    Revoked,
58    /// `device_sig` does not verify over the leaf key.
59    #[error("device signature")]
60    DeviceSig,
61}
62
63impl LeafCheckError {
64    /// Whether the scope was the problem (the client also reports `scope_invalid`).
65    pub fn is_scope(&self) -> bool {
66        matches!(self, LeafCheckError::Scope(_))
67    }
68}
69
70/// The trust inputs of a leaf check.
71#[derive(Debug, Clone, Copy)]
72pub struct LeafContext<'a> {
73    /// This install.
74    pub install_id: u64,
75    /// The pinned CA key.
76    pub ca_public: &'a [u8; 32],
77    /// Revoked serials.
78    pub crl: &'a BTreeSet<u64>,
79    /// The call's scope (`CallKeysInit.scope`).
80    pub scope: CallScope,
81    /// Now (unix ms).
82    pub now: UnixMs,
83    /// Certificate skew (seconds).
84    pub skew_s: u64,
85}
86
87/// Checks one leaf (credential plus its signature key).
88pub fn check_leaf(
89    credential: &Credential,
90    leaf_signature_key: &[u8],
91    ctx: &LeafContext<'_>,
92) -> Result<LeafIdentity, LeafCheckError> {
93    if credential.credential_type() != CredentialType::Basic {
94        return Err(LeafCheckError::Credential("not_basic"));
95    }
96    let raw = credential.serialized_content();
97    if raw.len() > caps::CALL_IDENTITY {
98        return Err(LeafCheckError::Credential("size"));
99    }
100    let identity =
101        SewCallIdentity::from_bytes(raw).map_err(|_| LeafCheckError::Credential("decode"))?;
102    check_identity(&identity, leaf_signature_key, ctx)
103}
104
105/// [`check_leaf`] on decoded identity bytes.
106pub fn check_identity(
107    identity: &SewCallIdentity,
108    leaf_signature_key: &[u8],
109    ctx: &LeafContext<'_>,
110) -> Result<LeafIdentity, LeafCheckError> {
111    if identity.version != IDENTITY_VERSION {
112        return Err(LeafCheckError::Credential("version"));
113    }
114    if identity.kind != IDENTITY_KIND_MEMBER {
115        return Err(LeafCheckError::Credential("kind"));
116    }
117    if identity.scope.is_empty() {
118        return Err(LeafCheckError::Scope("empty"));
119    }
120    let scope = CallScope::parse(&identity.scope).ok_or(LeafCheckError::Scope("malformed"))?;
121    if scope != ctx.scope {
122        return Err(LeafCheckError::Scope("mismatch"));
123    }
124    if identity.device_cert.len() > caps::DEVICE_CERT {
125        return Err(LeafCheckError::Cert("size"));
126    }
127    let cert = sew_proto::e2ee::tls::SewDeviceCert::from_bytes(&identity.device_cert)
128        .map_err(|_| LeafCheckError::Cert("decode"))?;
129    let cctx = CertContext {
130        install_id: ctx.install_id,
131        ca_public: ctx.ca_public,
132        skew_s: ctx.skew_s,
133        now: ctx.now,
134    };
135    let verified = check_device_cert(cert, &cctx).map_err(|e| match e {
136        crate::error::IdentityError::BadCert(r) => LeafCheckError::Cert(r),
137        _ => LeafCheckError::Cert("cert"),
138    })?;
139    if ctx.crl.contains(&verified.serial()) {
140        return Err(LeafCheckError::Revoked);
141    }
142    let tbs = &verified.cert.tbs;
143    let input = DeviceSigInput {
144        install_id: tbs.install_id.clone(),
145        member_id: tbs.member_id,
146        device_id: tbs.device_id,
147        scope: identity.scope.clone(),
148        leaf_signature_key: leaf_signature_key.to_vec(),
149    };
150    if !verify_device_sig(&tbs.device_pubkey, &input, &identity.device_sig) {
151        return Err(LeafCheckError::DeviceSig);
152    }
153    Ok(LeafIdentity {
154        member_id: verified.member_id,
155        device_id: verified.device_id,
156        serial: tbs.serial,
157        platform: tbs.platform,
158        label: String::from_utf8_lossy(&tbs.label).into_owned(),
159        cert_not_after_s: tbs.not_after,
160    })
161}
162
163/// The bytes the device key signs for a leaf (`"sew call leaf v2" ‖ TLS(DeviceSigInput)`).
164pub fn device_sig_message(
165    install_id: u64,
166    member_id: Id,
167    device_id: Id,
168    scope: CallScope,
169    leaf_signature_key: &[u8],
170) -> Vec<u8> {
171    DeviceSigInput {
172        install_id: install_id_bytes(install_id),
173        member_id: member_id.get(),
174        device_id: device_id.get(),
175        scope: scope.to_bytes(),
176        leaf_signature_key: leaf_signature_key.to_vec(),
177    }
178    .signed_bytes()
179    .unwrap_or_default()
180}
181
182/// `TLS(SewCallIdentity)` v2, kind 1, for a scope, a certificate and a device signature.
183pub fn identity_bytes(scope: CallScope, device_cert: &[u8], device_sig: &[u8; 64]) -> Vec<u8> {
184    SewCallIdentity {
185        version: IDENTITY_VERSION,
186        kind: IDENTITY_KIND_MEMBER,
187        scope: scope.to_bytes(),
188        device_cert: device_cert.to_vec(),
189        device_sig: device_sig.to_vec(),
190    }
191    .to_bytes()
192    .unwrap_or_default()
193}