Skip to main content

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_PAYLOAD_CAP`.
39pub(crate) struct StackJsonBuf {
40    /// Inline stack storage for typical JWT claim payloads.
41    pub(crate) stack: [u8; JWT_STACK_PAYLOAD_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_PAYLOAD_CAP`.
45    pub(crate) heap: Option<Vec<u8>>,
46}
47
48/// Standard and extensible JSON Web Token claims payload.
49#[derive(Clone, Data, Debug, Default, Deserialize, PartialEq, Serialize)]
50pub struct JwtClaims {
51    /// Subject identifier (`sub`).
52    pub(crate) sub: String,
53    /// Optional issuer (`iss`).
54    #[serde(skip_serializing_if = "Option::is_none")]
55    #[get(type(clone))]
56    pub(crate) iss: Option<String>,
57    /// Optional audience (`aud`).
58    #[serde(skip_serializing_if = "Option::is_none")]
59    #[get(type(clone))]
60    pub(crate) aud: Option<String>,
61    /// Optional expiration Unix timestamp in seconds (`exp`).
62    #[serde(skip_serializing_if = "Option::is_none")]
63    #[get(type(copy))]
64    pub(crate) exp: Option<u64>,
65    /// Optional not-before Unix timestamp in seconds (`nbf`).
66    #[serde(skip_serializing_if = "Option::is_none")]
67    #[get(type(copy))]
68    pub(crate) nbf: Option<u64>,
69    /// Optional issued-at Unix timestamp in seconds (`iat`).
70    #[serde(skip_serializing_if = "Option::is_none")]
71    #[get(type(copy))]
72    pub(crate) iat: Option<u64>,
73    /// Optional unique JWT identifier (`jti`).
74    #[serde(skip_serializing_if = "Option::is_none")]
75    #[get(type(clone))]
76    pub(crate) jti: Option<String>,
77    /// Optional role list used for RBAC authorization checks.
78    #[serde(default, skip_serializing_if = "Vec::is_empty")]
79    pub(crate) roles: Vec<String>,
80    /// Arbitrary additional custom claims flattened into the JWT JSON object.
81    #[serde(flatten, default, skip_serializing_if = "HashMap::is_empty")]
82    pub(crate) extra: HashMap<String, Value>,
83}
84
85/// High-performance HS256 JWT signer and verifier with `kid` key-rotation support.
86#[derive(Clone, Debug)]
87pub struct JwtCodec {
88    /// Primary signing secret used when no `kid` is specified.
89    pub(crate) default_secret: Vec<u8>,
90    /// Precomputed HMAC-SHA256 midstates for `default_secret`.
91    pub(crate) default_hmac: HmacSha256Key,
92    /// Optional default `kid` stamped into minted tokens.
93    pub(crate) default_kid: Option<String>,
94    /// Pre-encoded base64url JWT header matching `default_kid`.
95    pub(crate) default_header_b64: String,
96    /// Key rotation keyring indexed by `kid` (`XxHash3_64`).
97    pub(crate) keyring: HashMapXxHash3_64<String, Vec<u8>>,
98    /// Precomputed HMAC-SHA256 midstates indexed by `kid` (`XxHash3_64`).
99    pub(crate) keyring_hmac: HashMapXxHash3_64<String, HmacSha256Key>,
100    /// Clock-skew leeway in seconds applied to `exp` and `nbf`.
101    pub(crate) leeway_secs: u64,
102    /// Optional required `iss` value.
103    pub(crate) required_issuer: Option<String>,
104    /// Optional required `aud` value.
105    pub(crate) required_audience: Option<String>,
106}
107
108/// Verified caller identity attached to a Hyperlane [`Context`] by [`AuthHook`].
109#[derive(Clone, Data, Debug, PartialEq)]
110pub struct AuthPrincipal {
111    /// Authenticated user or service subject identifier.
112    pub(crate) subject: String,
113    /// Granted RBAC roles.
114    pub(crate) roles: Vec<String>,
115    /// Scheme that authenticated this principal.
116    #[get(type(copy))]
117    pub(crate) scheme: AuthScheme,
118    /// Decoded JWT claims when authenticated via [`AuthScheme::BearerJwt`].
119    #[get(type(clone))]
120    pub(crate) claims: Option<JwtClaims>,
121}
122
123/// Built-in [`Authenticator`] validating `Authorization: Bearer <jwt>` via [`JwtCodec`].
124#[derive(Clone, Debug)]
125pub struct JwtAuthenticator {
126    /// Compiled JWT codec and validation policy.
127    pub(crate) codec: JwtCodec,
128}
129
130/// Built-in [`Authenticator`] validating static or rotated API keys from a configured header.
131#[derive(Clone, Debug)]
132pub struct ApiKeyAuthenticator {
133    /// Pre-lowercased header name carrying the API key (default `x-api-key`).
134    pub(crate) header_name: String,
135    /// Registered `(api_key, subject, roles)` records scanned with constant-time comparison.
136    pub(crate) entries: Vec<(Vec<u8>, String, Vec<String>)>,
137}
138
139/// Built-in [`Authenticator`] validating `Authorization: Basic <base64>` credentials.
140#[derive(Clone, Debug)]
141pub struct BasicAuthenticator {
142    /// Registered `(username, password_bytes, roles)` records.
143    pub(crate) users: HashMapXxHash3_64<String, (Vec<u8>, Vec<String>)>,
144}
145
146/// Composite [`Authenticator`] trying a sequence of authenticators until one succeeds.
147#[derive(Clone)]
148pub struct CompositeAuthenticator {
149    /// Ordered authenticator chain.
150    pub(crate) chain: Vec<SharedAuthenticator>,
151}
152
153/// Configuration policy for [`AuthPlugin`] and [`AuthHook`].
154#[derive(Clone, Data, Debug, Eq, PartialEq)]
155pub struct AuthConfig {
156    /// Exact paths bypassed without authentication (for example `"/healthz"`, `"/login"`).
157    pub(crate) exempt_paths: Vec<String>,
158    /// Optional roles required on every protected request (any match permits if `require_all_roles` is `false`).
159    pub(crate) required_roles: Vec<String>,
160    /// When `true`, caller must hold every role in `required_roles`; when `false`, any single match suffices.
161    #[get(type(copy))]
162    pub(crate) require_all_roles: bool,
163    /// `WWW-Authenticate` header value emitted on `401 Unauthorized`.
164    pub(crate) www_authenticate: String,
165}
166
167/// Process-wide [`AuthPlugin`] singleton storing [`AuthConfig`] and the active [`Authenticator`].
168#[derive(Clone)]
169pub struct AuthPlugin {
170    /// Authorization and path-exclusion configuration.
171    pub(crate) config: AuthConfig,
172    /// Active authenticator implementation.
173    pub(crate) authenticator: SharedAuthenticator,
174    /// Optional `O(1)` lookup set compiled when `exempt_paths.len() > EXEMPT_SET_THRESHOLD`.
175    pub(crate) exempt_set: Option<HashSetXxHash3_64<String>>,
176}
177
178/// Opt-in [`ServerHook`] authenticating incoming requests and populating [`ATTR_AUTH_PRINCIPAL`].
179#[derive(Clone, Copy, Debug, Default)]
180#[hyperlane::request_middleware(-90)]
181pub struct AuthHook;