Skip to main content

bitwarden_importers/importers/onepassword/access/sso/
cpace.rs

1//! The CPace exchange that hands the credentials of an enrolled device to a new one, reverse
2//! engineered from 1Password's WASM module: the local crypto, and the requests that carry it.
3//!
4//! The new device proves it knows the verification code the user reads off the enrolled device, and
5//! both sides end up with the same key to move the credential bundle through the server.
6
7use bitwarden_threading::time;
8use curve25519_dalek::{
9    ristretto::{CompressedRistretto, RistrettoPoint},
10    scalar::Scalar,
11    traits::Identity,
12};
13use data_encoding::BASE64URL_NOPAD;
14use hmac::{Hmac, KeyInit, Mac};
15use rand::Rng;
16use serde::de::DeserializeOwned;
17use serde_json::{Value, json};
18use sha2::{Digest, Sha384, Sha512};
19use zeroize::Zeroizing;
20
21use super::{
22    super::{
23        error::OnePasswordError,
24        kdf,
25        opdata::{AesKey, Encrypted, decode64_loose},
26        rest::RestClient,
27        wire::{self, CredentialBundle, EncryptedEnvelope, SuccessStatus},
28    },
29    Timing,
30};
31
32const PASSCODE_ITERATIONS: u32 = 100_000;
33
34/// Pads the second hash input through the passcode hash to one 128 byte SHA-512 block.
35const PADDING_LENGTH: usize = 76;
36
37/// The key id of the exchange key, which also keys the first step of deriving it.
38const TRANSPORT_KEY_ID: &str = "1P_SSO_ENROLLMENT_TRANSPORT_KEY";
39const EXCHANGE_KEY_INFO: &[u8] = b"1P_SSO_CREDENTIAL_BUNDLE_KEY:ENROLL\x01";
40const CREDENTIAL_BUNDLE_AAD: &[u8] = b"1P_SSO_CREDENTIAL_BUNDLE:ENROLL";
41
42/// The first CPace message, from the enrolled device.
43#[derive(Debug)]
44pub(super) struct MsgA {
45    /// The enrolled device's public point.
46    ya: RistrettoPoint,
47    ad: Ad,
48    /// The message as received, which goes into the transcript hash byte for byte.
49    original_message: Vec<u8>,
50}
51
52/// The associated data of a CPace message.
53#[derive(Debug)]
54struct Ad {
55    #[cfg_attr(not(test), allow(dead_code))]
56    version: i32,
57    salt: Vec<u8>,
58    session_id: Vec<u8>,
59}
60
61/// Parses the JSON of `msga`, after its base64 layer is removed.
62///
63/// Rejects a `ya` that is not the canonical encoding of a point, or is the identity, before
64/// anything is sent back.
65fn parse_msg_a(json: &[u8]) -> Result<MsgA, OnePasswordError> {
66    let msg_a: wire::MsgA = serde_json::from_slice(json).map_err(|_| OnePasswordError::Parse)?;
67    let ya = decompress_point(&decode64_loose(&msg_a.ya)?)?;
68    if ya == RistrettoPoint::identity() {
69        return Err(OnePasswordError::Internal(
70            "the CPace point must not be the identity".into(),
71        ));
72    }
73
74    Ok(MsgA {
75        ya,
76        ad: Ad {
77            version: msg_a.ad.version,
78            salt: decode64_loose(&msg_a.ad.salt)?,
79            session_id: msg_a.ad.session_id,
80        },
81        original_message: json.to_vec(),
82    })
83}
84
85/// Fails for anything but the canonical encoding of a point.
86fn decompress_point(bytes: &[u8]) -> Result<RistrettoPoint, OnePasswordError> {
87    CompressedRistretto::from_slice(bytes)
88        .ok()
89        .and_then(|point| point.decompress())
90        .ok_or_else(|| OnePasswordError::Internal("invalid CPace point".into()))
91}
92
93/// Calculates `msgb`, the new device's answer to `msga`.
94fn calculate_msg_b(
95    username: &str,
96    sign_in_address: &str,
97    enrollment_uuid: &str,
98    verification_code: &str,
99    msg_a: &MsgA,
100    client_secret: &[u8; 64],
101) -> [u8; 32] {
102    let passcode_hash = calculate_passcode_hash(verification_code, &msg_a.ad.salt);
103    let first_hash = calculate_first_hash(username, sign_in_address, enrollment_uuid, msg_a);
104    let second_hash = calculate_second_hash(first_hash.as_slice(), passcode_hash.as_slice(), msg_a);
105    let generator = RistrettoPoint::from_uniform_bytes(&second_hash);
106    multiply_by_client_scalar(&generator, client_secret)
107}
108
109/// Stretches the verification code, salted by the enrolled device.
110fn calculate_passcode_hash(passcode: &str, salt: &[u8]) -> Zeroizing<[u8; 32]> {
111    Zeroizing::new(kdf::pbes2(passcode, salt, PASSCODE_ITERATIONS))
112}
113
114/// Binds the exchange to the user, the sign-in address and the enrollment.
115fn calculate_first_hash(
116    email: &str,
117    sign_in_address: &str,
118    enrollment_uuid: &str,
119    msg_a: &MsgA,
120) -> Zeroizing<[u8; 64]> {
121    Zeroizing::new(sha512(&leb128_prefixed(&[
122        b"1P-SSO-TRUSTED-DEVICE",
123        b"1P-SSO-NEW-DEVICE",
124        email.as_bytes(),
125        sign_in_address.as_bytes(),
126        enrollment_uuid.as_bytes(),
127        &msg_a.ad.salt,
128        &[1],
129    ])))
130}
131
132/// The input of the CPace generator, which binds the passcode to the first hash and the session.
133fn calculate_second_hash(
134    first_hash: &[u8],
135    passcode_hash: &[u8],
136    msg_a: &MsgA,
137) -> Zeroizing<[u8; 64]> {
138    Zeroizing::new(sha512(&leb128_prefixed(&[
139        b"CPaceRistretto255",
140        passcode_hash,
141        &[0; PADDING_LENGTH],
142        first_hash,
143        &msg_a.ad.session_id,
144    ])))
145}
146
147/// Multiplies by the scalar the client secret reduces to, and compresses the result.
148fn multiply_by_client_scalar(point: &RistrettoPoint, client_secret: &[u8; 64]) -> [u8; 32] {
149    let scalar = Zeroizing::new(Scalar::from_bytes_mod_order_wide(client_secret));
150    (point * *scalar).compress().to_bytes()
151}
152
153/// Prefixes every field with its length as LEB128, and concatenates them.
154fn leb128_prefixed(fields: &[&[u8]]) -> Zeroizing<Vec<u8>> {
155    let mut buffer = Zeroizing::new(Vec::new());
156    for field in fields {
157        write_leb128_prefixed(&mut buffer, field);
158    }
159    buffer
160}
161
162/// Writes `data` after its length, as the little endian base 128 varint the WASM module uses.
163fn write_leb128_prefixed(buffer: &mut Vec<u8>, data: &[u8]) {
164    let mut length = data.len();
165    loop {
166        let byte = (length & 0x7f) as u8;
167        length >>= 7;
168        if length == 0 {
169            buffer.push(byte);
170            break;
171        }
172        buffer.push(byte | 0x80);
173    }
174    buffer.extend_from_slice(data);
175}
176
177/// Checks `taga`, the enrolled device's MAC of `msga` as received, under the same key as `tagb`. It
178/// only matches when both devices used the same verification code.
179fn verify_tag_a(tag_a: &[u8], auth_b: &[u8], msg_a: &MsgA) -> bool {
180    let mut mac = tag_mac(auth_b);
181    mac.update(&msg_a.original_message);
182    mac.verify_slice(tag_a).is_ok()
183}
184
185/// Calculates the shared secret `authB` and the `tagb` that proves knowing it.
186fn calculate_auth_b_tag_b(
187    client_secret: &[u8; 64],
188    msg_a: &MsgA,
189    msg_b: &[u8],
190) -> (Zeroizing<[u8; 64]>, [u8; 64]) {
191    let auth_a = calculate_auth_a_hash(msg_a, client_secret);
192    let auth_b = calculate_auth_b_hash(auth_a.as_slice(), msg_a, msg_b);
193    let tag_b = calculate_tag_b(auth_b.as_slice(), msg_b);
194    (auth_b, tag_b)
195}
196
197/// The point both sides agree on: `ya` times the client scalar.
198fn calculate_auth_a_hash(msg_a: &MsgA, client_secret: &[u8; 64]) -> Zeroizing<[u8; 32]> {
199    Zeroizing::new(multiply_by_client_scalar(&msg_a.ya, client_secret))
200}
201
202/// The session secret, hashed over the whole transcript.
203fn calculate_auth_b_hash(auth_a: &[u8], msg_a: &MsgA, msg_b: &[u8]) -> Zeroizing<[u8; 64]> {
204    let mut buffer = leb128_prefixed(&[b"CPaceRistretto255_ISK", &msg_a.ad.session_id, auth_a]);
205    buffer.extend_from_slice(&msg_a.original_message);
206    buffer.extend_from_slice(msg_b);
207    Zeroizing::new(sha512(&buffer))
208}
209
210/// The MAC of `msgb` under a key derived from `authB`.
211fn calculate_tag_b(auth_b: &[u8], msg_b: &[u8]) -> [u8; 64] {
212    let mut mac = tag_mac(auth_b);
213    mac.update(msg_b);
214    mac.finalize().into_bytes().into()
215}
216
217/// The MAC both tags are made with, keyed from `authB`.
218fn tag_mac(auth_b: &[u8]) -> Hmac<Sha512> {
219    let mac_key = Zeroizing::new(<[u8; 64]>::from(
220        Sha512::new()
221            .chain_update(b"CPaceMac")
222            .chain_update(auth_b)
223            .finalize(),
224    ));
225    <Hmac<Sha512> as KeyInit>::new_from_slice(mac_key.as_slice())
226        .expect("HMAC accepts any key length")
227}
228
229/// Derives the key that encrypts the credential bundle in transit from `authB`.
230fn derive_exchange_key(auth_b: &[u8]) -> Zeroizing<[u8; 32]> {
231    let transport_key = hmac_sha384(TRANSPORT_KEY_ID.as_bytes(), auth_b);
232    let exchange_key = hmac_sha384(transport_key.as_slice(), EXCHANGE_KEY_INFO);
233
234    let mut key = Zeroizing::new([0; 32]);
235    key.copy_from_slice(&exchange_key[..32]);
236    key
237}
238
239/// Decrypts the credential bundle the enrolled device shared.
240fn decrypt_credentials(
241    encrypted_credentials: &EncryptedEnvelope,
242    exchange_key: &[u8],
243) -> Result<CredentialBundle, OnePasswordError> {
244    let key = AesKey::new(TRANSPORT_KEY_ID, exchange_key.to_vec());
245    let encrypted = Encrypted::parse(encrypted_credentials)?;
246    let credentials = Zeroizing::new(key.decrypt_with_aad(&encrypted, CREDENTIAL_BUNDLE_AAD)?);
247
248    // The error is dropped, serde echoes the offending value.
249    serde_json::from_slice(&credentials).map_err(|_| OnePasswordError::Parse)
250}
251
252/// The JSON of the first message an enrolled device that shows `verification_code` sends, for the
253/// enrollment of `username` at `sign_in_address`. The mirror image of the new device's side, so
254/// tests can play the enrolled device for any address.
255#[cfg(test)]
256pub(super) fn enrolled_device_msg_a(
257    username: &str,
258    sign_in_address: &str,
259    enrollment_uuid: &str,
260    verification_code: &str,
261    ya_secret: &[u8; 64],
262    salt: &[u8],
263    session_id: &[u8],
264) -> Vec<u8> {
265    // The hashes only read the associated data, so the point is a placeholder.
266    let placeholder = MsgA {
267        ya: RistrettoPoint::identity(),
268        ad: Ad {
269            version: 1,
270            salt: salt.to_vec(),
271            session_id: session_id.to_vec(),
272        },
273        original_message: Vec::new(),
274    };
275    let passcode_hash = calculate_passcode_hash(verification_code, salt);
276    let first_hash = calculate_first_hash(username, sign_in_address, enrollment_uuid, &placeholder);
277    let second_hash = calculate_second_hash(
278        first_hash.as_slice(),
279        passcode_hash.as_slice(),
280        &placeholder,
281    );
282    let generator = RistrettoPoint::from_uniform_bytes(&second_hash);
283
284    serde_json::to_vec(&json!({
285        "ya": BASE64URL_NOPAD.encode(&multiply_by_client_scalar(&generator, ya_secret)),
286        "ad": {
287            "version": 1,
288            "salt": BASE64URL_NOPAD.encode(salt),
289            "session_id": session_id,
290        },
291    }))
292    .expect("the message serializes")
293}
294
295/// What the enrolled device shares once it has seen `msg_b`: the credentials, encrypted under the
296/// key both sides derive.
297#[cfg(test)]
298pub(super) fn share_credentials(
299    ya_secret: &[u8; 64],
300    msga_json: &[u8],
301    msg_b: &[u8],
302    credentials: &[u8],
303    iv: &[u8],
304) -> Result<EncryptedEnvelope, OnePasswordError> {
305    let auth_b = enrolled_device_auth_b(ya_secret, &parse_msg_a(msga_json)?, msg_b)?;
306    let exchange_key = derive_exchange_key(auth_b.as_slice());
307
308    AesKey::new(TRANSPORT_KEY_ID, exchange_key.to_vec()).encrypt_with_aad(
309        credentials,
310        iv,
311        CREDENTIAL_BUNDLE_AAD,
312    )
313}
314
315/// The `tagb` an enrolled device holding `ya_secret` expects in answer to `msg_b`.
316#[cfg(test)]
317pub(super) fn expected_tag_b(
318    ya_secret: &[u8; 64],
319    msga_json: &[u8],
320    msg_b: &[u8],
321) -> Result<[u8; 64], OnePasswordError> {
322    let auth_b = enrolled_device_auth_b(ya_secret, &parse_msg_a(msga_json)?, msg_b)?;
323    Ok(calculate_tag_b(auth_b.as_slice(), msg_b))
324}
325
326/// The `taga` an enrolled device holding `ya_secret` sends in answer to `msg_b`.
327#[cfg(test)]
328pub(super) fn enrolled_device_tag_a(
329    ya_secret: &[u8; 64],
330    msga_json: &[u8],
331    msg_b: &[u8],
332) -> Result<[u8; 64], OnePasswordError> {
333    let auth_b = enrolled_device_auth_b(ya_secret, &parse_msg_a(msga_json)?, msg_b)?;
334    let mut mac = tag_mac(auth_b.as_slice());
335    mac.update(msga_json);
336    Ok(mac.finalize().into_bytes().into())
337}
338
339/// `authB` as the enrolled device computes it, from its own secret and the new device's `msg_b`.
340#[cfg(test)]
341fn enrolled_device_auth_b(
342    ya_secret: &[u8; 64],
343    msg_a: &MsgA,
344    msg_b: &[u8],
345) -> Result<Zeroizing<[u8; 64]>, OnePasswordError> {
346    let ya_scalar = Scalar::from_bytes_mod_order_wide(ya_secret);
347    let auth_a = (decompress_point(msg_b)? * ya_scalar).compress().to_bytes();
348    Ok(calculate_auth_b_hash(&auth_a, msg_a, msg_b))
349}
350
351fn sha512(data: &[u8]) -> [u8; 64] {
352    Sha512::digest(data).into()
353}
354
355fn hmac_sha384(key: &[u8], message: &[u8]) -> Zeroizing<[u8; 48]> {
356    let mut mac =
357        <Hmac<Sha384> as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");
358    mac.update(message);
359    Zeroizing::new(mac.finalize().into_bytes().into())
360}
361
362/// Who signs in, where, and the token that authorizes it.
363#[derive(Clone, Copy)]
364pub(super) struct SignIn<'a> {
365    pub username: &'a str,
366    pub sign_in_address: &'a str,
367    pub sign_in_token: &'a str,
368}
369
370/// What identifies an enrollment to the server and binds an exchange to it.
371pub(super) struct EnrollmentSession<'a> {
372    pub sign_in: SignIn<'a>,
373    pub enrollment_uuid: &'a str,
374}
375
376/// How a CPace exchange that ran to the end turned out.
377pub(super) enum Exchange {
378    /// The enrolled device shared its credentials.
379    Shared(CredentialBundle),
380    /// The user typed another code than the enrolled device shows. That device goes on to show a
381    /// new one and to replace `msg_a`, the first message of this exchange, to start over.
382    WrongCode { msg_a: MsgA },
383}
384
385/// Runs the whole exchange over `rest` with a fresh random client secret.
386///
387/// A retry after a wrong code passes the `msg_a` it waited for. Without one it is requested here.
388pub(super) async fn perform_cpace(
389    session: &EnrollmentSession<'_>,
390    verification_code: &str,
391    msg_a: Option<MsgA>,
392    rest: &RestClient,
393    timing: &Timing,
394) -> Result<Exchange, OnePasswordError> {
395    let mut client_secret = Zeroizing::new([0u8; 64]);
396    bitwarden_random::rng().fill_bytes(&mut *client_secret);
397
398    perform_cpace_with_client_secret(
399        session,
400        verification_code,
401        msg_a,
402        &client_secret,
403        rest,
404        timing,
405    )
406    .await
407}
408
409/// The CPace exchange with the client secret injected so the test vectors can pin it.
410async fn perform_cpace_with_client_secret(
411    session: &EnrollmentSession<'_>,
412    verification_code: &str,
413    msg_a: Option<MsgA>,
414    client_secret: &[u8; 64],
415    rest: &RestClient,
416    timing: &Timing,
417) -> Result<Exchange, OnePasswordError> {
418    let msg_a = match msg_a {
419        Some(msg_a) => msg_a,
420        None => request_msg_a(session, None, rest, timing).await?,
421    };
422
423    let msg_b = calculate_msg_b(
424        session.sign_in.username,
425        session.sign_in.sign_in_address,
426        session.enrollment_uuid,
427        verification_code,
428        &msg_a,
429        client_secret,
430    );
431    send_msg_b(&msg_b, session, rest).await?;
432
433    let tag_a = get_tag_a(session, rest, timing).await?;
434    let (auth_b, tag_b) = calculate_auth_b_tag_b(client_secret, &msg_a, &msg_b);
435
436    // The enrolled device learns that the codes differ only from `tagb`, so it goes out either way.
437    send_tag_b(&tag_b, session, rest).await?;
438    if !verify_tag_a(&tag_a, auth_b.as_slice(), &msg_a) {
439        return Ok(Exchange::WrongCode { msg_a });
440    }
441
442    let encrypted_credentials = request_encrypted_credentials(session, rest, timing).await?;
443    let exchange_key = derive_exchange_key(auth_b.as_slice());
444
445    decrypt_credentials(&encrypted_credentials, exchange_key.as_slice()).map(Exchange::Shared)
446}
447
448/// Fetches and parses the enrolled device's first message, once the server has one other than
449/// `replaced`. It answers an empty 200 while it has none.
450pub(super) async fn request_msg_a(
451    session: &EnrollmentSession<'_>,
452    replaced: Option<&MsgA>,
453    rest: &RestClient,
454    timing: &Timing,
455) -> Result<MsgA, OnePasswordError> {
456    let endpoint = cpace_endpoint(session.enrollment_uuid, "msga");
457    for _ in 0..timing.until_result_attempts {
458        let response: Option<wire::CpaceMsgA> = rest
459            .post_json_or_empty(&endpoint, sign_in_body(session.sign_in.sign_in_token))
460            .await?;
461        if let Some(response) = response {
462            let msg_a = decode64_loose(&response.msga)?;
463            if replaced.is_none_or(|replaced| replaced.original_message != msg_a) {
464                return parse_msg_a(&msg_a);
465            }
466        }
467        time::sleep(timing.until_result_delay).await;
468    }
469
470    Err(no_result(&endpoint))
471}
472
473/// Replies with `msgb` and expects the server to accept it.
474async fn send_msg_b(
475    msg_b: &[u8],
476    session: &EnrollmentSession<'_>,
477    rest: &RestClient,
478) -> Result<(), OnePasswordError> {
479    let response: SuccessStatus = rest
480        .put_json(
481            &cpace_endpoint(session.enrollment_uuid, "msgb"),
482            json!({
483                "signInToken": session.sign_in.sign_in_token,
484                "msgb": BASE64URL_NOPAD.encode(msg_b),
485            }),
486        )
487        .await?;
488
489    expect_success(&response, "exchange credentials")
490}
491
492/// Waits for the enrolled device's `taga`.
493async fn get_tag_a(
494    session: &EnrollmentSession<'_>,
495    rest: &RestClient,
496    timing: &Timing,
497) -> Result<Vec<u8>, OnePasswordError> {
498    let result: wire::CpaceTagA = post_json_until_result(
499        &cpace_endpoint(session.enrollment_uuid, "taga"),
500        sign_in_body(session.sign_in.sign_in_token),
501        rest,
502        timing,
503    )
504    .await?;
505
506    decode64_loose(&result.taga)
507}
508
509/// Replies with `tagb` and expects the server to accept it.
510async fn send_tag_b(
511    tag_b: &[u8],
512    session: &EnrollmentSession<'_>,
513    rest: &RestClient,
514) -> Result<(), OnePasswordError> {
515    let response: SuccessStatus = rest
516        .put_json(
517            &cpace_endpoint(session.enrollment_uuid, "tagb"),
518            json!({
519                "signInToken": session.sign_in.sign_in_token,
520                "tagb": BASE64URL_NOPAD.encode(tag_b),
521            }),
522        )
523        .await?;
524
525    expect_success(&response, "submit tagb")
526}
527
528/// Waits for the credential bundle, still encrypted for the exchange key and so invisible to the
529/// server that relays it.
530async fn request_encrypted_credentials(
531    session: &EnrollmentSession<'_>,
532    rest: &RestClient,
533    timing: &Timing,
534) -> Result<EncryptedEnvelope, OnePasswordError> {
535    let result: wire::SharedCredentials = post_json_until_result(
536        &enrollment_endpoint(session.enrollment_uuid, "share/credentials"),
537        sign_in_body(session.sign_in.sign_in_token),
538        rest,
539        timing,
540    )
541    .await?;
542
543    Ok(result.encrypted_credentials)
544}
545
546/// POSTs until the endpoint answers a body instead of the empty 200 it sends while the enrolled
547/// device has not replied yet. The web frontend retries the same way.
548async fn post_json_until_result<T: DeserializeOwned>(
549    endpoint: &str,
550    body: Value,
551    rest: &RestClient,
552    timing: &Timing,
553) -> Result<T, OnePasswordError> {
554    for _ in 0..timing.until_result_attempts {
555        match rest.post_json_or_empty(endpoint, body.clone()).await? {
556            Some(result) => return Ok(result),
557            None => time::sleep(timing.until_result_delay).await,
558        }
559    }
560
561    Err(no_result(endpoint))
562}
563
564/// The error of a polled endpoint that never answered with what the client waits for.
565fn no_result(endpoint: &str) -> OnePasswordError {
566    OnePasswordError::Internal(format!(
567        "failed to get a response from the server (endpoint: {endpoint})"
568    ))
569}
570
571/// The body every CPace request carries besides the messages themselves.
572fn sign_in_body(sign_in_token: &str) -> Value {
573    json!({ "signInToken": sign_in_token })
574}
575
576/// The server confirms each CPace message with `success: 1`.
577fn expect_success(response: &SuccessStatus, action: &str) -> Result<(), OnePasswordError> {
578    if response.success != 1 {
579        return Err(OnePasswordError::Internal(format!("failed to {action}")));
580    }
581    Ok(())
582}
583
584/// `v3/device/enrollments/{enrollmentUuid}/{method}`
585fn enrollment_endpoint(enrollment_uuid: &str, method: &str) -> String {
586    format!("v3/device/enrollments/{enrollment_uuid}/{method}")
587}
588
589/// The CPace endpoints, under the enrollment's `cpace` prefix.
590fn cpace_endpoint(enrollment_uuid: &str, method: &str) -> String {
591    enrollment_endpoint(enrollment_uuid, &format!("cpace/{method}"))
592}
593
594#[cfg(test)]
595mod tests {
596    use data_encoding::HEXLOWER;
597    use serde::Deserialize;
598    use serde_json::{Value, json};
599    use wiremock::{Mock, MockServer, ResponseTemplate, matchers};
600
601    use super::{
602        super::test_support::{
603            CpaceVectors, SIGN_IN_TOKEN, hex, hex_array, mock_answers_to_msga,
604            mock_enrolled_device, mock_msga, path, quick_timing, rest_client, session, vectors,
605        },
606        *,
607    };
608
609    fn msg_a() -> MsgA {
610        parse_msg_a(vectors().cpace.msga_json.as_bytes()).expect("valid msga")
611    }
612
613    #[test]
614    fn parses_msg_a() {
615        let vectors = vectors().cpace;
616        let msg_a = msg_a();
617
618        assert_eq!(msg_a.original_message, vectors.msga_json.as_bytes());
619        assert_eq!(msg_a.ad.version, 1);
620        assert_eq!(msg_a.ad.salt, (1..=16).collect::<Vec<u8>>());
621        assert_eq!(msg_a.ad.session_id, (100..116).collect::<Vec<u8>>());
622        assert_eq!(
623            BASE64URL_NOPAD.encode(&msg_a.ya.compress().to_bytes()),
624            "IrCugkEa6t7w1_c8A8rYXtk4flTBrMStgtMSEf7qFUE"
625        );
626    }
627
628    /// The vector's `msga_json` with the value at `pointer` replaced, or removed for `None`.
629    fn edited_msg_a(pointer: &str, replacement: Option<Value>) -> Vec<u8> {
630        let mut msg_a: Value =
631            serde_json::from_str(&vectors().cpace.msga_json).expect("valid json");
632        let (parent, key) = pointer.rsplit_once('/').expect("a pointer to a member");
633        let parent = msg_a
634            .pointer_mut(parent)
635            .and_then(Value::as_object_mut)
636            .expect("an existing object");
637        match replacement {
638            Some(value) => parent.insert(key.into(), value),
639            None => parent.remove(key),
640        };
641        serde_json::to_vec(&msg_a).expect("serializes")
642    }
643
644    #[test]
645    fn rejects_malformed_msg_a() {
646        let point = |bytes: &[u8]| Some(json!(BASE64URL_NOPAD.encode(bytes)));
647
648        let cases = [
649            ("not json", b"not json".to_vec()),
650            ("empty", Vec::new()),
651            ("ya is not base64", edited_msg_a("/ya", Some(json!("***")))),
652            ("ya is null", edited_msg_a("/ya", Some(Value::Null))),
653            (
654                "ya is not canonical",
655                edited_msg_a("/ya", point(&[0xff; 32])),
656            ),
657            ("ya is too short", edited_msg_a("/ya", point(&[1; 31]))),
658            ("ya is too long", edited_msg_a("/ya", point(&[1; 33]))),
659            ("ya is the identity", edited_msg_a("/ya", point(&[0; 32]))),
660            (
661                "salt is not base64",
662                edited_msg_a("/ad/salt", Some(json!("***"))),
663            ),
664            (
665                "session id is above 255",
666                edited_msg_a("/ad/session_id", Some(json!([100, 256]))),
667            ),
668            (
669                "session id is negative",
670                edited_msg_a("/ad/session_id", Some(json!([-1]))),
671            ),
672            (
673                "session id is not an array",
674                edited_msg_a("/ad/session_id", Some(json!("abc"))),
675            ),
676            ("ya is missing", edited_msg_a("/ya", None)),
677            ("ad is missing", edited_msg_a("/ad", None)),
678            ("version is missing", edited_msg_a("/ad/version", None)),
679            ("salt is missing", edited_msg_a("/ad/salt", None)),
680            (
681                "session id is missing",
682                edited_msg_a("/ad/session_id", None),
683            ),
684        ];
685
686        for (name, json) in cases {
687            assert!(parse_msg_a(&json).is_err(), "{name}");
688        }
689    }
690
691    #[test]
692    fn rejects_an_invalid_point_with_an_internal_error() {
693        let json = edited_msg_a("/ya", Some(json!(BASE64URL_NOPAD.encode(&[0xff; 32]))));
694
695        assert!(matches!(
696            parse_msg_a(&json),
697            Err(OnePasswordError::Internal(_))
698        ));
699    }
700
701    #[test]
702    fn writes_leb128_length_prefixes() {
703        let table = vectors().leb128_prefix;
704        assert!(!table.is_empty());
705
706        for (length, prefix) in table {
707            let data = vec![0xab; length];
708            let mut buffer = Vec::new();
709            write_leb128_prefixed(&mut buffer, &data);
710
711            let (written_prefix, written_data) = buffer.split_at(buffer.len() - length);
712            assert_eq!(HEXLOWER.encode(written_prefix), prefix, "length {length}");
713            assert_eq!(written_data, data, "length {length}");
714        }
715    }
716
717    #[test]
718    fn calculates_passcode_hash() {
719        let vectors = vectors().cpace;
720
721        assert_eq!(
722            HEXLOWER.encode(
723                calculate_passcode_hash(&vectors.verification_code, &msg_a().ad.salt).as_slice()
724            ),
725            vectors.passcode_hash
726        );
727    }
728
729    #[test]
730    fn calculates_first_hash() {
731        let vectors = vectors().cpace;
732
733        let hash = calculate_first_hash(
734            &vectors.username,
735            &vectors.sign_in_address,
736            &vectors.enrollment_uuid,
737            &msg_a(),
738        );
739
740        assert_eq!(HEXLOWER.encode(hash.as_slice()), vectors.first_hash);
741    }
742
743    #[test]
744    fn calculates_second_hash() {
745        let vectors = vectors().cpace;
746
747        let hash = calculate_second_hash(
748            &hex(&vectors.first_hash),
749            &hex(&vectors.passcode_hash),
750            &msg_a(),
751        );
752
753        assert_eq!(HEXLOWER.encode(hash.as_slice()), vectors.second_hash);
754    }
755
756    #[test]
757    fn calculates_msg_b() {
758        let vectors = vectors().cpace;
759
760        let msg_b = calculate_msg_b(
761            &vectors.username,
762            &vectors.sign_in_address,
763            &vectors.enrollment_uuid,
764            &vectors.verification_code,
765            &msg_a(),
766            &hex_array(&vectors.client_secret),
767        );
768
769        assert_eq!(HEXLOWER.encode(&msg_b), vectors.msgb);
770    }
771
772    #[test]
773    fn calculates_auth_a() {
774        let vectors = vectors().cpace;
775
776        let auth_a = calculate_auth_a_hash(&msg_a(), &hex_array(&vectors.client_secret));
777
778        assert_eq!(HEXLOWER.encode(auth_a.as_slice()), vectors.auth_a);
779    }
780
781    #[test]
782    fn calculates_auth_b() {
783        let vectors = vectors().cpace;
784
785        let auth_b = calculate_auth_b_hash(&hex(&vectors.auth_a), &msg_a(), &hex(&vectors.msgb));
786
787        assert_eq!(HEXLOWER.encode(auth_b.as_slice()), vectors.auth_b);
788    }
789
790    #[test]
791    fn calculates_tag_b() {
792        let vectors = vectors().cpace;
793
794        let tag_b = calculate_tag_b(&hex(&vectors.auth_b), &hex(&vectors.msgb));
795
796        assert_eq!(HEXLOWER.encode(&tag_b), vectors.tag_b);
797    }
798
799    #[test]
800    fn calculates_auth_b_and_tag_b_together() {
801        let vectors = vectors().cpace;
802
803        let (auth_b, tag_b) = calculate_auth_b_tag_b(
804            &hex_array(&vectors.client_secret),
805            &msg_a(),
806            &hex(&vectors.msgb),
807        );
808
809        assert_eq!(HEXLOWER.encode(auth_b.as_slice()), vectors.auth_b);
810        assert_eq!(HEXLOWER.encode(&tag_b), vectors.tag_b);
811    }
812
813    #[test]
814    fn derives_exchange_key() {
815        let vectors = vectors().cpace;
816
817        let key = derive_exchange_key(&hex(&vectors.auth_b));
818
819        assert_eq!(HEXLOWER.encode(key.as_slice()), vectors.exchange_key);
820    }
821
822    #[test]
823    fn decrypts_credentials() {
824        let vectors = vectors().cpace;
825
826        let bundle =
827            decrypt_credentials(&vectors.encrypted_credentials, &hex(&vectors.exchange_key))
828                .expect("decrypts");
829
830        assert_eq!(*bundle.srpx, "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr8");
831        assert_eq!(*bundle.auk.k, "WyICHHlP5lPigZUGZYoivbJMqgHjSti86UKwdjCryYM");
832    }
833
834    /// The enrolled device's first message is the one of the vectors, when it is told the same.
835    #[test]
836    fn the_enrolled_device_sends_the_first_message_of_the_vectors() {
837        let vectors = vectors().cpace;
838        let vector_msg_a = msg_a();
839
840        let json = enrolled_device_msg_a(
841            &vectors.username,
842            &vectors.sign_in_address,
843            &vectors.enrollment_uuid,
844            &vectors.verification_code,
845            &hex_array(&vectors.ya_secret),
846            &vector_msg_a.ad.salt,
847            &vector_msg_a.ad.session_id,
848        );
849
850        let sent = parse_msg_a(&json).expect("parses");
851        assert_eq!(sent.ya.compress(), vector_msg_a.ya.compress());
852        assert_eq!(sent.ad.salt, vector_msg_a.ad.salt);
853        assert_eq!(sent.ad.session_id, vector_msg_a.ad.session_id);
854    }
855
856    /// The enrolled device's side reaches the exchange key of the vectors, from its own secret.
857    #[test]
858    fn the_enrolled_device_shares_credentials_the_exchange_key_opens() {
859        let vectors = vectors().cpace;
860
861        let shared = share_credentials(
862            &hex_array(&vectors.ya_secret),
863            vectors.msga_json.as_bytes(),
864            &hex(&vectors.msgb),
865            vectors.credential_bundle_json.as_bytes(),
866            &[7; 12],
867        )
868        .expect("shares");
869
870        let bundle =
871            decrypt_credentials(&shared, &hex(&vectors.exchange_key)).expect("the key opens it");
872        assert_eq!(*bundle.srpx, "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr8");
873    }
874
875    #[test]
876    fn decrypting_credentials_fails_with_another_key() {
877        let vectors = vectors().cpace;
878
879        assert!(decrypt_credentials(&vectors.encrypted_credentials, &[0; 32]).is_err());
880    }
881
882    #[test]
883    fn decrypting_credentials_fails_with_another_associated_data() {
884        let vectors = vectors().cpace;
885        let key = AesKey::new(TRANSPORT_KEY_ID, hex(&vectors.exchange_key));
886        let envelope = key
887            .encrypt_with_aad(
888                vectors.credential_bundle_json.as_bytes(),
889                &[7; 12],
890                b"other",
891            )
892            .expect("encrypts");
893
894        assert!(decrypt_credentials(&envelope, &key.key).is_err());
895    }
896
897    #[test]
898    fn decrypting_credentials_fails_on_malformed_bundle() {
899        let vectors = vectors().cpace;
900        let key = AesKey::new(TRANSPORT_KEY_ID, hex(&vectors.exchange_key));
901        let envelope = key
902            .encrypt_with_aad(br#"{"srpx":"x"}"#, &[7; 12], CREDENTIAL_BUNDLE_AAD)
903            .expect("encrypts");
904
905        assert!(matches!(
906            decrypt_credentials(&envelope, &key.key),
907            Err(OnePasswordError::Parse)
908        ));
909    }
910
911    /// The enrolled device holds `ya_secret`, and the vectors have to be consistent with it.
912    #[test]
913    fn ya_is_the_generator_times_the_enrolled_secret() {
914        let vectors = vectors().cpace;
915        let ya_scalar = Scalar::from_bytes_mod_order_wide(&hex_array(&vectors.ya_secret));
916        let generator = RistrettoPoint::from_uniform_bytes(&hex_array(&vectors.second_hash));
917
918        assert_eq!((generator * ya_scalar).compress(), msg_a().ya.compress());
919    }
920
921    #[test]
922    fn enrolled_device_expects_the_tag_b_of_the_vectors() {
923        let vectors = vectors().cpace;
924
925        let tag_b = expected_tag_b(
926            &hex_array(&vectors.ya_secret),
927            vectors.msga_json.as_bytes(),
928            &hex(&vectors.msgb),
929        )
930        .expect("a valid msgb");
931
932        assert_eq!(HEXLOWER.encode(&tag_b), vectors.tag_b);
933    }
934
935    #[test]
936    fn enrolled_device_derives_the_same_auth_a() {
937        let vectors = vectors().cpace;
938        let ya_scalar = Scalar::from_bytes_mod_order_wide(&hex_array(&vectors.ya_secret));
939        let msg_b = decompress_point(&hex(&vectors.msgb)).expect("a valid point");
940
941        assert_eq!(
942            HEXLOWER.encode(&(msg_b * ya_scalar).compress().to_bytes()),
943            vectors.auth_a
944        );
945    }
946
947    async fn run_cpace(
948        server: &MockServer,
949        vectors: &CpaceVectors,
950        msg_a: Option<MsgA>,
951        timing: &Timing,
952    ) -> Result<Exchange, OnePasswordError> {
953        perform_cpace_with_client_secret(
954            &session(vectors),
955            &vectors.verification_code,
956            msg_a,
957            &hex_array(&vectors.client_secret),
958            &rest_client(server),
959            timing,
960        )
961        .await
962    }
963
964    fn shared(exchange: Result<Exchange, OnePasswordError>) -> CredentialBundle {
965        match exchange.expect("the exchange runs to the end") {
966            Exchange::Shared(bundle) => bundle,
967            Exchange::WrongCode { .. } => panic!("the codes are expected to match"),
968        }
969    }
970
971    /// Exchanges recorded from 1Password's own CPace, see `fixtures/sso-1password-exchanges.json`.
972    #[derive(Deserialize)]
973    struct RecordedExchanges {
974        username: String,
975        sign_in_address: String,
976        enrollment_uuid: String,
977        client_secret: String,
978        right_code: RecordedExchange,
979        wrong_code: RecordedExchange,
980    }
981
982    /// The messages of one exchange, base64url as sent.
983    #[derive(Deserialize)]
984    struct RecordedExchange {
985        verification_code: String,
986        msga: String,
987        msgb: String,
988        taga: String,
989        tagb: String,
990        encrypted_credentials: Option<EncryptedEnvelope>,
991    }
992
993    fn recorded_exchanges() -> RecordedExchanges {
994        serde_json::from_str(include_str!("../fixtures/sso-1password-exchanges.json"))
995            .expect("the exchanges parse")
996    }
997
998    fn base64url(s: &str) -> Vec<u8> {
999        BASE64URL_NOPAD
1000            .decode(s.as_bytes())
1001            .expect("valid base64url")
1002    }
1003
1004    /// Plays the enrolled device of `exchange`: it sends the recorded `msga` and `taga`, expects
1005    /// exactly the recorded `msgb` and `tagb`, and shares the recorded credentials, if any.
1006    async fn mock_recorded_enrolled_device(
1007        server: &MockServer,
1008        exchanges: &RecordedExchanges,
1009        exchange: &RecordedExchange,
1010    ) {
1011        let path = |method: &str| {
1012            format!(
1013                "/api/v3/device/enrollments/{}/{method}",
1014                exchanges.enrollment_uuid
1015            )
1016        };
1017        let sends = |method: &str, body: Value| {
1018            Mock::given(matchers::method("POST"))
1019                .and(matchers::path(path(method)))
1020                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1021        };
1022        let expects = |method: &str, name: &str, value: &str| {
1023            Mock::given(matchers::method("PUT"))
1024                .and(matchers::path(path(method)))
1025                .and(matchers::body_json(
1026                    json!({ "signInToken": SIGN_IN_TOKEN, name: value }),
1027                ))
1028                .respond_with(ResponseTemplate::new(200).set_body_json(json!({"success": 1})))
1029                .expect(1)
1030        };
1031
1032        server
1033            .register(sends("cpace/msga", json!({ "msga": exchange.msga })))
1034            .await;
1035        server
1036            .register(expects("cpace/msgb", "msgb", &exchange.msgb))
1037            .await;
1038        server
1039            .register(sends("cpace/taga", json!({ "taga": exchange.taga })))
1040            .await;
1041        server
1042            .register(expects("cpace/tagb", "tagb", &exchange.tagb))
1043            .await;
1044        server
1045            .register(
1046                sends(
1047                    "share/credentials",
1048                    json!({ "encCreds": exchange.encrypted_credentials }),
1049                )
1050                .expect(u64::from(exchange.encrypted_credentials.is_some())),
1051            )
1052            .await;
1053    }
1054
1055    async fn run_recorded_exchange(
1056        server: &MockServer,
1057        exchanges: &RecordedExchanges,
1058        exchange: &RecordedExchange,
1059    ) -> Result<Exchange, OnePasswordError> {
1060        perform_cpace_with_client_secret(
1061            &EnrollmentSession {
1062                sign_in: SignIn {
1063                    username: &exchanges.username,
1064                    sign_in_address: &exchanges.sign_in_address,
1065                    sign_in_token: SIGN_IN_TOKEN,
1066                },
1067                enrollment_uuid: &exchanges.enrollment_uuid,
1068            },
1069            &exchange.verification_code,
1070            None,
1071            &hex_array(&exchanges.client_secret),
1072            &rest_client(server),
1073            &quick_timing(),
1074        )
1075        .await
1076    }
1077
1078    #[tokio::test]
1079    async fn exchanges_the_credentials_with_1password() {
1080        let exchanges = recorded_exchanges();
1081        let server = MockServer::start().await;
1082        mock_recorded_enrolled_device(&server, &exchanges, &exchanges.right_code).await;
1083
1084        let bundle =
1085            shared(run_recorded_exchange(&server, &exchanges, &exchanges.right_code).await);
1086
1087        assert_eq!(*bundle.srpx, "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr8");
1088        assert_eq!(*bundle.auk.k, "WyICHHlP5lPigZUGZYoivbJMqgHjSti86UKwdjCryYM");
1089        server.verify().await;
1090    }
1091
1092    #[tokio::test]
1093    async fn a_wrong_code_still_sends_tag_b_and_asks_for_no_credentials() {
1094        let exchanges = recorded_exchanges();
1095        let server = MockServer::start().await;
1096        mock_recorded_enrolled_device(&server, &exchanges, &exchanges.wrong_code).await;
1097
1098        let exchange = run_recorded_exchange(&server, &exchanges, &exchanges.wrong_code)
1099            .await
1100            .expect("the exchange runs to the end");
1101
1102        let Exchange::WrongCode { msg_a } = exchange else {
1103            panic!("the codes differ");
1104        };
1105        assert_eq!(
1106            msg_a.original_message,
1107            base64url(&exchanges.wrong_code.msga)
1108        );
1109        server.verify().await;
1110    }
1111
1112    #[test]
1113    fn verifies_only_the_tag_a_of_msg_a_under_the_shared_key() {
1114        let exchanges = recorded_exchanges();
1115        let right = &exchanges.right_code;
1116        let msg_a = parse_msg_a(&base64url(&right.msga)).expect("valid msga");
1117        let msg_b = base64url(&right.msgb);
1118        let auth_a = calculate_auth_a_hash(&msg_a, &hex_array(&exchanges.client_secret));
1119        let auth_b = calculate_auth_b_hash(auth_a.as_slice(), &msg_a, &msg_b);
1120        let tag_a = base64url(&right.taga);
1121        let mut flipped = tag_a.clone();
1122        flipped[17] ^= 1;
1123
1124        assert!(verify_tag_a(&tag_a, auth_b.as_slice(), &msg_a));
1125        assert!(!verify_tag_a(&flipped, auth_b.as_slice(), &msg_a));
1126        assert!(!verify_tag_a(&tag_a[..32], auth_b.as_slice(), &msg_a));
1127        assert!(!verify_tag_a(
1128            &base64url(&right.tagb),
1129            auth_b.as_slice(),
1130            &msg_a
1131        ));
1132        assert!(!verify_tag_a(&tag_a, &[0; 64], &msg_a));
1133    }
1134
1135    #[tokio::test]
1136    async fn waits_for_a_msg_a_other_than_the_replaced_one() {
1137        let vectors = vectors().cpace;
1138        let replaced_bytes = edited_msg_a("/ad/version", Some(json!(2)));
1139        let replaced = parse_msg_a(&replaced_bytes).expect("valid msga");
1140        let server = MockServer::start().await;
1141        for answer in [
1142            ResponseTemplate::new(200),
1143            ResponseTemplate::new(200)
1144                .set_body_json(json!({ "msga": BASE64URL_NOPAD.encode(&replaced_bytes) })),
1145        ] {
1146            server
1147                .register(
1148                    Mock::given(matchers::method("POST"))
1149                        .and(matchers::path(path(&vectors, "cpace/msga")))
1150                        .respond_with(answer)
1151                        .up_to_n_times(1)
1152                        .expect(1),
1153                )
1154                .await;
1155        }
1156        mock_msga(&server, &vectors).await;
1157
1158        let msg_a = request_msg_a(
1159            &session(&vectors),
1160            Some(&replaced),
1161            &rest_client(&server),
1162            &quick_timing(),
1163        )
1164        .await
1165        .expect("a new msga");
1166
1167        assert_eq!(msg_a.original_message, vectors.msga_json.as_bytes());
1168        server.verify().await;
1169    }
1170
1171    #[tokio::test]
1172    async fn an_exchange_starts_from_the_msg_a_it_is_given() {
1173        let vectors = vectors().cpace;
1174        let server = MockServer::start().await;
1175        mock_answers_to_msga(&server, &vectors).await;
1176
1177        let bundle = shared(run_cpace(&server, &vectors, Some(msg_a()), &quick_timing()).await);
1178
1179        assert_eq!(*bundle.srpx, "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr8");
1180        server.verify().await;
1181    }
1182
1183    #[tokio::test]
1184    async fn perform_cpace_sends_the_vector_messages_and_returns_the_bundle() {
1185        let vectors = vectors().cpace;
1186        let server = MockServer::start().await;
1187        mock_enrolled_device(&server, &vectors).await;
1188
1189        let bundle = shared(run_cpace(&server, &vectors, None, &quick_timing()).await);
1190
1191        assert_eq!(*bundle.srpx, "oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr8");
1192        assert_eq!(*bundle.auk.k, "WyICHHlP5lPigZUGZYoivbJMqgHjSti86UKwdjCryYM");
1193        server.verify().await;
1194    }
1195
1196    #[tokio::test]
1197    async fn a_rejected_msgb_is_an_error() {
1198        let vectors = vectors().cpace;
1199        let server = MockServer::start().await;
1200        mock_msga(&server, &vectors).await;
1201        server
1202            .register(
1203                Mock::given(matchers::method("PUT"))
1204                    .and(matchers::path(path(&vectors, "cpace/msgb")))
1205                    .respond_with(ResponseTemplate::new(200).set_body_json(json!({"success": 0})))
1206                    .expect(1),
1207            )
1208            .await;
1209
1210        let error = run_cpace(&server, &vectors, None, &quick_timing())
1211            .await
1212            .err()
1213            .expect("the exchange fails");
1214
1215        assert!(matches!(
1216            &error,
1217            OnePasswordError::Internal(message) if message.contains("exchange credentials")
1218        ));
1219        server.verify().await;
1220    }
1221
1222    #[tokio::test]
1223    async fn an_error_status_on_msga_is_returned_as_is() {
1224        let vectors = vectors().cpace;
1225        let server = MockServer::start().await;
1226        server
1227            .register(
1228                Mock::given(matchers::path(path(&vectors, "cpace/msga")))
1229                    .respond_with(ResponseTemplate::new(503))
1230                    .expect(1),
1231            )
1232            .await;
1233
1234        let error = run_cpace(&server, &vectors, None, &quick_timing())
1235            .await
1236            .err()
1237            .expect("the exchange fails");
1238
1239        assert!(matches!(
1240            &error,
1241            OnePasswordError::UnexpectedStatus { endpoint, status: 503 }
1242                if *endpoint == format!("v3/device/enrollments/{}/cpace/msga", vectors.enrollment_uuid)
1243        ));
1244        server.verify().await;
1245    }
1246
1247    #[tokio::test]
1248    async fn exhausting_the_empty_answers_is_an_error() {
1249        let vectors = vectors().cpace;
1250        let server = MockServer::start().await;
1251        mock_msga(&server, &vectors).await;
1252        server
1253            .register(
1254                Mock::given(matchers::method("PUT"))
1255                    .and(matchers::path(path(&vectors, "cpace/msgb")))
1256                    .respond_with(ResponseTemplate::new(200).set_body_json(json!({"success": 1})))
1257                    .expect(1),
1258            )
1259            .await;
1260        server
1261            .register(
1262                Mock::given(matchers::method("POST"))
1263                    .and(matchers::path(path(&vectors, "cpace/taga")))
1264                    .respond_with(ResponseTemplate::new(200))
1265                    .expect(3),
1266            )
1267            .await;
1268
1269        let timing = Timing {
1270            until_result_attempts: 3,
1271            ..quick_timing()
1272        };
1273        let error = run_cpace(&server, &vectors, None, &timing)
1274            .await
1275            .err()
1276            .expect("the exchange fails");
1277
1278        assert!(matches!(
1279            &error,
1280            OnePasswordError::Internal(message)
1281                if message.contains(&format!("v3/device/enrollments/{}/cpace/taga", vectors.enrollment_uuid))
1282        ));
1283        server.verify().await;
1284    }
1285}