jmap_chat_server/did_auth.rs
1//! DID-bound verification of a peer identity (draft-atwood-jmap-chat-did-00
2//! §Federation Authentication).
3//!
4//! The draft keeps draft-atwood-jmap-chat-federation-00's request signing
5//! as the only signature mechanism: "This document does not change that
6//! mechanism and defines no other." A request is first verified against
7//! the peer domain's `peerSigningKeys` (for example with
8//! [`jmap_peer_auth::SignedRequest::verify`], whose
9//! [`jmap_peer_auth::Accepted`] carries the key that verified it). Then,
10//! for a DID-form peer identity, §DID-Bound Verification: "It takes the
11//! Ed25519 public key that verified the request signature ... The
12//! verification succeeds only if the `authentication` verification
13//! relationship ({{DID-CORE}}) of the resolved DID Document contains a
14//! verification method whose public key is an Ed25519 public key
15//! ({{RFC8032}}) equal, octet for octet, to that key."
16//! [`verify_did_binding`] is that check. It does not verify a signature
17//! or record a nonce.
18//!
19//! "For a `did:web` peer identity, {{JMAP-CHAT-FED}} binds the identity by
20//! the domain name it encodes and does not require this verification".
21//!
22//! This crate does no I/O. The caller resolves the DID and passes the
23//! resolved DID Document as a [`DidDocument`], or `None` when resolution
24//! failed and no usable cached document is held.
25//!
26//! §Caching: "If the key that verified a request signature is not in the
27//! `authentication` verification relationship of the cached DID Document
28//! ..., the server MUST resolve the DID again, bypassing its cache,
29//! before failing the verification." A [`DidDocument::Cached`] document
30//! whose `authentication` keys do not include the signing key yields
31//! [`DidAuthRejection::RefreshRequired`]: the caller refreshes the
32//! document (for example with `jmap_did_resolver::Resolver::refresh`,
33//! which applies the draft's "once every 60 seconds" limit) and checks
34//! once more with [`DidDocument::Refreshed`].
35
36use std::fmt;
37
38use base64::Engine;
39use base64::engine::general_purpose::URL_SAFE_NO_PAD;
40use jmap_did_types::{Did, DidKey, KeyType};
41use jmap_peer_auth::ed25519_dalek::VerifyingKey;
42use serde_json::Value;
43
44/// A resolved DID Document and whether it may come from a cache.
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub enum DidDocument<'a> {
47 /// A document that may be cached, such as one from
48 /// `jmap_did_resolver::Resolver::resolve`.
49 Cached(&'a Value),
50 /// A document resolved again after a [`DidAuthRejection::RefreshRequired`],
51 /// or one that is never cached, such as a document derived from a
52 /// `did:key`.
53 Refreshed(&'a Value),
54}
55
56/// Why a DID-form peer identity is not bound to the signing key.
57///
58/// draft-atwood-jmap-chat-did-00 §DID-Bound Verification: "If the
59/// verification fails, including because the DID cannot be resolved
60/// ({{resolution}}), the identity binding of {{JMAP-CHAT-FED}} does not
61/// hold and the receiving server rejects the request."
62///
63/// `#[non_exhaustive]`, so new variants stay semver-additive.
64#[derive(Debug, Clone, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum DidAuthRejection {
67 /// No usable DID Document: resolution failed and nothing usable is
68 /// cached. §Resolution failure handling: "the DID-bound verification
69 /// fails ({{did-verification}}) and the request is rejected."
70 Unresolved,
71 /// The document's `id` is not the DID. W3C DID Core §7.1: "The value
72 /// of id in the resolved DID document MUST match the DID that was
73 /// resolved."
74 DocumentIdMismatch,
75 /// No Ed25519 key of the document's `authentication` relationship
76 /// equals the signing key.
77 KeyNotBound,
78 /// The signing key is absent from a [`DidDocument::Cached`]
79 /// document's `authentication` keys. Refresh the document and check
80 /// once more with [`DidDocument::Refreshed`] before rejecting.
81 RefreshRequired,
82}
83
84impl fmt::Display for DidAuthRejection {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 match self {
87 Self::Unresolved => f.write_str("DID could not be resolved"),
88 Self::DocumentIdMismatch => f.write_str("DID document id does not match the DID"),
89 Self::KeyNotBound => {
90 f.write_str("signing key is not in the DID document's authentication keys")
91 }
92 Self::RefreshRequired => {
93 f.write_str("signing key is not in the cached DID document's authentication keys")
94 }
95 }
96 }
97}
98
99impl std::error::Error for DidAuthRejection {}
100
101/// Checks that `signing_key`, the `peerSigningKeys` key that verified the
102/// request signature, is bound to `did` (draft-atwood-jmap-chat-did-00
103/// §DID-Bound Verification steps 2 and 3).
104///
105/// Call it only after the request signature has verified: "After the
106/// request signature has verified ({{JMAP-CHAT-FED}}), the receiving
107/// server verifies a DID-form peer identity as follows". `document` is
108/// the resolved DID Document of `did`, or `None` when resolution failed
109/// and no usable cached document is held. Pass a document that may be
110/// cached as [`DidDocument::Cached`].
111///
112/// The `authentication` entries are embedded verification methods or
113/// references to `verificationMethod` entries, absolute or `#fragment`
114/// relative to the DID (W3C DID Core §5.3.1, §3.2.2). A method is an
115/// Ed25519 key when it has a `publicKeyJwk` with `kty` `OKP`, `crv`
116/// `Ed25519` and no private member `d`, or a `publicKeyMultibase` that
117/// decodes as an `ed25519-pub` multikey. Other methods are ignored.
118///
119/// # Errors
120///
121/// [`DidAuthRejection::Unresolved`] when `document` is `None`,
122/// [`DidAuthRejection::DocumentIdMismatch`] when its `id` is not `did`,
123/// and, when no `authentication` key equals `signing_key`,
124/// [`DidAuthRejection::RefreshRequired`] for a [`DidDocument::Cached`]
125/// document or [`DidAuthRejection::KeyNotBound`] for a
126/// [`DidDocument::Refreshed`] one.
127pub fn verify_did_binding(
128 did: &Did,
129 document: Option<DidDocument<'_>>,
130 signing_key: &VerifyingKey,
131) -> Result<(), DidAuthRejection> {
132 let (document, cached) = match document.ok_or(DidAuthRejection::Unresolved)? {
133 DidDocument::Cached(document) => (document, true),
134 DidDocument::Refreshed(document) => (document, false),
135 };
136 if document.get("id").and_then(Value::as_str) != Some(did.as_str()) {
137 return Err(DidAuthRejection::DocumentIdMismatch);
138 }
139 if authentication_keys(did, document).any(|key| &key == signing_key.as_bytes()) {
140 Ok(())
141 } else if cached {
142 Err(DidAuthRejection::RefreshRequired)
143 } else {
144 Err(DidAuthRejection::KeyNotBound)
145 }
146}
147
148/// The Ed25519 public keys of the document's `authentication` relationship.
149fn authentication_keys<'a>(
150 did: &'a Did,
151 document: &'a Value,
152) -> impl Iterator<Item = [u8; 32]> + 'a {
153 // ponytail: only `#fragment` relative DID URLs are resolved; a
154 // relative path or query reference (RFC 3986 §5) matches nothing.
155 let absolute = move |id: &str| match id.strip_prefix('#') {
156 Some(_) => format!("{did}{id}"),
157 None => id.to_owned(),
158 };
159 let methods: Vec<&Value> = document
160 .get("verificationMethod")
161 .and_then(Value::as_array)
162 .into_iter()
163 .flatten()
164 .collect();
165 document
166 .get("authentication")
167 .and_then(Value::as_array)
168 .into_iter()
169 .flatten()
170 .filter_map(move |entry| match entry {
171 Value::String(reference) => {
172 let reference = absolute(reference);
173 methods.iter().copied().find(|method| {
174 method
175 .get("id")
176 .and_then(Value::as_str)
177 .map(absolute)
178 .as_deref()
179 == Some(reference.as_str())
180 })
181 }
182 Value::Object(_) => Some(entry),
183 _ => None,
184 })
185 .filter_map(ed25519_key)
186}
187
188/// The 32-octet Ed25519 public key of a verification method, if it has one.
189fn ed25519_key(method: &Value) -> Option<[u8; 32]> {
190 if let Some(jwk) = method.get("publicKeyJwk") {
191 let member = |name| jwk.get(name).and_then(Value::as_str);
192 if member("kty")? != "OKP" || member("crv")? != "Ed25519" || jwk.get("d").is_some() {
193 return None;
194 }
195 URL_SAFE_NO_PAD.decode(member("x")?).ok()?.try_into().ok()
196 } else {
197 // A did:key's method-specific id is exactly a multikey
198 // `publicKeyMultibase` value, so the did:key decoder reads it.
199 let multibase = method.get("publicKeyMultibase")?.as_str()?;
200 let key = DidKey::from_did(&format!("did:key:{multibase}").parse().ok()?).ok()?;
201 if key.key_type() != KeyType::Ed25519 {
202 return None;
203 }
204 key.public_key().try_into().ok()
205 }
206}