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!(
197 "Yubico API request failed: {}",
198 e.without_url()
199 ))
200 })?;
201
202 let body: String = response.text().await.map_err(|e: reqwest::Error| {
203 crate::errors::AuthError::internal(format!(
204 "Failed to read Yubico API response: {}",
205 e.without_url()
206 ))
207 })?;
208
209 for line in body.lines() {
212 if let Some(status) = line.strip_prefix("status=") {
213 let status = status.trim();
214 return match status {
215 "OK" => {
216 tracing::info!("Yubico API: OTP valid");
217 Ok(true)
218 }
219 "REPLAYED_OTP" => {
220 tracing::warn!("Yubico API: OTP already used (REPLAYED_OTP)");
221 Ok(false)
222 }
223 other => {
224 tracing::warn!("Yubico API: validation rejected — status={}", other);
225 Ok(false)
226 }
227 };
228 }
229 }
230
231 tracing::warn!("Yubico API: response contained no status line");
232 Ok(false)
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 fn yubikey(id: &str) -> HardwareOtpToken {
241 HardwareOtpToken::new(id.to_string(), "yubikey".to_string())
242 }
243
244 #[test]
247 fn test_new_stores_fields() {
248 let token = HardwareOtpToken::new("dev-001".to_string(), "yubikey".to_string());
249 assert_eq!(token.device_id, "dev-001");
250 assert_eq!(token.token_type, "yubikey");
251 }
252
253 #[tokio::test]
259 async fn test_yubikey_valid_otp_without_config_returns_err() {
260 let token = yubikey("yk-device-001");
261 let valid_otp = format!("cccc{}", "a".repeat(40));
263 assert!(
264 token.authenticate(&valid_otp).await.is_err(),
265 "Expected Err(Configuration) when no API credentials provided"
266 );
267 }
268
269 #[tokio::test]
270 async fn test_yubikey_wrong_prefix() {
271 let token = yubikey("yk-device-001");
272 let bad_otp = format!("xxxx{}", "a".repeat(40)); assert!(!token.authenticate(&bad_otp).await.unwrap());
274 }
275
276 #[tokio::test]
277 async fn test_yubikey_too_short() {
278 let token = yubikey("yk-device-001");
279 assert!(!token.authenticate("cccc123").await.unwrap()); }
281
282 #[tokio::test]
283 async fn test_yubikey_too_long() {
284 let token = yubikey("yk-device-001");
285 let long_otp = format!("cccc{}", "a".repeat(41)); assert!(!token.authenticate(&long_otp).await.unwrap());
287 }
288
289 #[tokio::test]
290 async fn test_yubikey_empty_challenge() {
291 let token = yubikey("yk-device-001");
292 assert!(!token.authenticate("").await.unwrap());
293 }
294
295 #[tokio::test]
301 async fn test_fido2_token_type_is_unknown() {
302 let token = HardwareOtpToken::new("dev-fido2".to_string(), "fido2".to_string());
303 assert!(!token.authenticate("some-challenge").await.unwrap());
305 }
306
307 #[tokio::test]
308 async fn test_unknown_token_type_returns_false() {
309 let token = HardwareOtpToken::new("dev-999".to_string(), "unknown_type".to_string());
310 assert!(!token.authenticate("some-challenge").await.unwrap());
311 }
312
313 #[test]
316 fn test_hardware_token_config_default() {
317 let cfg = HardwareOtpTokenConfig::default();
318 assert!(cfg.yubico_client_id.is_none());
319 assert!(cfg.yubico_secret_key.is_none());
320 assert_eq!(
321 cfg.yubico_validation_url,
322 "https://api.yubico.com/wsapi/2.0/verify"
323 );
324 }
325
326 #[test]
327 fn test_with_config_builder() {
328 let cfg = HardwareOtpTokenConfig {
329 yubico_client_id: Some("my_id".to_string()),
330 yubico_secret_key: Some("my_secret".to_string()),
331 yubico_validation_url: "https://example.com/verify".to_string(),
332 };
333 let token = HardwareOtpToken::new("dev-001".to_string(), "yubikey".to_string())
334 .with_config(cfg.clone());
335 let stored = token.config.as_ref().unwrap();
336 assert_eq!(stored.yubico_client_id.as_deref(), Some("my_id"));
337 assert_eq!(stored.yubico_validation_url, "https://example.com/verify");
338 }
339
340 #[tokio::test]
343 async fn test_yubikey_format_only_without_api_config() {
344 let token = HardwareOtpToken::new("yk-001".to_string(), "yubikey".to_string());
347 let valid_otp = format!("cccc{}", "b".repeat(40));
348 let result = token.authenticate(&valid_otp).await;
349 assert!(
350 result.is_err(),
351 "Expected Err when no API credentials configured, got {:?}",
352 result
353 );
354 }
355
356 fn make_yubikey_with_mock_url(mock_url: &str, client_id: &str) -> HardwareOtpToken {
359 let cfg = HardwareOtpTokenConfig {
360 yubico_client_id: Some(client_id.to_string()),
361 yubico_secret_key: None,
362 yubico_validation_url: mock_url.to_string(),
363 };
364 HardwareOtpToken::new("yk-mock".to_string(), "yubikey".to_string()).with_config(cfg)
365 }
366
367 #[tokio::test]
369 async fn test_yubikey_api_ok() {
370 let mut server = mockito::Server::new_async().await;
371 let _m = server
372 .mock("GET", mockito::Matcher::Any)
373 .with_status(200)
374 .with_body("t=2024-01-01T00:00:00Z0000\nnonce=abcdef\nstatus=OK\n")
375 .create_async()
376 .await;
377
378 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
379 let valid_otp = format!("cccc{}", "c".repeat(40));
380 assert!(token.authenticate(&valid_otp).await.unwrap());
381 }
382
383 #[tokio::test]
385 async fn test_yubikey_api_replayed_otp() {
386 let mut server = mockito::Server::new_async().await;
387 let _m = server
388 .mock("GET", mockito::Matcher::Any)
389 .with_status(200)
390 .with_body("t=2024-01-01T00:00:00Z0000\nnonce=abcdef\nstatus=REPLAYED_OTP\n")
391 .create_async()
392 .await;
393
394 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
395 let valid_otp = format!("cccc{}", "d".repeat(40));
396 assert!(!token.authenticate(&valid_otp).await.unwrap());
397 }
398
399 #[tokio::test]
401 async fn test_yubikey_api_bad_otp_status() {
402 let mut server = mockito::Server::new_async().await;
403 let _m = server
404 .mock("GET", mockito::Matcher::Any)
405 .with_status(200)
406 .with_body("t=2024-01-01T00:00:00Z0000\nnonce=abcdef\nstatus=BAD_OTP\n")
407 .create_async()
408 .await;
409
410 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
411 let valid_otp = format!("cccc{}", "e".repeat(40));
412 assert!(!token.authenticate(&valid_otp).await.unwrap());
413 }
414
415 #[tokio::test]
418 async fn test_yubikey_bad_format_skips_api() {
419 let mut server = mockito::Server::new_async().await;
420 let _m = server
422 .mock("GET", mockito::Matcher::Any)
423 .with_status(200)
424 .with_body("status=OK\n")
425 .expect(0)
426 .create_async()
427 .await;
428
429 let token = make_yubikey_with_mock_url(&server.url(), "test_client");
430 let bad_otp = "XXXX_this_is_not_a_valid_otp_at_all";
431 assert!(!token.authenticate(bad_otp).await.unwrap());
432 }
433}