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
//! RFC 6238 time-based one-time password (TOTP) support.
use std::collections::HashMap;
use ring::rand::{SecureRandom, SystemRandom};
use tokio::sync::Mutex;
use totp_rs::{Algorithm, Secret, TOTP};
use uuid::Uuid;
use crate::error::IdentityError;
use crate::mfa::{MfaChallenge, MfaChallengeKind, MfaProvider, MfaResponse};
/// A redacted string wrapper for TOTP secrets.
#[derive(Clone)]
pub struct SecretString(String);
impl SecretString {
/// Creates a new secret wrapper from raw string data.
///
/// # Examples
///
/// ```rust
/// use secure_identity::totp::SecretString;
///
/// let secret = SecretString::new("BASE32SECRET".to_string());
/// assert_eq!(secret.expose_secret(), "BASE32SECRET");
/// ```
#[must_use]
pub fn new(value: String) -> Self {
Self(value)
}
/// Exposes the wrapped secret value.
///
/// # Examples
///
/// ```rust
/// use secure_identity::totp::SecretString;
///
/// let secret = SecretString::new("BASE32SECRET".to_string());
/// assert_eq!(secret.expose_secret(), "BASE32SECRET");
/// ```
#[must_use]
pub fn expose_secret(&self) -> &str {
&self.0
}
}
impl std::fmt::Debug for SecretString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SecretString([REDACTED])")
}
}
/// Enrollment data returned when setting up TOTP.
#[derive(Debug, Clone)]
pub struct TotpEnrollment {
/// Shared secret used for code generation.
pub secret: SecretString,
/// Provisioning URI suitable for authenticator applications.
pub provisioning_uri: String,
}
/// TOTP provider implementing RFC 6238 with SHA-1 (compatibility-first default).
pub struct TotpProvider {
issuer: String,
skew: u8,
challenges: Mutex<HashMap<String, SecretString>>,
}
impl TotpProvider {
/// Creates a provider with the given issuer and allowed clock skew (steps).
///
/// # Examples
///
/// ```rust
/// use secure_identity::totp::TotpProvider;
///
/// let provider = TotpProvider::new("SunLit", 1);
/// let _ = provider;
/// ```
#[must_use]
pub fn new(issuer: impl Into<String>, skew: u8) -> Self {
Self {
issuer: issuer.into(),
skew,
challenges: Mutex::new(HashMap::new()),
}
}
/// Generates a new TOTP secret and provisioning URI for an account.
///
/// # Examples
///
/// ```rust
/// use secure_identity::totp::TotpProvider;
///
/// let provider = TotpProvider::new("SunLit", 1);
/// let enrollment = provider.generate_secret("alice@example.com")?;
/// assert!(enrollment.provisioning_uri.starts_with("otpauth://totp/"));
/// # Ok::<(), secure_identity::IdentityError>(())
/// ```
pub fn generate_secret(&self, account_name: &str) -> Result<TotpEnrollment, IdentityError> {
let rng = SystemRandom::new();
let mut bytes = [0_u8; 20];
rng.fill(&mut bytes)
.map_err(|_| IdentityError::ProviderUnavailable)?;
let secret = match Secret::Raw(bytes.to_vec()).to_encoded() {
Secret::Encoded(value) => value,
Secret::Raw(_) => return Err(IdentityError::ProviderUnavailable),
};
let secret = SecretString::new(secret);
let totp = self.build_totp(secret_bytes(secret.expose_secret())?, account_name)?;
Ok(TotpEnrollment {
secret,
provisioning_uri: totp.get_url(),
})
}
/// Generates the current six-digit TOTP code for a secret.
///
/// # Examples
///
/// ```rust
/// use secure_identity::totp::TotpProvider;
///
/// let provider = TotpProvider::new("SunLit", 1);
/// let enrollment = provider.generate_secret("alice@example.com")?;
/// let code = provider.generate_current_code(&enrollment.secret)?;
/// assert_eq!(code.len(), 6);
/// # Ok::<(), secure_identity::IdentityError>(())
/// ```
pub fn generate_current_code(&self, secret: &SecretString) -> Result<String, IdentityError> {
let totp = self.build_totp(secret_bytes(secret.expose_secret())?, "user")?;
totp.generate_current()
.map_err(|_| IdentityError::ProviderUnavailable)
}
/// Verifies a user-provided TOTP code for the current time window.
///
/// # Examples
///
/// ```rust
/// use secure_identity::totp::TotpProvider;
///
/// let provider = TotpProvider::new("SunLit", 1);
/// let enrollment = provider.generate_secret("alice@example.com")?;
/// let code = provider.generate_current_code(&enrollment.secret)?;
/// assert!(provider.verify_code(&enrollment.secret, &code)?);
/// # Ok::<(), secure_identity::IdentityError>(())
/// ```
pub fn verify_code(&self, secret: &SecretString, code: &str) -> Result<bool, IdentityError> {
let totp = self.build_totp(secret_bytes(secret.expose_secret())?, "user")?;
totp.check_current(code)
.map_err(|_| IdentityError::ProviderUnavailable)
}
fn build_totp(&self, secret: Vec<u8>, account_name: &str) -> Result<TOTP, IdentityError> {
TOTP::new(
Algorithm::SHA1,
6,
self.skew,
30,
secret,
Some(self.issuer.clone()),
account_name.to_owned(),
)
.map_err(|_| IdentityError::ProviderUnavailable)
}
}
fn secret_bytes(secret: &str) -> Result<Vec<u8>, IdentityError> {
Secret::Encoded(secret.to_owned())
.to_bytes()
.map_err(|_| IdentityError::InvalidCredentials)
}
impl Default for TotpProvider {
fn default() -> Self {
Self::new("SunLit", 1)
}
}
impl MfaProvider for TotpProvider {
async fn issue_challenge(&self, actor_id: &str) -> Result<MfaChallenge, IdentityError> {
let enrollment = self.generate_secret(actor_id)?;
let challenge_id = Uuid::new_v4().to_string();
self.challenges
.lock()
.await
.insert(challenge_id.clone(), enrollment.secret);
Ok(MfaChallenge {
challenge_id,
kind: MfaChallengeKind::Totp,
})
}
async fn verify_response(&self, response: &MfaResponse) -> Result<bool, IdentityError> {
let secret = self
.challenges
.lock()
.await
.get(&response.challenge_id)
.cloned()
.ok_or(IdentityError::InvalidCredentials)?;
self.verify_code(&secret, &response.code)
}
}