footing 0.1.9

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Small cryptographic building blocks for application glue code.
//!
//! The module intentionally stays below business protocols. It provides secure
//! random tokens and bytes, token hashing, PKCE S256 helpers, numeric
//! verification codes, constant-time comparison, and signed opaque tokens that
//! can rotate verification keys.
//!
//! ```rust
//! use footing::crypto::{SignedTokenCodec, TokenGenerator};
//!
//! let token = TokenGenerator::default().generate().unwrap();
//! assert!(!token.expose().is_empty());
//!
//! let codec = SignedTokenCodec::new(b"01234567890123456789012345678901").unwrap();
//! let signed = codec.encode(&serde_json::json!({ "sub": "usr_01" })).unwrap();
//! let decoded: serde_json::Value = codec.decode(&signed).unwrap();
//! assert_eq!(decoded["sub"], "usr_01");
//! ```
//!
use std::fmt;

use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use hmac::{Hmac, KeyInit, Mac};
use serde::{Serialize, de::DeserializeOwned};
use sha2::{Digest as _, Sha256};
use thiserror::Error;
use zeroize::Zeroizing;

use crate::result::{ClassifyError, ErrorKind};
use crate::secret::{ExposeSecret, SecretBytes, SecretString};

type HmacSha256 = Hmac<Sha256>;

/// Minimum signing key size for HMAC-SHA256 tokens.
pub const MIN_SIGNING_KEY_BYTES: usize = 32;

/// Default random token entropy.
pub const DEFAULT_TOKEN_BYTES: usize = 32;

/// Maximum accepted signed token length.
pub const DEFAULT_MAX_SIGNED_TOKEN_BYTES: usize = 8 * 1024;

/// Maximum supported numeric code length.
pub const MAX_NUMERIC_CODE_DIGITS: u32 = 18;

/// Compares two byte slices without early-exiting on the first different byte.
#[must_use]
pub fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    let mut diff = left.len() ^ right.len();
    let max_len = left.len().max(right.len());

    for index in 0..max_len {
        let left = left.get(index).copied().unwrap_or_default();
        let right = right.get(index).copied().unwrap_or_default();
        diff |= usize::from(left ^ right);
    }

    diff == 0
}

/// Generates random bytes from the operating system secure random source.
pub fn random_bytes(length: usize) -> Result<Vec<u8>, CryptoError> {
    if length == 0 {
        return Err(CryptoError::InvalidTokenSize);
    }

    let mut bytes = vec![0_u8; length];
    getrandom::fill(&mut bytes).map_err(|_| CryptoError::Random)?;
    Ok(bytes)
}

/// Generates a fixed-size random byte array.
pub fn random_array<const N: usize>() -> Result<[u8; N], CryptoError> {
    if N == 0 {
        return Err(CryptoError::InvalidTokenSize);
    }

    let mut bytes = [0_u8; N];
    getrandom::fill(&mut bytes).map_err(|_| CryptoError::Random)?;
    Ok(bytes)
}

/// Hashes bytes with SHA-256 and encodes the digest as URL-safe base64 without padding.
#[must_use]
pub fn sha256_urlsafe(value: impl AsRef<[u8]>) -> String {
    URL_SAFE_NO_PAD.encode(Sha256::digest(value.as_ref()))
}

/// Stable URL-safe SHA-256 hashing for tokens, lookup keys, and rate-limit keys.
///
/// The helper intentionally exposes a small API around a widely used digest so
/// application code does not hand-roll separators or encode digests
/// inconsistently. `hash_parts` length-prefixes each part before hashing, so
/// callers can compose keys without delimiter ambiguity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct StableKeyHasher;

impl StableKeyHasher {
    #[must_use]
    /// Creates a new instance.
    pub const fn new() -> Self {
        Self
    }

    /// Hashes one value with SHA-256 and URL-safe base64 without padding.
    #[must_use]
    pub fn hash(self, value: impl AsRef<[u8]>) -> String {
        sha256_urlsafe(value)
    }

    /// Hashes multiple key parts using unambiguous length-prefix framing.
    #[must_use]
    pub fn hash_parts<I, P>(self, parts: I) -> String
    where
        I: IntoIterator<Item = P>,
        P: AsRef<[u8]>,
    {
        let mut hasher = Sha256::new();
        for part in parts {
            let part = part.as_ref();
            let len = part.len() as u64;
            hasher.update(len.to_be_bytes());
            hasher.update(part);
        }
        URL_SAFE_NO_PAD.encode(hasher.finalize())
    }
}

/// A semantic alias for hashing opaque tokens before persistence.
pub type TokenHasher = StableKeyHasher;

/// Computes a PKCE S256 challenge for a verifier.
#[must_use]
pub fn pkce_s256_challenge(verifier: &str) -> String {
    sha256_urlsafe(verifier.as_bytes())
}

/// Verifies a PKCE S256 challenge.
#[must_use]
pub fn verify_pkce_s256(verifier: &str, expected_challenge: &str) -> bool {
    let actual = pkce_s256_challenge(verifier);
    constant_time_eq(actual.as_bytes(), expected_challenge.as_bytes())
}

/// Generates URL-safe random tokens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TokenGenerator {
    token_bytes: usize,
}

impl Default for TokenGenerator {
    fn default() -> Self {
        Self {
            token_bytes: DEFAULT_TOKEN_BYTES,
        }
    }
}

impl TokenGenerator {
    /// Creates a token generator.
    pub const fn new(token_bytes: usize) -> Result<Self, CryptoError> {
        if token_bytes == 0 {
            return Err(CryptoError::InvalidTokenSize);
        }
        Ok(Self { token_bytes })
    }

    /// Returns the number of random bytes used per token.
    #[must_use]
    pub const fn token_bytes(&self) -> usize {
        self.token_bytes
    }

    /// Generates a new URL-safe token.
    pub fn generate(&self) -> Result<OpaqueToken, CryptoError> {
        let bytes = random_bytes(self.token_bytes)?;
        Ok(OpaqueToken::new(URL_SAFE_NO_PAD.encode(bytes)))
    }
}

/// Generates human-entered numeric verification codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct NumericCodeGenerator {
    digits: u32,
}

impl NumericCodeGenerator {
    /// Creates a numeric code generator.
    pub const fn new(digits: u32) -> Result<Self, CryptoError> {
        if digits == 0 || digits > MAX_NUMERIC_CODE_DIGITS {
            return Err(CryptoError::InvalidNumericCodeDigits {
                min_digits: 1,
                max_digits: MAX_NUMERIC_CODE_DIGITS,
            });
        }
        Ok(Self { digits })
    }

    /// Returns the configured number of digits.
    #[must_use]
    pub const fn digits(&self) -> u32 {
        self.digits
    }

    /// Generates a zero-padded numeric code using unbiased rejection sampling.
    pub fn generate(&self) -> Result<String, CryptoError> {
        let modulo = 10_u64.pow(self.digits);
        let value = random_u64_below(modulo)?;
        Ok(format!("{value:0width$}", width = self.digits as usize))
    }
}

/// A random token that redacts all implicit formatting.
#[derive(Clone, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub struct OpaqueToken {
    value: SecretString,
}

impl OpaqueToken {
    /// Wraps a token string.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: SecretString::new(value),
        }
    }

    /// Explicitly exposes the token value.
    #[must_use]
    pub fn expose(&self) -> &str {
        self.value.expose_secret()
    }

    /// Consumes the wrapper and returns the token value.
    #[must_use]
    pub fn into_secret(self) -> String {
        self.value.into_secret()
    }
}

impl fmt::Debug for OpaqueToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(formatter)
    }
}

impl fmt::Display for OpaqueToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(formatter)
    }
}

/// Encodes and verifies signed JSON tokens.
#[derive(Clone)]
#[non_exhaustive]
pub struct SignedTokenCodec {
    active_key: Zeroizing<Vec<u8>>,
    previous_keys: Vec<Zeroizing<Vec<u8>>>,
    max_token_bytes: usize,
}

impl SignedTokenCodec {
    /// Creates a codec with the active signing key.
    pub fn new(active_key: impl AsRef<[u8]>) -> Result<Self, CryptoError> {
        Ok(Self {
            active_key: validate_signing_key(active_key)?,
            previous_keys: Vec::new(),
            max_token_bytes: DEFAULT_MAX_SIGNED_TOKEN_BYTES,
        })
    }

    /// Adds one previous verification key for key rotation.
    pub fn with_previous_key(mut self, key: impl AsRef<[u8]>) -> Result<Self, CryptoError> {
        self.previous_keys.push(validate_signing_key(key)?);
        Ok(self)
    }

    /// Adds multiple previous verification keys for key rotation.
    pub fn with_previous_keys<I, K>(mut self, keys: I) -> Result<Self, CryptoError>
    where
        I: IntoIterator<Item = K>,
        K: AsRef<[u8]>,
    {
        for key in keys {
            self.previous_keys.push(validate_signing_key(key)?);
        }
        Ok(self)
    }

    /// Sets the maximum accepted signed token size.
    pub fn with_max_token_bytes(mut self, max_token_bytes: usize) -> Result<Self, CryptoError> {
        if max_token_bytes == 0 {
            return Err(CryptoError::InvalidSignedTokenMaxBytes);
        }
        self.max_token_bytes = max_token_bytes;
        Ok(self)
    }

    /// Encodes and signs a serializable payload.
    pub fn encode<T>(&self, value: &T) -> Result<String, CryptoError>
    where
        T: Serialize,
    {
        let bytes = serde_json::to_vec(value).map_err(|_| CryptoError::Serialization)?;
        let payload = URL_SAFE_NO_PAD.encode(bytes);
        let signature = sign(self.active_key.as_slice(), payload.as_bytes())?;
        let token = format!("v1.{payload}.{signature}");
        validate_signed_token_length(&token, self.max_token_bytes)?;
        Ok(token)
    }

    /// Verifies and decodes a signed token.
    pub fn decode<T>(&self, token: &str) -> Result<T, CryptoError>
    where
        T: DeserializeOwned,
    {
        validate_signed_token_length(token, self.max_token_bytes)?;
        let (version, rest) = token.split_once('.').ok_or(CryptoError::InvalidToken)?;
        if version != "v1" {
            return Err(CryptoError::UnsupportedTokenVersion);
        }
        let (payload, signature) = rest.split_once('.').ok_or(CryptoError::InvalidToken)?;
        self.verify(payload.as_bytes(), signature)?;
        let bytes = URL_SAFE_NO_PAD
            .decode(payload)
            .map_err(|_| CryptoError::InvalidToken)?;
        serde_json::from_slice(&bytes).map_err(|_| CryptoError::Serialization)
    }

    fn verify(&self, payload: &[u8], signature: &str) -> Result<(), CryptoError> {
        if verify_signature(self.active_key.as_slice(), payload, signature).is_ok() {
            return Ok(());
        }

        if self
            .previous_keys
            .iter()
            .any(|key| verify_signature(key.as_slice(), payload, signature).is_ok())
        {
            return Ok(());
        }

        Err(CryptoError::InvalidSignature)
    }
}

impl fmt::Debug for SignedTokenCodec {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SignedTokenCodec")
            .field("active_key", &SecretBytes::new(self.active_key.to_vec()))
            .field("previous_key_count", &self.previous_keys.len())
            .field("max_token_bytes", &self.max_token_bytes)
            .finish()
    }
}

/// Crypto helper errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum CryptoError {
    /// Token size must be non-zero.
    #[error("token size must be greater than zero")]
    InvalidTokenSize,
    /// Numeric code size is unsupported.
    #[error("numeric code digits must be between {min_digits} and {max_digits}")]
    InvalidNumericCodeDigits {
        #[doc = "The minimum number of digits."]
        min_digits: u32,
        #[doc = "The maximum number of digits."]
        max_digits: u32,
    },
    /// Random integer upper bound is invalid.
    #[error("random integer upper bound must be greater than zero")]
    InvalidRandomBound,
    /// Random source failed.
    #[error("secure random source failed")]
    Random,
    /// Signing key is too short.
    #[error("signing key must be at least {min_bytes} bytes")]
    InvalidSigningKey {
        #[doc = "The minimum number of bytes."]
        min_bytes: usize,
    },
    /// Token exceeds the configured maximum length.
    #[error("signed token is too large")]
    TokenTooLarge,
    /// Signed token maximum length is invalid.
    #[error("signed token max bytes must be greater than zero")]
    InvalidSignedTokenMaxBytes,
    /// Token shape is invalid.
    #[error("signed token is invalid")]
    InvalidToken,
    /// Token version is unsupported.
    #[error("signed token version is unsupported")]
    UnsupportedTokenVersion,
    /// Token signature is invalid.
    #[error("signed token signature is invalid")]
    InvalidSignature,
    /// JSON serialization or deserialization failed.
    #[error("signed token payload serialization failed")]
    Serialization,
}

impl ClassifyError for CryptoError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidTokenSize
            | Self::InvalidNumericCodeDigits { .. }
            | Self::InvalidRandomBound
            | Self::InvalidSigningKey { .. }
            | Self::TokenTooLarge
            | Self::InvalidSignedTokenMaxBytes
            | Self::InvalidToken
            | Self::UnsupportedTokenVersion
            | Self::InvalidSignature
            | Self::Serialization => ErrorKind::Validation,
            Self::Random => ErrorKind::Unavailable,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidTokenSize => "invalid_token_size",
            Self::InvalidNumericCodeDigits { .. } => "invalid_numeric_code_digits",
            Self::InvalidRandomBound => "invalid_random_bound",
            Self::Random => "secure_random_unavailable",
            Self::InvalidSigningKey { .. } => "invalid_signing_key",
            Self::TokenTooLarge => "token_too_large",
            Self::InvalidSignedTokenMaxBytes => "invalid_signed_token_max_bytes",
            Self::InvalidToken => "invalid_token",
            Self::UnsupportedTokenVersion => "unsupported_token_version",
            Self::InvalidSignature => "invalid_signature",
            Self::Serialization => "token_serialization_failed",
        })
    }
}

fn validate_signing_key(key: impl AsRef<[u8]>) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
    let key = key.as_ref();
    if key.len() < MIN_SIGNING_KEY_BYTES {
        return Err(CryptoError::InvalidSigningKey {
            min_bytes: MIN_SIGNING_KEY_BYTES,
        });
    }
    Ok(Zeroizing::new(key.to_vec()))
}

fn validate_signed_token_length(token: &str, max_token_bytes: usize) -> Result<(), CryptoError> {
    if max_token_bytes == 0 {
        return Err(CryptoError::InvalidSignedTokenMaxBytes);
    }
    if token.len() > max_token_bytes {
        return Err(CryptoError::TokenTooLarge);
    }
    Ok(())
}

fn sign(key: &[u8], payload: &[u8]) -> Result<String, CryptoError> {
    let mut mac = HmacSha256::new_from_slice(key).map_err(|_| CryptoError::InvalidSigningKey {
        min_bytes: MIN_SIGNING_KEY_BYTES,
    })?;
    mac.update(payload);
    Ok(URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()))
}

fn verify_signature(key: &[u8], payload: &[u8], signature: &str) -> Result<(), CryptoError> {
    let expected = URL_SAFE_NO_PAD
        .decode(signature)
        .map_err(|_| CryptoError::InvalidSignature)?;
    let mut mac = HmacSha256::new_from_slice(key).map_err(|_| CryptoError::InvalidSignature)?;
    mac.update(payload);
    mac.verify_slice(&expected)
        .map_err(|_| CryptoError::InvalidSignature)
}

fn random_u64_below(upper_bound: u64) -> Result<u64, CryptoError> {
    if upper_bound == 0 {
        return Err(CryptoError::InvalidRandomBound);
    }

    let acceptance_zone = u64::MAX - (u64::MAX % upper_bound);
    loop {
        let candidate = u64::from_be_bytes(random_array::<8>()?);
        if candidate < acceptance_zone {
            return Ok(candidate % upper_bound);
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    const KEY: &[u8] = b"01234567890123456789012345678901";
    const OLD_KEY: &[u8] = b"abcdefghijklmnopqrstuvwxyz123456";

    #[test]
    fn constant_time_compare_requires_same_bytes() {
        assert!(constant_time_eq(b"same", b"same"));
        assert!(!constant_time_eq(b"same", b"diff"));
        assert!(!constant_time_eq(b"same", b"same-but-longer"));
    }

    #[test]
    fn token_generator_returns_redacted_url_safe_token() {
        let token = TokenGenerator::new(16)
            .expect("valid token size")
            .generate()
            .expect("token should generate");

        assert!(!token.expose().is_empty());
        assert_eq!(format!("{token:?}"), "[REDACTED]");
        assert_eq!(format!("{token}"), "[REDACTED]");
    }

    #[test]
    fn random_numeric_code_is_zero_padded() {
        let code = NumericCodeGenerator::new(8)
            .expect("valid digits")
            .generate()
            .expect("code should generate");

        assert_eq!(code.len(), 8);
        assert!(code.chars().all(|ch| ch.is_ascii_digit()));
    }

    #[test]
    fn stable_key_hasher_hashes_parts_without_delimiter_ambiguity() {
        let hasher = StableKeyHasher::new();

        assert_ne!(
            hasher.hash_parts([b"ab".as_slice(), b"c".as_slice()]),
            hasher.hash_parts([b"a".as_slice(), b"bc".as_slice()])
        );
        assert!(!hasher.hash(b"token").is_empty());
        assert!(!hasher.hash_parts([b"token".as_slice()]).is_empty());
    }

    #[test]
    fn pkce_s256_matches_rfc_vector() {
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";

        assert_eq!(
            pkce_s256_challenge(verifier),
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        );
        assert!(verify_pkce_s256(
            verifier,
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        ));
        assert!(!verify_pkce_s256(verifier, "invalid"));
    }

    #[test]
    fn signed_token_round_trips_json_payload() {
        let codec = SignedTokenCodec::new(KEY).expect("valid key");
        let token = codec
            .encode(&json!({ "sub": "usr_01" }))
            .expect("token should encode");
        let decoded: serde_json::Value = codec.decode(&token).expect("token should decode");

        assert_eq!(decoded["sub"], "usr_01");
    }

    #[test]
    fn signed_token_accepts_previous_key_for_rotation() {
        let old_codec = SignedTokenCodec::new(OLD_KEY).expect("valid key");
        let token = old_codec
            .encode(&json!({ "sub": "usr_01" }))
            .expect("token should encode");

        let rotated = SignedTokenCodec::new(KEY)
            .expect("valid key")
            .with_previous_key(OLD_KEY)
            .expect("valid previous key");
        let decoded: serde_json::Value = rotated.decode(&token).expect("token should decode");

        assert_eq!(decoded["sub"], "usr_01");
    }

    #[test]
    fn signed_token_rejects_tampering() {
        let codec = SignedTokenCodec::new(KEY).expect("valid key");
        let token = codec
            .encode(&json!({ "sub": "usr_01" }))
            .expect("token should encode");
        let mut tampered = token.clone();
        let last = tampered.pop().expect("token should not be empty");
        tampered.push(if last == 'A' { 'B' } else { 'A' });

        assert_eq!(
            codec.decode::<serde_json::Value>(&tampered).unwrap_err(),
            CryptoError::InvalidSignature
        );
    }

    #[test]
    fn signed_token_rejects_invalid_size_limits() {
        assert_eq!(
            SignedTokenCodec::new(KEY)
                .expect("valid key")
                .with_max_token_bytes(0)
                .expect_err("zero max token bytes should fail"),
            CryptoError::InvalidSignedTokenMaxBytes
        );

        let codec = SignedTokenCodec::new(KEY)
            .expect("valid key")
            .with_max_token_bytes(8)
            .expect("limit should be valid");
        assert_eq!(
            codec.encode(&json!({ "sub": "usr_01" })).unwrap_err(),
            CryptoError::TokenTooLarge
        );
    }
}