Skip to main content

auth_framework/methods/hardware_token/
mod.rs

1//! OTP-mode hardware token authentication.
2//!
3//! This module covers hardware tokens that authenticate via a **one-time password (OTP)**
4//! delivered as a plain string — currently YubiKey OTP validated against the Yubico
5//! cloud API.
6//!
7//! It also accepts `smart_card` and `piv_card` token types in its dispatch table, but
8//! those return a configuration error explaining that PC/SC-based PKI authentication
9//! cannot be reduced to a string exchange and must go through mTLS instead.
10//!
11//! # What does NOT belong here
12//!
13//! **FIDO2 / WebAuthn** is intentionally absent.  WebAuthn is a two-phase protocol
14//! (challenge generation → signed assertion) that requires credential storage and
15//! cryptographic signature verification.  Use
16//! [`PasskeyAuthMethod`](crate::methods::passkey::PasskeyAuthMethod) for that.
17
18use crate::errors::Result;
19
20/// Configuration for [`HardwareOtpToken`] validation.
21///
22/// By default, the Yubico API URL points to the official Yubico validation
23/// service. Override `yubico_validation_url` in tests to point at a mock server.
24#[derive(Clone)]
25pub struct HardwareOtpTokenConfig {
26    /// Yubico client ID — required to call the Yubico OTP validation API.
27    pub yubico_client_id: Option<String>,
28    /// Yubico HMAC-SHA1 secret key — reserved for request signing.
29    pub yubico_secret_key: Option<String>,
30    /// Base URL of the Yubico OTP validation endpoint.
31    /// Defaults to `https://api.yubico.com/wsapi/2.0/verify`.
32    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
58/// OTP-mode hardware token authenticator.
59///
60/// Supports YubiKey OTP (validated via the Yubico cloud API) and exposes
61/// `smart_card` / `piv_card` variants that return a clear error directing
62/// callers to mTLS-based authentication.
63///
64/// For FIDO2/WebAuthn use [`PasskeyAuthMethod`](crate::methods::passkey::PasskeyAuthMethod).
65pub struct HardwareOtpToken {
66    /// Device identifier
67    pub device_id: String,
68    /// Token type
69    pub token_type: String,
70    /// Optional configuration (Yubico API credentials, custom URL for tests)
71    config: Option<HardwareOtpTokenConfig>,
72}
73
74impl HardwareOtpToken {
75    /// Create a new OTP hardware token.
76    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    /// Builder: attach a [`HardwareOtpTokenConfig`] (e.g., Yubico API credentials).
85    pub fn with_config(mut self, config: HardwareOtpTokenConfig) -> Self {
86        self.config = Some(config);
87        self
88    }
89
90    /// Authenticate using hardware token
91    pub async fn authenticate(&self, challenge: &str) -> Result<bool> {
92        // Hardware token authentication implementation
93
94        // Basic validation
95        if challenge.is_empty() {
96            return Ok(false);
97        }
98
99        // Simulate hardware token authentication process
100        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    /// Validate YubiKey response
118    async fn validate_yubikey_response(&self, challenge: &str) -> Result<bool> {
119        tracing::debug!("Validating YubiKey response for challenge: {}", challenge);
120
121        // YubiKey OTP format: starts with the 12-char device prefix (modhex) followed
122        // by a 32-char encrypted OTP — total 44 characters.  The default public-ID
123        // prefix for most keys shipped by Yubico starts with "cccc", but any 44-char
124        // modhex string is structurally valid.
125        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 the caller supplied API credentials, validate against the Yubico cloud.
134        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        // No API credentials configured: format alone proves nothing.
143        // A well-formed OTP can be constructed by anyone; without the Yubico
144        // validation API (or equivalent HMAC verification) we cannot confirm
145        // the OTP is genuine.  Reject and tell the operator what to fix.
146        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    /// Call the Yubico OTP validation API.
169    ///
170    /// Returns `true` only when the API responds with `status=OK`.
171    /// All other statuses (e.g. `REPLAYED_OTP`, `BAD_OTP`) return `false`.
172    async fn validate_yubikey_via_api(
173        &self,
174        otp: &str,
175        client_id: &str,
176        validation_url: &str,
177    ) -> Result<bool> {
178        // Generate a random nonce to prevent reply attacks.
179        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        // otp, client_id, and nonce are all modhex/hex/numeric — no URL encoding needed.
191        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        // The Yubico API returns a CRLF-delimited key=value list.
204        // We only need the `status` line.
205        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    // ── HardwareOtpToken::new ─────────────────────────────────────────────────
239
240    #[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    // ── YubiKey ──────────────────────────────────────────────────────────────
248
249    /// A well-formed OTP (correct prefix + length) with **no API config** must
250    /// return a configuration `Err` — format alone cannot prove OTP authenticity.
251    /// (Full end-to-end validation is covered by the mockito API tests below.)
252    #[tokio::test]
253    async fn test_yubikey_valid_otp_without_config_returns_err() {
254        let token = yubikey("yk-device-001");
255        // 4 prefix chars + 40 more = 44 total — structurally valid
256        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)); // wrong prefix
267        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()); // < 44 chars
274    }
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)); // 45 chars > 44
280        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    // ── Unknown token type ───────────────────────────────────────────────────
290
291    /// The `"fido2"` token type was removed — it is not an OTP protocol.
292    /// Callers that previously used `token_type = "fido2"` now hit the unknown-type
293    /// branch and get `false`, with a tracing warning directing them to `PasskeyAuthMethod`.
294    #[tokio::test]
295    async fn test_fido2_token_type_is_unknown() {
296        let token = HardwareOtpToken::new("dev-fido2".to_string(), "fido2".to_string());
297        // Hits the `_ =>` arm — returns false, logs a warning.
298        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    // ── HardwareOtpTokenConfig / with_config builder ─────────────────────────
308
309    #[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    // ── YubiKey format-only fallback (no API config) ─────────────────────────
335
336    #[tokio::test]
337    async fn test_yubikey_format_only_without_api_config() {
338        // Valid format, no API config → must be rejected with a configuration error.
339        // Format alone proves nothing; the Yubico API is required.
340        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    // ── YubiKey Yubico API tests (mockito) ────────────────────────────────────
351
352    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    /// Valid OTP format + Yubico API responds `status=OK` → should return `true`.
362    #[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    /// Valid OTP format + API responds `status=REPLAYED_OTP` → `false`.
378    #[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    /// Valid OTP format + API responds `status=BAD_OTP` → `false`.
394    #[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    /// Bad OTP format → rejected before any API call is made.
410    /// The mock has zero expected calls; mockito will panic on drop if hit.
411    #[tokio::test]
412    async fn test_yubikey_bad_format_skips_api() {
413        let mut server = mockito::Server::new_async().await;
414        // Expect zero hits — if the API is called, the test fails.
415        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}