seiva_identity/lib.rs
1//! Identity for Delonix Seiva: the authenticated caller ([`Principal`]) and how a
2//! transport authenticates one ([`Authenticator`]).
3//!
4//! This crate is **transport-free** — it names no axum/HTTP type — so every
5//! transport builds the same identity model on it: `seiva-http`'s middleware,
6//! the `seiva-mcp` endpoint, a future gRPC server. The authorization layers
7//! (`seiva-http`'s `permission_guard` and `Scoped<T>`) read the [`Principal`]
8//! this crate produces (ADR 0006).
9//!
10//! # Deny by default
11//!
12//! An [`Authenticator`] turns a bearer token into a [`Principal`] or rejects it.
13//! An empty or unrecognised bearer is a rejection, never a silent anonymous pass:
14//! the caller decides (for HTTP, a *missing* token becomes [`Principal::anonymous`]
15//! so public routes still serve, while a *present-but-invalid* one is a `401`).
16//!
17//! - [`TokenAuthenticator`] — a static token → principal map (dev/test).
18//! - [`ApiKeyAuthenticator`] — an opaque `X-API-Key` → principal map with
19//! revocation; the key is stored only as its SHA-256 digest (hash at rest).
20//! - [`JwtAuthenticator`] — verifies an OIDC/JWT against an injected JWKS
21//! (RS256 / ES256, `iss`/`aud`/`exp`/`nbf`), mapping its claims to a principal.
22
23#![forbid(unsafe_code)]
24#![deny(missing_docs)]
25
26use std::collections::BTreeSet;
27
28pub mod jwt;
29
30pub use jwt::JwtAuthenticator;
31
32/// The authenticated caller: who they are, the tenant their requests are scoped
33/// to (if any), and the permissions they hold.
34///
35/// Built only by an [`Authenticator`] from verified credentials — never from a
36/// request argument. `tenant` of `None` means the caller is not tenant-scoped
37/// (a tenant-wide or single-tenant deployment); an empty [`Principal`] is the
38/// anonymous caller.
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
40pub struct Principal {
41 /// A stable, loggable identity for the caller (the token's subject). Never
42 /// the bearer token itself. Empty for the anonymous principal.
43 pub subject: String,
44 /// The tenant every tenant-scoped resource is constrained to, if any.
45 pub tenant: Option<String>,
46 /// The permissions the caller holds, compared verbatim against a facade
47 /// method's `requires`.
48 pub permissions: BTreeSet<String>,
49}
50
51impl Principal {
52 /// The anonymous principal: no subject, no tenant, no permissions.
53 #[must_use]
54 pub fn anonymous() -> Self {
55 Self::default()
56 }
57
58 /// A principal with the given subject holding `permissions`, belonging to no
59 /// particular tenant. Use [`in_tenant`](Self::in_tenant) to scope it.
60 pub fn new<I, P>(subject: impl Into<String>, permissions: I) -> Self
61 where
62 I: IntoIterator<Item = P>,
63 P: Into<String>,
64 {
65 Self {
66 subject: subject.into(),
67 tenant: None,
68 permissions: permissions.into_iter().map(Into::into).collect(),
69 }
70 }
71
72 /// A principal scoped to `tenant`, holding `permissions`.
73 pub fn in_tenant<I, P>(
74 subject: impl Into<String>,
75 tenant: impl Into<String>,
76 permissions: I,
77 ) -> Self
78 where
79 I: IntoIterator<Item = P>,
80 P: Into<String>,
81 {
82 Self {
83 subject: subject.into(),
84 tenant: Some(tenant.into()),
85 permissions: permissions.into_iter().map(Into::into).collect(),
86 }
87 }
88
89 /// Whether the caller holds `permission`.
90 #[must_use]
91 pub fn has(&self, permission: &str) -> bool {
92 self.permissions.contains(permission)
93 }
94
95 /// Whether the caller owns a resource belonging to `resource_tenant`.
96 ///
97 /// True only when the caller has a tenant and it matches `resource_tenant`.
98 /// An anonymous or tenant-less principal owns nothing — a missing tenant
99 /// never grants cross-tenant access.
100 #[must_use]
101 pub fn owns(&self, resource_tenant: &str) -> bool {
102 self.tenant.as_deref() == Some(resource_tenant)
103 }
104}
105
106/// Why authentication failed. Free of any HTTP type so the trait does not drag a
107/// transport into the auth contract; each transport maps the variants to its own
108/// status codes.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum AuthError {
111 /// No bearer credential was presented. Deny by default: the zero-trust answer.
112 MissingCredentials,
113 /// A credential was presented but did not authenticate (bad signature,
114 /// unknown key, wrong `aud`/`iss`, expired, disallowed algorithm, …).
115 InvalidToken,
116 /// The caller authenticated but is not permitted to do what they asked.
117 Forbidden,
118}
119
120impl std::fmt::Display for AuthError {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 f.write_str(match self {
123 AuthError::MissingCredentials => "missing bearer credentials",
124 AuthError::InvalidToken => "invalid bearer token",
125 AuthError::Forbidden => "forbidden",
126 })
127 }
128}
129
130impl std::error::Error for AuthError {}
131
132/// Turns a presented bearer token into a [`Principal`], or rejects it.
133///
134/// Implementations **must deny by default**: an empty or unrecognised bearer is
135/// an error, never an anonymous pass. A transport calls this before it routes to
136/// a handler, so an unauthenticated request never reaches business logic with a
137/// forged identity.
138pub trait Authenticator: Send + Sync {
139 /// Authenticate `bearer` (the raw token, the `Bearer ` scheme already
140 /// stripped). Return the [`Principal`] on success, or the reason it failed.
141 fn authenticate(&self, bearer: &str) -> Result<Principal, AuthError>;
142}
143
144/// A static bearer-token → [`Principal`] map: the first-cut authenticator.
145///
146/// A fine dev/test authenticator; real OIDC/JWT is [`JwtAuthenticator`], and both
147/// slot behind the same [`Authenticator`] trait. An empty map denies every
148/// request — zero trust out of the box.
149///
150/// Tokens are indexed by their **SHA-256 digest**, never stored or compared in
151/// clear: the lookup keys on the digest, so a timing side-channel over the map
152/// leaks only digest bytes (which are pre-image-resistant — useless for forging a
153/// token), and no bearer secret ever sits in process memory.
154#[derive(Clone, Default)]
155pub struct TokenAuthenticator {
156 tokens: std::collections::HashMap<[u8; 32], Principal>,
157}
158
159/// The SHA-256 digest of a bearer token — the key the authenticator indexes on.
160fn token_digest(token: &str) -> [u8; 32] {
161 use sha2::{Digest, Sha256};
162 let mut hasher = Sha256::new();
163 hasher.update(token.as_bytes());
164 hasher.finalize().into()
165}
166
167impl TokenAuthenticator {
168 /// A new, empty authenticator. On its own it rejects everything.
169 #[must_use]
170 pub fn new() -> Self {
171 Self::default()
172 }
173
174 /// Register one `token` → `principal`, builder-style. The token is stored as
175 /// its SHA-256 digest, not in clear.
176 #[must_use]
177 pub fn with_token(mut self, token: impl Into<String>, principal: Principal) -> Self {
178 self.tokens.insert(token_digest(&token.into()), principal);
179 self
180 }
181
182 /// Register one `token` → `principal` in place (stored as a SHA-256 digest).
183 pub fn insert(&mut self, token: impl Into<String>, principal: Principal) {
184 self.tokens.insert(token_digest(&token.into()), principal);
185 }
186
187 /// How many tokens are registered. Mostly for tests and health checks.
188 #[must_use]
189 pub fn len(&self) -> usize {
190 self.tokens.len()
191 }
192
193 /// Whether no tokens are registered (so every request is denied).
194 #[must_use]
195 pub fn is_empty(&self) -> bool {
196 self.tokens.is_empty()
197 }
198}
199
200impl Authenticator for TokenAuthenticator {
201 fn authenticate(&self, bearer: &str) -> Result<Principal, AuthError> {
202 if bearer.is_empty() {
203 return Err(AuthError::MissingCredentials);
204 }
205 // Look up by the token's digest: the comparison is over digest bytes, which
206 // do not reveal the token even under a timing side-channel.
207 self.tokens
208 .get(&token_digest(bearer))
209 .cloned()
210 .ok_or(AuthError::InvalidToken)
211 }
212}
213
214/// An opaque **API-key** → [`Principal`] map with revocation: the `X-API-Key`
215/// counterpart to [`TokenAuthenticator`], sitting behind the same
216/// [`Authenticator`] trait so a transport treats it like any other bearer path.
217///
218/// An API key is a long-lived opaque secret a service presents instead of an
219/// interactive OIDC/JWT login — never a JWT (it carries no claims; the [`Principal`]
220/// and its scopes are what the key was *registered* with). The two mechanisms run
221/// side by side: `seiva-http`'s middleware reads `X-API-Key` against this, and
222/// `Authorization: Bearer` against the JWT path.
223///
224/// # Hash at rest, revocation
225///
226/// A key is stored **only as its SHA-256 digest**, exactly like
227/// [`TokenAuthenticator`] — the clear secret never sits in process memory, and the
228/// digest-keyed lookup leaks only pre-image-resistant bytes under a timing
229/// side-channel. [`revoke`](Self::revoke) drops a key by its digest; a revoked or
230/// never-registered key authenticates to nothing (`InvalidToken`), so rejection is
231/// the default. An empty map denies every request — zero trust out of the box.
232#[derive(Clone, Default)]
233pub struct ApiKeyAuthenticator {
234 keys: std::collections::HashMap<[u8; 32], Principal>,
235}
236
237impl ApiKeyAuthenticator {
238 /// A new, empty authenticator. On its own it rejects every key.
239 #[must_use]
240 pub fn new() -> Self {
241 Self::default()
242 }
243
244 /// Register one `key` → `principal` (the scopes the key grants), builder-style.
245 /// The key is stored as its SHA-256 digest, never in clear.
246 #[must_use]
247 pub fn with_key(mut self, key: impl AsRef<str>, principal: Principal) -> Self {
248 self.keys.insert(token_digest(key.as_ref()), principal);
249 self
250 }
251
252 /// Register one `key` → `principal` in place (stored as a SHA-256 digest).
253 pub fn insert(&mut self, key: impl AsRef<str>, principal: Principal) {
254 self.keys.insert(token_digest(key.as_ref()), principal);
255 }
256
257 /// Revoke `key`: after this it authenticates to nothing (`InvalidToken`).
258 /// Returns `true` if the key was registered (and is now gone), `false` if it
259 /// was not known. Keyed on the digest, so the clear key is never compared.
260 pub fn revoke(&mut self, key: impl AsRef<str>) -> bool {
261 self.keys.remove(&token_digest(key.as_ref())).is_some()
262 }
263
264 /// How many keys are registered. Mostly for tests and health checks.
265 #[must_use]
266 pub fn len(&self) -> usize {
267 self.keys.len()
268 }
269
270 /// Whether no keys are registered (so every request is denied).
271 #[must_use]
272 pub fn is_empty(&self) -> bool {
273 self.keys.is_empty()
274 }
275}
276
277impl Authenticator for ApiKeyAuthenticator {
278 fn authenticate(&self, key: &str) -> Result<Principal, AuthError> {
279 if key.is_empty() {
280 return Err(AuthError::MissingCredentials);
281 }
282 // Look up by the key's digest: a revoked or unknown key simply has no entry,
283 // and the comparison is over digest bytes, which never reveal the key.
284 self.keys
285 .get(&token_digest(key))
286 .cloned()
287 .ok_or(AuthError::InvalidToken)
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn principal_ownership_and_permissions() {
297 let p = Principal::in_tenant("alice", "acme", ["notes.read"]);
298 assert!(p.has("notes.read"));
299 assert!(p.owns("acme"));
300 assert!(!p.owns("globex"));
301 // A permission alone never implies ownership.
302 assert!(!Principal::new("svc", ["notes.read"]).owns("acme"));
303 assert!(!Principal::anonymous().owns("acme"));
304 }
305
306 #[test]
307 fn token_authenticator_denies_by_default() {
308 let auth = TokenAuthenticator::new().with_token(
309 "s3cr3t",
310 Principal::in_tenant("alice", "acme", ["notes.read"]),
311 );
312 assert_eq!(auth.authenticate("s3cr3t").unwrap().subject, "alice");
313 assert_eq!(auth.authenticate("nope"), Err(AuthError::InvalidToken));
314 assert_eq!(auth.authenticate(""), Err(AuthError::MissingCredentials));
315 assert!(TokenAuthenticator::new().authenticate("anything").is_err());
316 }
317
318 #[test]
319 fn api_key_authenticates_to_principal_with_scopes() {
320 let auth = ApiKeyAuthenticator::new().with_key(
321 "sk_live_abc123",
322 Principal::in_tenant("svc-billing", "acme", ["invoices.read", "invoices.write"]),
323 );
324 let principal = auth.authenticate("sk_live_abc123").expect("valid key");
325 assert_eq!(principal.subject, "svc-billing");
326 assert!(principal.owns("acme"));
327 assert!(principal.has("invoices.read"));
328 assert!(principal.has("invoices.write"));
329 }
330
331 #[test]
332 fn api_key_denies_unknown_empty_and_revoked() {
333 let mut auth = ApiKeyAuthenticator::new()
334 .with_key("sk_live_abc123", Principal::new("svc", ["invoices.read"]));
335 // Unknown and empty are refused — deny by default.
336 assert_eq!(
337 auth.authenticate("sk_live_nope"),
338 Err(AuthError::InvalidToken)
339 );
340 assert_eq!(auth.authenticate(""), Err(AuthError::MissingCredentials));
341 // An empty authenticator rejects everything.
342 assert!(ApiKeyAuthenticator::new().authenticate("anything").is_err());
343 // Revocation: the once-valid key now authenticates to nothing.
344 assert!(auth.authenticate("sk_live_abc123").is_ok());
345 assert!(auth.revoke("sk_live_abc123"));
346 assert_eq!(
347 auth.authenticate("sk_live_abc123"),
348 Err(AuthError::InvalidToken)
349 );
350 assert_eq!(auth.len(), 0);
351 // Revoking an unknown key is a no-op that reports it was not present.
352 assert!(!auth.revoke("sk_live_never"));
353 }
354}