tollgate-auth 0.32.0

Credential verification for latency-critical services: digests at rest, and a session-scoped cache that removes the per-request digest without widening the revocation window.
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
//! The concrete verifier in the box: server-issued API keys held as
//! HMAC-SHA256 digests.
//!
//! The digest table is a *projection*, not the system of record. Durable
//! credential lifecycle lives in a `KeyDirectory` (`tollgate-store`), and the
//! control plane installs the active set here the way it installs account
//! snapshots into a `SnapshotMap`. That split is why verification can stay
//! I/O-free on the request path (INVARIANTS.md GL-5, GL-6) while issuance and
//! revocation remain transactional and fleet-wide.

use std::collections::HashMap;
use std::sync::Arc;

use arc_swap::ArcSwap;
use hmac::{Hmac, Mac};
use jiff::Timestamp;
use sha2::Sha256;
use subtle::ConstantTimeEq;
use tollgate_core::{KeyId, Principal};
use zeroize::Zeroizing;

use crate::verifier::{CredentialVerifier, Verified};

type HmacSha256 = Hmac<Sha256>;

/// How many bytes of entropy a minted secret carries.
///
/// 32 bytes from the OS CSPRNG. The digest is HMAC-SHA256 and its own output
/// is 32 bytes, so a longer secret would not raise the strength of what is
/// stored, and a shorter one would be the weakest link in a chain whose other
/// links are all 256 bits.
const SECRET_BYTES: usize = 32;

/// A freshly minted credential, returned exactly once.
///
/// The secret is [`Zeroizing`], so the only copy the process holds is wiped
/// when this value drops. The digest is suitable for durable storage; debug
/// output exposes only the non-secret identifiers.
///
/// **Nothing can recover the secret from the record.** That is the point of
/// storing digests, and it is also the constraint on issuance ordering: the
/// record must be durable *before* the secret is disclosed, because a crash
/// between the two leaves a credential the server has never heard of and no
/// reconciliation can repair it.
pub struct MintedKey {
    /// The non-secret identifier for this credential, used to revoke it.
    pub key_id: KeyId,
    /// The principal it authenticates as: the digest's leading 128 bits.
    pub principal: Principal,
    /// HMAC-SHA256 of the secret under the server secret. This is what a
    /// `tollgate_store::KeyDirectory` stores.
    pub digest: [u8; 32],
    /// The credential: 64 lowercase hexadecimal characters, exactly the bytes
    /// the digest covers. It is what is disclosed, what a customer presents
    /// (for example after `Bearer `), and what a verifier is handed, with no
    /// encoding step anywhere between them. Hand it to its owner and drop it;
    /// it cannot be derived again from anything retained.
    pub secret: Zeroizing<Vec<u8>>,
}

impl std::fmt::Debug for MintedKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MintedKey")
            .field("key_id", &self.key_id)
            .field("principal", &self.principal)
            .finish_non_exhaustive()
    }
}

/// One credential as the projection holds it.
#[derive(Clone, Copy)]
struct ProjectedKey {
    digest: [u8; 32],
    /// Surfaced through [`Verified::reusable_until`], so a session cache
    /// cannot outlive the credential it authenticated with.
    not_after: Option<Timestamp>,
}

/// Credentials held as HMAC-SHA256 digests under a server secret.
///
/// **Digests at rest is the non-negotiable property.** A raw-credential map
/// would verify in tens of nanoseconds, but every place the map lives —
/// process memory, a core dump, a backup — would then hold usable
/// credentials, so one read leaks every customer's key. Timing is not what
/// rules that out (credentials are high-entropy and the map is randomly
/// keyed); exposure is.
///
/// The truncated digest is the [`Principal`] admission is keyed by, and the
/// *full* digest is what the comparison decides on, so truncation is never the
/// deciding comparison.
///
/// **Why HMAC and not a plain SHA-256 digest**, which is cheaper: HMAC splits
/// the secret from the digest table, so neither alone verifies anything. That
/// is worth paying for at the rate a digest is actually computed — once per
/// session under [`SessionCredential`], not once per request. Measured on one
/// machine: HMAC-SHA256 741 ns against SHA-256 184 ns, a 4x difference that
/// amortises to about 5.6 ns per request at a hundred requests per session,
/// against a ~23 ns cached path neither touches. The cheaper digest buys a
/// saving that rounds to nothing and costs a real security property.
///
/// **The table is arc-swapped**, not locked. Installation is an operator-rate
/// event and verification is on the request path, so readers must never block
/// behind a writer — the same reasoning, and the same mechanism, as
/// `ArcSwapSnapshotMap`. A write clones the table; that cost is paid by
/// whoever is issuing keys, not by whoever is serving requests.
///
/// An embedder who disagrees is not stuck with this: implement
/// [`CredentialVerifier`] instead.
///
/// [`SessionCredential`]: crate::SessionCredential
pub struct HmacRegistry {
    secret: Zeroizing<Vec<u8>>,
    keys: ArcSwap<HashMap<u128, ProjectedKey>>,
}

impl std::fmt::Debug for HmacRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HmacRegistry")
            .field("projected_keys", &self.len())
            .finish_non_exhaustive()
    }
}

impl HmacRegistry {
    /// A registry keyed by `secret`, holding no credentials until one is
    /// installed. Load the secret from the environment or a secret store;
    /// never commit one.
    #[must_use]
    pub fn new(secret: &[u8]) -> Self {
        HmacRegistry {
            secret: Zeroizing::new(secret.to_vec()),
            keys: ArcSwap::from_pointee(HashMap::new()),
        }
    }

    fn digest(&self, credential: &[u8]) -> [u8; 32] {
        let mut mac = HmacSha256::new_from_slice(&self.secret).expect("any key length works");
        mac.update(credential);
        mac.finalize().into_bytes().into()
    }

    /// The stable identity of a digest: its leading 128 bits.
    fn fingerprint(digest: &[u8; 32]) -> u128 {
        let mut bytes = [0u8; 16];
        bytes.copy_from_slice(&digest[..16]);
        u128::from_be_bytes(bytes)
    }

    /// Derive the durable digest and identity of an existing credential without
    /// installing it. This supports fixture bootstrap and imports; new issuance
    /// should use [`Self::mint`] so entropy comes from the OS. Persist the digest
    /// before projecting it, and never persist or log the credential argument.
    pub fn digest_credential(&self, credential: &[u8]) -> (Principal, [u8; 32]) {
        let digest = self.digest(credential);
        (Principal(Self::fingerprint(&digest)), digest)
    }

    /// Generate a credential and return it once, with the non-secret record
    /// its durable half needs.
    ///
    /// The secret comes from the OS CSPRNG rather than from a caller, because
    /// "generate it properly, show it once, never store it" is exactly the
    /// part of issuance that goes wrong quietly, and it is not a thing each
    /// embedder should re-implement. The registry does **not** install the
    /// result: publish the record durably first, then project it.
    ///
    /// # Errors
    ///
    /// Fails only if the operating system cannot supply entropy, which is not
    /// a condition to paper over with a weaker source.
    ///
    /// The credential is minted in its textual form, and the digest covers
    /// that text. A credential disclosed as text but digested as the bytes it
    /// encodes verifies only for a caller that decodes it first, and every
    /// caller that forwards what it was presented — a `Bearer` header, as the
    /// reference embedder does — would be refused with no error anywhere.
    pub fn mint(&self, key_id: KeyId) -> Result<MintedKey, EntropyUnavailable> {
        const DIGITS: &[u8; 16] = b"0123456789abcdef";
        let mut entropy = Zeroizing::new([0u8; SECRET_BYTES]);
        getrandom::fill(entropy.as_mut_slice()).map_err(|_| EntropyUnavailable)?;
        let mut secret = Zeroizing::new(Vec::with_capacity(SECRET_BYTES * 2));
        for byte in entropy.iter() {
            secret.push(DIGITS[usize::from(byte >> 4)]);
            secret.push(DIGITS[usize::from(byte & 0x0f)]);
        }
        let (principal, digest) = self.digest_credential(&secret);
        Ok(MintedKey {
            key_id,
            principal,
            digest,
            secret,
        })
    }

    /// Replace the projection with the currently active credential set.
    ///
    /// Whole-table replacement, never a merge: the directory decides which
    /// credentials are live, and a registry that merged would keep verifying
    /// a credential the directory has already retired. This is the same
    /// contract `SnapshotMap` publication has, for the same reason.
    pub fn install(
        &self,
        keys: impl IntoIterator<Item = (Principal, [u8; 32], Option<Timestamp>)>,
    ) {
        let projected: HashMap<u128, ProjectedKey> = keys
            .into_iter()
            .map(|(principal, digest, not_after)| (principal.0, ProjectedKey { digest, not_after }))
            .collect();
        self.keys.store(Arc::new(projected));
    }

    /// Project a set of credentials this process did not mint.
    ///
    /// For fixtures, and for an embedder importing a key set it already
    /// holds. Prefer [`mint`](Self::mint) with a durable record: a credential
    /// accepted here was generated somewhere this crate cannot vouch for, and
    /// "shown once, never stored" then rests on the caller having done it
    /// right — the part of issuance most worth centralising.
    ///
    /// Returns the principal each credential authenticates as, in the order
    /// given.
    pub fn install_credentials(
        &self,
        credentials: impl IntoIterator<Item = impl AsRef<[u8]>>,
    ) -> Vec<Principal> {
        let projected: Vec<_> = credentials
            .into_iter()
            .map(|credential| {
                let (principal, digest) = self.digest_credential(credential.as_ref());
                (principal, digest, None)
            })
            .collect();
        let principals = projected.iter().map(|(p, _, _)| *p).collect();
        self.install(projected);
        principals
    }

    /// How many credentials the projection currently holds. For readiness
    /// reporting and tests; the digests themselves are never exposed.
    #[must_use]
    pub fn len(&self) -> usize {
        self.keys.load().len()
    }

    /// Whether the projection is empty, which for a serving instance means
    /// every credential will be refused.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// The operating system could not supply entropy for a new credential.
///
/// Its own type rather than a `bool` or a swallowed default: a mint that
/// cannot be random must fail loudly, because the alternative is issuing a
/// guessable credential that verifies perfectly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EntropyUnavailable;

impl std::fmt::Display for EntropyUnavailable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("the operating system could not supply entropy for a new credential")
    }
}

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

impl CredentialVerifier for HmacRegistry {
    /// A credential's own expiry, when it carries one, travels back through
    /// [`Verified::reusable_until`] so the session cache cannot outlive it.
    /// A credential without one is indefinite: it stops being accepted when
    /// it stops being projected, or when the account behind it is revoked —
    /// and revocation travels by snapshot, which admission consults on every
    /// request regardless of any cache.
    fn verify(&self, credential: &[u8]) -> Option<Verified> {
        let digest = self.digest(credential);
        let principal = Self::fingerprint(&digest);
        let keys = self.keys.load();
        let projected = keys.get(&principal)?;
        if projected.digest.ct_eq(&digest).into() {
            Some(match projected.not_after {
                Some(until) => Verified::until(Principal(principal), until),
                None => Verified::indefinite(Principal(principal)),
            })
        } else {
            None
        }
    }
}

impl crate::CredentialIssuer for HmacRegistry {
    /// The inherent method, exposed through the seam. Minting is the registry's
    /// job either way; the trait exists so a server can hold the capability
    /// without naming this type — and so a deployment that does not issue can
    /// hold nothing at all.
    fn mint(&self, key_id: KeyId) -> Result<MintedKey, EntropyUnavailable> {
        HmacRegistry::mint(self, key_id)
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::disallowed_methods,
        reason = "unit tests that build an arbitrary `now` the assertions are relative to; \
                  no assertion here depends on what the clock actually said"
    )]
    #[test]
    fn credential_diagnostics_never_disclose_issuer_or_customer_secrets() {
        let secret = b"fixture-debug-redaction-hmac-secret-108";
        let registry = HmacRegistry::new(secret);
        let key = registry.mint(KeyId(1)).unwrap();
        registry.install([(key.principal, key.digest, None)]);
        let diagnostic = format!("{registry:?} {key:?}");
        for protected in [
            format!("{secret:?}"),
            format!("{:?}", *key.secret),
            format!("{:?}", key.digest),
        ] {
            assert!(!diagnostic.contains(&protected));
        }
        assert!(diagnostic.contains("projected_keys: 1"));
    }

    use super::*;

    /// The minted credential is its presented form: 64 lowercase hex
    /// characters, verified exactly as disclosed and not after decoding.
    #[test]
    fn a_minted_credential_verifies_as_the_text_it_is_disclosed_as() {
        let registry = HmacRegistry::new(b"fixture-presented-form-secret-143");
        let key = registry.mint(KeyId(1)).unwrap();
        assert_eq!(key.secret.len(), 64);
        assert!(
            key.secret
                .iter()
                .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
        );
        registry.install([(key.principal, key.digest, None)]);
        assert_eq!(
            registry.verify(&key.secret).map(|v| v.principal),
            Some(key.principal)
        );
        let decoded: Vec<u8> = key
            .secret
            .chunks(2)
            .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
            .collect();
        assert!(
            registry.verify(&decoded).is_none(),
            "the decoded bytes are not the credential"
        );
    }

    fn registry() -> HmacRegistry {
        let registry = HmacRegistry::new(b"server-secret");
        registry.install_credentials([b"key-one".as_slice()]);
        registry
    }

    #[test]
    fn a_registered_credential_verifies_to_a_stable_principal_with_no_expiry() {
        let registry = registry();
        assert_eq!(registry.verify(b"key-one"), registry.verify(b"key-one"));
        let verified = registry.verify(b"key-one").expect("registered");
        assert_eq!(
            verified.reusable_until, None,
            "a server-issued key does not expire on its own; withdrawal travels by snapshot"
        );
    }

    #[test]
    fn an_unregistered_or_altered_credential_does_not_verify() {
        let registry = registry();
        assert_eq!(registry.verify(b"key-two"), None);
        assert_eq!(registry.verify(b"key-one "), None);
        assert_eq!(registry.verify(b""), None);
    }

    /// The secret is half the proof: a digest table lifted without it verifies
    /// nothing. This is the property HMAC is paid for, so it is checked rather
    /// than assumed.
    #[test]
    fn the_same_credential_under_a_different_secret_is_a_different_principal() {
        let other = HmacRegistry::new(b"a-different-secret");
        let elsewhere = other.install_credentials([b"key-one".as_slice()])[0];
        assert_ne!(
            registry().verify(b"key-one").expect("registered").principal,
            elsewhere
        );
    }

    /// The registry stores digests, never credentials. Nothing else in the
    /// crate would notice if that broke, and it is the whole reason for the
    /// design, so it gets its own witness.
    #[test]
    fn no_credential_is_retained_in_the_registry() {
        let registry = registry();
        let credential: &[u8] = b"key-one";
        for projected in registry.keys.load().values() {
            assert!(
                !projected
                    .digest
                    .windows(credential.len())
                    .any(|w| w == credential),
                "a stored digest contains the credential it came from"
            );
        }
        assert!(
            !registry
                .secret
                .windows(credential.len())
                .any(|w| w == credential),
            "the secret contains the credential"
        );
    }
}