bhmdoc 0.6.3

TBTL's library for handling mDL/mdoc specification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// Copyright (C) 2020-2026  The Blockhouse Technology Limited (TBTL).
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
// License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! This module defines the data model described in the section "9.1.3 mdoc authentication" of the
//! [ISO/IEC 18013-5:2021][1] standard, but modified for [OpenID for Verifiable Presentations][2].
//!
//! [1]: <https://www.iso.org/standard/69084.html>
//! [2]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html>

use bh_jws_utils::{jwk_sha256_thumbprint_bytes, JwkPublic, SignatureVerifier, SigningAlgorithm};
use bherror::traits::{
    ErrorContext as _, ForeignBoxed as _, ForeignError as _, PropagateError as _,
};
use ciborium::{into_writer, Value};
use coset::{CoseMac0, CoseSign1, CoseSign1Builder, RegisteredLabelWithPrivate};
use serde::{ser::SerializeSeq as _, Deserialize, Serialize};

use super::response::DeviceNameSpacesBytes;
use crate::{
    models::{data_retrieval::common::DocType, Bytes, BytesCbor},
    utils::{
        coset::{coset_alg_to_jws_alg, deserialize_coset, jws_alg_to_coset_alg, serialize_coset},
        digest::sha256,
    },
    DeviceKey, MdocError, Result,
};

/// A string contained in the payload for the device signature, as specified in
/// the `Section 9.1.3.4` of the [ISO/IEC 18013-5:2021][1].
///
/// [1]: <https://www.iso.org/standard/69084.html>
const DEVICE_AUTHENTICATION_IDENTIFIER: &str = "DeviceAuthentication";

/// A string contained in the payload for the device signature, as specified in
/// the `Section B.2.6.1.` of the [OpenID4VP][1].
///
/// [1]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#appendix-B.2.6.1>
const DEVICE_HANDOVER_IDENTIFIER: &str = "OpenID4VPHandover";

/// The signature or MAC generated by the `mDoc` device.
///
/// The underlying structure is either the `COSE_Sign1` or the `COSE_Mac0`,
/// depending on whether the signature or MAC is used, respectively.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DeviceAuth {
    /// `COSE_Sign1` variant.
    DeviceSignature(DeviceSignature),
    /// `COSE_Mac0` variant.
    DeviceMac(DeviceMac),
}

impl DeviceAuth {
    /// Creates a new [`DeviceAuth`] with the [`DeviceSignature`].
    pub(crate) fn new_signature(
        device_authentication: DeviceAuthentication,
        signer: &impl bh_jws_utils::Signer,
    ) -> Result<Self> {
        Ok(Self::DeviceSignature(DeviceSignature::new(
            device_authentication,
            signer,
        )?))
    }

    /// Verifies the underlying signature or MAC.
    ///
    /// The payload itself is detached, i.e. it is not contained in the
    /// underlying structure, and needs to be provided as an argument.
    ///
    /// **Note**: currently, only the signature is supported. Verifying the MAC
    /// results in the [DeviceMac][MdocError::DeviceMac] error.
    pub(crate) fn verify_signature<'a>(
        &self,
        device_authentication: DeviceAuthentication,
        get_signature_verifier: impl Fn(SigningAlgorithm) -> Option<&'a dyn SignatureVerifier>,
        device_key: &DeviceKey,
    ) -> Result<()> {
        match self {
            Self::DeviceSignature(device_signature) => device_signature.verify_signature(
                device_authentication,
                get_signature_verifier,
                device_key,
            ),
            Self::DeviceMac(_device_mac) => Err(bherror::Error::root(MdocError::DeviceMac)),
        }
    }

    #[cfg(test)]
    pub(crate) fn device_signature_inner_mut(&mut self) -> &mut CoseSign1 {
        match self {
            DeviceAuth::DeviceSignature(signature) => &mut signature.0,
            _ => unimplemented!(),
        }
    }
}

/// [`DeviceSignature`] as defined in the section `9.1.3.4` of the [ISO/IEC 18013-5:2021][1]
/// standard.
///
/// [1]: <https://www.iso.org/standard/69084.html>
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeviceSignature(
    #[serde(
        serialize_with = "serialize_coset",
        deserialize_with = "deserialize_coset"
    )]
    pub(crate) CoseSign1,
);

impl From<CoseSign1> for DeviceSignature {
    fn from(value: coset::CoseSign1) -> Self {
        Self(value)
    }
}

impl DeviceSignature {
    fn new(
        device_authentication: DeviceAuthentication,
        signer: &impl bh_jws_utils::Signer,
    ) -> Result<Self> {
        let protected = coset::Header {
            alg: Some(RegisteredLabelWithPrivate::Assigned(jws_alg_to_coset_alg(
                &signer.algorithm(),
            ))),
            ..Default::default()
        };

        let payload = device_signature_and_mac_payload(device_authentication)?;

        let cose_sign1 = CoseSign1Builder::new()
            .protected(protected)
            .try_create_detached_signature(&payload, &[], |data| signer.sign(data))
            .foreign_boxed_err(|| MdocError::Signing)?
            .build();

        Ok(Self(cose_sign1))
    }

    fn verify_signature<'a>(
        &self,
        device_authentication: DeviceAuthentication,
        get_signature_verifier: impl Fn(SigningAlgorithm) -> Option<&'a dyn SignatureVerifier>,
        device_key: &DeviceKey,
    ) -> Result<()> {
        let alg = self
            .signing_algorithm()
            .ok_or_else(|| bherror::Error::root(MdocError::MissingSigningAlgorithm))
            .ctx(|| "device authentication")?;

        let jwk = device_key.as_jwk()?;

        let signature_verifier = get_signature_verifier(alg)
            .ok_or_else(|| bherror::Error::root(MdocError::MissingSignatureVerifier(alg)))?;

        let payload = device_signature_and_mac_payload(device_authentication)?;

        self.0
            .verify_detached_signature(&payload, &[], |sig, data| {
                let verified = signature_verifier
                    .verify(data, sig, &jwk)
                    .foreign_boxed_err(|| MdocError::InvalidSignature)
                    .ctx(|| "error while verifying signature")?;

                if !verified {
                    return Err(bherror::Error::root(MdocError::InvalidSignature)
                        .ctx("the signature is not valid"));
                };

                Ok(())
            })
    }

    /// Return the `alg` element from the protected header of the underlying
    /// `COSE_Sign1` structure.
    pub fn signing_algorithm(&self) -> Option<SigningAlgorithm> {
        let alg = self.0.protected.header.alg.as_ref()?;

        let RegisteredLabelWithPrivate::Assigned(alg) = alg else {
            return None;
        };

        coset_alg_to_jws_alg(alg)
    }
}

/// [`DeviceMac`] as defined in the section `9.1.3.4` of the [ISO/IEC 18013-5:2021][1] standard.
///
/// [1]: <https://www.iso.org/standard/69084.html>
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeviceMac(
    #[serde(
        serialize_with = "serialize_coset",
        deserialize_with = "deserialize_coset"
    )]
    pub(crate) CoseMac0,
);

#[derive(Debug, Serialize)]
struct DeviceAuthenticationBytes<'a>(BytesCbor<DeviceAuthentication<'a>>);

impl<'a> From<DeviceAuthentication<'a>> for DeviceAuthenticationBytes<'a> {
    fn from(value: DeviceAuthentication<'a>) -> Self {
        Self(value.into())
    }
}

/// The payload for the device signature.
///
/// It borrows all the underlying fields to generate a serialized payload, and
/// those fields are `client_id`, `response_uri`, `nonce`, `jwk_public`,
/// `doc_type` and `name_spaces`.
///
/// The payload is constructed as specified in the `Section 9.1.3.4` of the
/// [ISO/IEC 18013-5:2021][1] and the `Section B.2.6.1.` of the [OpenID4VP][2].
///
/// [1]: <https://www.iso.org/standard/69084.html>
/// [2]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#appendix-B.2.6.1>
#[derive(Debug)]
pub struct DeviceAuthentication<'a> {
    session_transcript: SessionTranscript<'a>,
    doc_type: &'a DocType,
    name_spaces: &'a DeviceNameSpacesBytes,
}

impl<'a> DeviceAuthentication<'a> {
    /// Create a new [`DeviceAuthentication`] payload for the device signature.
    pub fn new(
        client_id: &'a str,
        response_uri: &'a str,
        nonce: &'a str,
        jwk_public: Option<&JwkPublic>,
        doc_type: &'a DocType,
        name_spaces: &'a DeviceNameSpacesBytes,
    ) -> Result<Self> {
        let jwk_thumbprint = jwk_public.map(JwkThumbprint::new).transpose()?;

        Ok(Self {
            session_transcript: SessionTranscript {
                handover: OID4VPHandover(OpenID4VPHandoverInfoHash(OpenID4VPHandoverInfo {
                    client_id,
                    nonce,
                    jwk_thumbprint,
                    response_uri,
                })),
            },
            doc_type,
            name_spaces,
        })
    }
}

impl Serialize for DeviceAuthentication<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(4))?;

        seq.serialize_element(DEVICE_AUTHENTICATION_IDENTIFIER)?;
        seq.serialize_element(&self.session_transcript)?;
        seq.serialize_element(self.doc_type)?;
        seq.serialize_element(self.name_spaces)?;

        seq.end()
    }
}

#[derive(Debug)]
struct SessionTranscript<'a> {
    handover: OID4VPHandover<'a>,
}

impl Serialize for SessionTranscript<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(3))?;

        seq.serialize_element(&Value::Null)?;
        seq.serialize_element(&Value::Null)?;
        seq.serialize_element(&self.handover)?;

        seq.end()
    }
}

#[derive(Debug)]
struct OID4VPHandover<'a>(OpenID4VPHandoverInfoHash<'a>);

impl Serialize for OID4VPHandover<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(2))?;

        seq.serialize_element(DEVICE_HANDOVER_IDENTIFIER)?;
        seq.serialize_element(&self.0)?;

        seq.end()
    }
}

#[derive(Debug)]
struct OpenID4VPHandoverInfoHash<'a>(OpenID4VPHandoverInfo<'a>);

impl Serialize for OpenID4VPHandoverInfoHash<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut payload = Vec::new();
        into_writer(&self.0, &mut payload).map_err(serde::ser::Error::custom)?;

        let bytes: Bytes = sha256(payload).to_vec().into();

        bytes.serialize(serializer)
    }
}

#[derive(Debug)]
struct OpenID4VPHandoverInfo<'a> {
    client_id: &'a str,
    nonce: &'a str,
    jwk_thumbprint: Option<JwkThumbprint>,
    response_uri: &'a str,
}

impl Serialize for OpenID4VPHandoverInfo<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(4))?;

        seq.serialize_element(self.client_id)?;
        seq.serialize_element(self.nonce)?;

        if let Some(jwk_thumbprint) = &self.jwk_thumbprint {
            seq.serialize_element(jwk_thumbprint)?;
        } else {
            seq.serialize_element(&Value::Null)?;
        }

        seq.serialize_element(self.response_uri)?;

        seq.end()
    }
}

#[derive(Debug, Serialize)]
struct JwkThumbprint(Bytes);

impl JwkThumbprint {
    fn new(jwk: &JwkPublic) -> Result<Self> {
        let jwk_thumbprint = jwk_sha256_thumbprint_bytes(jwk.to_owned())
            .with_err(|| MdocError::InvalidJwkPublic)?
            .into();

        Ok(Self(jwk_thumbprint))
    }
}

/// Constructs the payload for the [`DeviceSignature`] or the [`DeviceMac`].
fn device_signature_and_mac_payload(
    device_authentication: DeviceAuthentication,
) -> Result<Vec<u8>> {
    let mut payload = Vec::new();
    into_writer(
        &DeviceAuthenticationBytes::from(device_authentication),
        &mut payload,
    )
    .foreign_err(|| MdocError::DeviceAuthentication)?;

    Ok(payload)
}

#[cfg(test)]
mod tests {
    use std::sync::LazyLock;

    use assert_matches::assert_matches;

    use super::*;

    const CLIENT_ID: &str = "x509_san_dns:example.com";
    const NONCE: &str = "exc7gBkxjx1rdc9udRrveKvSsJIq80avlXeLHhGwqtA";
    static JWK_PUBLIC: LazyLock<serde_json::Value> = LazyLock::new(|| {
        serde_json::json!({
            "kty": "EC",
            "crv": "P-256",
            "x": "DxiH5Q4Yx3UrukE2lWCErq8N8bqC9CHLLrAwLz5BmE0",
            "y": "XtLM4-3h5o3HUH0MHVJV0kyq0iBlrBwlh8qEDMZ4-Pc",
            "use": "enc",
            "alg": "ECDH-ES",
            "kid": "1",
        })
    });
    const RESPONSE_URI: &str = "https://example.com/response";

    /// Example taken from the section `B.2.6.1.` of the [OpenID4VP][1].
    ///
    /// [1]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#appendix-B.2.6.1>
    fn example_session_transcript() -> SessionTranscript<'static> {
        SessionTranscript {
            handover: OID4VPHandover(OpenID4VPHandoverInfoHash(OpenID4VPHandoverInfo {
                client_id: CLIENT_ID,
                nonce: NONCE,
                jwk_thumbprint: Some(JwkThumbprint::new(JWK_PUBLIC.as_object().unwrap()).unwrap()),
                response_uri: RESPONSE_URI,
            })),
        }
    }

    /// Example taken from the section `B.2.6.1.` of the [OpenID4VP][1].
    ///
    /// [1]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#appendix-B.2.6.1>
    #[test]
    fn test_oid4vp_handover_info_serialization() {
        let session_transcript = example_session_transcript();
        let handover_info = session_transcript.handover.0 .0;

        let expected_hex = "847818783530395f73616e5f646e733a6578616d706c652e636f6d782b6578633767\
426b786a7831726463397564527276654b7653734a4971383061766c58654c486847\
7771744158204283ec927ae0f208daaa2d026a814f2b22dca52cf85ffa8f3f8626c6\
bd669047781c68747470733a2f2f6578616d706c652e636f6d2f726573706f6e7365";

        let mut encoded = Vec::new();
        into_writer(&handover_info, &mut encoded).unwrap();

        let encoded_hex = hex::encode(encoded);

        assert_eq!(expected_hex, encoded_hex);
    }

    /// Example taken from the section `B.2.6.1.` of the [OpenID4VP][1].
    ///
    /// [1]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#appendix-B.2.6.1>
    #[test]
    fn test_oid4vp_handover_serialization() {
        let session_transcript = example_session_transcript();
        let handover = session_transcript.handover;

        let expected_hex = "82714f70656e494434565048616e646f7665725820048bc053c00442af9b8eed494c\
efdd9d95240d254b046b11b68013722aad38ac";

        let mut encoded = Vec::new();
        into_writer(&handover, &mut encoded).unwrap();

        let encoded_hex = hex::encode(encoded);

        assert_eq!(expected_hex, encoded_hex);
    }

    /// Example taken from the section `B.2.6.1.` of the [OpenID4VP][1].
    ///
    /// [1]: <https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#appendix-B.2.6.1>
    #[test]
    fn test_session_transcript_serialization() {
        let session_transcript = example_session_transcript();

        let expected_hex = "83f6f682714f70656e494434565048616e646f7665725820048bc053c00442af9b8e\
ed494cefdd9d95240d254b046b11b68013722aad38ac";

        let mut encoded = Vec::new();
        into_writer(&session_transcript, &mut encoded).unwrap();

        let encoded_hex = hex::encode(encoded);

        assert_eq!(expected_hex, encoded_hex);
    }

    #[test]
    fn test_jwk_thumbprint_from_jwk_success() {
        let jwk_public = serde_json::json!({
            "kty": "EC",
            "crv": "P-256",
            "x": "f83OJ3D2xF4p6uZ8l9QWmK7rT2cVbYq1H0sLzX9aBcE",
            "y": "x_FEzRu9y7kQ8Lm2pV4nC6tWq1sJd3Hg5KaZ0bN7cYQ",
        });

        let _thumbprint = JwkThumbprint::new(jwk_public.as_object().unwrap()).unwrap();
    }

    #[test]
    fn test_jwk_thumbprint_from_invalid_jwk_fails() {
        let jwk_public = serde_json::json!({
            "name": "John",
        });

        let err = JwkThumbprint::new(jwk_public.as_object().unwrap()).unwrap_err();

        assert_matches!(err.error, MdocError::InvalidJwkPublic);
    }
}