auth_framework/methods/hardware_token/
mod.rs1use crate::errors::Result;
19
20#[derive(Clone)]
25pub struct HardwareOtpTokenConfig {
26 pub yubico_client_id: Option<String>,
28 pub yubico_secret_key: Option<String>,
30 pub yubico_validation_url: String,
33}
34
35impl std::fmt::Debug for HardwareOtpTokenConfig {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 let mut d = f.debug_struct("HardwareOtpTokenConfig");
38 d.field("yubico_client_id", &self.yubico_client_id);
39 d.field(
40 "yubico_secret_key",
41 &crate::utils::redact::redacted(&self.yubico_secret_key),
42 );
43 d.field("yubico_validation_url", &self.yubico_validation_url);
44 d.finish()
45 }
46}
47
48impl Default for HardwareOtpTokenConfig {
49 fn default() -> Self {
50 Self {
51 yubico_client_id: None,
52 yubico_secret_key: None,
53 yubico_validation_url: "https://api.yubico.com/wsapi/2.0/verify".to_string(),
54 }
55 }
56}
57
58pub struct HardwareOtpToken {
66 pub device_id: String,
68 pub token_type: String,
70 config: Option<HardwareOtpTokenConfig>,
72}
73
74impl HardwareOtpToken {
75 pub fn new(device_id: String, token_type: String) -> Self {
77 Self {
78 device_id,
79 token_type,
80 config: None,
81 }
82 }
83
84 pub fn with_config(mut self, config: HardwareOtpTokenConfig) -> Self {
86 self.config = Some(config);
87 self
88 }
89
90 pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
92 if challenge.is_empty() {
96 return Ok(false);
97 }
98
99 match self.token_type.as_str() {
101 "yubikey" => {
102 tracing::info!("Authenticating with YubiKey device: {}", self.device_id);
103 self.validate_yubikey_response(challenge).await
104 }
105 _ => {
106 tracing::warn!(
107 "Unknown OTP token type '{}'. HardwareOtpToken only supports 'yubikey'. \
108 For smart card / PIV certificate authentication use ClientCertAuthMethod; \
109 for FIDO2/WebAuthn use PasskeyAuthMethod.",
110 self.token_type
111 );
112 Ok(false)
113 }
114 }
115 }
116
117 async fn validate_yubikey_response(&self, challenge: &str) -> Result<bool> {
119 tracing::debug!("Validating YubiKey response");
120
121 if !challenge.starts_with("cccc") || challenge.len() != 44 {
126 tracing::warn!(
127 "YubiKey validation failed — invalid OTP format \
128 (expected 44-char modhex starting with 'cccc')"
129 );
130 return Ok(false);
131 }
132
133 if let Some(cfg) = &self.config
135 && let Some(client_id) = &cfg.yubico_client_id
136 {
137 return self
138 .validate_yubikey_via_api(challenge, client_id, &cfg.yubico_validation_url)
139 .await;
140 }
141
142 Err(crate::errors::AuthError::Configuration {
147 message: "YubiKey OTP validation requires a Yubico client_id and secret_key. \
148 Call HardwareOtpToken::with_config(HardwareOtpTokenConfig { yubico_client_id: Some(...), \
149 yubico_secret_key: Some(...), .. }) before authenticating."
150 .to_string(),
151 source: None,
152 help: Some(
153 "Register at https://upgrade.yubico.com/getapikey/ to obtain API credentials."
154 .to_string(),
155 ),
156 docs_url: Some(
157 "https://developers.yubico.com/yubikey-val/Getting_Started_Writing_Clients.html"
158 .to_string(),
159 ),
160 suggested_fix: Some(
161 "HardwareOtpToken::new(id, \"yubikey\") \
162 .with_config(HardwareOtpTokenConfig { yubico_client_id: Some(client_id), .. })"
163 .to_string(),
164 ),
165 })
166 }
167
168 async fn validate_yubikey_via_api(
173 &self,
174 otp: &str,
175 client_id: &str,
176 validation_url: &str,
177 ) -> Result<bool> {
178 let nonce = {
180 use ring::rand::{SecureRandom, SystemRandom};
181 let rng = SystemRandom::new();
182 let mut bytes = [0u8; 16];
183 rng.fill(&mut bytes).map_err(|_| {
184 crate::errors::AuthError::internal("Failed to generate nonce for Yubico request")
185 })?;
186 hex::encode(bytes)
187 };
188
189 let client = reqwest::Client::new();
190 let url = format!(
192 "{}?id={}&otp={}&nonce={}",
193 validation_url, client_id, otp, nonce
194 );
195 let response = client.get(&url).send().await.map_err(|e| {
196 crate::errors::AuthError::internal(format!("Yubico API request failed: {}", e))
197 })?;
198
199 let body: String = response.text().await.map_err(|e: reqwest::Error| {
200 crate::errors::AuthError::internal(format!("Failed to read Yubico API response: {}", e))
201 })?;
202
203 for line in body.lines() {
206 if let Some(status) = line.strip_prefix("status=") {
207 let status = status.trim();
208 return match status {
209 "OK" => {
210 tracing::info!("Yubico API: OTP valid");
211 Ok(true)
212 }
213 "REPLAYED_OTP" => {
214 tracing::warn!("Yubico API: OTP already used (REPLAYED_OTP)");
215 Ok(false)
216 }
217 other => {
218 tracing::warn!("Yubico API: validation rejected — status={}", other);
219 Ok(false)
220 }
221 };
222 }
223 }
224
225 tracing::warn!("Yubico API: response contained no status line");
226 Ok(false)
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 fn yubikey(id: &str) -> HardwareOtpToken {
235 HardwareOtpToken::new(id.to_string(), "yubikey".to_string())
236 }
237
238 #[test]
241 fn test_new_stores_fields() {
242 let token = HardwareOtpToken::new("dev-001".to_string(), "yubikey".to_string());
243 assert_eq!(token.device_id, "dev-001");
244 assert_eq!(token.token_type, "yubikey");
245 }
246
247 #[tokio::test]
253 async fn test_yubikey_valid_otp_without_config_returns_err() {
254 let token = yubikey("yk-device-001");
255 let valid_otp = format!("cccc{}", "a".repeat(40));
257 assert!(
258 token.authenticate(&valid_otp).await.is_err(),
259 "Expected Err(Configuration) when no API credentials provided"
260 );
261 }
262
263 #[tokio::test]
264 async fn test_yubikey_wrong_prefix() {
265 let token = yubikey("yk-device-001");
266 let bad_otp = format!("xxxx{}", "a".repeat(40)); assert!(!token.authenticate(&bad_otp).await.unwrap());
268 }
269
270 #[tokio::test]
271 async fn test_yubikey_too_short() {
272 let token = yubikey("yk-device-001");
273 assert!(!token.authenticate("cccc123").await.unwrap()); }
275
276 #[tokio::test]
277 async fn test_yubikey_too_long() {
278 let token = yubikey("yk-device-001");
279 let long_otp = format!("cccc{}", "a".repeat(41)); assert!(!token.authenticate(&long_otp).await.unwrap());
281 }
282
283 #[tokio::test]
284 async fn test_yubikey_empty_challenge() {
285 let token = yubikey("yk-device-001");
286 assert!(!token.authenticate("").await.unwrap());
287 }
288
289 #[tokio::test]
295 async fn test_fido2_token_type_is_unknown() {
296 let token = HardwareOtpToken::new("dev-fido2".to_string(), "fido2".to_string());
297 assert!(!token.authenticate("some-challenge").await.unwrap());
299 }
300
301 #[tokio::test]
302 async fn test_unknown_token_type_returns_false() {
303 let token = HardwareOtpToken::new("dev-999".to_string(), "unknown_type".to_string());
304 assert!(!token.authenticate("some-challenge").await.unwrap());
305 }
306
307 #[test]
310 fn test_hardware_token_config_default() {
311 let cfg = HardwareOtpTokenConfig::default();
312 assert!(cfg.yubico_client_id.is_none());
313 assert!(cfg.yubico_secret_key.is_none());
314 assert_eq!(
315 cfg.yubico_validation_url,
316 "https://api.yubico.com/wsapi/2.0/verify"
317 );
318 }
319
320 #[test]
321 fn test_with_config_builder() {
322 let cfg = HardwareOtpTokenConfig {
323 yubico_client_id: Some("my_id".to_string()),
324 yubico_secret_key: Some("my_secret".to_string()),
325 yubico_validation_url: "https://example.com/verify".to_string(),
326 };
327 let token = HardwareOtpToken::new("dev-001".to_string(), "yubikey".to_string())
328 .with_config(cfg.clone());
329 let stored = token.config.as_ref().unwrap();
330 assert_eq!(stored.yubico_client_id.as_deref(), Some("my_id"));
331 assert_eq!(stored.yubico_validation_url, "https://example.com/verify");
332 }
333
334 #[tokio::test]
337 async fn test_yubikey_format_only_without_api_config() {
338 let token = HardwareOtpToken::new("yk-001".to_string(), "yubikey".to_string());
341 let valid_otp = format!("cccc{}", "b".repeat(40));
342 let result = token.authenticate(&valid_otp).await;
343 assert!(
344 result.is_err(),
345 "Expected Err when no API credentials configured, got {:?}",
346 result
347 );
348 }
349
350 fn make_yubikey_with_mock_url(mock_url: &str, client_id: &str) -> HardwareOtpToken {
353 let cfg = HardwareOtpTokenConfig {
354 yubico_client_id: Some(client_id.to_string()),
355 yubico_secret_key: None,
356 yubico_validation_url: mock_url.to_string(),
357 };
358 HardwareOtpToken::new("yk-mock".to_string(), "yubikey".to_string()).with_config(cfg)
359 }
360
361 #[tokio::test]
363 async fn test_yubikey_api_ok() {
364 let mut server = mockito::Server::new_async().await;
365 let _m = server
366 .mock("GET", mockito::Matcher::Any)
367 .with_status(200)
368 .with_body("t=2024-01-01T00:00:00Z0000\nnonce=abcdef\nstatus=OK\n")
369 .create_async()
370 .await;
371
372 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
373 let valid_otp = format!("cccc{}", "c".repeat(40));
374 assert!(token.authenticate(&valid_otp).await.unwrap());
375 }
376
377 #[tokio::test]
379 async fn test_yubikey_api_replayed_otp() {
380 let mut server = mockito::Server::new_async().await;
381 let _m = server
382 .mock("GET", mockito::Matcher::Any)
383 .with_status(200)
384 .with_body("t=2024-01-01T00:00:00Z0000\nnonce=abcdef\nstatus=REPLAYED_OTP\n")
385 .create_async()
386 .await;
387
388 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
389 let valid_otp = format!("cccc{}", "d".repeat(40));
390 assert!(!token.authenticate(&valid_otp).await.unwrap());
391 }
392
393 #[tokio::test]
395 async fn test_yubikey_api_bad_otp_status() {
396 let mut server = mockito::Server::new_async().await;
397 let _m = server
398 .mock("GET", mockito::Matcher::Any)
399 .with_status(200)
400 .with_body("t=2024-01-01T00:00:00Z0000\nnonce=abcdef\nstatus=BAD_OTP\n")
401 .create_async()
402 .await;
403
404 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
405 let valid_otp = format!("cccc{}", "e".repeat(40));
406 assert!(!token.authenticate(&valid_otp).await.unwrap());
407 }
408
409 #[tokio::test]
412 async fn test_yubikey_bad_format_skips_api() {
413 let mut server = mockito::Server::new_async().await;
414 let _m = server
416 .mock("GET", mockito::Matcher::Any)
417 .with_status(200)
418 .with_body("status=OK\n")
419 .expect(0)
420 .create_async()
421 .await;
422
423 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
424 let bad_otp = "XXXX_this_is_not_a_valid_otp_at_all";
425 assert!(!token.authenticate(bad_otp).await.unwrap());
426 }
427}