webauthn/credential.rs
1//! Core domain types for stored credentials, challenges, and ceremony results.
2
3use std::collections::HashMap;
4use std::time::{Duration, SystemTime};
5
6use ciborium::value::Value;
7
8use ring::rand::{SecureRandom, SystemRandom};
9
10use crate::error::{Result, WebAuthnError};
11
12// ─── Public key ───────────────────────────────────────────────────────────────
13
14/// The public key extracted from a COSE key structure during registration.
15///
16/// Four algorithms are supported:
17/// - **ES256** — ECDSA P-256 with SHA-256 (COSE alg `-7`). Most common.
18/// - **ES384** — ECDSA P-384 with SHA-384 (COSE alg `-35`).
19/// - **EdDSA** — Ed25519 (COSE alg `-8`). Used by newer FIDO2 authenticators.
20/// - **RS256** — RSA PKCS#1 v1.5 with SHA-256 (COSE alg `-257`). Used by
21/// older YubiKey 4-series devices and Windows Hello.
22#[derive(Debug, Clone)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub enum PublicKey {
25 /// P-256 ECDSA public key (COSE alg `-7`, kty `2`).
26 ///
27 /// `x` and `y` are the 32-byte affine coordinates of the public point.
28 /// To obtain the 65-byte uncompressed point for ring, prepend `0x04`:
29 /// `0x04 || x (32 bytes) || y (32 bytes)`.
30 ES256 {
31 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
32 x: Vec<u8>,
33 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
34 y: Vec<u8>,
35 },
36
37 /// P-384 ECDSA public key (COSE alg `-35`, kty `2`).
38 ///
39 /// `x` and `y` are the 48-byte affine coordinates of the public point.
40 /// To obtain the 97-byte uncompressed point for ring, prepend `0x04`:
41 /// `0x04 || x (48 bytes) || y (48 bytes)`.
42 ES384 {
43 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
44 x: Vec<u8>,
45 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
46 y: Vec<u8>,
47 },
48
49 /// Ed25519 EdDSA public key (COSE alg `-8`, kty `1` OKP).
50 ///
51 /// The inner `Vec<u8>` is the raw 32-byte Ed25519 public key,
52 /// as encoded in COSE OKP key parameter `-2` (`x`).
53 EdDSA(#[cfg_attr(feature = "serde", serde(with = "serde_bytes"))] Vec<u8>),
54
55 /// RSA PKCS#1 v1.5 SHA-256 public key (COSE alg `-257`, kty `3`).
56 ///
57 /// `n` is the big-endian modulus (256 bytes for a 2048-bit key).
58 /// `e` is the big-endian public exponent (typically `[0x01, 0x00, 0x01]`).
59 RS256 {
60 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
61 n: Vec<u8>,
62 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
63 e: Vec<u8>,
64 },
65}
66
67impl PublicKey {
68 /// Return the COSE algorithm identifier for this key.
69 pub fn algorithm(&self) -> i64 {
70 match self {
71 PublicKey::ES256 { .. } => crate::algorithm::COSE_ES256,
72 PublicKey::ES384 { .. } => crate::algorithm::COSE_ES384,
73 PublicKey::EdDSA(_) => crate::algorithm::COSE_EDDSA,
74 PublicKey::RS256 { .. } => crate::algorithm::COSE_RS256,
75 }
76 }
77
78 /// Return a human-readable description of the key type.
79 pub fn key_type(&self) -> &'static str {
80 match self {
81 PublicKey::ES256 { .. } => "EC2 P-256",
82 PublicKey::ES384 { .. } => "EC2 P-384",
83 PublicKey::EdDSA(_) => "OKP Ed25519",
84 PublicKey::RS256 { .. } => "RSA 2048",
85 }
86 }
87}
88
89// ─── Stored credential ────────────────────────────────────────────────────────
90
91/// A registered credential persisted on the relying-party side after a
92/// successful registration ceremony.
93///
94/// The caller is responsible for storing this in a durable, server-side store
95/// keyed by `id` (the credential ID) and associated with `user_id`.
96#[derive(Debug, Clone)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
98pub struct Credential {
99 /// Opaque byte string that uniquely identifies this credential.
100 /// Produced by the authenticator during registration.
101 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
102 pub id: Vec<u8>,
103
104 /// The authenticator's public key in the format signalled during registration.
105 pub public_key: PublicKey,
106
107 /// Monotonically increasing counter maintained by the authenticator.
108 /// Used to detect cloned authenticators.
109 pub sign_count: u32,
110
111 /// Application-defined identifier for the user this credential belongs to.
112 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
113 pub user_id: Vec<u8>,
114
115 /// Relying party ID (e.g. `"example.com"`).
116 /// Stored so authentication can verify the credential is bound to this RP.
117 pub rp_id: String,
118
119 /// When this credential was first registered.
120 pub created_at: SystemTime,
121
122 /// Whether this credential is eligible for backup to a platform sync
123 /// service (BE flag, §6.1 bit 3).
124 ///
125 /// This value is immutable per spec — the authenticator sets it once at
126 /// registration and it must not change in subsequent ceremonies. A change
127 /// in `backup_eligible` between registration and authentication is treated
128 /// as a credential substitution attempt and rejected with
129 /// [`crate::error::WebAuthnError::BackupEligibilityChanged`].
130 pub backup_eligible: bool,
131}
132
133// ─── Wire-format input types ──────────────────────────────────────────────────
134
135/// The response produced by the authenticator after `navigator.credentials.create()`.
136///
137/// Both fields carry the **raw decoded bytes** — base64url decoding happens
138/// outside the library before constructing this struct. This matches the
139/// ArrayBuffer values you get after calling `response.clientDataJSON` in JS.
140#[derive(Debug, Clone)]
141pub struct AuthenticatorAttestationResponse {
142 /// Raw UTF-8 bytes of the `clientDataJSON` object.
143 pub client_data_json: Vec<u8>,
144
145 /// Raw CBOR bytes of the `attestationObject`.
146 pub attestation_object: Vec<u8>,
147}
148
149// ─── Challenge ────────────────────────────────────────────────────────────────
150
151/// A single-use challenge issued by the relying party before a ceremony.
152///
153/// **Security contract**: each `Challenge` must be used at most once and must
154/// expire after a short window (typically 60–300 seconds). The caller is
155/// responsible for enforcing both properties.
156#[derive(Debug, Clone)]
157#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
158pub struct Challenge {
159 /// 32 cryptographically random bytes.
160 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
161 pub bytes: Vec<u8>,
162
163 /// When this challenge was generated — used for expiry checks.
164 pub created_at: SystemTime,
165}
166
167impl Challenge {
168 /// Generate a fresh 32-byte challenge using the OS cryptographic RNG.
169 ///
170 /// 32 bytes provides 256 bits of entropy — far beyond any brute-force threat.
171 ///
172 /// # Errors
173 /// Returns [`WebAuthnError::InvalidClientData`] if the system RNG fails
174 /// (extremely unlikely; would indicate a kernel-level failure).
175 pub fn new() -> Result<Self> {
176 let rng = SystemRandom::new();
177 let mut bytes = vec![0u8; 32];
178 rng.fill(&mut bytes).map_err(|_| {
179 WebAuthnError::InvalidClientData(
180 "system random number generator failed to produce bytes".to_string(),
181 )
182 })?;
183 Ok(Self {
184 bytes,
185 created_at: SystemTime::now(),
186 })
187 }
188
189 /// Returns `true` if this challenge is older than `ttl_secs` seconds.
190 ///
191 /// Returns `true` if the system clock has gone backwards since the challenge
192 /// was created — treating an unverifiable age as expired is the safe default.
193 pub fn is_expired(&self, ttl_secs: u64) -> bool {
194 self.created_at
195 .elapsed()
196 .map(|age| age >= Duration::from_secs(ttl_secs))
197 .unwrap_or(true)
198 }
199}
200
201// ─── Ceremony result types ────────────────────────────────────────────────────
202
203/// Successful outcome of a registration ceremony.
204#[derive(Debug)]
205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
206pub struct RegistrationResult {
207 /// The newly registered credential — persist this in your database.
208 pub credential: Credential,
209
210 /// What kind of attestation the authenticator provided.
211 pub attestation_type: AttestationType,
212
213 /// Whether the registered credential is eligible for backup to a platform
214 /// sync service (BE flag). This value is set by the authenticator and is
215 /// immutable — it will not change in future ceremonies for this credential.
216 pub backup_eligible: bool,
217
218 /// Whether the credential was backed up at the time of registration (BS flag).
219 pub backup_state: bool,
220
221 /// Authenticator extension data from registration (§6.1 / §10.5), or `None` if the
222 /// ED flag was not set. Keys are extension identifiers (e.g. `"credProps"`); values
223 /// are raw CBOR that callers inspect themselves.
224 ///
225 /// Excluded from serde serialization: `ciborium::value::Value` has no portable JSON
226 /// encoding. Extract the values you need and convert them before serializing.
227 #[cfg_attr(feature = "serde", serde(skip))]
228 pub extensions: Option<HashMap<String, Value>>,
229}
230
231/// Successful outcome of an authentication ceremony.
232#[derive(Debug)]
233#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
234pub struct AuthenticationResult {
235 /// The credential ID used to authenticate.
236 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
237 pub credential_id: Vec<u8>,
238
239 /// The sign count returned by the authenticator this ceremony.
240 /// Update the stored credential's `sign_count` to this value after success.
241 pub new_sign_count: u32,
242
243 /// Whether the User Present (UP) flag was set — the authenticator confirmed
244 /// that a human was at the device (button press, touch, etc.).
245 pub user_present: bool,
246
247 /// Whether the authenticator signalled that the user was verified
248 /// (biometric check, PIN, etc.) — corresponds to the UV flag.
249 pub user_verified: bool,
250
251 /// Whether the credential is eligible for backup (BE flag).
252 /// Should remain constant across authentications for a given credential.
253 pub backup_eligible: bool,
254
255 /// Whether the credential is currently backed up (BS flag).
256 /// May change between ceremonies as backup state varies.
257 pub backup_state: bool,
258
259 /// Authenticator extension data from authentication (§6.1 / §10.5), or `None` if the
260 /// ED flag was not set. Keys are extension identifiers (e.g. `"appid"`); values are
261 /// raw CBOR that callers inspect themselves.
262 ///
263 /// Excluded from serde serialization: `ciborium::value::Value` has no portable JSON
264 /// encoding. Extract the values you need and convert them before serializing.
265 #[cfg_attr(feature = "serde", serde(skip))]
266 pub extensions: Option<HashMap<String, Value>>,
267}
268
269/// The level of attestation the authenticator provided.
270#[derive(Debug, PartialEq, Eq)]
271#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
272pub enum AttestationType {
273 /// The authenticator explicitly provided no attestation (`"fmt": "none"`).
274 /// The credential is still usable, but device provenance cannot be verified.
275 None,
276
277 /// The attestation was signed by the same key used for authentication
278 /// (self-attestation). Proves the credential is fresh but not the device model.
279 SelfAttestation,
280
281 /// The attestation was signed by a separate attestation key with an `x5c`
282 /// certificate chain present. The chain order has been verified (each cert is
283 /// signed by the next), but the root has **not** been checked against a trust
284 /// anchor because none were configured on [`crate::RelyingParty`]. Device
285 /// provenance is structurally plausible but not cryptographically anchored.
286 Basic,
287
288 /// Same as [`Basic`](AttestationType::Basic) but the root certificate was
289 /// additionally verified to be signed by one of the trust anchors configured
290 /// via [`crate::RelyingParty::trust_anchors`]. Device provenance is
291 /// cryptographically anchored to the configured CA set.
292 BasicVerified,
293}
294
295// ─── Serde round-trip tests ───────────────────────────────────────────────────
296
297#[cfg(all(test, feature = "serde"))]
298mod serde_tests {
299 use std::time::{Duration, SystemTime};
300
301 use super::*;
302
303 fn epoch_plus(secs: u64) -> SystemTime {
304 SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
305 }
306
307 #[test]
308 fn challenge_round_trips() {
309 let c = Challenge {
310 bytes: vec![0xDE, 0xAD, 0xBE, 0xEF],
311 created_at: epoch_plus(1_700_000_000),
312 };
313 let json = serde_json::to_string(&c).unwrap();
314 let back: Challenge = serde_json::from_str(&json).unwrap();
315 assert_eq!(back.bytes, c.bytes);
316 assert_eq!(back.created_at, c.created_at);
317 }
318
319 #[test]
320 fn public_key_es256_round_trips() {
321 let key = PublicKey::ES256 {
322 x: vec![0x01u8; 32],
323 y: vec![0x02u8; 32],
324 };
325 let json = serde_json::to_string(&key).unwrap();
326 let back: PublicKey = serde_json::from_str(&json).unwrap();
327 match back {
328 PublicKey::ES256 { x, y } => {
329 assert_eq!(x, vec![0x01u8; 32]);
330 assert_eq!(y, vec![0x02u8; 32]);
331 }
332 _ => panic!("wrong variant"),
333 }
334 }
335
336 #[test]
337 fn public_key_eddsa_round_trips() {
338 let key = PublicKey::EdDSA(vec![0x03u8; 32]);
339 let json = serde_json::to_string(&key).unwrap();
340 let back: PublicKey = serde_json::from_str(&json).unwrap();
341 match back {
342 PublicKey::EdDSA(bytes) => assert_eq!(bytes, vec![0x03u8; 32]),
343 _ => panic!("wrong variant"),
344 }
345 }
346
347 #[test]
348 fn public_key_rs256_round_trips() {
349 let key = PublicKey::RS256 {
350 n: vec![0x04u8; 256],
351 e: vec![0x01, 0x00, 0x01],
352 };
353 let json = serde_json::to_string(&key).unwrap();
354 let back: PublicKey = serde_json::from_str(&json).unwrap();
355 match back {
356 PublicKey::RS256 { n, e } => {
357 assert_eq!(n, vec![0x04u8; 256]);
358 assert_eq!(e, vec![0x01, 0x00, 0x01]);
359 }
360 _ => panic!("wrong variant"),
361 }
362 }
363
364 #[test]
365 fn credential_round_trips() {
366 let cred = Credential {
367 id: vec![0xAAu8; 16],
368 public_key: PublicKey::ES256 {
369 x: vec![0x01u8; 32],
370 y: vec![0x02u8; 32],
371 },
372 sign_count: 42,
373 user_id: vec![0xBBu8; 8],
374 rp_id: "example.com".to_string(),
375 created_at: epoch_plus(1_700_000_000),
376 backup_eligible: true,
377 };
378 let json = serde_json::to_string(&cred).unwrap();
379 let back: Credential = serde_json::from_str(&json).unwrap();
380 assert_eq!(back.id, cred.id);
381 assert_eq!(back.sign_count, cred.sign_count);
382 assert_eq!(back.user_id, cred.user_id);
383 assert_eq!(back.rp_id, cred.rp_id);
384 assert_eq!(back.created_at, cred.created_at);
385 assert_eq!(back.backup_eligible, cred.backup_eligible);
386 }
387}