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");
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!(
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        // The Yubico API returns a CRLF-delimited key=value list.
210        // We only need the `status` line.
211        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    // ── HardwareOtpToken::new ─────────────────────────────────────────────────
245
246    #[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    // ── YubiKey ──────────────────────────────────────────────────────────────
254
255    /// A well-formed OTP (correct prefix + length) with **no API config** must
256    /// return a configuration `Err` — format alone cannot prove OTP authenticity.
257    /// (Full end-to-end validation is covered by the mockito API tests below.)
258    #[tokio::test]
259    async fn test_yubikey_valid_otp_without_config_returns_err() {
260        let token = yubikey("yk-device-001");
261        // 4 prefix chars + 40 more = 44 total — structurally valid
262        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)); // wrong prefix
273        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()); // < 44 chars
280    }
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)); // 45 chars > 44
286        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    // ── Unknown token type ───────────────────────────────────────────────────
296
297    /// The `"fido2"` token type was removed — it is not an OTP protocol.
298    /// Callers that previously used `token_type = "fido2"` now hit the unknown-type
299    /// branch and get `false`, with a tracing warning directing them to `PasskeyAuthMethod`.
300    #[tokio::test]
301    async fn test_fido2_token_type_is_unknown() {
302        let token = HardwareOtpToken::new("dev-fido2".to_string(), "fido2".to_string());
303        // Hits the `_ =>` arm — returns false, logs a warning.
304        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    // ── HardwareOtpTokenConfig / with_config builder ─────────────────────────
314
315    #[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    // ── YubiKey format-only fallback (no API config) ─────────────────────────
341
342    #[tokio::test]
343    async fn test_yubikey_format_only_without_api_config() {
344        // Valid format, no API config → must be rejected with a configuration error.
345        // Format alone proves nothing; the Yubico API is required.
346        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    // ── YubiKey Yubico API tests (mockito) ────────────────────────────────────
357
358    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    /// Valid OTP format + Yubico API responds `status=OK` → should return `true`.
368    #[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    /// Valid OTP format + API responds `status=REPLAYED_OTP` → `false`.
384    #[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    /// Valid OTP format + API responds `status=BAD_OTP` → `false`.
400    #[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    /// Bad OTP format → rejected before any API call is made.
416    /// The mock has zero expected calls; mockito will panic on drop if hit.
417    #[tokio::test]
418    async fn test_yubikey_bad_format_skips_api() {
419        let mut server = mockito::Server::new_async().await;
420        // Expect zero hits — if the API is called, the test fails.
421        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}