tightbeam-rs 0.9.0

A secure, high-performance messaging protocol library
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
//! Pluggable key backend abstraction for tightbeam transport encryption.
//!
//! This module provides the [`KeyProvider`] trait, which abstracts cryptographic
//! key operations to enable flexible backend integration (in-memory, HSM, KMS, enclave).
//!
//! The trait is algorithm-agnostic, using byte representations for all values.
//! Concrete implementations (e.g., [`InMemoryKeyProvider`]) handle algorithm-specific
//! encoding/decoding.

use core::fmt::Debug;

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(all(not(feature = "std"), any(feature = "signature", feature = "aead")))]
use alloc::{boxed::Box, sync::Arc, vec::Vec};

#[cfg(any(feature = "signature", feature = "aead"))]
use core::marker::PhantomData;

#[cfg(any(feature = "signature", feature = "aead"))]
use core::future::Future;
#[cfg(any(feature = "signature", feature = "aead"))]
use core::pin::Pin;
#[cfg(all(feature = "std", any(feature = "signature", feature = "aead")))]
use std::sync::Arc;

#[cfg(feature = "signature")]
mod signing {
	pub use crate::crypto::sign::ecdsa::{
		DigestPrimitive, Secp256k1, Secp256k1Signature, Secp256k1SigningKey, SignPrimitive, Signature, SignatureSize,
		SigningKey, VerifyPrimitive,
	};
	pub use crate::crypto::sign::elliptic_curve::generic_array::{ArrayLength, GenericArray};
	pub use crate::crypto::sign::elliptic_curve::ops::{Invert, Reduce};
	pub use crate::crypto::sign::elliptic_curve::point::PointCompression;
	pub use crate::crypto::sign::elliptic_curve::scalar::Scalar;
	pub use crate::crypto::sign::elliptic_curve::sec1::ModulusSize;
	pub use crate::crypto::sign::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
	pub use crate::crypto::sign::elliptic_curve::subtle::CtOption;
	pub use crate::crypto::sign::elliptic_curve::{
		AffinePoint, CurveArithmetic, Error as EllipticCurveError, FieldBytesSize, PrimeCurve,
	};
	pub use crate::crypto::sign::{
		Error as SignatureError, Keypair, PrehashSigner, SignatureAlgorithmIdentifier, SignatureEncoding,
	};

	#[cfg(feature = "ecdh")]
	pub use crate::crypto::sign::elliptic_curve::ecdh::diffie_hellman;
	#[cfg(feature = "ecdh")]
	pub use crate::crypto::sign::elliptic_curve::PublicKey;
}

#[cfg(feature = "signature")]
use signing::*;

#[cfg(feature = "aead")]
mod encryption {
	pub use crate::crypto::aead::{
		Aead, AeadCore, Aes128Gcm, Aes128GcmOid, Aes256Gcm, Aes256GcmOid, Error as AeadError, Nonce,
	};
	pub use crate::crypto::common::typenum::Unsigned;
}

#[cfg(feature = "aead")]
use encryption::*;

#[cfg(any(feature = "signature", feature = "aead"))]
mod common {
	pub use crate::der::oid::AssociatedOid;
	pub use crate::spki::AlgorithmIdentifierOwned;

	#[cfg(feature = "signature")]
	pub use crate::spki::EncodePublicKey;
}

#[cfg(any(feature = "signature", feature = "aead"))]
use common::*;

#[cfg(feature = "signature")]
use crate::crypto::secret::SecretSlice;

// =============================================================================
// KeyError
// =============================================================================

/// Errors from key provider operations.
///
/// Deliberately does not derive `Errorizable`: this module builds without
/// the `derive` feature, so the message strings live in exactly one place --
/// the `impl_error_display!` block below.
#[derive(Debug)]
pub enum KeyError {
	/// SPKI encoding/decoding error
	SpkiError(crate::spki::Error),

	/// Elliptic curve operation error
	#[cfg(feature = "signature")]
	EllipticCurveError(EllipticCurveError),

	/// Signature/ECDSA error (e.g., invalid key bytes)
	#[cfg(feature = "signature")]
	SignatureError(SignatureError),

	/// AEAD encryption/decryption error
	#[cfg(feature = "aead")]
	AeadError(AeadError),

	/// Nonce length mismatch
	#[cfg(feature = "aead")]
	NonceLengthError(crate::error::ReceivedExpectedError<usize, usize>),

	/// Operation not supported by this key provider
	UnsupportedOperation,
}

crate::impl_error_display!(unconditional KeyError {
	SpkiError(e) => "SPKI error: {e}",
	#[cfg(feature = "signature")]
	EllipticCurveError(e) => "Elliptic curve error: {e}",
	#[cfg(feature = "signature")]
	SignatureError(e) => "Signature error: {e}",
	#[cfg(feature = "aead")]
	AeadError(e) => "AEAD error: {e}",
	#[cfg(feature = "aead")]
	NonceLengthError(e) => "Nonce length mismatch: {e}",
	UnsupportedOperation => "Operation not supported by this key provider",
});

crate::impl_from!(crate::spki::Error => KeyError::SpkiError);
crate::impl_from!(#[cfg(feature = "signature")] EllipticCurveError => KeyError::EllipticCurveError);
crate::impl_from!(#[cfg(feature = "signature")] SignatureError => KeyError::SignatureError);
crate::impl_from!(#[cfg(feature = "aead")] AeadError => KeyError::AeadError);

/// Specification for providing a cryptographic signing key in various formats.
///
/// This enum allows keys to be specified in multiple ways for flexible
/// configuration in const contexts (e.g., servlet! macro).
#[cfg(feature = "signature")]
#[derive(Debug, Clone)]
pub enum SigningKeySpec {
	/// Raw key bytes (e.g., secp256k1 scalar - 32 bytes)
	Bytes(&'static [u8]),

	/// Key provider instance (for HSM/KMS)
	Provider(Arc<dyn SigningKeyProvider>),
}

#[cfg(feature = "signature")]
impl SigningKeySpec {
	/// Convert this key specification to a key provider for the given ECDSA curve.
	///
	/// For `KeySpec::Bytes`, constructs an ECDSA signing key from the raw bytes
	/// and wraps it in an `InMemoryKeyProvider`. For `KeySpec::Provider`, returns
	/// a clone of the existing provider Arc.
	///
	/// # Type Parameters
	///
	/// * `C` - The elliptic curve type (e.g., `k256::Secp256k1`)
	pub fn to_provider<C>(&self) -> Result<Arc<dyn SigningKeyProvider>, KeyError>
	where
		C: PrimeCurve + CurveArithmetic + DigestPrimitive + PointCompression + AssociatedOid + Send + Sync + 'static,
		Scalar<C>: Invert<Output = CtOption<Scalar<C>>> + SignPrimitive<C> + Reduce<C::Uint>,
		SignatureSize<C>: ArrayLength<u8>,
		FieldBytesSize<C>: ModulusSize,
		AffinePoint<C>: VerifyPrimitive<C> + FromEncodedPoint<C> + ToEncodedPoint<C>,
		SigningKey<C>: PrehashSigner<Signature<C>> + Keypair + Send + Sync + Debug + 'static,
		<SigningKey<C> as Keypair>::VerifyingKey: EncodePublicKey,
		Signature<C>: SignatureEncoding + SignatureAlgorithmIdentifier + Send + Sync + 'static,
	{
		match self {
			SigningKeySpec::Bytes(bytes) => {
				let field_bytes = GenericArray::from_slice(bytes);
				let signing_key = SigningKey::<C>::from_bytes(field_bytes)?;
				Ok(Arc::new(EcdsaKeyProvider::from(signing_key)))
			}
			SigningKeySpec::Provider(provider) => Ok(Arc::clone(provider)),
		}
	}
}

/// Trait for pluggable cryptographic key backends.
///
/// Implementations of this trait provide access to private key operations
/// (key agreement, signing) without exposing the raw key material. This
/// enables integration with Hardware Security Modules (HSMs), Key Management
/// Services (KMS), and secure enclaves where private keys cannot leave the
/// secure boundary.
///
/// # Security Properties
///
/// - **Key Encapsulation**: Private keys never leave the provider boundary
/// - **Uniform Interface**: In-memory and remote backends use identical APIs
/// - **Async by Default**: All operations async for maximum flexibility
/// - **Algorithm Agnostic**: Byte encoding allows any signature/key algorithm
#[cfg(feature = "signature")]
pub trait SigningKeyProvider: Send + Sync + Debug {
	/// Returns the algorithm identifier for this key.
	fn algorithm(&self) -> AlgorithmIdentifierOwned;

	/// Returns the public key as DER-encoded bytes.
	///
	/// # Errors
	///
	/// Returns [`KeyError`] if the backend cannot retrieve the public key.
	fn to_public_key_bytes(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>>;

	/// Signs a precomputed digest (prehash) using this provider's private key.
	///
	/// The canonical tightbeam convention hashes content exactly once (see
	/// `crypto::sign::sign_canonical`); providers MUST sign the given prehash
	/// directly and MUST NOT rehash it, so the produced signature matches the
	/// advertised signature-algorithm OID regardless of backend.
	///
	/// # Arguments
	///
	/// * `prehash` - The digest of the content to sign
	///
	/// # Returns
	///
	/// DER-encoded signature bytes.
	fn sign_prehash(&self, prehash: &[u8]) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>>;

	/// Performs key agreement (ECDH, X25519, etc).
	///
	/// Computes a shared secret from this provider's private key and the peer's
	/// public key. The shared secret is used for session key derivation.
	///
	/// # Arguments
	///
	/// * `peer_public_key` - The peer's public key bytes (SEC1 or DER encoded)
	///
	/// # Returns
	///
	/// The computed shared secret, wrapped in [`SecretSlice`] so it is
	/// zeroized on drop (CWE-212).
	///
	/// # Default
	///
	/// Returns `UnsupportedOperation` - not all key types support key agreement.
	fn key_agreement(
		&self,
		_peer_public_key: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<SecretSlice<u8>, KeyError>> + Send + '_>> {
		Box::pin(async { Err(KeyError::UnsupportedOperation) })
	}
}

/// In-memory key provider generic over any RustCrypto signing key.
///
/// This is the reference implementation for [`KeyProvider`], storing the private
/// key directly in memory. Suitable for development, testing, and applications
/// where HSM/KMS integration is not required.
///
/// # Type Parameters
///
/// * `K` - The signing key type (e.g., `Secp256k1SigningKey`, `Ed25519SigningKey`)
/// * `S` - The signature type produced by `K`
///
/// # Security
///
/// For zeroization on drop, use keys that implement `ZeroizeOnDrop`
/// (e.g., k256's `SigningKey`).
#[cfg(feature = "signature")]
pub struct InMemorySigningKeyProvider<K, S>
where
	K: PrehashSigner<S> + Keypair,
	S: SignatureEncoding,
{
	signing_key: K,
	_sig: PhantomData<S>,
}

#[cfg(feature = "signature")]
impl<K, S> From<K> for InMemorySigningKeyProvider<K, S>
where
	K: PrehashSigner<S> + Keypair,
	S: SignatureEncoding,
{
	fn from(signing_key: K) -> Self {
		InMemorySigningKeyProvider { signing_key, _sig: PhantomData }
	}
}

#[cfg(feature = "signature")]
impl<K, S> Debug for InMemorySigningKeyProvider<K, S>
where
	K: PrehashSigner<S> + Keypair + Debug,
	S: SignatureEncoding,
{
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("InMemoryKeyProvider")
			.field("signing_key", &self.signing_key)
			.finish()
	}
}

#[cfg(feature = "signature")]
impl<K, S> SigningKeyProvider for InMemorySigningKeyProvider<K, S>
where
	K: PrehashSigner<S> + Keypair + Send + Sync + Debug + 'static,
	K::VerifyingKey: EncodePublicKey,
	S: SignatureEncoding + SignatureAlgorithmIdentifier + Send + Sync + 'static,
{
	fn algorithm(&self) -> AlgorithmIdentifierOwned {
		AlgorithmIdentifierOwned { oid: S::ALGORITHM_OID, parameters: None }
	}

	fn to_public_key_bytes(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		let result = self
			.signing_key
			.verifying_key()
			.to_public_key_der()
			.map(|der| der.into_vec())
			.map_err(KeyError::from);

		Box::pin(async move { result })
	}

	fn sign_prehash(&self, prehash: &[u8]) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		let result = self
			.signing_key
			.sign_prehash(prehash)
			.map(|signature: S| signature.to_bytes().as_ref().to_vec())
			.map_err(KeyError::from);

		Box::pin(async move { result })
	}
}

// Implement KeyProvider for Arc<InMemoryKeyProvider<K, S>> for convenience
#[cfg(feature = "signature")]
impl<K, S> SigningKeyProvider for Arc<InMemorySigningKeyProvider<K, S>>
where
	K: PrehashSigner<S> + Keypair + Send + Sync + Debug + 'static,
	K::VerifyingKey: EncodePublicKey,
	S: SignatureEncoding + SignatureAlgorithmIdentifier + Send + Sync + 'static,
{
	fn algorithm(&self) -> AlgorithmIdentifierOwned {
		self.as_ref().algorithm()
	}

	fn to_public_key_bytes(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		self.as_ref().to_public_key_bytes()
	}

	fn sign_prehash(&self, prehash: &[u8]) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		self.as_ref().sign_prehash(prehash)
	}
}

/// Type alias for secp256k1 key provider (signing only, no ECDH)
#[cfg(all(feature = "signature", feature = "secp256k1"))]
pub type Secp256k1Provider = InMemorySigningKeyProvider<Secp256k1SigningKey, Secp256k1Signature>;

// ============================================================================
// ECDSA Key Provider with ECDH Support (Generic)
// ============================================================================

/// Generic ECDSA key provider with signing and key agreement (ECDH) support.
///
/// This provider wraps an ECDSA signing key for any curve `C` and provides both
/// signing and ECDH operations. This is the recommended provider for TLS handshakes.
///
/// # Type Parameters
///
/// * `C` - The elliptic curve type (e.g., `k256::Secp256k1`, `p256::NistP256`)
#[cfg(all(feature = "signature", feature = "secp256k1"))]
pub struct EcdsaKeyProvider<C>
where
	C: PrimeCurve + CurveArithmetic,
	Scalar<C>: Invert<Output = CtOption<Scalar<C>>> + SignPrimitive<C>,
	SignatureSize<C>: ArrayLength<u8>,
{
	signing_key: SigningKey<C>,
}

#[cfg(all(feature = "signature", feature = "secp256k1"))]
impl<C> From<SigningKey<C>> for EcdsaKeyProvider<C>
where
	C: PrimeCurve + CurveArithmetic,
	Scalar<C>: Invert<Output = CtOption<Scalar<C>>> + SignPrimitive<C>,
	SignatureSize<C>: ArrayLength<u8>,
{
	fn from(signing_key: SigningKey<C>) -> Self {
		EcdsaKeyProvider { signing_key }
	}
}

#[cfg(all(feature = "signature", feature = "secp256k1"))]
impl<C> Debug for EcdsaKeyProvider<C>
where
	C: PrimeCurve + CurveArithmetic,
	Scalar<C>: Invert<Output = CtOption<Scalar<C>>> + SignPrimitive<C>,
	SignatureSize<C>: ArrayLength<u8>,
{
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("EcdsaKeyProvider")
			.field("curve", &core::any::type_name::<C>())
			.finish_non_exhaustive()
	}
}

#[cfg(all(feature = "signature", feature = "secp256k1"))]
impl<C> SigningKeyProvider for EcdsaKeyProvider<C>
where
	C: PrimeCurve + CurveArithmetic + DigestPrimitive + PointCompression + AssociatedOid + Send + Sync + 'static,
	Scalar<C>: Invert<Output = CtOption<Scalar<C>>> + SignPrimitive<C> + Reduce<C::Uint>,
	SignatureSize<C>: ArrayLength<u8>,
	FieldBytesSize<C>: ModulusSize,
	AffinePoint<C>: VerifyPrimitive<C> + FromEncodedPoint<C> + ToEncodedPoint<C>,
	SigningKey<C>: PrehashSigner<Signature<C>> + Keypair + Send + Sync + Debug,
	<SigningKey<C> as Keypair>::VerifyingKey: EncodePublicKey,
	Signature<C>: SignatureEncoding + SignatureAlgorithmIdentifier + Send + Sync,
{
	fn algorithm(&self) -> AlgorithmIdentifierOwned {
		AlgorithmIdentifierOwned { oid: Signature::<C>::ALGORITHM_OID, parameters: None }
	}

	fn to_public_key_bytes(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		let result = self
			.signing_key
			.verifying_key()
			.to_public_key_der()
			.map(|der| der.into_vec())
			.map_err(KeyError::from);

		Box::pin(async move { result })
	}

	fn sign_prehash(&self, prehash: &[u8]) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		let result = self
			.signing_key
			.sign_prehash(prehash)
			.map(|signature: Signature<C>| signature.to_bytes().as_ref().to_vec())
			.map_err(KeyError::from);

		Box::pin(async move { result })
	}

	#[cfg(feature = "ecdh")]
	fn key_agreement(
		&self,
		peer_public_key: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<SecretSlice<u8>, KeyError>> + Send + '_>> {
		let pk_result = PublicKey::<C>::from_sec1_bytes(peer_public_key);
		let secret_key = *self.signing_key.as_nonzero_scalar();

		Box::pin(async move {
			let pk = pk_result?;
			let shared_secret = diffie_hellman(secret_key, pk.as_affine());

			Ok(SecretSlice::from(shared_secret.raw_secret_bytes().to_vec()))
		})
	}
}

#[cfg(all(feature = "signature", feature = "secp256k1"))]
impl<C> SigningKeyProvider for Arc<EcdsaKeyProvider<C>>
where
	C: PrimeCurve + CurveArithmetic + DigestPrimitive + PointCompression + AssociatedOid + Send + Sync + 'static,
	Scalar<C>: Invert<Output = CtOption<Scalar<C>>> + SignPrimitive<C> + Reduce<C::Uint>,
	SignatureSize<C>: ArrayLength<u8>,
	FieldBytesSize<C>: ModulusSize,
	AffinePoint<C>: VerifyPrimitive<C> + FromEncodedPoint<C> + ToEncodedPoint<C>,
	SigningKey<C>: PrehashSigner<Signature<C>> + Keypair + Send + Sync + Debug,
	<SigningKey<C> as Keypair>::VerifyingKey: EncodePublicKey,
	Signature<C>: SignatureEncoding + SignatureAlgorithmIdentifier + Send + Sync,
{
	fn algorithm(&self) -> AlgorithmIdentifierOwned {
		self.as_ref().algorithm()
	}

	fn to_public_key_bytes(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		self.as_ref().to_public_key_bytes()
	}

	fn sign_prehash(&self, prehash: &[u8]) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		self.as_ref().sign_prehash(prehash)
	}

	fn key_agreement(
		&self,
		peer_public_key: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<SecretSlice<u8>, KeyError>> + Send + '_>> {
		self.as_ref().key_agreement(peer_public_key)
	}
}

/// Type alias for secp256k1-specific ECDSA key provider with ECDH
#[cfg(feature = "signature")]
pub type Secp256k1KeyProvider = EcdsaKeyProvider<Secp256k1>;

// ============================================================================
// EncryptingKeyProvider Trait
// ============================================================================

/// Trait for pluggable symmetric encryption key backends.
///
/// Implementations of this trait provide access to symmetric encryption
/// and decryption operations without exposing the raw key material. This
/// enables integration with Hardware Security Modules (HSMs), Key Management
/// Services (KMS), and secure enclaves where encryption keys cannot leave the
/// secure boundary.
///
/// # Security Properties
///
/// - **Key Encapsulation**: Encryption keys never leave the provider boundary
/// - **Uniform Interface**: In-memory and remote backends use identical APIs
/// - **Async by Default**: All operations async for maximum flexibility
/// - **Algorithm Agnostic**: Byte encoding allows any AEAD cipher
#[cfg(feature = "aead")]
pub trait EncryptingKeyProvider: Send + Sync + Debug {
	/// Returns the algorithm identifier for this encryption key.
	fn algorithm(&self) -> AlgorithmIdentifierOwned;

	/// Encrypts plaintext using the provided nonce.
	///
	/// # Arguments
	///
	/// * `nonce` - The nonce/IV for this encryption operation. The caller MUST
	///   ensure the `(key, nonce)` pair is never reused for AEAD ciphers.
	/// * `plaintext` - The data to encrypt
	///
	/// # Returns
	///
	/// Encrypted ciphertext bytes (includes authentication tag for AEAD ciphers).
	fn encrypt(
		&self,
		nonce: &[u8],
		plaintext: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>>;

	/// Decrypts ciphertext using the provided nonce.
	///
	/// # Arguments
	///
	/// * `nonce` - The nonce/IV used for encryption
	/// * `ciphertext` - The encrypted data to decrypt
	///
	/// # Returns
	///
	/// Decrypted plaintext bytes.
	fn decrypt(
		&self,
		nonce: &[u8],
		ciphertext: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>>;
}

// =============================================================================
// InMemoryEncryptingKeyProvider
// =============================================================================

/// In-memory encryption key provider generic over any RustCrypto AEAD cipher.
///
/// This is the reference implementation for [`EncryptingKeyProvider`], storing the
/// encryption key directly in memory. Suitable for development, testing, and applications
/// where HSM/KMS integration is not required.
///
/// # Type Parameters
///
/// * `A` - The AEAD cipher type (e.g., `Aes256Gcm`, `Aes128Gcm`)
/// * `O` - The OID type associated with this cipher (e.g., `Aes256GcmOid`)
///
/// # Security
///
/// For zeroization on drop, use keys that implement `ZeroizeOnDrop`.
#[cfg(feature = "aead")]
pub struct InMemoryEncryptingKeyProvider<A, O>
where
	A: Aead + Send + Sync + 'static,
	O: AssociatedOid + Send + Sync,
{
	cipher: A,
	_oid: PhantomData<O>,
}

#[cfg(feature = "aead")]
impl<A, O> From<A> for InMemoryEncryptingKeyProvider<A, O>
where
	A: Aead + Send + Sync + 'static,
	O: AssociatedOid + Send + Sync,
{
	fn from(cipher: A) -> Self {
		InMemoryEncryptingKeyProvider { cipher, _oid: PhantomData }
	}
}

#[cfg(feature = "aead")]
impl<A, O> Debug for InMemoryEncryptingKeyProvider<A, O>
where
	A: Aead + Send + Sync + 'static,
	O: AssociatedOid + Send + Sync,
{
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("InMemoryEncryptingKeyProvider")
			.field("algorithm", &O::OID)
			.finish_non_exhaustive()
	}
}

#[cfg(feature = "aead")]
impl<A, O> EncryptingKeyProvider for InMemoryEncryptingKeyProvider<A, O>
where
	A: Aead + Send + Sync + 'static,
	O: AssociatedOid + Send + Sync,
{
	fn algorithm(&self) -> AlgorithmIdentifierOwned {
		AlgorithmIdentifierOwned { oid: O::OID, parameters: None }
	}

	fn encrypt(
		&self,
		nonce: &[u8],
		plaintext: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		let nonce_size = <<A as AeadCore>::NonceSize as Unsigned>::USIZE;
		let received_len = nonce.len();
		if received_len != nonce_size {
			return Box::pin(async move {
				Err(KeyError::NonceLengthError(crate::error::ReceivedExpectedError::from((
					received_len,
					nonce_size,
				))))
			});
		}

		let nonce_ref = Nonce::<A>::from_slice(nonce);
		let result = self.cipher.encrypt(nonce_ref, plaintext).map_err(KeyError::from);
		Box::pin(async move { result })
	}

	fn decrypt(
		&self,
		nonce: &[u8],
		ciphertext: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		let nonce_size = <<A as AeadCore>::NonceSize as Unsigned>::USIZE;
		let received_len = nonce.len();
		if received_len != nonce_size {
			return Box::pin(async move {
				Err(KeyError::NonceLengthError(crate::error::ReceivedExpectedError::from((
					received_len,
					nonce_size,
				))))
			});
		}

		let nonce_ref = Nonce::<A>::from_slice(nonce);
		let result = self.cipher.decrypt(nonce_ref, ciphertext).map_err(KeyError::from);
		Box::pin(async move { result })
	}
}

#[cfg(feature = "aead")]
impl<A, O> EncryptingKeyProvider for Arc<InMemoryEncryptingKeyProvider<A, O>>
where
	A: Aead + Send + Sync + 'static,
	O: AssociatedOid + Send + Sync,
{
	fn algorithm(&self) -> AlgorithmIdentifierOwned {
		self.as_ref().algorithm()
	}

	fn encrypt(
		&self,
		nonce: &[u8],
		plaintext: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		self.as_ref().encrypt(nonce, plaintext)
	}

	fn decrypt(
		&self,
		nonce: &[u8],
		ciphertext: &[u8],
	) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, KeyError>> + Send + '_>> {
		self.as_ref().decrypt(nonce, ciphertext)
	}
}

// =============================================================================
// AES Type Aliases
// =============================================================================

#[cfg(all(feature = "aead", feature = "aes-gcm"))]
/// Type alias for AES-256-GCM encryption key provider
pub type Aes256GcmKeyProvider = InMemoryEncryptingKeyProvider<Aes256Gcm, Aes256GcmOid>;

#[cfg(all(feature = "aead", feature = "aes-gcm"))]
/// Type alias for AES-128-GCM encryption key provider
pub type Aes128GcmKeyProvider = InMemoryEncryptingKeyProvider<Aes128Gcm, Aes128GcmOid>;

#[cfg(test)]
mod tests {
	use rand_core::OsRng;

	use super::*;
	use crate::crypto::hash::{Digest, Sha3_256};
	use crate::crypto::secret::ToInsecure;
	use crate::crypto::sign::ecdsa::k256::ecdsa::SigningKey;
	use crate::crypto::sign::PrehashVerifier;

	fn prehash(data: &[u8]) -> Vec<u8> {
		let mut hasher = Sha3_256::new();
		hasher.update(data);
		hasher.finalize().to_vec()
	}

	#[tokio::test]
	async fn test_secp256k1_provider_public_key() -> Result<(), Box<dyn std::error::Error>> {
		let signing_key = SigningKey::random(&mut OsRng);
		let provider = Secp256k1KeyProvider::from(signing_key);

		let public_key_bytes = provider.to_public_key_bytes().await?;
		// DER-encoded SPKI for secp256k1 is 88 bytes
		assert_eq!(public_key_bytes.len(), 88);
		Ok(())
	}

	#[tokio::test]
	async fn test_secp256k1_provider_sign() -> Result<(), Box<dyn std::error::Error>> {
		let signing_key = SigningKey::random(&mut OsRng);
		let provider = Secp256k1KeyProvider::from(signing_key.clone());

		let digest = prehash(b"test data to sign");
		let signature_bytes = provider.sign_prehash(&digest).await?;

		// Verify signature using the public key
		let signature = Secp256k1Signature::from_slice(&signature_bytes)?;
		signing_key.verifying_key().verify_prehash(&digest, &signature)?;

		Ok(())
	}

	#[tokio::test]
	async fn test_secp256k1_provider_key_agreement() -> Result<(), Box<dyn std::error::Error>> {
		let signing_key1 = SigningKey::random(&mut OsRng);
		let signing_key2 = SigningKey::random(&mut OsRng);

		let provider1 = Secp256k1KeyProvider::from(signing_key1.clone());
		let provider2 = Secp256k1KeyProvider::from(signing_key2.clone());

		// key_agreement expects SEC1 encoded public keys (not DER/SPKI)
		let public1 = signing_key1.verifying_key().to_encoded_point(false).as_bytes().to_vec();
		let public2 = signing_key2.verifying_key().to_encoded_point(false).as_bytes().to_vec();

		// Both sides should compute the same shared secret
		let shared1 = provider1.key_agreement(&public2).await?.to_insecure()?;
		let shared2 = provider2.key_agreement(&public1).await?.to_insecure()?;

		assert_eq!(shared1, shared2);
		assert_eq!(shared1.len(), 32); // secp256k1 shared secret is 32 bytes
		Ok(())
	}

	#[tokio::test]
	async fn test_generic_provider_sign() -> Result<(), Box<dyn std::error::Error>> {
		let signing_key = SigningKey::random(&mut OsRng);
		let provider: Secp256k1Provider = InMemorySigningKeyProvider::from(signing_key.clone());

		let digest = prehash(b"test data to sign");
		let signature_bytes = provider.sign_prehash(&digest).await?;

		// Verify signature using the public key
		let signature = Secp256k1Signature::from_slice(&signature_bytes)?;
		signing_key.verifying_key().verify_prehash(&digest, &signature)?;

		Ok(())
	}

	#[tokio::test]
	async fn test_arc_secp256k1_provider() -> Result<(), Box<dyn std::error::Error>> {
		let signing_key = SigningKey::random(&mut OsRng);
		let provider = Arc::new(Secp256k1KeyProvider::from(signing_key.clone()));

		// Test that Arc<Secp256k1KeyProvider> implements KeyProvider
		let public_key_bytes = provider.to_public_key_bytes().await?;
		// DER-encoded SPKI for secp256k1 is 88 bytes
		assert_eq!(public_key_bytes.len(), 88);

		let digest = prehash(b"test");
		let signature_bytes = provider.sign_prehash(&digest).await?;

		let signature = Secp256k1Signature::from_slice(&signature_bytes)?;
		signing_key.verifying_key().verify_prehash(&digest, &signature)?;

		Ok(())
	}

	#[tokio::test]
	async fn test_algorithm_identifier() -> Result<(), Box<dyn std::error::Error>> {
		let signing_key = SigningKey::random(&mut OsRng);
		let provider = Secp256k1KeyProvider::from(signing_key);

		let alg = provider.algorithm();
		assert_eq!(alg.oid, Secp256k1Signature::ALGORITHM_OID);
		Ok(())
	}
}