entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
624
625
626
627
//! API key generation, hashing, and verification.
//!
//! API keys follow the format `esw_<prefix>_<secret>` where:
//!
//! - `prefix` is 8 hex characters (4 random bytes) used for key
//!   identification in logs and dashboards without exposing the secret.
//! - `secret` is 64 hex characters (32 random bytes) — the sensitive
//!   portion that proves possession.
//!
//! Only the SHA-256 hash of the secret is stored for verification. The
//! plaintext secret is shown to the user exactly once at generation time
//! and is never persisted.
//!
//! # Security
//!
//! - The secret portion is wrapped in [`Zeroizing`] so it is cleared from
//!   memory on drop.
//! - Verification uses constant-time comparison to prevent timing
//!   side-channel attacks.
//! - `Debug` and `Display` implementations redact the secret, showing
//!   only the prefix.

use core::fmt;

use crate::crypto::constant_time::constant_time_eq;
use crate::crypto::zeroize::Zeroizing;
use crate::crypto::{Sha256, fill_random};
use crate::encoding::{hex_decode, hex_encode};
use crate::util::log::{debug, info, warn};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Key format prefix identifying Entropy Softworks API keys.
const KEY_PREFIX: &str = "esw";

/// Number of random bytes for the visible prefix (encoded as 8 hex chars).
const PREFIX_BYTE_LEN: usize = 4;

/// Number of random bytes for the secret portion (encoded as 64 hex chars).
const SECRET_BYTE_LEN: usize = 32;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// The kind of error encountered during API key operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ApiKeyErrorKind {
    /// The platform CSPRNG failed during key generation.
    RandomFailure,
    /// The key string does not match the expected `esw_<prefix>_<secret>` format.
    InvalidFormat,
    /// The prefix segment is not valid hex or has the wrong length.
    InvalidPrefix,
    /// The secret segment is not valid hex or has the wrong length.
    InvalidSecret,
}

/// Error returned by API key generation and parsing operations.
///
/// Error messages describe the failure without revealing any secret material.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiKeyError {
    kind: ApiKeyErrorKind,
}

impl ApiKeyError {
    const fn new(kind: ApiKeyErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for ApiKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            ApiKeyErrorKind::RandomFailure => {
                write!(f, "api_key: CSPRNG failed during key generation")
            }
            ApiKeyErrorKind::InvalidFormat => {
                write!(
                    f,
                    "api_key: key does not match \"esw_<prefix>_<secret>\" format"
                )
            }
            ApiKeyErrorKind::InvalidPrefix => {
                write!(
                    f,
                    "api_key: prefix segment is invalid (expected 8 hex characters)"
                )
            }
            ApiKeyErrorKind::InvalidSecret => {
                write!(
                    f,
                    "api_key: secret segment is invalid (expected 64 hex characters)"
                )
            }
        }
    }
}

impl std::error::Error for ApiKeyError {}

// ---------------------------------------------------------------------------
// ApiKey — holds the plaintext key (shown once at generation)
// ---------------------------------------------------------------------------

/// A plaintext API key in `esw_<prefix>_<secret>` format.
///
/// The secret portion is wrapped in [`Zeroizing`] and cleared from memory
/// on drop. This type is returned from [`generate`](Self::generate) and
/// should be displayed to the user exactly once — it must **never** be
/// persisted or logged.
pub struct ApiKey {
    /// The 8-character hex prefix used for identification.
    prefix: String,
    // SECURITY: The secret portion is zeroized on drop to prevent it
    // from lingering in process memory after use.
    /// The 64-character hex-encoded secret.
    secret: Zeroizing<String>,
    /// The full key string `esw_<prefix>_<secret>`.
    full_key: Zeroizing<String>,
}

impl ApiKey {
    /// Generates a new API key and its corresponding hash for storage.
    ///
    /// Returns the plaintext key (to show to the user once) and the hash
    /// (to store in the database for later verification).
    ///
    /// # Errors
    ///
    /// Returns [`ApiKeyError`] if the platform CSPRNG fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::ApiKey;
    ///
    /// let (key, hash) = ApiKey::generate().unwrap();
    /// // Show `key.as_str()` to the user once; persist only `hash`.
    /// assert!(key.verify(&hash));
    /// ```
    pub fn generate() -> Result<(Self, ApiKeyHash), ApiKeyError> {
        // Generate random bytes for prefix and secret.
        let mut prefix_bytes = [0u8; PREFIX_BYTE_LEN];
        let mut secret_bytes = [0u8; SECRET_BYTE_LEN];

        fill_random(&mut prefix_bytes)
            .map_err(|_| ApiKeyError::new(ApiKeyErrorKind::RandomFailure))?;
        fill_random(&mut secret_bytes)
            .map_err(|_| ApiKeyError::new(ApiKeyErrorKind::RandomFailure))?;

        let prefix = hex_encode(&prefix_bytes);
        let secret_hex = hex_encode(&secret_bytes);

        // SECURITY: Hash the secret for storage. Only the hash is persisted;
        // the plaintext secret is returned to the caller and then forgotten.
        // A single unsalted SHA-256 is deliberate (not Argon2/salted): the
        // secret is a full-entropy 256-bit random value, so there is no
        // low-entropy/dictionary space to attack and no need to slow guessing
        // — unlike a human-chosen password. Verification compares the stored
        // hash in constant time.
        let secret_hash = Sha256::digest(secret_bytes.as_slice());

        // SECURITY: Zeroize the raw secret bytes from the stack now that
        // we have the hex encoding and the hash.
        crate::crypto::zeroize::zeroize(&mut secret_bytes);

        let full_key = format!("{KEY_PREFIX}_{prefix}_{secret_hex}");

        let api_key = Self {
            prefix: prefix.clone(),
            secret: Zeroizing::new(secret_hex),
            full_key: Zeroizing::new(full_key),
        };

        let hash = ApiKeyHash {
            prefix,
            secret_hash,
        };

        // SECURITY: Log only the prefix — never the secret portion.
        info!(prefix = %api_key.prefix, "api_key: generated");

        Ok((api_key, hash))
    }

    /// Parses an API key from its string representation.
    ///
    /// The input must match the format `esw_<prefix>_<secret>` where
    /// `prefix` is 8 hex characters and `secret` is 64 hex characters.
    ///
    /// # Errors
    ///
    /// Returns [`ApiKeyError`] if the format, prefix, or secret segment
    /// is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::ApiKey;
    ///
    /// let (key, hash) = ApiKey::generate().unwrap();
    /// let parsed = ApiKey::parse(key.as_str()).unwrap();
    /// assert!(parsed.verify(&hash));
    ///
    /// assert!(ApiKey::parse("not-an-api-key").is_err());
    /// ```
    pub fn parse(key_str: &str) -> Result<Self, ApiKeyError> {
        let parts: Vec<&str> = key_str.splitn(3, '_').collect();
        if parts.len() != 3 || parts[0] != KEY_PREFIX {
            return Err(ApiKeyError::new(ApiKeyErrorKind::InvalidFormat));
        }

        let prefix_str = parts[1];
        let secret_str = parts[2];

        // Validate prefix: must be exactly 8 hex characters (4 bytes).
        if prefix_str.len() != PREFIX_BYTE_LEN * 2 {
            return Err(ApiKeyError::new(ApiKeyErrorKind::InvalidPrefix));
        }
        // Verify it decodes as valid hex.
        hex_decode(prefix_str).map_err(|_| ApiKeyError::new(ApiKeyErrorKind::InvalidPrefix))?;

        // Validate secret: must be exactly 64 hex characters (32 bytes).
        if secret_str.len() != SECRET_BYTE_LEN * 2 {
            return Err(ApiKeyError::new(ApiKeyErrorKind::InvalidSecret));
        }
        hex_decode(secret_str).map_err(|_| ApiKeyError::new(ApiKeyErrorKind::InvalidSecret))?;

        Ok(Self {
            prefix: prefix_str.to_owned(),
            secret: Zeroizing::new(secret_str.to_owned()),
            full_key: Zeroizing::new(key_str.to_owned()),
        })
    }

    /// Returns the 8-character hex prefix used for key identification.
    ///
    /// The prefix is safe to log and display — it does not contain
    /// secret material.
    #[must_use]
    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    /// Returns the full key string `esw_<prefix>_<secret>`.
    ///
    /// **Security warning**: This exposes the secret. Only use this to
    /// display the key to the user at generation time.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.full_key
    }

    /// Verifies this key against a stored [`ApiKeyHash`] using
    /// constant-time comparison.
    ///
    /// Returns `true` if the prefix matches and the SHA-256 hash of
    /// this key's secret matches the stored hash.
    ///
    /// # Security
    ///
    /// The hash comparison uses [`constant_time_eq`](crate::constant_time_eq)
    /// so an attacker cannot learn how many leading hash bytes they guessed
    /// correctly via timing. The prefix comparison is *not* constant-time
    /// because the prefix is not secret (it appears in logs and dashboards).
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::ApiKey;
    ///
    /// let (key, hash) = ApiKey::generate().unwrap();
    /// assert!(key.verify(&hash));
    ///
    /// let (other, _) = ApiKey::generate().unwrap();
    /// assert!(!other.verify(&hash));
    /// ```
    #[must_use]
    pub fn verify(&self, hash: &ApiKeyHash) -> bool {
        if self.prefix != hash.prefix {
            warn!(prefix = %self.prefix, "api_key: verification failed (prefix mismatch)");
            return false;
        }

        // Decode the hex secret to bytes, then hash for comparison. Wrap in
        // `Zeroizing` so the plaintext secret copy is scrubbed on drop,
        // matching the discipline in `generate`.
        let Ok(secret_bytes) = hex_decode(&self.secret).map(Zeroizing::new) else {
            warn!(prefix = %self.prefix, "api_key: verification failed");
            return false;
        };

        let computed_hash = Sha256::digest(&secret_bytes);

        // SECURITY: constant_time_eq prevents an attacker from learning
        // how many leading bytes of the hash they have guessed correctly.
        let matches = constant_time_eq(&computed_hash, &hash.secret_hash);

        if matches {
            debug!(prefix = %self.prefix, "api_key: verified");
        } else {
            warn!(prefix = %self.prefix, "api_key: verification failed");
        }

        matches
    }
}

// SECURITY: Debug redacts the secret, showing only the prefix.
impl fmt::Debug for ApiKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ApiKey")
            .field("prefix", &self.prefix)
            .field("secret", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

// SECURITY: Display shows the key in redacted form for safe logging.
impl fmt::Display for ApiKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "esw_{}_[REDACTED]", self.prefix)
    }
}

// ---------------------------------------------------------------------------
// ApiKeyHash — stored in the database for verification
// ---------------------------------------------------------------------------

/// The stored representation of an API key.
///
/// Contains the visible prefix (for lookup) and the SHA-256 hash of the
/// secret (for verification). This type is safe to persist — it does not
/// contain the plaintext secret.
#[derive(Clone)]
pub struct ApiKeyHash {
    /// The 8-character hex prefix for key identification / lookup.
    prefix: String,
    /// SHA-256 hash of the secret portion.
    secret_hash: [u8; 32],
}

impl ApiKeyHash {
    /// Returns the 8-character hex prefix.
    #[must_use]
    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    /// Returns the SHA-256 hash of the secret portion.
    #[must_use]
    pub fn secret_hash(&self) -> &[u8; 32] {
        &self.secret_hash
    }

    /// Constructs an `ApiKeyHash` from a prefix and secret hash.
    ///
    /// This is useful when loading a stored key hash from a database.
    #[must_use]
    pub fn from_parts(prefix: String, secret_hash: [u8; 32]) -> Self {
        Self {
            prefix,
            secret_hash,
        }
    }
}

// SECURITY: Debug does not reveal the secret hash bytes.
impl fmt::Debug for ApiKeyHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ApiKeyHash")
            .field("prefix", &self.prefix)
            .field("secret_hash", &"[HASH]")
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // --- Generation and Verification ---

    #[test]
    fn generate_and_verify() {
        let (key, hash) = ApiKey::generate().unwrap();
        assert!(
            key.verify(&hash),
            "generated key should verify against its own hash",
        );
    }

    #[test]
    fn generate_produces_correct_format() {
        let (key, _hash) = ApiKey::generate().unwrap();
        let full = key.as_str();
        assert!(full.starts_with("esw_"), "key should start with 'esw_'");

        let parts: Vec<&str> = full.splitn(3, '_').collect();
        assert_eq!(
            parts.len(),
            3,
            "key should have 3 underscore-delimited parts"
        );
        assert_eq!(parts[0], "esw");
        assert_eq!(parts[1].len(), 8, "prefix should be 8 hex chars");
        assert_eq!(parts[2].len(), 64, "secret should be 64 hex chars");
    }

    #[test]
    fn generate_keys_are_unique() {
        let (key1, _) = ApiKey::generate().unwrap();
        let (key2, _) = ApiKey::generate().unwrap();
        assert_ne!(
            key1.as_str(),
            key2.as_str(),
            "two generated keys should differ",
        );
    }

    // --- Parse Round-Trip ---

    #[test]
    fn parse_round_trip() {
        let (key, hash) = ApiKey::generate().unwrap();
        let key_str = key.as_str().to_owned();

        let parsed = ApiKey::parse(&key_str).unwrap();
        assert_eq!(parsed.prefix(), key.prefix());
        assert!(
            parsed.verify(&hash),
            "parsed key should verify against the original hash",
        );
    }

    #[test]
    fn parse_valid_key() {
        // Construct a known-good key string.
        let key_str =
            "esw_deadbeef_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let key = ApiKey::parse(key_str).unwrap();
        assert_eq!(key.prefix(), "deadbeef");
        assert_eq!(key.as_str(), key_str);
    }

    // --- Parse Error Cases ---

    #[test]
    fn parse_rejects_missing_esw_prefix() {
        let err = ApiKey::parse("xxx_deadbeef_aabb").unwrap_err();
        assert_eq!(err.kind, ApiKeyErrorKind::InvalidFormat);
    }

    #[test]
    fn parse_rejects_too_few_segments() {
        let err = ApiKey::parse("esw_onlyone").unwrap_err();
        assert_eq!(err.kind, ApiKeyErrorKind::InvalidFormat);
    }

    #[test]
    fn parse_rejects_wrong_prefix_length() {
        // Prefix too short (6 chars instead of 8).
        let err = ApiKey::parse(
            "esw_abcdef_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        )
        .unwrap_err();
        assert_eq!(err.kind, ApiKeyErrorKind::InvalidPrefix);
    }

    #[test]
    fn parse_rejects_wrong_secret_length() {
        // Secret too short.
        let err = ApiKey::parse("esw_deadbeef_aabbccdd").unwrap_err();
        assert_eq!(err.kind, ApiKeyErrorKind::InvalidSecret);
    }

    #[test]
    fn parse_rejects_non_hex_prefix() {
        let err = ApiKey::parse(
            "esw_zzzzzzzz_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        )
        .unwrap_err();
        assert_eq!(err.kind, ApiKeyErrorKind::InvalidPrefix);
    }

    #[test]
    fn parse_rejects_non_hex_secret() {
        let err = ApiKey::parse(
            "esw_deadbeef_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
        )
        .unwrap_err();
        assert_eq!(err.kind, ApiKeyErrorKind::InvalidSecret);
    }

    // --- Verification Failures ---

    #[test]
    fn wrong_key_fails_verify() {
        let (_key1, hash1) = ApiKey::generate().unwrap();
        let (key2, _hash2) = ApiKey::generate().unwrap();

        assert!(
            !key2.verify(&hash1),
            "a different key should not verify against another key's hash",
        );
    }

    #[test]
    fn tampered_secret_fails_verify() {
        let (key, hash) = ApiKey::generate().unwrap();
        // Modify one character in the secret portion.
        let key_str = key.as_str();
        let mut chars: Vec<char> = key_str.chars().collect();
        // The secret starts after "esw_" + 8 prefix chars + "_" = index 13
        let idx = 13;
        chars[idx] = if chars[idx] == 'a' { 'b' } else { 'a' };
        let tampered: String = chars.into_iter().collect();

        let tampered_key = ApiKey::parse(&tampered).unwrap();
        assert!(
            !tampered_key.verify(&hash),
            "tampered key should fail verification",
        );
    }

    // --- Prefix Visibility ---

    #[test]
    fn prefix_is_visible() {
        let (key, hash) = ApiKey::generate().unwrap();
        // Prefix should be 8 hex characters.
        assert_eq!(key.prefix().len(), 8);
        assert!(key.prefix().chars().all(|c| c.is_ascii_hexdigit()));
        // Hash prefix should match.
        assert_eq!(key.prefix(), hash.prefix());
    }

    // --- Debug / Display Redaction ---

    #[test]
    fn debug_redacts_secret() {
        let (key, _) = ApiKey::generate().unwrap();
        let debug = format!("{key:?}");
        assert!(
            debug.contains("[REDACTED]"),
            "Debug should contain [REDACTED]: {debug}",
        );
        // The full secret should NOT appear in debug output.
        // The secret is 64 hex chars — check that a substantial
        // portion is not present.
        let secret_start = &key.as_str()[13..29]; // 16 chars of secret
        assert!(
            !debug.contains(secret_start),
            "Debug should not contain secret material: {debug}",
        );
    }

    #[test]
    fn display_shows_redacted_form() {
        let (key, _) = ApiKey::generate().unwrap();
        let display = format!("{key}");
        assert!(
            display.starts_with("esw_"),
            "Display should start with esw_"
        );
        assert!(
            display.ends_with("_[REDACTED]"),
            "Display should end with _[REDACTED]: {display}",
        );
        assert!(
            display.contains(key.prefix()),
            "Display should contain the prefix",
        );
    }

    #[test]
    fn api_key_hash_debug_redacts_hash() {
        let (_, hash) = ApiKey::generate().unwrap();
        let debug = format!("{hash:?}");
        assert!(
            debug.contains("[HASH]"),
            "ApiKeyHash Debug should contain [HASH]: {debug}",
        );
    }

    // --- Error Display ---

    #[test]
    fn error_display_messages() {
        let cases = [
            (
                ApiKeyError::new(ApiKeyErrorKind::RandomFailure),
                "api_key: CSPRNG failed during key generation",
            ),
            (
                ApiKeyError::new(ApiKeyErrorKind::InvalidFormat),
                "api_key: key does not match \"esw_<prefix>_<secret>\" format",
            ),
            (
                ApiKeyError::new(ApiKeyErrorKind::InvalidPrefix),
                "api_key: prefix segment is invalid (expected 8 hex characters)",
            ),
            (
                ApiKeyError::new(ApiKeyErrorKind::InvalidSecret),
                "api_key: secret segment is invalid (expected 64 hex characters)",
            ),
        ];
        for (err, expected) in &cases {
            assert_eq!(err.to_string(), *expected);
        }
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(ApiKeyError::new(ApiKeyErrorKind::InvalidFormat));
        let _ = err.to_string();
    }
}