pxp 0.1.0

FIDO Proximity Exchange Protocol (PXP, formerly CTAP hybrid / caBLE) client for Linux, written in Rust
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
//! Transport-agnostic Noise handshake and encrypted CTAP framing for the
//! hybrid transport. Runs over any [`PxpDataChannel`].
use std::collections::BTreeMap;
use std::sync::Arc;

use hmac::{Hmac, Mac};
use p256::{ecdh, NonZeroScalar};
use p256::{PublicKey, SecretKey};
use serde::Deserialize;
use serde_bytes::ByteBuf;
use serde_cbor_2 as serde_cbor;
use serde_indexed::DeserializeIndexed;
use sha2::Sha256;
use snow::{Builder, TransportState};
use tokio::sync::mpsc::Sender;
use tracing::{debug, error, trace, warn};

use super::data_channel::PxpDataChannel;
use super::known_devices::ClientPayload;
use super::known_devices::{PxpKnownDeviceInfo, PxpKnownDeviceInfoStore};
use crate::cbor::{self, Value};
use crate::connection_stages::TunnelConnectionInput;
use crate::error::PxpError;
use crate::get_info::GetInfoResponse;
use crate::known_devices::PxpKnownDeviceId;

const P256_X962_LENGTH: usize = 65;
const MAX_CBOR_SIZE: usize = 1024 * 1024;
const PADDING_GRANULARITY: usize = 32;
/// After sending Shutdown, how long to wait for the peer to close its side.
const PEER_CLOSE_GRACE: std::time::Duration = std::time::Duration::from_secs(2);

const PXP_PROLOGUE_STATE_ASSISTED: &[u8] = &[0u8];
const PXP_PROLOGUE_QR_INITIATED: &[u8] = &[1u8];

/// CTAP2 authenticatorGetInfo command byte. The only CTAP fact PXP relies on:
/// the post-handshake message already carries the getInfo response.
const CTAP2_GET_INFO: u8 = 0x04;
/// CTAP2 success status byte, prefixed to the cached getInfo response.
const CTAP2_OK: u8 = 0x00;

#[derive(Debug, Clone)]
struct PxpTunnelMessage {
    message_type: PxpTunnelMessageType,
    payload: ByteBuf,
}

impl PxpTunnelMessage {
    pub fn new(message_type: PxpTunnelMessageType, payload: &[u8]) -> Self {
        Self {
            message_type,
            payload: ByteBuf::from(payload.to_vec()),
        }
    }
    pub fn from_slice(slice: &[u8]) -> Result<Self, PxpError> {
        let (type_byte, payload) = slice.split_first().ok_or(PxpError::InvalidFraming)?;
        // Shutdown is the type byte alone (Chromium sends exactly that);
        // every other message carries a payload.
        if payload.is_empty() && *type_byte != 0 {
            return Err(PxpError::InvalidFraming);
        }

        let message_type = match *type_byte {
            0 => PxpTunnelMessageType::Shutdown,
            1 => PxpTunnelMessageType::Ctap,
            2 => PxpTunnelMessageType::Update,
            _ => {
                return Err(PxpError::InvalidFraming);
            }
        };

        Ok(Self {
            message_type,
            payload: ByteBuf::from(payload.to_vec()),
        })
    }

    pub fn to_vec(&self) -> Vec<u8> {
        let mut vec = Vec::new();
        // TODO: multiple versions
        vec.push(self.message_type as u8);
        vec.extend(self.payload.iter());
        vec
    }
}

#[derive(Clone, Debug, DeserializeIndexed)]
struct PxpInitialMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(index = 0x00)]
    pub _padding: Option<ByteBuf>,

    #[serde(index = 0x01)]
    pub info: ByteBuf,

    #[serde(skip_serializing_if = "SupportedFeatures::is_default")]
    #[serde(index = 0x03)]
    pub supported_features: SupportedFeatures,
}

/// Post-handshake message key 3. Its absence MUST be treated as `["ctap"]`.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(transparent)]
struct SupportedFeatures(Vec<String>);

impl Default for SupportedFeatures {
    fn default() -> Self {
        Self(vec!["ctap".to_string()])
    }
}

impl SupportedFeatures {
    #[allow(dead_code)]
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct PxpLinkingInfo {
    /// Used by the tunnel to identify the authenticator (eg. Android FCM token)
    pub contact_id: Vec<u8>,
    /// Used by the authenticator to identify the client platform
    pub link_id: Vec<u8>,
    /// Shared secret between authenticator and client platform
    pub link_secret: Vec<u8>,
    /// Authenticator's public key, X9.62 uncompressed format
    pub authenticator_public_key: Vec<u8>,
    /// User-friendly name of the authenticator
    pub authenticator_name: String,
    /// HMAC of the handshake hash (Noise's channel binding value) using the
    /// shared secret (link_secret) as key
    #[allow(dead_code)]
    pub handshake_signature: Vec<u8>,
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, Deserialize)]
enum PxpTunnelMessageType {
    Shutdown = 0,
    Ctap = 1,
    Update = 2,
}

/// Result of processing a single inbound tunnel frame.
enum RecvOutcome {
    /// Frame handled, keep the loop running.
    Continue,
    /// Peer sent a `Shutdown` control message; close the channel cleanly.
    PeerShutdown,
}

#[derive(Clone)]
pub(crate) enum PxpTunnelConnectionType {
    QrCode {
        routing_id: String,
        tunnel_id: String,
        private_key: NonZeroScalar,
    },
    KnownDevice {
        contact_id: String,
        authenticator_public_key: Vec<u8>,
        client_payload: ClientPayload,
    },
}

impl std::fmt::Debug for PxpTunnelConnectionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::QrCode {
                routing_id,
                tunnel_id,
                private_key: _,
            } => f
                .debug_struct("QrCode")
                .field("routing_id", routing_id)
                .field("tunnel_id", tunnel_id)
                .field("private_key", &"[REDACTED]")
                .finish(),
            Self::KnownDevice {
                contact_id,
                authenticator_public_key,
                client_payload,
            } => f
                .debug_struct("KnownDevice")
                .field("contact_id", contact_id)
                .field("authenticator_public_key", authenticator_public_key)
                .field("client_payload", client_payload)
                .finish(),
        }
    }
}

pub(crate) struct TunnelNoiseState {
    pub transport_state: TransportState,
    #[allow(dead_code)]
    pub handshake_hash: Vec<u8>,
}

pub(crate) async fn do_handshake(
    data_channel: &mut dyn PxpDataChannel,
    psk: [u8; 32],
    connection_type: &PxpTunnelConnectionType,
) -> Result<TunnelNoiseState, PxpError> {
    let noise_handshake = match connection_type {
        PxpTunnelConnectionType::QrCode { private_key, .. } => {
            let local_private_key = private_key.to_owned().to_bytes();
            Builder::new("Noise_KNpsk0_P256_AESGCM_SHA256".parse()?)
                .prologue(PXP_PROLOGUE_QR_INITIATED)?
                .local_private_key(local_private_key.as_slice())?
                .psk(0, &psk)?
                .build_initiator()
        }
        PxpTunnelConnectionType::KnownDevice {
            authenticator_public_key,
            ..
        } => Builder::new("Noise_NKpsk0_P256_AESGCM_SHA256".parse()?)
            .prologue(PXP_PROLOGUE_STATE_ASSISTED)?
            .remote_public_key(authenticator_public_key)?
            .psk(0, &psk)?
            .build_initiator(),
    };

    // Build the Noise handshake as the initiator
    let mut noise_handshake = match noise_handshake {
        Ok(handshake) => handshake,
        Err(e) => {
            error!(?e, "Failed to build Noise handshake");
            return Err(PxpError::ConnectionFailed);
        }
    };

    let mut initial_msg_buffer = vec![0u8; 1024];
    let initial_msg_len = match noise_handshake.write_message(&[], &mut initial_msg_buffer) {
        Ok(msg_len) => msg_len,
        Err(e) => {
            error!(?e, "Failed to write initial handshake message");
            return Err(PxpError::ConnectionFailed);
        }
    };

    let initial_msg: Vec<u8> = initial_msg_buffer
        .get(..initial_msg_len)
        .map(<[u8]>::to_vec)
        .ok_or(PxpError::ConnectionFailed)?;
    trace!(handshake = ?initial_msg, "Sending initial handshake message");

    data_channel.send(&initial_msg).await?;
    debug!("Sent initial handshake message");

    // Read the response from the peer and process it
    let response = match data_channel.recv().await {
        Ok(Some(response)) => {
            debug!(response_len = response.len(), "Received handshake response");
            trace!(?response);
            response
        }
        Ok(None) => {
            warn!("Connection was closed before handshake was complete");
            return Err(PxpError::ConnectionFailed);
        }
        Err(e) => {
            warn!(?e, "Failed to read handshake response");
            return Err(e);
        }
    };

    if response.len() < P256_X962_LENGTH {
        warn!(len = response.len(), "Peer handshake message is too short");
        return Err(PxpError::ConnectionFailed);
    }

    let mut payload = [0u8; 1024];
    let payload_len = match noise_handshake.read_message(&response, &mut payload) {
        Ok(len) => len,
        Err(e) => {
            warn!(?e, "Failed to read handshake response message");
            return Err(PxpError::ConnectionFailed);
        }
    };

    debug!(handshake_len = payload_len, "Received handshake response");

    if !noise_handshake.is_handshake_finished() {
        warn!("Handshake did not complete");
        return Err(PxpError::ConnectionFailed);
    }

    Ok(TunnelNoiseState {
        handshake_hash: noise_handshake.get_handshake_hash().to_vec(),
        transport_state: noise_handshake.into_transport_mode()?,
    })
}

/// Returns `Ok(())` on a clean close and `Err(_)` on any fault that leaves
/// the encrypted channel unusable; callers surface `Err(_)` via `send_error`.
pub(crate) async fn connection(mut input: TunnelConnectionInput) -> Result<(), PxpError> {
    let get_info_response_serialized: Vec<u8> = match input.data_channel.recv().await {
        Ok(Some(message)) => match connection_recv_initial(message, &mut input.noise_state).await {
            Ok(initial) => initial,
            Err(e) => {
                warn!(?e, "Failed to process initial message");
                return Err(e);
            }
        },
        Ok(None) => {
            warn!("Connection closed before initial message was received");
            return Err(PxpError::ConnectionLost);
        }
        Err(e) => {
            warn!(?e, "Failed to read initial message");
            return Err(e);
        }
    };
    debug!(
        get_info_response_serialized_len = get_info_response_serialized.len(),
        "Received initial message"
    );

    loop {
        tokio::select! {
            result = input.data_channel.recv() => {
                match result {
                    Ok(Some(message)) => {
                        debug!("Received data channel message");
                        trace!(?message);
                        match connection_recv(
                            &input.connection_type,
                            &input.tunnel_domain,
                            &input.known_device_store,
                            message,
                            &input.ctap_rx_send,
                            &mut input.noise_state,
                        )
                        .await
                        {
                            Ok(RecvOutcome::Continue) => {}
                            Ok(RecvOutcome::PeerShutdown) => return Ok(()),
                            Err(e) => {
                                warn!(?e, "Fatal error processing inbound frame");
                                return Err(e);
                            }
                        }
                    }
                    Ok(None) => {
                        debug!("Data channel closed, closing connection");
                        return Ok(());
                    }
                    Err(e) => {
                        warn!(?e, "Failed to read encrypted CBOR message");
                        return Err(e);
                    }
                }
            }
            // `TunnelHandle::close` asked to end the session. Send
            // Shutdown, as Chromium does, so the authenticator ends in its
            // success state, then give the peer a moment to close first.
            _ = &mut input.shutdown_recv => {
                debug!("Sending Shutdown control message");
                if let Err(e) = send_tunnel_message(
                    PxpTunnelMessageType::Shutdown,
                    &[],
                    &mut *input.data_channel,
                    &mut input.noise_state,
                )
                .await
                {
                    debug!(?e, "Could not send Shutdown");
                    return Ok(());
                }
                let _ = tokio::time::timeout(PEER_CLOSE_GRACE, async {
                    while let Ok(Some(_)) = input.data_channel.recv().await {}
                })
                .await;
                return Ok(());
            }
            Some(request) = input.ctap_tx_recv.recv() => {
                match request.first() {
                    // Optimisation: respond to GetInfo requests immediately with the cached response
                    Some(&CTAP2_GET_INFO) => {
                        debug!("Responding to GetInfo request with cached response");
                        let mut response = vec![CTAP2_OK];
                        response.extend_from_slice(&get_info_response_serialized);
                        if let Err(e) = input.ctap_rx_send.send(response).await {
                            warn!(?e, "CTAP response receiver dropped");
                            return Err(PxpError::ConnectionFailed);
                        }
                    }
                    command => {
                        debug!(?command, "Sending CTAP request");
                        if let Err(e) = connection_send(
                            request,
                            &mut *input.data_channel,
                            &mut input.noise_state,
                        )
                        .await
                        {
                            warn!(?e, "Fatal error sending CBOR request");
                            return Err(e);
                        }
                    }
                }
            }
        };
    }
}

async fn connection_send(
    cbor_request: Vec<u8>,
    data_channel: &mut dyn PxpDataChannel,
    noise_state: &mut TunnelNoiseState,
) -> Result<(), PxpError> {
    debug!("Sending CBOR request");
    if cbor_request.len() > MAX_CBOR_SIZE {
        warn!(
            cbor_request_len = cbor_request.len(),
            "CBOR request too large"
        );
        return Err(PxpError::InvalidFraming);
    }
    trace!({ ?cbor_request, cbor_request_len = cbor_request.len() });

    send_tunnel_message(
        PxpTunnelMessageType::Ctap,
        &cbor_request,
        data_channel,
        noise_state,
    )
    .await
}

/// Pad, frame, encrypt and send one tunnel message. Shared by CTAP requests
/// and the Shutdown control message.
async fn send_tunnel_message(
    message_type: PxpTunnelMessageType,
    payload: &[u8],
    data_channel: &mut dyn PxpDataChannel,
    noise_state: &mut TunnelNoiseState,
) -> Result<(), PxpError> {
    let extra_bytes = PADDING_GRANULARITY - (payload.len() % PADDING_GRANULARITY);
    let padded_len = payload.len() + extra_bytes;

    let mut padded_payload = payload.to_vec();
    padded_payload.resize(padded_len, 0u8);
    if let Some(last) = padded_payload.last_mut() {
        *last = (extra_bytes - 1) as u8;
    }

    let frame = PxpTunnelMessage::new(message_type, &padded_payload);
    let frame_serialized = frame.to_vec();
    trace!(?frame_serialized);

    let mut encrypted_frame = vec![0u8; MAX_CBOR_SIZE + 1];
    match noise_state
        .transport_state
        .write_message(&frame_serialized, &mut encrypted_frame)
    {
        Ok(size) => {
            encrypted_frame.resize(size, 0u8);
        }
        Err(e) => {
            error!(?e, "Failed to encrypt frame");
            return Err(PxpError::EncryptionFailed);
        }
    }

    debug!("Sending encrypted frame");
    trace!(?encrypted_frame);

    data_channel.send(&encrypted_frame).await?;
    Ok(())
}

/// Strip the trailing padding-length byte and `padding_len` bytes of padding
/// from a decrypted Noise transport frame, returning `InvalidFraming` on an
/// empty plaintext or a declared padding length that exceeds the frame.
fn strip_frame_padding(mut decrypted_frame: Vec<u8>) -> Result<Vec<u8>, PxpError> {
    let padding_len = match decrypted_frame.last() {
        Some(&b) => b as usize,
        None => {
            warn!("Decrypted frame is empty; cannot read padding length");
            return Err(PxpError::InvalidFraming);
        }
    };
    let new_len = decrypted_frame
        .len()
        .checked_sub(padding_len + 1)
        .ok_or_else(|| {
            warn!(
                { frame_len = decrypted_frame.len(), padding_len },
                "Padding length exceeds frame length"
            );
            PxpError::InvalidFraming
        })?;
    decrypted_frame.truncate(new_len);
    Ok(decrypted_frame)
}

async fn decrypt_frame(
    encrypted_frame: Vec<u8>,
    noise_state: &mut TunnelNoiseState,
) -> Result<Vec<u8>, PxpError> {
    let mut decrypted_frame = vec![0u8; MAX_CBOR_SIZE];
    match noise_state
        .transport_state
        .read_message(&encrypted_frame, &mut decrypted_frame)
    {
        Ok(size) => {
            debug!(decrypted_frame_len = size, "Decrypted CBOR response");
            decrypted_frame.resize(size, 0u8);
            trace!(?decrypted_frame);
        }
        Err(e) => {
            warn!(?e, "Failed to decrypt CBOR response");
            return Err(PxpError::EncryptionFailed);
        }
    }

    let decrypted_frame = strip_frame_padding(decrypted_frame)?;
    trace!(
        { ?decrypted_frame, decrypted_frame_len = decrypted_frame.len() },
        "Trimmed padding"
    );

    Ok(decrypted_frame)
}

async fn connection_recv_initial(
    encrypted_frame: Vec<u8>,
    noise_state: &mut TunnelNoiseState,
) -> Result<Vec<u8>, PxpError> {
    let decrypted_frame = decrypt_frame(encrypted_frame, noise_state).await?;

    let initial_message: PxpInitialMessage = match cbor::from_slice(&decrypted_frame) {
        Ok(initial_message) => initial_message,
        Err(e) => {
            warn!(?e, "Failed to decode initial message");
            return Err(PxpError::InvalidFraming);
        }
    };

    if let Err(e) = cbor::from_slice::<GetInfoResponse>(&initial_message.info) {
        warn!(?e, "Failed to decode GetInfo response");
        return Err(PxpError::InvalidFraming);
    }

    debug!(?initial_message.supported_features, "Received post-handshake message");

    Ok(initial_message.info.to_vec())
}

async fn connection_recv_update(message: &[u8]) -> Result<Option<PxpLinkingInfo>, PxpError> {
    // TODO(#66): Android adds a 999-key to the end the message, which is not part of the standard.
    // For now, we parse the message to a map and manuually import fields.

    let update_message: BTreeMap<Value, Value> = match serde_cbor::from_slice(message) {
        Ok(update_message) => update_message,
        Err(e) => {
            warn!(?e, "Failed to decode update message");
            return Err(PxpError::InvalidFraming);
        }
    };

    let Some(Value::Map(linking_info_map)) = update_message.get(&Value::Integer(0x01)) else {
        warn!("Empty linking info map");
        return Ok(None);
    };

    trace!(?linking_info_map);

    let Some(Value::Bytes(contact_id)) = linking_info_map.get(&Value::Integer(0x01)) else {
        warn!("Missing contact ID");
        return Ok(None);
    };

    let Some(Value::Bytes(link_id)) = linking_info_map.get(&Value::Integer(0x02)) else {
        warn!("Missing link ID");
        return Ok(None);
    };

    let Some(Value::Bytes(link_secret)) = linking_info_map.get(&Value::Integer(0x03)) else {
        warn!("Missing link secret");
        return Ok(None);
    };

    let Some(Value::Bytes(authenticator_public_key)) = linking_info_map.get(&Value::Integer(0x04))
    else {
        warn!("Missing authenticator public key");
        return Ok(None);
    };

    let Some(Value::Text(authenticator_name)) = linking_info_map.get(&Value::Integer(0x05)) else {
        warn!("Missing authenticator name");
        return Ok(None);
    };

    let Some(Value::Bytes(handshake_signature)) = linking_info_map.get(&Value::Integer(0x06))
    else {
        warn!("Missing handshake_signature");
        return Ok(None);
    };

    let linking_info = PxpLinkingInfo {
        contact_id: contact_id.clone(),
        link_id: link_id.clone(),
        link_secret: link_secret.clone(),
        authenticator_public_key: authenticator_public_key.clone(),
        authenticator_name: authenticator_name.clone(),
        handshake_signature: handshake_signature.clone(),
    };

    Ok(Some(linking_info))
}

async fn connection_recv(
    connection_type: &PxpTunnelConnectionType,
    tunnel_domain: &str,
    known_device_store: &Option<Arc<dyn PxpKnownDeviceInfoStore>>,
    encrypted_frame: Vec<u8>,
    ctap_rx_send: &Sender<Vec<u8>>,
    noise_state: &mut TunnelNoiseState,
) -> Result<RecvOutcome, PxpError> {
    let decrypted_frame = decrypt_frame(encrypted_frame, noise_state).await?;

    let pxp_message: PxpTunnelMessage = PxpTunnelMessage::from_slice(&decrypted_frame)
        .inspect_err(|e| warn!(?e, "Failed to decode CABLE tunnel message"))?;

    trace!(?pxp_message);
    match pxp_message.message_type {
        PxpTunnelMessageType::Shutdown => {
            debug!("Peer sent Shutdown control message; closing connection cleanly");
            Ok(RecvOutcome::PeerShutdown)
        }
        PxpTunnelMessageType::Ctap => {
            debug!("Received CTAP response");
            trace!(?pxp_message.payload);
            ctap_rx_send
                .send(pxp_message.payload.into_vec())
                .await
                .or(Err(PxpError::ConnectionFailed))?;
            Ok(RecvOutcome::Continue)
        }
        PxpTunnelMessageType::Update => {
            // Malformed or unsigned update: log, drop the update, keep the channel.
            let maybe_update_message = match connection_recv_update(&pxp_message.payload).await {
                Ok(m) => m,
                Err(e) => {
                    warn!(?e, "Malformed update message; ignoring");
                    return Ok(RecvOutcome::Continue);
                }
            };

            let Some(linking_info) = maybe_update_message else {
                warn!("Ignoring update message without linking info");
                return Ok(RecvOutcome::Continue);
            };

            let PxpTunnelConnectionType::QrCode { private_key, .. } = connection_type else {
                warn!("Ignoring update message for non-QR code connection");
                return Ok(RecvOutcome::Continue);
            };

            debug!("Received update message with linking info");
            trace!(?linking_info);

            match known_device_store {
                Some(store) => {
                    apply_linking_update(
                        store,
                        private_key,
                        tunnel_domain,
                        &linking_info,
                        &noise_state.handshake_hash,
                    )
                    .await;
                }
                None => {
                    warn!("Ignoring update message without a device store");
                }
            };
            Ok(RecvOutcome::Continue)
        }
    }
}

/// Stores the update only on a valid signature; invalid updates are dropped without evicting.
async fn apply_linking_update(
    store: &Arc<dyn PxpKnownDeviceInfoStore>,
    private_key: &NonZeroScalar,
    tunnel_domain: &str,
    linking_info: &PxpLinkingInfo,
    handshake_hash: &[u8],
) {
    let device_id: PxpKnownDeviceId = linking_info.into();
    match parse_known_device(private_key, tunnel_domain, linking_info, handshake_hash) {
        Ok(known_device) => {
            debug!(?device_id, "Updating known device");
            trace!(?known_device);
            store.put_known_device(&device_id, &known_device).await;
        }
        Err(e) => {
            warn!(?e, "Ignoring invalid linking update from authenticator");
        }
    }
}

/// Validation requires a shared key computed on the QR code ephemeral identity key (private_key here).
/// We're currently unable to validate the signature on linking information received for state-assisted transactions,
/// so these should be discarded. This is the same Chrome currently does, although it may change in future spec versions.
/// See: https://github.com/chromium/chromium/blob/88e250200e59daf52554bcc74870138143a830c4/device/fido/cable/fido_tunnel_device.cc#L547-L549
fn parse_known_device(
    private_key: &NonZeroScalar,
    tunnel_domain: &str,
    linking_info: &PxpLinkingInfo,
    handshake_hash: &[u8],
) -> Result<PxpKnownDeviceInfo, PxpError> {
    let known_device = PxpKnownDeviceInfo::new(tunnel_domain, linking_info)?;
    let secret_key = SecretKey::from(private_key);

    let Ok(authenticator_public_key) =
        PublicKey::from_sec1_bytes(&linking_info.authenticator_public_key)
    else {
        warn!("Failed to parse public key");
        return Err(PxpError::InvalidKey);
    };

    let shared_secret: Vec<u8> = ecdh::diffie_hellman(
        secret_key.to_nonzero_scalar(),
        authenticator_public_key.as_affine(),
    )
    .raw_secret_bytes()
    .to_vec();

    let mut hmac =
        Hmac::<Sha256>::new_from_slice(&shared_secret).map_err(|_| PxpError::InvalidKey)?;
    hmac.update(handshake_hash);
    let expected_mac = hmac.finalize().into_bytes().to_vec();

    if expected_mac != linking_info.handshake_signature {
        warn!("Invalid handshake signature, rejecting update message");
        trace!({ ?expected_mac, ?linking_info.handshake_signature });
        return Err(PxpError::InvalidSignature);
    }

    debug!("Parsed known device with valid signature");
    Ok(known_device)
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::sync::Mutex;

    use async_trait::async_trait;
    use p256::elliptic_curve::sec1::ToEncodedPoint;
    use rand::rngs::OsRng;

    #[derive(Debug, Default)]
    struct RecordingStore {
        puts: Mutex<Vec<PxpKnownDeviceId>>,
        deletes: Mutex<Vec<PxpKnownDeviceId>>,
    }

    #[async_trait]
    impl PxpKnownDeviceInfoStore for RecordingStore {
        async fn put_known_device(
            &self,
            device_id: &PxpKnownDeviceId,
            _device: &PxpKnownDeviceInfo,
        ) {
            if let Ok(mut puts) = self.puts.lock() {
                puts.push(device_id.clone());
            }
        }
        async fn delete_known_device(&self, device_id: &PxpKnownDeviceId) {
            if let Ok(mut deletes) = self.deletes.lock() {
                deletes.push(device_id.clone());
            }
        }
    }

    fn linking_info_with_authenticator_key(authenticator_public_key: Vec<u8>) -> PxpLinkingInfo {
        PxpLinkingInfo {
            contact_id: vec![0u8; 4],
            link_id: vec![0u8; 8],
            link_secret: vec![0u8; 32],
            authenticator_public_key,
            authenticator_name: "alice's authenticator".to_string(),
            handshake_signature: vec![0xFFu8; 32],
        }
    }

    #[tokio::test]
    async fn invalid_signature_does_not_evict() {
        let client_private_key = NonZeroScalar::random(&mut OsRng);
        let authenticator_secret = SecretKey::random(&mut OsRng);
        let authenticator_public_key = authenticator_secret
            .public_key()
            .to_encoded_point(false)
            .as_bytes()
            .to_vec();

        let linking_info = linking_info_with_authenticator_key(authenticator_public_key);

        let recording = Arc::new(RecordingStore::default());
        let store: Arc<dyn PxpKnownDeviceInfoStore> = recording.clone();

        // Signature is intentionally bogus, so the update must be rejected.
        apply_linking_update(
            &store,
            &client_private_key,
            "example.com",
            &linking_info,
            &[0u8; 32],
        )
        .await;

        assert!(
            recording.deletes.lock().expect("deletes").is_empty(),
            "invalid update must not delete a known device"
        );
        assert!(
            recording.puts.lock().expect("puts").is_empty(),
            "invalid update must not store anything"
        );
    }

    /// A connected pair of Noise transport states, standing in for the
    /// desktop and the phone after the handshake.
    fn noise_pair() -> (TunnelNoiseState, TunnelNoiseState) {
        let params: snow::params::NoiseParams = "Noise_NN_P256_AESGCM_SHA256".parse().unwrap();
        let mut initiator = Builder::new(params.clone()).build_initiator().unwrap();
        let mut responder = Builder::new(params).build_responder().unwrap();
        let (mut buf, mut out) = ([0u8; 1024], [0u8; 1024]);
        let len = initiator.write_message(&[], &mut buf).unwrap();
        responder.read_message(&buf[..len], &mut out).unwrap();
        let len = responder.write_message(&[], &mut buf).unwrap();
        initiator.read_message(&buf[..len], &mut out).unwrap();
        let state = |hs: snow::HandshakeState| TunnelNoiseState {
            handshake_hash: hs.get_handshake_hash().to_vec(),
            transport_state: hs.into_transport_mode().unwrap(),
        };
        (state(initiator), state(responder))
    }

    #[derive(Default)]
    struct RecordingChannel {
        sent: Vec<Vec<u8>>,
    }

    #[async_trait]
    impl PxpDataChannel for RecordingChannel {
        async fn send(&mut self, message: &[u8]) -> Result<(), PxpError> {
            self.sent.push(message.to_vec());
            Ok(())
        }
        async fn recv(&mut self) -> Result<Option<Vec<u8>>, PxpError> {
            Ok(None)
        }
    }

    /// A data channel the test scripts: inbound messages come from `inbox`
    /// (closing it is the peer closing), outbound ones are recorded.
    struct ScriptedChannel {
        inbox: tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
        sent: Arc<Mutex<Vec<Vec<u8>>>>,
    }

    #[async_trait]
    impl PxpDataChannel for ScriptedChannel {
        async fn send(&mut self, message: &[u8]) -> Result<(), PxpError> {
            self.sent.lock().unwrap().push(message.to_vec());
            Ok(())
        }
        async fn recv(&mut self) -> Result<Option<Vec<u8>>, PxpError> {
            Ok(self.inbox.recv().await)
        }
    }

    /// The phone's post-handshake message: `{1: getInfo}` with a minimal
    /// getInfo (`{1: ["FIDO_2_0"], 3: aaguid}`), plus the zero-padding marker.
    fn initial_message_plaintext() -> Vec<u8> {
        let mut get_info = vec![0xA2, 0x01, 0x81, 0x68];
        get_info.extend_from_slice(b"FIDO_2_0");
        get_info.extend_from_slice(&[0x03, 0x50]);
        get_info.extend_from_slice(&[0u8; 16]);
        let mut initial = vec![0xA1, 0x01, 0x58, get_info.len() as u8];
        initial.extend_from_slice(&get_info);
        initial.push(0x00);
        initial
    }

    #[tokio::test]
    async fn closing_while_a_request_is_pending_sends_one_shutdown_and_ends_when_the_peer_closes() {
        let (desktop, mut phone) = noise_pair();
        let (inbox_tx, inbox) = tokio::sync::mpsc::unbounded_channel();
        let sent = Arc::new(Mutex::new(Vec::new()));
        let (ctap_tx, ctap_tx_recv) = tokio::sync::mpsc::channel(4);
        let (ctap_rx_send, _ctap_rx_recv) = tokio::sync::mpsc::channel(4);
        let (shutdown, shutdown_recv) = tokio::sync::oneshot::channel();
        let input = TunnelConnectionInput {
            connection_type: PxpTunnelConnectionType::QrCode {
                routing_id: "000000".into(),
                tunnel_id: "00".repeat(16),
                private_key: NonZeroScalar::random(&mut OsRng),
            },
            tunnel_domain: "cable.example.com".into(),
            known_device_store: None,
            data_channel: Box::new(ScriptedChannel {
                inbox,
                sent: Arc::clone(&sent),
            }),
            noise_state: desktop,
            ctap_tx_recv,
            ctap_rx_send,
            shutdown_recv,
        };
        let task = tokio::spawn(connection(input));

        // The phone says hello, the desktop sends a request, and the phone
        // is still working on it (a chooser or a fingerprint prompt).
        let mut frame = vec![0u8; 1024];
        let len = phone
            .transport_state
            .write_message(&initial_message_plaintext(), &mut frame)
            .unwrap();
        inbox_tx.send(frame[..len].to_vec()).unwrap();
        ctap_tx.send(vec![0x02]).await.unwrap();
        while sent.lock().unwrap().is_empty() {
            tokio::task::yield_now().await;
        }

        // The person cancels on the desktop.
        shutdown.send(()).unwrap();
        while sent.lock().unwrap().len() < 2 {
            tokio::task::yield_now().await;
        }
        assert!(!task.is_finished(), "waits for the phone to close first");
        drop(inbox_tx); // the phone closes its side
        assert!(task.await.unwrap().is_ok(), "a clean close, not an error");

        let frames = sent.lock().unwrap().clone();
        assert_eq!(frames.len(), 2, "the request, then exactly one more frame");
        let request = decrypt_frame(frames[0].clone(), &mut phone).await.unwrap();
        assert_eq!(request[0], PxpTunnelMessageType::Ctap as u8);
        let shutdown = decrypt_frame(frames[1].clone(), &mut phone).await.unwrap();
        assert_eq!(shutdown, vec![0u8], "the second frame is Shutdown");
    }

    #[test]
    fn a_bare_shutdown_parses_and_other_empty_messages_do_not() {
        let message = PxpTunnelMessage::from_slice(&[0]).unwrap();
        assert!(matches!(
            message.message_type,
            PxpTunnelMessageType::Shutdown
        ));
        assert!(matches!(
            PxpTunnelMessage::from_slice(&[1]),
            Err(PxpError::InvalidFraming)
        ));
        assert!(matches!(
            PxpTunnelMessage::from_slice(&[2]),
            Err(PxpError::InvalidFraming)
        ));
    }

    #[tokio::test]
    async fn shutdown_goes_on_the_wire_as_an_encrypted_padded_type_byte() {
        let (mut desktop, mut phone) = noise_pair();
        let mut channel = RecordingChannel::default();
        send_tunnel_message(
            PxpTunnelMessageType::Shutdown,
            &[],
            &mut channel,
            &mut desktop,
        )
        .await
        .unwrap();
        assert_eq!(channel.sent.len(), 1, "exactly one frame");
        let plaintext = decrypt_frame(channel.sent.remove(0), &mut phone)
            .await
            .unwrap();
        assert_eq!(plaintext, vec![0u8], "Shutdown is the type byte alone");
        let message = PxpTunnelMessage::from_slice(&plaintext).unwrap();
        assert!(matches!(
            message.message_type,
            PxpTunnelMessageType::Shutdown
        ));
    }

    #[tokio::test]
    async fn ctap_frames_still_round_trip_through_the_shared_path() {
        let (mut desktop, mut phone) = noise_pair();
        let mut channel = RecordingChannel::default();
        let payload = vec![0xA1, 0x01, 0x02];
        send_tunnel_message(
            PxpTunnelMessageType::Ctap,
            &payload,
            &mut channel,
            &mut desktop,
        )
        .await
        .unwrap();
        let plaintext = decrypt_frame(channel.sent.remove(0), &mut phone)
            .await
            .unwrap();
        assert_eq!(plaintext[0], PxpTunnelMessageType::Ctap as u8);
        assert_eq!(&plaintext[1..], payload.as_slice());
    }

    #[test]
    fn absent_supported_features_defaults_to_ctap() {
        let map = BTreeMap::from([(Value::Integer(1), Value::Bytes(vec![]))]);
        let bytes = cbor::to_vec(&map).unwrap();
        let message: PxpInitialMessage = cbor::from_slice(&bytes).unwrap();
        assert_eq!(message.supported_features.0, vec!["ctap"]);
    }

    #[test]
    fn strip_frame_padding_rejects_empty() {
        let result = strip_frame_padding(Vec::new());
        assert!(matches!(result, Err(PxpError::InvalidFraming)));
    }

    #[test]
    fn strip_frame_padding_rejects_overlong_padding() {
        // Length 1 + declared padding of 5 -> would require subtracting 6 from 1.
        let frame = vec![0x05u8];
        let result = strip_frame_padding(frame);
        assert!(matches!(result, Err(PxpError::InvalidFraming)));
    }

    #[test]
    fn strip_frame_padding_strips_normal_padding() {
        // 4 bytes of payload, 3 bytes of zero padding, then padding-length 3.
        let frame = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x00, 0x00, 0x00, 0x03];
        let stripped = strip_frame_padding(frame).unwrap();
        assert_eq!(stripped, vec![0xAA, 0xBB, 0xCC, 0xDD]);
    }
}