diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-14 14:20:54 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-14 14:20:54 +0000 |
| commit | 586b0f63ef31fde987e00a305e91ee4e2136332e (patch) | |
| tree | 47eea9436d52d4634023b053f99049fa3ff21f39 /src/auth.rs | |
| parent | c822ba22ce00c1615bf47fc8a13f28590aba424a (diff) | |
| download | genenetwork4-586b0f63ef31fde987e00a305e91ee4e2136332e.tar.gz | |
tokens: short opaque API tokens in a single tokens.sqlite
A second credential format beside gn-auth's JWT, for agents and scripts:
`gn4ai_` + 56 body characters + 2 checksum characters = 64, from an
alphabet with no look-alikes, so a typo is refused before the registry is
consulted. Opaque by design -- nothing is stored in the token; every fact
lives in one SQLite database (`tokens.sqlite`, GN4_API_TOKENS_DB, mode
0600, gitignored) keyed by the SHA-256 of the secret. Revoking is a row,
takes effect on the next request, and a token in a log line reveals
nothing; lose the registry and every short token stops working.
Administration is local-only: GET/POST /tokens, DELETE /tokens/{id} and
GET /tokens/who are behind a router layer that refuses any caller whose
TCP peer is not 127.x.x.x/::1, and any request claiming to come through a
proxy. A layer rather than a per-handler check, so nothing of a remote
request is parsed before it is refused; there is no configuration switch,
because minting credentials must never be reachable from the network.
A short token reads public data only: every token-only endpoint, and
`#[gnauth(secured)]` endpoints for public rows; a confidential dataset is
refused with a 403 that names the JWT route, since gn-auth cannot validate
an opaque token (the on-the-fly-bridge and registry-grant alternatives
were both rejected for v1).
scripts/gn4-token.py create|list|revoke|who drives the routes, so there is
one implementation of the format and the revocation rules; the token is
printed exactly once.
Tests: the localhost guard over all four routes (remote peer, no peer,
proxied header), and mint -> authenticate -> who -> revoke -> 401.
Diffstat (limited to 'src/auth.rs')
| -rw-r--r-- | src/auth.rs | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/src/auth.rs b/src/auth.rs index 20145b8..a2036e1 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -83,8 +83,35 @@ impl CallerSlot { /// treats them as optional, not every token carries them) checked. /// Does not by itself mean the caller is authorized for anything; see /// [`authorise`] for that. +/// Which kind of credential a request presented. Downstream code -- the +/// `#[gnauth(secured)]` gate, basket ownership, the access log -- treats +/// both the same way; only the `raw` field's meaning and the places that +/// forward it to gn-auth differ. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scheme { + /// A gn-auth JWT: signed, and readable. + Jwt, + /// A `gn4ai_` token from this server's own registry: opaque, and + /// only meaningful here. + Opaque, +} + +impl Scheme { + /// For the access log and the `who` reply. + pub fn as_str(&self) -> &'static str { + match self { + Scheme::Jwt => "jwt", + Scheme::Opaque => "opaque", + } + } +} + #[derive(Debug, Clone)] pub struct AuthToken { + /// Which kind of credential this is (see [`Scheme`]). + pub scheme: Scheme, + /// The registry id for an opaque token (`zachs-1`), `None` for a JWT. + pub id: Option<String>, /// The token subject (gn-auth user id). pub sub: String, /// Space-separated OAuth2 scopes, e.g. "profile group resource". @@ -117,6 +144,34 @@ impl<S: Send + Sync> FromRequestParts<S> for AuthToken { .ok_or_else(|| unauthorized("Authorization header must be a Bearer token."))?; let config = Config::load(); + + // A `gn4ai_` credential never reaches gn-auth: it is opaque, and + // only this server's registry can say who it is. The prefix check + // comes first so a short token is never fed to the JWT validator + // (which would answer with a confusing signature error). + if token.starts_with(crate::tokens::PREFIX) { + let registry = crate::tokens::registry(&config.api_tokens_db) + .map_err(|e| unauthorized(&format!("token registry unavailable: {e}")))?; + let peer = parts + .extensions + .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>() + .map(|axum::extract::ConnectInfo(address)| address.ip().to_string()); + let record = registry + .authenticate(token, peer.as_deref()) + .map_err(|e| unauthorized(&format!("token registry error: {e}")))? + .ok_or_else(|| unauthorized("That token is not valid, has been revoked or has expired."))?; + if let Some(slot) = parts.extensions.get::<CallerSlot>() { + slot.set(&record.subject); + } + return Ok(AuthToken { + scheme: Scheme::Opaque, + id: Some(record.id), + sub: record.subject, + scope: record.scope, + raw: token.to_string(), + }); + } + let claims = verify(token, &config.auth_server_url).map_err(|e| unauthorized(&e.to_string()))?; // For the response header the proxy logs (see `CallerSlot`). @@ -124,6 +179,8 @@ impl<S: Send + Sync> FromRequestParts<S> for AuthToken { slot.set(&claims.sub); } Ok(AuthToken { + scheme: Scheme::Jwt, + id: None, sub: claims.sub, scope: claims.scope, raw: token.to_string(), @@ -306,6 +363,21 @@ pub fn check( if is_publicly_readable(public, confidentiality, create_time) { return Ok(Some(Authorized(()))); } + // A `gn4ai_` token cannot authorise confidential data: gn-auth has + // never heard of an opaque token, and the alternatives -- minting a + // gn-auth token on the fly from a stored credential, or keeping a + // second grant model in step with gn-auth's -- were both rejected for + // v1 (see the project memory: "API tokens: the one hard edge is + // gn-auth's resource-authorization round trip"). Say so explicitly, + // so the caller knows to use a JWT rather than that they lack a + // privilege. + if token.scheme == Scheme::Opaque { + return Err( + "Short API tokens can only read public data. This resource is not public; \ + use a gn-auth JWT (Authorization: Bearer <jwt>) for confidential datasets." + .to_string(), + ); + } let authorised = match trait_name { Some(trait_name) => authorise_trait( auth_server_url, |
