Skip to main content

auths_pairing_protocol/
response.rs

1use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
2use chrono::{DateTime, Utc};
3use p256::elliptic_curve::rand_core::OsRng;
4use p256::elliptic_curve::sec1::ToEncodedPoint;
5use serde::{Deserialize, Serialize};
6use zeroize::Zeroizing;
7
8use auths_crypto::{CurveType, TypedSeed};
9use auths_keri::KeriPublicKey;
10
11use crate::error::ProtocolError;
12use crate::token::PairingToken;
13
14/// A response to a pairing request from the responding device.
15///
16/// The `curve` field carries the device's signing curve in-band, so verifiers
17/// never infer curve from pubkey byte length (a silent-correctness hazard —
18/// see `docs/architecture/cryptography.md` → Wire-format Curve Tagging). The
19/// serialized value is `"ed25519"` or `"p256"`.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct PairingResponse {
22    pub short_code: String,
23    pub device_ephemeral_pubkey: String,
24    pub device_signing_pubkey: String,
25    /// Curve tag for `device_signing_pubkey` / `signature`. Absent → defaults to `P256`
26    /// per the approved Wire-format Curve Tagging rule.
27    #[serde(default)]
28    pub curve: CurveTag,
29    pub device_did: String,
30    pub signature: String,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub device_name: Option<String>,
33}
34
35/// Wire-format curve tag for the pairing response.
36///
37/// Serializes as lowercase `"ed25519"` / `"p256"`. Defaults to `P256` per the
38/// workspace-wide curve default.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(rename_all = "lowercase")]
42pub enum CurveTag {
43    Ed25519,
44    #[default]
45    P256,
46}
47
48impl From<CurveTag> for CurveType {
49    fn from(tag: CurveTag) -> Self {
50        match tag {
51            CurveTag::Ed25519 => CurveType::Ed25519,
52            CurveTag::P256 => CurveType::P256,
53        }
54    }
55}
56
57impl From<CurveType> for CurveTag {
58    fn from(curve: CurveType) -> Self {
59        match curve {
60            CurveType::Ed25519 => CurveTag::Ed25519,
61            CurveType::P256 => CurveTag::P256,
62        }
63    }
64}
65
66impl PairingResponse {
67    /// Create a new pairing response (responder side).
68    ///
69    /// The device's curve flows through the typed seed — no byte-length guessing.
70    /// The emitted `curve` field records the signer's curve so verifiers read it
71    /// off the wire instead of inferring from pubkey length.
72    ///
73    /// Args:
74    /// * `now` - Current time for expiry checking
75    /// * `token` - The pairing token from the initiating device
76    /// * `device_seed` - Typed signing seed (curve carried in-band)
77    /// * `device_pubkey` - The responding device's public key (length matches curve)
78    /// * `device_did` - The responding device's DID string
79    /// * `device_name` - Optional friendly name for the device
80    pub fn create(
81        now: DateTime<Utc>,
82        token: &PairingToken,
83        device_seed: &TypedSeed,
84        device_pubkey: &[u8],
85        device_did: String,
86        device_name: Option<String>,
87    ) -> Result<(Self, Zeroizing<[u8; 32]>), ProtocolError> {
88        if token.is_expired(now) {
89            return Err(ProtocolError::Expired);
90        }
91
92        let expected_len = device_seed.curve().public_key_len();
93        if device_pubkey.len() != expected_len {
94            return Err(ProtocolError::KeyExchangeFailed(format!(
95                "device_pubkey length {} does not match {} (expected {} bytes)",
96                device_pubkey.len(),
97                device_seed.curve(),
98                expected_len,
99            )));
100        }
101
102        let device_ecdh_secret = p256::ecdh::EphemeralSecret::random(&mut OsRng);
103        let device_ecdh_public = device_ecdh_secret.public_key();
104
105        let initiator_ecdh_bytes = token.ephemeral_pubkey_bytes()?;
106        let initiator_pk =
107            p256::PublicKey::from_sec1_bytes(&initiator_ecdh_bytes).map_err(|_| {
108                ProtocolError::KeyExchangeFailed(
109                    "Invalid initiator P-256 ephemeral pubkey (SEC1 decode failed)".to_string(),
110                )
111            })?;
112
113        let shared = device_ecdh_secret.diffie_hellman(&initiator_pk);
114        let shared_bytes: [u8; 32] =
115            shared
116                .raw_secret_bytes()
117                .as_slice()
118                .try_into()
119                .map_err(|_| {
120                    ProtocolError::KeyExchangeFailed("Shared secret not 32 bytes".to_string())
121                })?;
122        let shared_secret = Zeroizing::new(shared_bytes);
123
124        let device_signing_pubkey = URL_SAFE_NO_PAD.encode(device_pubkey);
125        let device_ecdh_pubkey_bytes = device_ecdh_public.to_encoded_point(true);
126        let device_ephemeral_pubkey_str =
127            URL_SAFE_NO_PAD.encode(device_ecdh_pubkey_bytes.as_bytes());
128
129        let mut message = Vec::new();
130        message.extend_from_slice(token.session_id.as_bytes());
131        message.extend_from_slice(token.short_code.as_bytes());
132        message.extend_from_slice(&initiator_ecdh_bytes);
133        message.extend_from_slice(device_ecdh_pubkey_bytes.as_bytes());
134
135        let sig_bytes = typed_sign_sync(device_seed, &message)?;
136        let signature = URL_SAFE_NO_PAD.encode(&sig_bytes);
137
138        let response = PairingResponse {
139            short_code: token.short_code.clone(),
140            device_ephemeral_pubkey: device_ephemeral_pubkey_str,
141            device_signing_pubkey,
142            curve: device_seed.curve().into(),
143            device_did,
144            signature,
145            device_name,
146        };
147
148        Ok((response, shared_secret))
149    }
150
151    /// Verify the response's signature using the curve tag carried on the wire.
152    ///
153    /// Curve dispatch reads `self.curve` directly — never inferred from pubkey
154    /// byte length. See `docs/architecture/cryptography.md` → Wire-format Curve
155    /// Tagging.
156    pub fn verify(&self, now: DateTime<Utc>, token: &PairingToken) -> Result<(), ProtocolError> {
157        if token.is_expired(now) {
158            return Err(ProtocolError::Expired);
159        }
160
161        let initiator_ecdh_bytes = token.ephemeral_pubkey_bytes()?;
162        let device_ecdh_bytes = self.device_ephemeral_pubkey_bytes()?;
163        let device_signing_bytes = self.device_signing_pubkey_bytes()?;
164        let signature_bytes = URL_SAFE_NO_PAD
165            .decode(&self.signature)
166            .map_err(|_| ProtocolError::InvalidSignature)?;
167
168        let mut message = Vec::new();
169        message.extend_from_slice(token.session_id.as_bytes());
170        message.extend_from_slice(token.short_code.as_bytes());
171        message.extend_from_slice(&initiator_ecdh_bytes);
172        message.extend_from_slice(&device_ecdh_bytes);
173
174        let key = build_keri_public_key(self.curve.into(), &device_signing_bytes)?;
175        key.verify_signature(&message, &signature_bytes)
176            .map_err(|_| ProtocolError::InvalidSignature)
177    }
178
179    /// Decode the device's ephemeral P-256 ECDH public key from base64url.
180    pub fn device_ephemeral_pubkey_bytes(&self) -> Result<Vec<u8>, ProtocolError> {
181        URL_SAFE_NO_PAD
182            .decode(&self.device_ephemeral_pubkey)
183            .map_err(|_| ProtocolError::InvalidSignature)
184    }
185
186    pub fn device_signing_pubkey_bytes(&self) -> Result<Vec<u8>, ProtocolError> {
187        URL_SAFE_NO_PAD
188            .decode(&self.device_signing_pubkey)
189            .map_err(|_| ProtocolError::InvalidSignature)
190    }
191}
192
193/// Build a typed `KeriPublicKey` from a curve tag + raw bytes. Rejects
194/// length/curve mismatches — this is the curve-aware replacement for
195/// `match bytes.len() { 32 => …, 33 => … }` at the pairing wire boundary.
196fn build_keri_public_key(curve: CurveType, bytes: &[u8]) -> Result<KeriPublicKey, ProtocolError> {
197    match curve {
198        CurveType::Ed25519 => {
199            let arr: [u8; 32] = bytes.try_into().map_err(|_| {
200                ProtocolError::KeyExchangeFailed(format!(
201                    "Ed25519 pubkey must be 32 bytes, got {}",
202                    bytes.len()
203                ))
204            })?;
205            Ok(KeriPublicKey::Ed25519(arr))
206        }
207        CurveType::P256 => {
208            let arr: [u8; 33] = bytes.try_into().map_err(|_| {
209                ProtocolError::KeyExchangeFailed(format!(
210                    "P-256 compressed pubkey must be 33 bytes, got {}",
211                    bytes.len()
212                ))
213            })?;
214            Ok(KeriPublicKey::P256 {
215                key: arr,
216                transferable: true,
217            })
218        }
219    }
220}
221
222/// Sign a message with a typed device seed (sync, no tokio).
223///
224/// Replaces the earlier `sign_ed25519_sync`: the curve travels with the
225/// `TypedSeed`, so the pairing response path is curve-agnostic end-to-end.
226fn typed_sign_sync(seed: &TypedSeed, message: &[u8]) -> Result<Vec<u8>, ProtocolError> {
227    auths_crypto::typed_sign(seed, message).map_err(|e| ProtocolError::KeyGenFailed(format!("{e}")))
228}
229
230/// Generate a fresh curve-defaulted (P-256) keypair for tests.
231///
232/// Tests that specifically exercise the Ed25519 branch construct their own
233/// `TypedSeed::Ed25519` explicitly.
234#[cfg(test)]
235fn generate_test_keypair() -> Result<(TypedSeed, Vec<u8>), ProtocolError> {
236    use p256::ecdsa::SigningKey;
237    use p256::elliptic_curve::rand_core::OsRng as P256Rng;
238    use p256::pkcs8::EncodePrivateKey;
239
240    let sk = SigningKey::random(&mut P256Rng);
241    #[allow(clippy::disallowed_methods)] // test-only keygen
242    let pkcs8 = sk
243        .to_pkcs8_der()
244        .map_err(|e| ProtocolError::KeyGenFailed(format!("{e}")))?;
245    let parsed = auths_crypto::parse_key_material(pkcs8.as_bytes())
246        .map_err(|e| ProtocolError::KeyGenFailed(format!("{e}")))?;
247    Ok((parsed.seed, parsed.public_key))
248}
249
250#[cfg(test)]
251#[allow(clippy::disallowed_methods)]
252mod tests {
253    use super::*;
254    use crate::token::PairingToken;
255
256    fn make_token() -> crate::token::PairingSession {
257        PairingToken::generate(
258            chrono::Utc::now(),
259            "did:keri:test123".to_string(),
260            "http://localhost:3000".to_string(),
261            vec!["sign_commit".to_string()],
262        )
263        .unwrap()
264    }
265
266    #[test]
267    fn test_create_and_verify_response_p256() {
268        let now = chrono::Utc::now();
269        let session = make_token();
270        let (seed, pubkey) = generate_test_keypair().unwrap();
271
272        let (response, _shared_secret) = PairingResponse::create(
273            now,
274            &session.token,
275            &seed,
276            &pubkey,
277            "did:key:zDnaTest".to_string(),
278            Some("Test Device".to_string()),
279        )
280        .unwrap();
281
282        assert_eq!(response.curve, CurveTag::P256);
283        assert!(response.verify(now, &session.token).is_ok());
284    }
285
286    #[test]
287    fn test_create_and_verify_response_ed25519() {
288        use ring::rand::SystemRandom;
289        use ring::signature::Ed25519KeyPair;
290
291        let now = chrono::Utc::now();
292        let session = make_token();
293        let rng = SystemRandom::new();
294        let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
295        let parsed = auths_crypto::parse_key_material(pkcs8.as_ref()).unwrap();
296
297        let (response, _shared_secret) = PairingResponse::create(
298            now,
299            &session.token,
300            &parsed.seed,
301            &parsed.public_key,
302            "did:key:z6MkTest".to_string(),
303            Some("Test Device".to_string()),
304        )
305        .unwrap();
306
307        assert_eq!(response.curve, CurveTag::Ed25519);
308        assert!(response.verify(now, &session.token).is_ok());
309    }
310
311    #[test]
312    fn test_expired_token_rejected() {
313        use chrono::Duration;
314
315        let now = chrono::Utc::now();
316        let session = PairingToken::generate_with_expiry(
317            now,
318            "did:keri:test".to_string(),
319            "http://localhost:3000".to_string(),
320            vec![],
321            Duration::seconds(-1),
322        )
323        .unwrap();
324        let (seed, pubkey) = generate_test_keypair().unwrap();
325
326        let result = PairingResponse::create(
327            now,
328            &session.token,
329            &seed,
330            &pubkey,
331            "did:key:zDnaTest".to_string(),
332            None,
333        );
334        assert!(matches!(result, Err(ProtocolError::Expired)));
335    }
336
337    #[test]
338    fn test_tampered_signature_rejected() {
339        let now = chrono::Utc::now();
340        let session = make_token();
341        let (seed, pubkey) = generate_test_keypair().unwrap();
342
343        let (mut response, _) = PairingResponse::create(
344            now,
345            &session.token,
346            &seed,
347            &pubkey,
348            "did:key:zDnaTest".to_string(),
349            None,
350        )
351        .unwrap();
352
353        let mut sig_bytes = URL_SAFE_NO_PAD.decode(&response.signature).unwrap();
354        sig_bytes[0] ^= 0xFF;
355        response.signature = URL_SAFE_NO_PAD.encode(&sig_bytes);
356
357        let result = response.verify(now, &session.token);
358        assert!(matches!(result, Err(ProtocolError::InvalidSignature)));
359    }
360
361    #[test]
362    fn test_curve_length_mismatch_rejected() {
363        // A P-256 seed paired with a 32-byte pubkey is a length/curve mismatch and
364        // must fail at emission time — the curve tag travels with the seed, so the
365        // check is local to `create()` and doesn't depend on wire parsing.
366        let now = chrono::Utc::now();
367        let session = make_token();
368        let (seed, _good_pubkey) = generate_test_keypair().unwrap();
369        let wrong_len_pubkey = vec![0u8; 32];
370
371        let result = PairingResponse::create(
372            now,
373            &session.token,
374            &seed,
375            &wrong_len_pubkey,
376            "did:key:zDnaTest".to_string(),
377            None,
378        );
379        assert!(matches!(result, Err(ProtocolError::KeyExchangeFailed(_))));
380    }
381
382    #[test]
383    fn test_shared_secret_matches() {
384        let now = chrono::Utc::now();
385        let mut session = make_token();
386        let (seed, pubkey) = generate_test_keypair().unwrap();
387
388        let (response, responder_secret) = PairingResponse::create(
389            now,
390            &session.token,
391            &seed,
392            &pubkey,
393            "did:key:zDnaTest".to_string(),
394            None,
395        )
396        .unwrap();
397
398        let device_ecdh_bytes = response.device_ephemeral_pubkey_bytes().unwrap();
399        let initiator_secret = session.complete_exchange(&device_ecdh_bytes).unwrap();
400
401        assert_eq!(*initiator_secret, *responder_secret);
402    }
403
404    #[test]
405    fn test_session_consumed_prevents_reuse() {
406        let now = chrono::Utc::now();
407        let mut session = make_token();
408        let (seed, pubkey) = generate_test_keypair().unwrap();
409
410        let (response, _) = PairingResponse::create(
411            now,
412            &session.token,
413            &seed,
414            &pubkey,
415            "did:key:zDnaTest".to_string(),
416            None,
417        )
418        .unwrap();
419
420        let device_ecdh_bytes = response.device_ephemeral_pubkey_bytes().unwrap();
421
422        assert!(session.complete_exchange(&device_ecdh_bytes).is_ok());
423
424        let result = session.complete_exchange(&device_ecdh_bytes);
425        assert!(matches!(result, Err(ProtocolError::SessionConsumed)));
426    }
427}