scp-platform 0.1.0-beta.1

Platform abstraction traits for SCP (Shared Context Protocol)
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
//! In-memory [`KeyCustody`] implementation for testing.
//!
//! Stores Ed25519 and X25519 keypairs in `HashMap`s indexed by opaque integer
//! handles. Supports optional seeded RNG for deterministic key generation.
//! See ADR-006 in `.docs/adrs/phase-1.md`.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use rand::{CryptoRng, RngCore, SeedableRng};
use sha2::Sha256;
use tokio::sync::Mutex;
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret};
use zeroize::Zeroizing;

use crate::error::PlatformError;
use crate::traits::{
    CustodyType, KeyCustody, KeyHandle, KeyType, PseudonymKeypair, PublicKey, SharedSecret,
    Signature,
};

/// Tracks what type of key material is stored for a given handle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StoredKeyType {
    Ed25519,
    X25519,
}

/// Internal key storage that holds both Ed25519 and X25519 private keys.
struct KeyStore {
    ed25519_keys: HashMap<u64, SigningKey>,
    x25519_keys: HashMap<u64, StaticSecret>,
    key_types: HashMap<u64, StoredKeyType>,
}

impl KeyStore {
    fn new() -> Self {
        Self {
            ed25519_keys: HashMap::new(),
            x25519_keys: HashMap::new(),
            key_types: HashMap::new(),
        }
    }

    /// Returns the stored key type for a handle, or an error if not found.
    fn lookup_type(&self, handle: KeyHandle) -> Result<StoredKeyType, PlatformError> {
        self.key_types
            .get(&handle.id())
            .copied()
            .ok_or(PlatformError::KeyNotFound)
    }
}

/// In-memory implementation of [`KeyCustody`] for testing and development.
///
/// Stores cryptographic key material in memory using `HashMap`s. Keys are
/// identified by opaque integer handles allocated by an atomic counter. This
/// implementation provides the same API surface as production hardware-backed
/// adapters (Secure Enclave, Android Keystore) but requires no platform
/// dependencies.
///
/// # Deterministic Testing
///
/// Use [`InMemoryKeyCustody::from_seed`] to create an instance with a seedable
/// RNG for reproducible test scenarios.
///
/// # Thread Safety
///
/// All mutable state is protected by a `tokio::sync::Mutex`, making this type
/// safe to share across async tasks.
///
/// See ADR-006 in `.docs/adrs/phase-1.md`.
pub struct InMemoryKeyCustody {
    store: Mutex<KeyStore>,
    rng: Mutex<Box<dyn RngCore + Send>>,
    next_id: AtomicU64,
}

/// A type-erased RNG that is both `RngCore` and `CryptoRng`.
///
/// Needed because `rand::rngs::StdRng` implements `CryptoRng` but we store
/// a `Box<dyn RngCore + Send>` for flexibility. This wrapper preserves the
/// `CryptoRng` marker for the seedable path while the non-seeded path uses
/// `rand::rngs::OsRng` (which is also `CryptoRng`).
struct CryptoRngWrapper<R: RngCore + CryptoRng + Send>(R);

impl<R: RngCore + CryptoRng + Send> RngCore for CryptoRngWrapper<R> {
    fn next_u32(&mut self) -> u32 {
        self.0.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.0.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.0.fill_bytes(dest);
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
        self.0.try_fill_bytes(dest)
    }
}

impl InMemoryKeyCustody {
    /// Creates a new in-memory key custody with a cryptographically secure RNG.
    #[must_use]
    pub fn new() -> Self {
        Self {
            store: Mutex::new(KeyStore::new()),
            rng: Mutex::new(Box::new(CryptoRngWrapper(rand::rngs::OsRng))),
            next_id: AtomicU64::new(1),
        }
    }

    /// Creates a new in-memory key custody with a deterministic RNG seeded by
    /// `seed`.
    ///
    /// Useful for reproducible test scenarios: the same seed always produces
    /// the same sequence of keys.
    #[must_use]
    pub fn from_seed(seed: u64) -> Self {
        let mut seed_bytes = [0u8; 32];
        seed_bytes[..8].copy_from_slice(&seed.to_le_bytes());
        let rng = rand::rngs::StdRng::from_seed(seed_bytes);
        Self {
            store: Mutex::new(KeyStore::new()),
            rng: Mutex::new(Box::new(CryptoRngWrapper(rng))),
            next_id: AtomicU64::new(1),
        }
    }

    /// Allocates the next key handle ID.
    fn next_handle(&self) -> KeyHandle {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        KeyHandle::new(id)
    }

    /// Imports an existing Ed25519 private key and returns a handle to it.
    ///
    /// This is used in tests where the signing key must match an externally
    /// provided key (e.g., the MLS group member's signing key for inner
    /// envelope signing in `open_envelope` tests).
    pub async fn import_ed25519_key(&self, private_key_bytes: &[u8; 32]) -> KeyHandle {
        let handle = self.next_handle();
        let signing_key = SigningKey::from_bytes(private_key_bytes);
        let mut store = self.store.lock().await;
        store.ed25519_keys.insert(handle.id(), signing_key);
        store.key_types.insert(handle.id(), StoredKeyType::Ed25519);
        handle
    }

    /// Exports a clone of the Ed25519 signing key for the given handle.
    ///
    /// Required by FFI bridges that need the raw `ed25519_dalek::SigningKey`
    /// for core governance functions (`propose_governance_action`,
    /// `approve_governance_proposal`, etc.) which take `&SigningKey` directly.
    ///
    /// # Errors
    ///
    /// Returns [`PlatformError::KeyNotFound`] if the handle is invalid.
    /// Returns [`PlatformError::WrongKeyType`] if the handle refers to an
    /// X25519 key.
    pub async fn export_ed25519_signing_key(
        &self,
        handle: &KeyHandle,
    ) -> Result<SigningKey, PlatformError> {
        let store = self.store.lock().await;
        let key_type = store.lookup_type(*handle)?;
        if key_type != StoredKeyType::Ed25519 {
            return Err(PlatformError::WrongKeyType {
                expected: KeyType::Ed25519,
                actual: KeyType::X25519,
            });
        }
        store
            .ed25519_keys
            .get(&handle.id())
            .cloned()
            .ok_or(PlatformError::KeyNotFound)
    }
}

impl Default for InMemoryKeyCustody {
    fn default() -> Self {
        Self::new()
    }
}

/// Salt for HKDF-SHA-256 pseudonym secret derivation (§9.10.4A).
#[allow(dead_code)] // Used by derive_pseudonym_secret, retained for future pseudonym wiring
const PSEUDONYM_SECRET_SALT: &[u8] = b"scp-pseudonym-secret-v1";

/// Derives a `pseudonym_secret` from Ed25519 private key bytes via HKDF-SHA-256.
///
/// ```text
/// pseudonym_secret = HKDF-SHA256(
///     ikm: ed25519_private_key_bytes,
///     salt: "scp-pseudonym-secret-v1",
///     info: "",
///     len: 32
/// )
/// ```
///
/// CRITICAL PRIVACY REQUIREMENT (§9.10.4A): Using public key bytes as the
/// HMAC key would be a membership enumeration oracle — anyone who knows a
/// member's public key could compute their pseudonym for any `context_id`
/// and check relay subscriptions. The `pseudonym_secret` is derived from
/// private key bytes, making it unknowable without the private key.
#[allow(dead_code)] // Retained for future pseudonym wiring
fn derive_pseudonym_secret(signing_key: &SigningKey) -> Zeroizing<[u8; 32]> {
    let hk = Hkdf::<Sha256>::new(Some(PSEUDONYM_SECRET_SALT), signing_key.as_bytes());
    let mut secret = Zeroizing::new([0u8; 32]);
    // HKDF-Expand with 32-byte output cannot fail (32 <= 255 * HashLen).
    assert!(
        hk.expand(b"", secret.as_mut()).is_ok(),
        "HKDF-Expand with 32-byte output is infallible"
    );
    secret
}

// Trait uses RPITIT with explicit `+ Send` bound; async fn in trait
// does not guarantee Send futures, so manual impl Future is required.
#[allow(clippy::manual_async_fn)]
impl KeyCustody for InMemoryKeyCustody {
    fn generate_keypair(
        &self,
        key_type: KeyType,
    ) -> impl Future<Output = Result<KeyHandle, PlatformError>> + Send {
        async move {
            let handle = self.next_handle();
            let mut key_bytes = Zeroizing::new([0u8; 32]);
            self.rng.lock().await.fill_bytes(key_bytes.as_mut());

            let mut store = self.store.lock().await;
            match key_type {
                KeyType::Ed25519 => {
                    let signing_key = SigningKey::from_bytes(&key_bytes);
                    store.ed25519_keys.insert(handle.id(), signing_key);
                    store.key_types.insert(handle.id(), StoredKeyType::Ed25519);
                }
                KeyType::X25519 => {
                    let secret = StaticSecret::from(*key_bytes);
                    store.x25519_keys.insert(handle.id(), secret);
                    store.key_types.insert(handle.id(), StoredKeyType::X25519);
                }
            }
            drop(store);

            Ok(handle)
        }
    }

    fn sign(
        &self,
        key: &KeyHandle,
        data: &[u8],
    ) -> impl Future<Output = Result<Signature, PlatformError>> + Send {
        let key_id = key.id();
        async move {
            let store = self.store.lock().await;
            let key_type = store.lookup_type(KeyHandle::new(key_id))?;

            if key_type != StoredKeyType::Ed25519 {
                return Err(PlatformError::WrongKeyType {
                    expected: KeyType::Ed25519,
                    actual: KeyType::X25519,
                });
            }

            let signing_key = store
                .ed25519_keys
                .get(&key_id)
                .ok_or(PlatformError::KeyNotFound)?;

            let signature = signing_key.sign(data);
            drop(store);
            Ok(Signature::new(signature.to_bytes().to_vec()))
        }
    }

    fn public_key(
        &self,
        key: &KeyHandle,
    ) -> impl Future<Output = Result<PublicKey, PlatformError>> + Send {
        let key_id = key.id();
        async move {
            let store = self.store.lock().await;
            let key_type = store.lookup_type(KeyHandle::new(key_id))?;

            let result = match key_type {
                StoredKeyType::Ed25519 => {
                    let signing_key = store
                        .ed25519_keys
                        .get(&key_id)
                        .ok_or(PlatformError::KeyNotFound)?;
                    let verifying_key: VerifyingKey = signing_key.verifying_key();
                    Ok(PublicKey::new(verifying_key.to_bytes().to_vec()))
                }
                StoredKeyType::X25519 => {
                    let secret = store
                        .x25519_keys
                        .get(&key_id)
                        .ok_or(PlatformError::KeyNotFound)?;
                    let public = X25519PublicKey::from(secret);
                    Ok(PublicKey::new(public.to_bytes().to_vec()))
                }
            };
            drop(store);
            result
        }
    }

    fn destroy_key(
        &self,
        key: &KeyHandle,
    ) -> impl Future<Output = Result<(), PlatformError>> + Send {
        let key_id = key.id();
        async move {
            let mut store = self.store.lock().await;
            let key_type = store.lookup_type(KeyHandle::new(key_id))?;

            match key_type {
                StoredKeyType::Ed25519 => {
                    store.ed25519_keys.remove(&key_id);
                }
                StoredKeyType::X25519 => {
                    store.x25519_keys.remove(&key_id);
                }
            }
            store.key_types.remove(&key_id);
            drop(store);

            Ok(())
        }
    }

    fn dh_agree(
        &self,
        key: &KeyHandle,
        peer_public: &[u8; 32],
    ) -> impl Future<Output = Result<SharedSecret, PlatformError>> + Send {
        let key_id = key.id();
        let peer = *peer_public;
        async move {
            let store = self.store.lock().await;
            let key_type = store.lookup_type(KeyHandle::new(key_id))?;

            if key_type != StoredKeyType::X25519 {
                return Err(PlatformError::WrongKeyType {
                    expected: KeyType::X25519,
                    actual: KeyType::Ed25519,
                });
            }

            let secret = store
                .x25519_keys
                .get(&key_id)
                .ok_or(PlatformError::KeyNotFound)?;

            let peer_key = X25519PublicKey::from(peer);
            let shared = secret.diffie_hellman(&peer_key);
            drop(store);
            let shared_bytes = Zeroizing::new(shared.to_bytes());
            Ok(SharedSecret::new(*shared_bytes))
        }
    }

    fn derive_pseudonym(
        &self,
        key: &KeyHandle,
        context_id: &[u8],
    ) -> impl Future<Output = Result<PseudonymKeypair, PlatformError>> + Send {
        let key_id = key.id();
        let context_id = context_id.to_vec();
        async move {
            let mut store = self.store.lock().await;
            let key_type = store.lookup_type(KeyHandle::new(key_id))?;

            if key_type != StoredKeyType::Ed25519 {
                return Err(PlatformError::WrongKeyType {
                    expected: KeyType::Ed25519,
                    actual: KeyType::X25519,
                });
            }

            let signing_key = store
                .ed25519_keys
                .get(&key_id)
                .ok_or(PlatformError::KeyNotFound)?;

            // HMAC-SHA256(ed25519_public_key_bytes, context_id || "scp-pseudonym")
            // ADR-027 amendment: uses verifying (public) key bytes, not signing
            // (private) key bytes, for cross-platform determinism with hardware
            // TEE adapters that cannot export private key material.
            let verifying_key = signing_key.verifying_key();
            let mut mac =
                <Hmac<Sha256> as Mac>::new_from_slice(verifying_key.to_bytes().as_slice())
                    .map_err(|e| PlatformError::CustodyError(e.to_string()))?;
            mac.update(&context_id);
            mac.update(b"scp-pseudonym");
            let hmac_output = mac.finalize().into_bytes();

            // Derive Ed25519 keypair from first 32 bytes of HMAC output.
            let mut seed = Zeroizing::new([0u8; 32]);
            seed.copy_from_slice(&hmac_output[..32]);
            let pseudonym_signing_key = SigningKey::from_bytes(&seed);
            let pseudonym_verifying_key = pseudonym_signing_key.verifying_key();

            // Store the derived signing key and return a handle.
            let handle = self.next_handle();
            store
                .ed25519_keys
                .insert(handle.id(), pseudonym_signing_key);
            store.key_types.insert(handle.id(), StoredKeyType::Ed25519);
            drop(store);

            Ok(PseudonymKeypair {
                public_key: PublicKey::new(pseudonym_verifying_key.to_bytes().to_vec()),
                key_handle: handle,
            })
        }
    }

    fn derive_rotatable_pseudonym(
        &self,
        key: &KeyHandle,
        context_id: &[u8],
        pseudonym_epoch: u64,
    ) -> impl Future<Output = Result<PseudonymKeypair, PlatformError>> + Send {
        let key_id = key.id();
        let context_id = context_id.to_vec();
        async move {
            let mut store = self.store.lock().await;
            let key_type = store.lookup_type(KeyHandle::new(key_id))?;

            if key_type != StoredKeyType::Ed25519 {
                return Err(PlatformError::WrongKeyType {
                    expected: KeyType::Ed25519,
                    actual: KeyType::X25519,
                });
            }

            let signing_key = store
                .ed25519_keys
                .get(&key_id)
                .ok_or(PlatformError::KeyNotFound)?;

            // HMAC-SHA256(ed25519_public_key_bytes, context_id || epoch_BE || "scp-pseudonym-v2")
            // ADR-027 amendment: uses verifying (public) key bytes, not signing
            // (private) key bytes, for cross-platform determinism with hardware
            // TEE adapters that cannot export private key material.
            // BLACK-001 mitigation: epoch_BE breaks long-term pseudonym correlation.
            let verifying_key = signing_key.verifying_key();
            let mut mac =
                <Hmac<Sha256> as Mac>::new_from_slice(verifying_key.to_bytes().as_slice())
                    .map_err(|e| PlatformError::CustodyError(e.to_string()))?;
            mac.update(&context_id);
            mac.update(&pseudonym_epoch.to_be_bytes());
            mac.update(b"scp-pseudonym-v2");
            let hmac_output = mac.finalize().into_bytes();

            // Derive Ed25519 keypair from first 32 bytes of HMAC output.
            let mut seed = Zeroizing::new([0u8; 32]);
            seed.copy_from_slice(&hmac_output[..32]);
            let pseudonym_signing_key = SigningKey::from_bytes(&seed);
            let pseudonym_verifying_key = pseudonym_signing_key.verifying_key();

            // Store the derived signing key and return a handle.
            let handle = self.next_handle();
            store
                .ed25519_keys
                .insert(handle.id(), pseudonym_signing_key);
            store.key_types.insert(handle.id(), StoredKeyType::Ed25519);
            drop(store);

            Ok(PseudonymKeypair {
                public_key: PublicKey::new(pseudonym_verifying_key.to_bytes().to_vec()),
                key_handle: handle,
            })
        }
    }

    fn custody_type(&self, _key: &KeyHandle) -> CustodyType {
        CustodyType::InMemory
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn generate_ed25519_keypair_returns_handle() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        assert!(handle.id() > 0);
    }

    #[tokio::test]
    async fn generate_x25519_keypair_returns_handle() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::X25519).await.unwrap();
        assert!(handle.id() > 0);
    }

    #[tokio::test]
    async fn sign_with_ed25519_key_succeeds() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let data = b"hello world";
        let sig = custody.sign(&handle, data).await.unwrap();
        assert_eq!(sig.as_bytes().len(), 64);
    }

    #[tokio::test]
    async fn sign_with_x25519_key_fails() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::X25519).await.unwrap();
        let result = custody.sign(&handle, b"data").await;
        assert!(result.is_err());
        match result.unwrap_err() {
            PlatformError::WrongKeyType { expected, actual } => {
                assert_eq!(expected, KeyType::Ed25519);
                assert_eq!(actual, KeyType::X25519);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn public_key_ed25519_returns_32_bytes() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let pubkey = custody.public_key(&handle).await.unwrap();
        assert_eq!(pubkey.as_bytes().len(), 32);
    }

    #[tokio::test]
    async fn public_key_x25519_returns_32_bytes() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::X25519).await.unwrap();
        let pubkey = custody.public_key(&handle).await.unwrap();
        assert_eq!(pubkey.as_bytes().len(), 32);
    }

    #[tokio::test]
    async fn destroy_key_makes_subsequent_operations_fail() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();

        // Key works before destruction.
        custody.sign(&handle, b"test").await.unwrap();

        // Destroy the key.
        custody.destroy_key(&handle).await.unwrap();

        // All operations should now fail.
        assert!(custody.sign(&handle, b"test").await.is_err());
        assert!(custody.public_key(&handle).await.is_err());
        assert!(custody.destroy_key(&handle).await.is_err());
    }

    #[tokio::test]
    async fn dh_agree_with_x25519_keys_produces_shared_secret() {
        let custody = InMemoryKeyCustody::new();

        let alice_handle = custody.generate_keypair(KeyType::X25519).await.unwrap();
        let bob_handle = custody.generate_keypair(KeyType::X25519).await.unwrap();

        let alice_pub = custody.public_key(&alice_handle).await.unwrap();
        let bob_pub = custody.public_key(&bob_handle).await.unwrap();

        let alice_bytes: [u8; 32] = alice_pub.as_bytes().try_into().unwrap();
        let bob_bytes: [u8; 32] = bob_pub.as_bytes().try_into().unwrap();

        let secret_ab = custody.dh_agree(&alice_handle, &bob_bytes).await.unwrap();
        let secret_ba = custody.dh_agree(&bob_handle, &alice_bytes).await.unwrap();

        // Both sides compute the same shared secret.
        assert_eq!(secret_ab.as_bytes(), secret_ba.as_bytes());
    }

    #[tokio::test]
    async fn dh_agree_with_ed25519_key_fails() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let peer = [0u8; 32];
        let result = custody.dh_agree(&handle, &peer).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            PlatformError::WrongKeyType { expected, actual } => {
                assert_eq!(expected, KeyType::X25519);
                assert_eq!(actual, KeyType::Ed25519);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn derive_pseudonym_is_deterministic() {
        let custody = InMemoryKeyCustody::from_seed(42);
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let context_id = b"test-context";

        let first = custody.derive_pseudonym(&handle, context_id).await.unwrap();
        let second = custody.derive_pseudonym(&handle, context_id).await.unwrap();

        // Same identity key + same context_id = same pseudonym public key.
        assert_eq!(first.public_key.as_bytes(), second.public_key.as_bytes());
    }

    #[tokio::test]
    async fn derive_pseudonym_different_contexts_produce_different_keys() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();

        let first = custody
            .derive_pseudonym(&handle, b"context-a")
            .await
            .unwrap();
        let second = custody
            .derive_pseudonym(&handle, b"context-b")
            .await
            .unwrap();

        // Different contexts produce different pseudonyms.
        assert_ne!(first.public_key.as_bytes(), second.public_key.as_bytes());
    }

    #[tokio::test]
    async fn derive_pseudonym_with_x25519_key_fails() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::X25519).await.unwrap();
        let result = custody.derive_pseudonym(&handle, b"ctx").await;
        assert!(result.is_err());
        match result.unwrap_err() {
            PlatformError::WrongKeyType { expected, actual } => {
                assert_eq!(expected, KeyType::Ed25519);
                assert_eq!(actual, KeyType::X25519);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn custody_type_always_returns_in_memory() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        assert_eq!(custody.custody_type(&handle), CustodyType::InMemory);
    }

    #[tokio::test]
    async fn sign_with_destroyed_key_returns_key_not_found() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        custody.destroy_key(&handle).await.unwrap();
        match custody.sign(&handle, b"data").await.unwrap_err() {
            PlatformError::KeyNotFound => {}
            other => panic!("expected KeyNotFound, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn sign_with_invalid_handle_returns_key_not_found() {
        let custody = InMemoryKeyCustody::new();
        let bogus = KeyHandle::new(9999);
        match custody.sign(&bogus, b"data").await.unwrap_err() {
            PlatformError::KeyNotFound => {}
            other => panic!("expected KeyNotFound, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn seeded_custody_produces_deterministic_keys() {
        let first = InMemoryKeyCustody::from_seed(12345);
        let second = InMemoryKeyCustody::from_seed(12345);

        let handle_first = first.generate_keypair(KeyType::Ed25519).await.unwrap();
        let handle_second = second.generate_keypair(KeyType::Ed25519).await.unwrap();

        let pk_first = first.public_key(&handle_first).await.unwrap();
        let pk_second = second.public_key(&handle_second).await.unwrap();

        assert_eq!(pk_first.as_bytes(), pk_second.as_bytes());
    }

    #[tokio::test]
    async fn ed25519_signature_verifies_correctly() {
        use ed25519_dalek::Verifier;

        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let data = b"important message";

        let sig = custody.sign(&handle, data).await.unwrap();
        let pubkey = custody.public_key(&handle).await.unwrap();

        let pk_bytes: [u8; 32] = pubkey.as_bytes().try_into().unwrap();
        let verifying_key = VerifyingKey::from_bytes(&pk_bytes).unwrap();
        let sig_bytes: [u8; 64] = sig.as_bytes().try_into().unwrap();
        let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);

        assert!(verifying_key.verify(data, &signature).is_ok());
    }

    #[tokio::test]
    async fn derive_pseudonym_key_handle_can_sign() {
        use ed25519_dalek::Verifier;

        let custody = InMemoryKeyCustody::new();
        let identity_handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let pseudonym = custody
            .derive_pseudonym(&identity_handle, b"context-1")
            .await
            .unwrap();

        let data = b"pseudonym signed message";
        let sig = custody.sign(&pseudonym.key_handle, data).await.unwrap();

        let pk_bytes: [u8; 32] = pseudonym.public_key.as_bytes().try_into().unwrap();
        let verifying_key = VerifyingKey::from_bytes(&pk_bytes).unwrap();
        let sig_bytes: [u8; 64] = sig.as_bytes().try_into().unwrap();
        let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);

        assert!(verifying_key.verify(data, &signature).is_ok());
    }

    #[tokio::test]
    async fn handles_are_unique_across_key_types() {
        let custody = InMemoryKeyCustody::new();
        let h1 = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let h2 = custody.generate_keypair(KeyType::X25519).await.unwrap();
        let h3 = custody.generate_keypair(KeyType::Ed25519).await.unwrap();

        assert_ne!(h1.id(), h2.id());
        assert_ne!(h2.id(), h3.id());
        assert_ne!(h1.id(), h3.id());
    }

    // -----------------------------------------------------------------------
    // derive_rotatable_pseudonym tests — BLACK-001 mitigation
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn derive_rotatable_pseudonym_is_deterministic() {
        let custody = InMemoryKeyCustody::from_seed(42);
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let context_id = b"test-context";

        let first = custody
            .derive_rotatable_pseudonym(&handle, context_id, 5)
            .await
            .unwrap();
        let second = custody
            .derive_rotatable_pseudonym(&handle, context_id, 5)
            .await
            .unwrap();

        assert_eq!(
            first.public_key.as_bytes(),
            second.public_key.as_bytes(),
            "same identity + context + epoch = same pseudonym"
        );
    }

    #[tokio::test]
    async fn derive_rotatable_pseudonym_different_epochs_produce_different_keys() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let context_id = b"test-context";

        let epoch0 = custody
            .derive_rotatable_pseudonym(&handle, context_id, 0)
            .await
            .unwrap();
        let epoch1 = custody
            .derive_rotatable_pseudonym(&handle, context_id, 1)
            .await
            .unwrap();

        assert_ne!(
            epoch0.public_key.as_bytes(),
            epoch1.public_key.as_bytes(),
            "different epochs must produce different pseudonyms (BLACK-001)"
        );
    }

    #[tokio::test]
    async fn derive_rotatable_pseudonym_differs_from_v1() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::Ed25519).await.unwrap();
        let context_id = b"test-context";

        let v1 = custody.derive_pseudonym(&handle, context_id).await.unwrap();
        let v2_epoch0 = custody
            .derive_rotatable_pseudonym(&handle, context_id, 0)
            .await
            .unwrap();

        assert_ne!(
            v1.public_key.as_bytes(),
            v2_epoch0.public_key.as_bytes(),
            "v2 epoch 0 must differ from v1 (different domain separator)"
        );
    }

    #[tokio::test]
    async fn derive_rotatable_pseudonym_with_x25519_key_fails() {
        let custody = InMemoryKeyCustody::new();
        let handle = custody.generate_keypair(KeyType::X25519).await.unwrap();
        let result = custody.derive_rotatable_pseudonym(&handle, b"ctx", 0).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            PlatformError::WrongKeyType { expected, actual } => {
                assert_eq!(expected, KeyType::Ed25519);
                assert_eq!(actual, KeyType::X25519);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn derive_rotatable_pseudonym_golden_vector() {
        // Known identity key seed: 0x00...01 (31 zeros, then 0x01).
        let seed_bytes: [u8; 32] = {
            let mut s = [0u8; 32];
            s[31] = 1;
            s
        };
        let context_id = b"test";
        let epoch: u64 = 7;

        // Compute expected pseudonym seed using the v2 reference algorithm:
        // seed = HMAC-SHA256(public_key_bytes, context_id || epoch_BE || "scp-pseudonym-v2")
        let identity_signing_key = SigningKey::from_bytes(&seed_bytes);
        let identity_public_key = identity_signing_key.verifying_key();
        let mut mac =
            Hmac::<Sha256>::new_from_slice(identity_public_key.to_bytes().as_slice()).unwrap();
        mac.update(context_id);
        mac.update(&epoch.to_be_bytes());
        mac.update(b"scp-pseudonym-v2");
        let expected_seed: [u8; 32] = mac.finalize().into_bytes().into();

        let expected_signing_key = SigningKey::from_bytes(&expected_seed);
        let expected_pubkey = expected_signing_key.verifying_key();

        let custody = InMemoryKeyCustody::new();
        let handle = custody.import_ed25519_key(&seed_bytes).await;

        let pseudo = custody
            .derive_rotatable_pseudonym(&handle, context_id, epoch)
            .await
            .unwrap();

        assert_eq!(
            pseudo.public_key.as_bytes(),
            expected_pubkey.as_bytes(),
            "v2 pseudonym must match reference HMAC-SHA256 algorithm output"
        );
    }

    /// Cross-platform golden-value test for pseudonym derivation.
    ///
    /// Verifies that `derive_pseudonym` is deterministic and that different
    /// context IDs produce different pseudonyms. The `expected_seed` value is
    /// computed from the reference HMAC-SHA256 algorithm using public key bytes
    /// as the HMAC key (ADR-027 amendment). This golden vector is authoritative
    /// for cross-language (Swift, Kotlin, TypeScript) verification.
    #[tokio::test]
    async fn derive_pseudonym_cross_platform_golden_vector() {
        // Known identity key seed: 0x00...01 (31 zeros, then 0x01).
        // This is a deterministic test key; never use in production.
        let seed_bytes: [u8; 32] = {
            let mut s = [0u8; 32];
            s[31] = 1;
            s
        };
        let context_id = b"test";

        // Compute expected pseudonym seed using the reference algorithm directly:
        // seed = HMAC-SHA256(public_key_bytes, context_id || "scp-pseudonym")
        // ADR-027 amendment: HMAC key is the Ed25519 PUBLIC key, not the private
        // key, for cross-platform determinism with hardware TEE adapters.
        let identity_signing_key = SigningKey::from_bytes(&seed_bytes);
        let identity_public_key = identity_signing_key.verifying_key();
        let mut mac =
            Hmac::<Sha256>::new_from_slice(identity_public_key.to_bytes().as_slice()).unwrap();
        mac.update(context_id);
        mac.update(b"scp-pseudonym");
        let expected_seed: [u8; 32] = mac.finalize().into_bytes().into();

        // Import the known seed as an Ed25519 signing key so derivation is
        // deterministic regardless of the RNG state.
        let custody = InMemoryKeyCustody::new();
        let handle = custody.import_ed25519_key(&seed_bytes).await;

        // Verify determinism across two calls with same inputs.
        let pseudo1 = custody.derive_pseudonym(&handle, context_id).await.unwrap();
        let pseudo2 = custody.derive_pseudonym(&handle, context_id).await.unwrap();
        assert_eq!(
            pseudo1.public_key.as_bytes(),
            pseudo2.public_key.as_bytes(),
            "pseudonym derivation must be deterministic for identical inputs"
        );

        let pseudo_other = custody
            .derive_pseudonym(&handle, b"other_context")
            .await
            .unwrap();
        assert_ne!(
            pseudo1.public_key.as_bytes(),
            pseudo_other.public_key.as_bytes(),
            "different context_id must produce different pseudonym"
        );

        // Assert that the implementation matches the reference algorithm.
        // expected_seed is HMAC-SHA256(sk, context_id || "scp-pseudonym"), so
        // the expected public key is the verifying key of the Ed25519 signing key
        // derived from that seed. This is the authoritative golden value —
        // Swift, Kotlin, and TypeScript implementations MUST produce the same
        // public key bytes for these inputs.
        let expected_signing_key = SigningKey::from_bytes(&expected_seed);
        let expected_pubkey = expected_signing_key.verifying_key();
        assert_eq!(
            pseudo1.public_key.as_bytes(),
            expected_pubkey.as_bytes(),
            "pseudonym public key must match reference HMAC-SHA256 algorithm output"
        );
    }
}