hyperlane_plugin_auth/struct.rs
1use super::*;
2
3/// JWT JWS header decoded from the first segment of a compact token.
4#[derive(Clone, Data, Debug, Deserialize, Eq, PartialEq, Serialize)]
5pub struct JwtHeader {
6 /// JWS algorithm identifier (must be `"HS256"`).
7 pub(crate) alg: String,
8 /// Optional token type (`"JWT"`).
9 #[serde(skip_serializing_if = "Option::is_none")]
10 #[get(type(clone))]
11 pub(crate) typ: Option<String>,
12 /// Optional key identifier used for zero-downtime key rotation.
13 #[serde(skip_serializing_if = "Option::is_none")]
14 #[get(type(clone))]
15 pub(crate) kid: Option<String>,
16}
17
18/// Zero-copy borrowed JWT JWS header used during token verification.
19#[derive(Deserialize)]
20pub(crate) struct JwtHeaderRef<'a> {
21 /// JWS algorithm identifier borrowed from decoded stack bytes when unescaped.
22 #[serde(borrow)]
23 pub(crate) alg: Cow<'a, str>,
24 /// Optional key identifier borrowed from decoded stack bytes when unescaped.
25 #[serde(borrow, default)]
26 pub(crate) kid: Option<Cow<'a, str>>,
27}
28
29/// Precomputed HMAC-SHA256 inner and outer SHA-256 midstates for a secret key.
30#[derive(Clone, Copy, Debug)]
31pub(crate) struct HmacSha256Key {
32 /// SHA-256 state after compressing the 64-byte `key ^ 0x36` ipad block.
33 pub(crate) inner_state: [u32; 8],
34 /// SHA-256 state after compressing the 64-byte `key ^ 0x5c` opad block.
35 pub(crate) outer_state: [u32; 8],
36}
37
38/// Stack-backed `io::Write` buffer spilling to the heap only when payload exceeds `JWT_STACK_ENCODE_CAP`.
39pub(crate) struct StackJsonBuf {
40 /// Inline stack storage for typical JWT claim payloads.
41 pub(crate) stack: [u8; JWT_STACK_ENCODE_CAP],
42 /// Number of valid bytes in `stack` when `heap` is `None`.
43 pub(crate) len: usize,
44 /// Heap fallback used only for payloads exceeding `JWT_STACK_ENCODE_CAP`.
45 pub(crate) heap: Option<Vec<u8>>,
46}
47
48/// Zero-buffering Serde [`Visitor`] for single-pass [`JwtClaims`] JSON deserialization.
49pub(crate) struct JwtClaimsVisitor;
50
51/// Zero-allocation Serde [`Visitor`] decoding [`JwtClaimField`] keys without cloning standard names.
52pub(crate) struct JwtClaimFieldVisitor;
53
54/// Standard and extensible JSON Web Token claims payload.
55#[derive(Clone, Data, Debug, Default, PartialEq)]
56pub struct JwtClaims {
57 /// Subject identifier (`sub`).
58 pub(crate) sub: String,
59 /// Optional issuer (`iss`).
60 #[get(type(clone))]
61 pub(crate) iss: Option<String>,
62 /// Optional audience (`aud`).
63 #[get(type(clone))]
64 pub(crate) aud: Option<String>,
65 /// Optional expiration Unix timestamp in seconds (`exp`).
66 #[get(type(copy))]
67 pub(crate) exp: Option<u64>,
68 /// Optional not-before Unix timestamp in seconds (`nbf`).
69 #[get(type(copy))]
70 pub(crate) nbf: Option<u64>,
71 /// Optional issued-at Unix timestamp in seconds (`iat`).
72 #[get(type(copy))]
73 pub(crate) iat: Option<u64>,
74 /// Optional unique JWT identifier (`jti`).
75 #[get(type(clone))]
76 pub(crate) jti: Option<String>,
77 /// Optional role list used for RBAC authorization checks.
78 pub(crate) roles: Vec<String>,
79 /// Arbitrary additional custom claims flattened into the JWT JSON object.
80 pub(crate) extra: HashMap<String, Value>,
81}
82
83/// High-performance HS256 JWT signer and verifier with `kid` key-rotation support.
84#[derive(Clone, Debug)]
85pub struct JwtCodec {
86 /// Primary signing secret used when no `kid` is specified.
87 pub(crate) default_secret: Vec<u8>,
88 /// Precomputed HMAC-SHA256 midstates for `default_secret`.
89 pub(crate) default_hmac: HmacSha256Key,
90 /// Optional default `kid` stamped into minted tokens.
91 pub(crate) default_kid: Option<String>,
92 /// Pre-encoded base64url JWT header matching `default_kid`.
93 pub(crate) default_header_b64: String,
94 /// Key rotation keyring indexed by `kid` (`XxHash3_64`).
95 pub(crate) keyring: HashMapXxHash3_64<String, Vec<u8>>,
96 /// Precomputed HMAC-SHA256 midstates indexed by `kid` (`XxHash3_64`).
97 pub(crate) keyring_hmac: HashMapXxHash3_64<String, HmacSha256Key>,
98 /// Clock-skew leeway in seconds applied to `exp` and `nbf`.
99 pub(crate) leeway_secs: u64,
100 /// Optional required `iss` value.
101 pub(crate) required_issuer: Option<String>,
102 /// Optional required `aud` value.
103 pub(crate) required_audience: Option<String>,
104}
105
106/// Verified caller identity attached to a Hyperlane [`Context`] by [`AuthHook`].
107#[derive(Clone, Data, Debug, PartialEq)]
108pub struct AuthPrincipal {
109 /// Authenticated user or service subject identifier.
110 pub(crate) subject: String,
111 /// Granted RBAC roles.
112 pub(crate) roles: Vec<String>,
113 /// Scheme that authenticated this principal.
114 #[get(type(copy))]
115 pub(crate) scheme: AuthScheme,
116 /// Decoded JWT claims when authenticated via [`AuthScheme::BearerJwt`].
117 #[get(type(clone))]
118 pub(crate) claims: Option<JwtClaims>,
119}
120
121/// Built-in [`Authenticator`] validating `Authorization: Bearer <jwt>` via [`JwtCodec`].
122#[derive(Clone, Debug)]
123pub struct JwtAuthenticator {
124 /// Compiled JWT codec and validation policy.
125 pub(crate) codec: JwtCodec,
126}
127
128/// Built-in [`Authenticator`] validating static or rotated API keys from a configured header.
129#[derive(Clone, Debug)]
130pub struct ApiKeyAuthenticator {
131 /// Pre-lowercased header name carrying the API key (default `x-api-key`).
132 pub(crate) header_name: String,
133 /// Registered `(api_key, subject, roles)` records scanned with constant-time comparison.
134 pub(crate) entries: Vec<(Vec<u8>, String, Vec<String>)>,
135}
136
137/// Built-in [`Authenticator`] validating `Authorization: Basic <base64>` credentials.
138#[derive(Clone, Debug)]
139pub struct BasicAuthenticator {
140 /// Registered `(username, password_bytes, roles)` records.
141 pub(crate) users: HashMapXxHash3_64<String, (Vec<u8>, Vec<String>)>,
142}
143
144/// Composite [`Authenticator`] trying a sequence of authenticators until one succeeds.
145#[derive(Clone)]
146pub struct CompositeAuthenticator {
147 /// Ordered authenticator chain.
148 pub(crate) chain: Vec<Arc<dyn Authenticator>>,
149}
150
151/// Configuration policy for [`AuthPlugin`] and [`AuthHook`].
152#[derive(Clone, Data, Debug, Eq, PartialEq)]
153pub struct AuthConfig {
154 /// Exact paths bypassed without authentication (for example `"/healthz"`, `"/login"`).
155 pub(crate) exempt_paths: Vec<String>,
156 /// Optional roles required on every protected request (any match permits if `require_all_roles` is `false`).
157 pub(crate) required_roles: Vec<String>,
158 /// When `true`, caller must hold every role in `required_roles`; when `false`, any single match suffices.
159 #[get(type(copy))]
160 pub(crate) require_all_roles: bool,
161 /// `WWW-Authenticate` header value emitted on `401 Unauthorized`.
162 pub(crate) www_authenticate: String,
163}
164
165/// Process-wide [`AuthPlugin`] singleton storing [`AuthConfig`] and the active [`Authenticator`].
166#[derive(Clone)]
167pub struct AuthPlugin {
168 /// Authorization and path-exclusion configuration.
169 pub(crate) config: AuthConfig,
170 /// Active authenticator implementation.
171 pub(crate) authenticator: Arc<dyn Authenticator>,
172 /// Optional `O(1)` lookup set compiled when `exempt_paths.len() > EXEMPT_SET_THRESHOLD`.
173 pub(crate) exempt_set: Option<HashSetXxHash3_64<String>>,
174 /// Pre-serialized `401 Unauthorized` wire response including configured `WWW-Authenticate`.
175 pub(crate) prebuilt_401_wire: Vec<u8>,
176 /// Pre-serialized `403 Forbidden` wire response.
177 pub(crate) prebuilt_403_wire: Vec<u8>,
178}
179
180/// Opt-in [`ServerHook`] authenticating incoming requests and populating [`ATTR_AUTH_PRINCIPAL`].
181#[derive(Clone, Copy, Debug, Default)]
182#[hyperlane::request_middleware(-90)]
183pub struct AuthHook;