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
//! Authentication and authorization primitives for Entropy Softworks
//! Rust projects.
//!
//! This crate provides a reusable authentication foundation for server
//! and API backends. Dependencies are kept minimal: [`argon2`] for
//! memory-hard password hashing and [`tracing`] for structured
//! diagnostic instrumentation. Beyond these, all cryptographic
//! primitives, encoding utilities, and protocol logic are implemented
//! from their respective specifications using only `std`.
//!
//! # Quick start
//!
//! ```
//! use entropy_auth::crypto::{Sha256, HmacSha256};
//! use entropy_auth::encoding::{base64_encode, hex_encode};
//!
//! // SHA-256 digest
//! let hash = Sha256::digest(b"hello world");
//! assert_eq!(hex_encode(&hash).len(), 64);
//!
//! // HMAC-SHA256
//! let mac = HmacSha256::mac(b"secret-key", b"message");
//! assert!(HmacSha256::verify(b"secret-key", b"message", &mac));
//! ```
//!
//! # Dependencies
//!
//! | Dependency | Kind | Purpose |
//! |---|---|---|
//! | `argon2` | required | Argon2id memory-hard password hashing |
//! | `tracing` | required | Structured diagnostic instrumentation |
//! | `aes-gcm` | required | AES-256-GCM for the secret-box (encryption at rest) |
//! | `rand_core` | required | CSPRNG plumbing for the secret-box nonce |
//! | `webauthn-rs` | required | `WebAuthn` / passkey ceremonies (pulls in `OpenSSL` transitively) |
//! | `serde` + `serde_json` | required | PRF-extension JSON wiring for `WebAuthn` |
//! | `ed25519-dalek`, `p256`, `rsa`, `sha2` | optional (`asym-jwt`) | Asymmetric JWT signing/verification |
//!
//! The always-on cryptographic primitives that *are* implemented in-crate
//! — SHA-2, HMAC, encoding (Base64, hex, URL), and protocol logic
//! (OAuth 2.0, JWT, OIDC, SAML) — use only `std`. The AES-GCM secret-box
//! and `WebAuthn` ceremonies are the exception: they delegate to the
//! well-audited `aes-gcm` and `webauthn-rs` crates rather than
//! reimplementing AEAD or the `WebAuthn` state machine.
//!
//! # Feature flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `saml` | no | SAML 2.0 support (includes XML parser) |
//! | `oidc` | no | `OpenID` Connect support (enables `asym-jwt`) |
//! | `asym-jwt` | no | Asymmetric JWT: EdDSA/ES256 signing + verification, RS256/RS512 **verify-only**, and JWKS (pulls in `RustCrypto` curve crates and `rsa`) |
//! | `ssh-keys` | no | SSH public key parsing and fingerprinting |
//!
//! Core security capabilities — TOTP (RFC 6238), Have I Been Pwned
//! breach checking, the AES-GCM secret-box, and `WebAuthn` / passkey
//! ceremonies — are **always compiled in**: per the crate's "no feature
//! flags for core security" policy they have no opt-in flag and are
//! available regardless of the features above.
//!
//! # Security
//!
//! All cryptographic implementations are tested against published test
//! vectors (NIST CAVP, RFC 4231, RFC 6238). Secret material is stored
//! in [`Zeroizing`] wrappers (this crate's
//! own zero-dependency implementation) that clear memory on drop. All
//! secret comparisons use
//! [`constant_time_eq`] to prevent
//! timing side-channel attacks.
//!
//! See [`SECURITY.md`](https://gitlab.com/entropysoftworks/crates/auth/-/blob/main/SECURITY.md)
//! for the full security policy.
//!
//! # Error handling
//!
//! Each module defines its own error type that implements
//! `std::error::Error`, `Debug`, `Clone`, `Display`. Error messages
//! never contain secret material — passwords, tokens, and keys are
//! redacted from all diagnostic output.
//!
//! # Modules
//!
//! - [`crypto`] — SHA-1/2, HMAC, platform CSPRNG, AES-GCM secret-box, plus
//!   the [`constant_time`](crypto::constant_time) (timing-safe comparison)
//!   and [`zeroize`](crypto::zeroize) (secret-memory clearing) primitives.
//! - [`encoding`] — Base64, Base32, hex, and URL percent-encoding.
//! - [`util`] — Shared utilities: [`timestamp`](util::timestamp) (UTC via
//!   the Hinnant civil-date algorithm) and [`validation`](util::validation)
//!   (names, usernames, and OAuth parameters).
//! - [`session`] — Session token management with expiry and idle timeout,
//!   plus opaque [`token`](session::token) generation.
//! - [`local`] — Local username/password credential management, including
//!   [`password`](local::password) hashing and verification (Argon2id).
//! - [`api`] — API key generation/verification, HMAC request signing, bearer tokens.
//! - [`json`] — Minimal RFC 8259 JSON parser for token responses.
//! - [`jwt`] — JWT minting + verification: HMAC (HS256/HS512) always-on,
//!   asymmetric (EdDSA/ES256) + JWKS + key rotation behind `asym-jwt` (RFC
//!   7519/7515/7517/7518/7638/8037).
//! - [`oauth`] — OAuth 2.0 Authorization Code + PKCE flow (RFC 6749/7636).
//! - [`provider`] — Unified [`AuthProviderKind`], [`AuthIdentity`], [`AuthResult`], [`AuthError`].
//! - [`mfa`] — Multi-factor / account security: [`totp`](mfa::totp) (always-on)
//!   and [`hibp`](mfa::hibp) k-anonymity breach checking (always-on).
//! - [`ssh`] — SSH public key parsing and fingerprinting (requires `ssh-keys`).
//! - [`webauthn`] — `WebAuthn` / passkey ceremonies (always-on).

// Lint configuration lives in `Cargo.toml` under `[lints]`. Only
// crate-level attributes that cannot be expressed there remain here.
//
// Forbid unsafe code in production. Tests may use `unsafe` for env var
// manipulation (Rust 2024 edition marks env mutations as unsafe).
// The only production-code exceptions are the volatile-write zeroization
// helpers in `crypto/zeroize.rs`, `crypto/sha1.rs`, and `crypto/sha2.rs`,
// which carry scoped `#[allow(unsafe_code)]` for `core::ptr::write_volatile`
// (the CSPRNG goes through `rand_core::OsRng`, which contains no `unsafe`).
// NOTE: `deny` rather than `forbid` so those scoped `#[allow(unsafe_code)]`
// sites can opt back in — `forbid` cannot be overridden by `allow`.
#![cfg_attr(not(test), deny(unsafe_code))]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

pub mod api;
pub mod crypto;
pub mod encoding;
pub mod json;
pub mod jwt;
pub mod local;
pub mod mfa;
pub mod oauth;
pub mod session;
pub mod util;

pub mod provider;

#[cfg(feature = "oidc")]
pub mod oidc;

#[cfg(feature = "saml")]
pub mod saml;

#[cfg(feature = "scim")]
pub mod scim;

#[cfg(feature = "ldap")]
pub mod ldap;
#[cfg(feature = "policy")]
pub mod policy;
#[cfg(feature = "saml")]
pub mod xml;

#[cfg(feature = "ssh-keys")]
pub mod ssh;

pub mod webauthn;

// ---------------------------------------------------------------------------
// Re-exports — crate root convenience imports
// ---------------------------------------------------------------------------

// Re-export the most commonly used items at the crate root for
// convenience. The full module paths remain available for explicit
// imports.
pub use crypto::constant_time::constant_time_eq;
pub use crypto::zeroize::{ZeroizeOnDrop, Zeroizing};
pub use crypto::{
    HmacSha1, HmacSha256, HmacSha512, RandomError, Sha1, Sha256, Sha512, fill_random,
    random_token_base64url, random_token_hex,
};
pub use encoding::{
    Base32DecodeError, Base64DecodeError, HexDecodeError, UrlDecodeError, base32_decode,
    base32_encode, base64_decode, base64_encode, base64url_decode, base64url_encode, hex_decode,
    hex_encode, hex_encode_upper, url_decode, url_encode, url_encode_component,
};
pub use util::timestamp::Timestamp;
pub use util::validation::{
    CLIENT_ID_RULES, DEFAULT_SPECIAL_CHARS, EMAIL_RULES, MAX_CLIENT_ID_LEN, MAX_EMAIL_LEN,
    MAX_NAME_LEN, MAX_REDIRECT_URI_LEN, MAX_SCOPE_LEN, MAX_USERNAME_LEN, NAME_RULES,
    PASSWORD_RULES, PasswordRules, REDIRECT_URI_RULES, SCOPE_RULES, USERNAME_RULES, is_https_url,
    is_valid_client_id, is_valid_email, is_valid_name, is_valid_redirect_uri, is_valid_scope,
    is_valid_username, validate_password_strength,
};

// Local authentication, password, and session/token types.
pub use local::password::{PasswordConfig, PasswordError, PasswordHash, verify_credential};
pub use local::{
    CredentialStore, Credentials, InMemoryCredentialStore, InMemoryStoreError, StoredCredential,
    Username, UsernameError,
};
pub use session::token::{generate_token, generate_token_with_hash, hash_token_for_lookup};
pub use session::{Session, SessionConfig, SessionError, SessionValidation};

// API authentication types.
pub use api::{
    ApiKey, ApiKeyError, ApiKeyHash, BearerError, HmacAuthError, HmacRequestSigner,
    HmacRequestVerifier, extract_bearer_token,
};

// JSON and JWT types.
pub use json::{JsonParseError, JsonValue};
pub use jwt::{
    IntoCustomClaim, JwtAlgorithm, JwtClaims, JwtClaimsError, JwtEncoder, JwtHeader,
    JwtHeaderError, JwtSignatureError, JwtSigningAlgorithm, verify_jwt,
};

// Asymmetric JWT signing/verification + JWKS (feature `asym-jwt`,
// transitively enabled by `oidc`).
#[cfg(feature = "asym-jwt")]
pub use jwt::{
    AsymmetricAlgorithm, AsymmetricKeyError, AsymmetricSigningKey, AsymmetricVerifyingKey, Jwk,
    JwkError, JwkSet, KeyRing, verify_jwt_asymmetric,
};

// OAuth 2.0 types.
pub use oauth::{
    AuthorizationRequest, OAuthConfig, OAuthConfigBuilder, OAuthConfigError, OAuthState,
    PkceChallenge, RefreshRequest, TokenExchangeRequest, TokenResponse, TokenResponseError,
};

// OAuth 2.0 authorization-server (IdP) types.
pub use oauth::server::{
    AuthorizeError, AuthorizeErrorCode, AuthorizeRedirectError, AuthorizeRequest, ClientAuthResult,
    ClientCredentialsDenied, ClientCredentialsRequest, ClientCredentialsVerdict, ClientType,
    CodeRedemptionDenied, CodeRedemptionVerdict, DisplayErrorReason, IdTokenBuilder,
    IntrospectionResponse, RefreshDenied, RefreshOutcome, RefreshPresented, RegisteredClient,
    RegisteredClientBuilder, RegisteredClientError, StoredAuthCode, StoredRefreshToken,
    TokenRequestPresented, ValidatedAuthorizeRequest, evaluate_client_credentials,
    evaluate_code_redemption, evaluate_refresh, validate_authorize_request,
};
// `private_key_jwt` client-assertion verification (asymmetric — feature-gated).
#[cfg(feature = "asym-jwt")]
pub use oauth::server::{ClientAssertion, ClientAssertionDenied, verify_client_assertion};

// OpenID Connect types (feature-gated).
#[cfg(feature = "oidc")]
pub use oidc::{
    FederatedClaims, FederationContext, FederationDenied, FederationOutcome, FederationVerdict,
    IdTokenClaims, IdTokenClaimsError, IdTokenError, IdTokenValidator, OidcDiscovery,
    OidcDiscoveryError, UserInfo, UserInfoError, evaluate_federation,
};

// SAML 2.0 types (feature-gated).
#[cfg(feature = "saml")]
pub use saml::{
    SamlAssertion, SamlAttribute, SamlConditions, SamlConfig, SamlConfigError, SamlResponse,
    SamlResponseError, SamlStatus, SamlSubject, generate_sp_metadata,
};
#[cfg(feature = "saml")]
pub use xml::{XmlElement, XmlParseError, parse_xml, xml_escape};

// MFA / account-security types: TOTP and HIBP breach checking.
pub use mfa::hibp::{BreachResult, HibpError, HibpPrefix, HibpResponse, hibp_sha1_hex};
pub use mfa::totp::{
    TotpAlgorithm, TotpConfig, TotpError, TotpSecret, generate_recovery_codes, totp_generate,
    totp_verify, totp_verify_step,
};

// SSH key types (feature-gated).
#[cfg(feature = "ssh-keys")]
pub use ssh::{SshKeyAlgorithm, SshKeyError, SshPublicKey};

// WebAuthn / passkey types.
pub use webauthn::{
    AuthenticationCeremony, AuthenticationChallenge, AuthenticationOutcome, CredentialID,
    InMemoryPasskeyStore, InMemoryPasskeyStoreError, PRF_SALT_LEN, Passkey, PasskeyAuthentication,
    PasskeyCredential, PasskeyCredentialStore, PasskeyRegistration, PasskeyUser,
    PrfAuthenticationRequest, PrfClientResult, PrfRegistrationRequest, PrfSalt,
    PublicKeyCredential, RegisterPublicKeyCredential, RegistrationCeremony, RegistrationChallenge,
    RegistrationOutcome, RelyingParty, RelyingPartyBuilder, StoredPasskey, Uuid, WebAuthnError,
};

// Secret-box (AES-GCM) re-exports.
pub use crate::crypto::secret_box::{SecretBox, SecretBoxError};

// Integration layer types.
pub use provider::{AuthError, AuthIdentity, AuthProviderKind, AuthResult};

// Compile-time assertions that all public types are thread-safe. These
// prevent accidental regressions from future refactors that might
// introduce non-Send/Sync fields.
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    // Crypto types.
    assert_send_sync::<Sha1>();
    assert_send_sync::<Sha256>();
    assert_send_sync::<Sha512>();
    assert_send_sync::<HmacSha1>();
    assert_send_sync::<HmacSha256>();
    assert_send_sync::<HmacSha512>();

    // Encoding error types.
    assert_send_sync::<Base32DecodeError>();
    assert_send_sync::<Base64DecodeError>();
    assert_send_sync::<HexDecodeError>();
    assert_send_sync::<UrlDecodeError>();
    assert_send_sync::<RandomError>();

    // Timestamp.
    assert_send_sync::<Timestamp>();

    // Zeroize wrapper (Vec<u8> and String are Send+Sync).
    assert_send_sync::<Zeroizing<Vec<u8>>>();
    assert_send_sync::<Zeroizing<String>>();

    // Password, session, credential, and local auth types.
    assert_send_sync::<PasswordHash>();
    assert_send_sync::<PasswordConfig>();
    assert_send_sync::<PasswordError>();
    assert_send_sync::<Session>();
    assert_send_sync::<SessionConfig>();
    assert_send_sync::<SessionError>();
    assert_send_sync::<SessionValidation>();
    assert_send_sync::<Username>();
    assert_send_sync::<UsernameError>();
    assert_send_sync::<Credentials>();
    assert_send_sync::<StoredCredential>();
    assert_send_sync::<InMemoryCredentialStore>();

    // API authentication types (API keys, HMAC signing, bearer tokens).
    assert_send_sync::<ApiKey>();
    assert_send_sync::<ApiKeyHash>();
    assert_send_sync::<ApiKeyError>();
    assert_send_sync::<HmacRequestSigner>();
    assert_send_sync::<HmacRequestVerifier>();
    assert_send_sync::<HmacAuthError>();
    assert_send_sync::<BearerError>();

    // JSON and JWT types.
    assert_send_sync::<JsonValue>();
    assert_send_sync::<JsonParseError>();
    assert_send_sync::<JwtAlgorithm>();
    assert_send_sync::<JwtHeader>();
    assert_send_sync::<JwtHeaderError>();
    assert_send_sync::<JwtClaims>();
    assert_send_sync::<JwtClaimsError>();
    assert_send_sync::<JwtSignatureError>();
    assert_send_sync::<JwtEncoder>();
    assert_send_sync::<JwtSigningAlgorithm>();

    // OAuth 2.0 types.
    assert_send_sync::<OAuthConfig>();
    assert_send_sync::<OAuthConfigBuilder>();
    assert_send_sync::<OAuthConfigError>();
    assert_send_sync::<PkceChallenge>();
    assert_send_sync::<OAuthState>();
    assert_send_sync::<AuthorizationRequest>();
    assert_send_sync::<TokenExchangeRequest>();
    assert_send_sync::<TokenResponse>();
    assert_send_sync::<TokenResponseError>();
    assert_send_sync::<RefreshRequest>();

    // OAuth 2.0 authorization-server (IdP) types. The borrowed view types
    // (AuthorizeRequest<'_>, StoredAuthCode<'_>, …) are asserted with a
    // 'static lifetime; their fields are &str / Copy and Send + Sync.
    assert_send_sync::<RegisteredClient>();
    assert_send_sync::<RegisteredClientBuilder>();
    assert_send_sync::<ClientType>();
    assert_send_sync::<AuthorizeRequest<'static>>();
    assert_send_sync::<ValidatedAuthorizeRequest>();
    assert_send_sync::<AuthorizeError>();
    assert_send_sync::<AuthorizeErrorCode>();
    assert_send_sync::<AuthorizeRedirectError>();
    assert_send_sync::<DisplayErrorReason>();
    assert_send_sync::<ClientAuthResult>();
    assert_send_sync::<StoredAuthCode<'static>>();
    assert_send_sync::<TokenRequestPresented<'static>>();
    assert_send_sync::<CodeRedemptionDenied>();
    assert_send_sync::<CodeRedemptionVerdict>();
    assert_send_sync::<StoredRefreshToken<'static>>();
    assert_send_sync::<RefreshPresented<'static>>();
    assert_send_sync::<RefreshDenied>();
    assert_send_sync::<RefreshOutcome>();
    assert_send_sync::<IntrospectionResponse>();
    assert_send_sync::<IdTokenBuilder>();

    // Integration layer types.
    assert_send_sync::<AuthProviderKind>();
    assert_send_sync::<AuthIdentity>();
    assert_send_sync::<AuthResult>();
    assert_send_sync::<AuthError>();
};

// Feature-gated Send+Sync assertions.
#[cfg(feature = "oidc")]
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<OidcDiscovery>();
    assert_send_sync::<OidcDiscoveryError>();
    assert_send_sync::<IdTokenClaims>();
    assert_send_sync::<IdTokenClaimsError>();
    assert_send_sync::<IdTokenValidator>();
    assert_send_sync::<IdTokenError>();
    assert_send_sync::<UserInfo>();
    assert_send_sync::<UserInfoError>();
};

// Asymmetric JWT + JWKS types (feature-gated).
#[cfg(feature = "asym-jwt")]
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<AsymmetricAlgorithm>();
    assert_send_sync::<AsymmetricKeyError>();
    assert_send_sync::<AsymmetricSigningKey>();
    assert_send_sync::<AsymmetricVerifyingKey>();
    assert_send_sync::<Jwk>();
    assert_send_sync::<JwkError>();
    assert_send_sync::<JwkSet>();
    assert_send_sync::<KeyRing>();
};

#[cfg(feature = "saml")]
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<SamlConfig>();
    assert_send_sync::<SamlConfigError>();
    assert_send_sync::<SamlResponse>();
    assert_send_sync::<SamlResponseError>();
    assert_send_sync::<SamlStatus>();
    assert_send_sync::<SamlAssertion>();
    assert_send_sync::<SamlSubject>();
    assert_send_sync::<SamlConditions>();
    assert_send_sync::<SamlAttribute>();
    assert_send_sync::<XmlElement>();
    assert_send_sync::<XmlParseError>();
};

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<BreachResult>();
    assert_send_sync::<HibpError>();
    assert_send_sync::<HibpPrefix>();
    assert_send_sync::<HibpResponse>();
};

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<TotpAlgorithm>();
    assert_send_sync::<TotpConfig>();
    assert_send_sync::<TotpError>();
    assert_send_sync::<TotpSecret>();
};

#[cfg(feature = "ssh-keys")]
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<SshKeyAlgorithm>();
    assert_send_sync::<SshKeyError>();
    assert_send_sync::<SshPublicKey>();
};

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<SecretBox>();
    assert_send_sync::<SecretBoxError>();
};

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<WebAuthnError>();
    assert_send_sync::<PrfSalt>();
    assert_send_sync::<PrfClientResult>();
    assert_send_sync::<RelyingParty>();
    assert_send_sync::<RelyingPartyBuilder>();
    assert_send_sync::<PasskeyCredential>();
    assert_send_sync::<InMemoryPasskeyStore>();
    assert_send_sync::<InMemoryPasskeyStoreError>();
    assert_send_sync::<StoredPasskey>();
    assert_send_sync::<RegistrationOutcome>();
    assert_send_sync::<AuthenticationOutcome>();
    assert_send_sync::<PasskeyUser>();
    assert_send_sync::<webauthn::RegistrationChallenge>();
    assert_send_sync::<webauthn::AuthenticationChallenge>();
};