Skip to main content

auths_crypto/
provider.rs

1//! Pluggable cryptographic abstraction for Ed25519 operations.
2//!
3//! Defines the [`CryptoProvider`] trait for Ed25519 verification, signing, and
4//! key generation — enabling `ring` on native targets and `WebCrypto` on WASM.
5
6use async_trait::async_trait;
7use zeroize::{Zeroize, ZeroizeOnDrop};
8
9/// Error type for cryptographic operations.
10///
11/// Usage:
12/// ```ignore
13/// match result {
14///     Err(CryptoError::InvalidSignature) => { /* signature did not verify */ }
15///     Err(CryptoError::UnsupportedTarget) => { /* not available on this platform */ }
16///     Err(CryptoError::OperationFailed(msg)) => { /* backend error */ }
17///     Ok(()) => { /* success */ }
18/// }
19/// ```
20#[derive(Debug, Clone, thiserror::Error)]
21#[non_exhaustive]
22pub enum CryptoError {
23    #[error("Invalid signature")]
24    InvalidSignature,
25
26    #[error("Invalid public key length: expected {expected}, got {actual}")]
27    InvalidKeyLength { expected: usize, actual: usize },
28
29    #[error("Invalid private key: {0}")]
30    InvalidPrivateKey(String),
31
32    #[error("Crypto operation failed: {0}")]
33    OperationFailed(String),
34
35    #[error("Operation not supported on current compilation target")]
36    UnsupportedTarget,
37}
38
39/// Zeroize-on-drop wrapper for a raw 32-byte Ed25519 seed.
40///
41/// This is the portable key representation that crosses the [`CryptoProvider`]
42/// boundary. No ring types leak through the trait — only this raw seed.
43/// The provider materializes the internal keypair from the seed on each call.
44///
45/// Usage:
46/// ```ignore
47/// let (seed, pubkey) = provider.generate_ed25519_keypair().await?;
48/// let sig = provider.sign_ed25519(&seed, b"hello").await?;
49/// // seed is securely zeroed when dropped
50/// ```
51#[derive(Clone, Zeroize, ZeroizeOnDrop)]
52pub struct SecureSeed([u8; 32]);
53
54impl SecureSeed {
55    pub fn new(bytes: [u8; 32]) -> Self {
56        Self(bytes)
57    }
58
59    pub fn as_bytes(&self) -> &[u8; 32] {
60        &self.0
61    }
62}
63
64impl std::fmt::Debug for SecureSeed {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.write_str("SecureSeed([REDACTED])")
67    }
68}
69
70/// Abstraction for Ed25519 cryptographic operations across target architectures.
71///
72/// All method signatures use primitive Rust types or [`SecureSeed`] — no
73/// ring-specific types. This ensures domain crates (`auths-core`, `auths-sdk`)
74/// compile without any ring dependency.
75///
76/// Usage:
77/// ```ignore
78/// use auths_crypto::CryptoProvider;
79///
80/// async fn roundtrip(provider: &dyn CryptoProvider) {
81///     let (seed, pk) = provider.generate_ed25519_keypair().await.unwrap();
82///     let sig = provider.sign_ed25519(&seed, b"msg").await.unwrap();
83///     provider.verify_ed25519(&pk, b"msg", &sig).await.unwrap();
84/// }
85/// ```
86#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
87#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
88pub trait CryptoProvider: Send + Sync {
89    /// Verify an Ed25519 signature against a public key and message.
90    async fn verify_ed25519(
91        &self,
92        pubkey: &[u8],
93        message: &[u8],
94        signature: &[u8],
95    ) -> Result<(), CryptoError>;
96
97    /// Sign a message using a raw 32-byte Ed25519 seed.
98    ///
99    /// The provider materializes the internal keypair from the seed on each
100    /// call. This trades minor CPU overhead for a pure, ring-free domain layer.
101    ///
102    /// Args:
103    /// * `seed`: Raw 32-byte Ed25519 private key seed.
104    /// * `message`: The data to sign.
105    ///
106    /// Usage:
107    /// ```ignore
108    /// let sig = provider.sign_ed25519(&seed, b"hello").await?;
109    /// assert_eq!(sig.len(), 64);
110    /// ```
111    async fn sign_ed25519(&self, seed: &SecureSeed, message: &[u8])
112    -> Result<Vec<u8>, CryptoError>;
113
114    /// Generate a fresh Ed25519 keypair.
115    ///
116    /// Returns the raw 32-byte seed and 32-byte public key.
117    ///
118    /// Usage:
119    /// ```ignore
120    /// let (seed, pubkey) = provider.generate_ed25519_keypair().await?;
121    /// assert_eq!(pubkey.len(), 32);
122    /// ```
123    async fn generate_ed25519_keypair(&self) -> Result<(SecureSeed, [u8; 32]), CryptoError>;
124
125    /// Derive the 32-byte public key from a raw seed.
126    ///
127    /// Args:
128    /// * `seed`: Raw 32-byte Ed25519 private key seed.
129    ///
130    /// Usage:
131    /// ```ignore
132    /// let pk = provider.ed25519_public_key_from_seed(&seed).await?;
133    /// assert_eq!(pk.len(), 32);
134    /// ```
135    async fn ed25519_public_key_from_seed(
136        &self,
137        seed: &SecureSeed,
138    ) -> Result<[u8; 32], CryptoError>;
139}
140
141/// Ed25519 public key length in bytes.
142pub const ED25519_PUBLIC_KEY_LEN: usize = 32;
143
144/// Ed25519 signature length in bytes.
145pub const ED25519_SIGNATURE_LEN: usize = 64;