about summary refs log tree commit diff
path: root/src/routes
diff options
context:
space:
mode:
Diffstat (limited to 'src/routes')
-rw-r--r--src/routes/dev.rs4
-rw-r--r--src/routes/mod.rs1
-rw-r--r--src/routes/tokens.rs426
3 files changed, 429 insertions, 2 deletions
diff --git a/src/routes/dev.rs b/src/routes/dev.rs
index 58f50c2..ef87986 100644
--- a/src/routes/dev.rs
+++ b/src/routes/dev.rs
@@ -50,7 +50,7 @@ struct TokenResponse {
 /// Whether the connection's peer is this machine: an address in
 /// 127.0.0.0/8 (127.0.x.x), the IPv6 loopback `::1`, or an IPv4-mapped
 /// 127.x.
-fn is_local(peer: &SocketAddr) -> bool {
+pub(crate) fn is_local(peer: &SocketAddr) -> bool {
     match peer.ip() {
         IpAddr::V4(ip) => ip.is_loopback(),
         IpAddr::V6(ip) => {
@@ -63,7 +63,7 @@ fn is_local(peer: &SocketAddr) -> bool {
 /// these headers to anything, so they are never trusted to *establish*
 /// that a caller is local -- only used to refuse a request that claims to
 /// have come through a proxy.
-fn via_proxy(headers: &HeaderMap) -> bool {
+pub(crate) fn via_proxy(headers: &HeaderMap) -> bool {
     ["x-forwarded-for", "forwarded", "x-real-ip"]
         .into_iter()
         .any(|name| headers.contains_key(name))
diff --git a/src/routes/mod.rs b/src/routes/mod.rs
index 55c8ce2..2bf783e 100644
--- a/src/routes/mod.rs
+++ b/src/routes/mod.rs
@@ -10,6 +10,7 @@ pub mod bulklmm;
 pub mod correlation;
 pub mod datasets;
 pub mod dev;
+pub mod tokens;
 pub mod fitqtl;
 pub mod gemma;
 pub mod frequencies;
diff --git a/src/routes/tokens.rs b/src/routes/tokens.rs
new file mode 100644
index 0000000..6bd7425
--- /dev/null
+++ b/src/routes/tokens.rs
@@ -0,0 +1,426 @@
+//! Administering the short API tokens (see src/tokens.rs).
+//!
+//! **These routes answer only a caller on this machine**: the TCP peer
+//! address must be 127.0.x.x or ::1, the connection must be direct (no
+//! `X-Forwarded-For` / `Forwarded` / `X-Real-IP`, which a reverse proxy
+//! on the same host would add), and a request with no known peer is
+//! refused. Anything else is a 403 (`not_local`). That guard is shared
+//! with `/get-test-token` (src/routes/dev.rs) rather than reinvented:
+//! minting credentials must never be reachable from the network, and
+//! there is no configuration switch that can change that.
+//!
+//! What is deliberately absent:
+//!
+//! - **no token in a query string.** Creating one is a POST, introspection
+//!   reads the caller's own `Authorization: Bearer`, and nothing here
+//!   takes a secret as a parameter, because query strings end up in
+//!   nginx's access log and in `next` links;
+//! - **no secret is ever returned again.** `POST /tokens` shows the token
+//!   exactly once, in its reply; `GET /tokens` lists handles, subjects and
+//!   timestamps, never the token or its hash;
+//! - **no way to impersonate with `x-gn4-user`.** That header is set by
+//!   this server on responses; it is never read as a credential.
+
+use axum::Json;
+use axum::extract::{ConnectInfo, Extension, Path};
+use axum::http::{HeaderMap, StatusCode};
+use serde::{Deserialize, Serialize};
+use std::net::SocketAddr;
+
+use crate::auth::AuthToken;
+use crate::config::Config;
+use crate::error::ApiError;
+use crate::response::{Ctx, Envelope};
+use crate::routes::dev::{is_local, via_proxy};
+use crate::tokens::{self, Record};
+
+/// One registry row as the API reports it: no secret, no hash.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct TokenView {
+    pub id: String,
+    pub subject: String,
+    pub scope: String,
+    /// The first characters of the secret, so an operator can match a
+    /// row to a token they are holding without the row storing it.
+    pub prefix: String,
+    pub created_at: i64,
+    pub expires_at: Option<i64>,
+    pub last_used_at: Option<i64>,
+    pub note: Option<String>,
+    pub revoked_at: Option<i64>,
+    pub status: String,
+}
+
+impl TokenView {
+    fn of(record: &Record) -> Self {
+        let now = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map(|d| d.as_secs() as i64)
+            .unwrap_or(0);
+        let status = if record.revoked() {
+            "revoked"
+        } else if record.expired(now) {
+            "expired"
+        } else {
+            "active"
+        };
+        Self {
+            id: record.id.clone(),
+            subject: record.subject.clone(),
+            scope: record.scope.clone(),
+            prefix: record.prefix.clone(),
+            created_at: record.created_at,
+            expires_at: record.expires_at,
+            last_used_at: record.last_used_at,
+            note: record.note.clone(),
+            revoked_at: record.revoked_at,
+            status: status.to_string(),
+        }
+    }
+}
+
+#[derive(Deserialize, utoipa::ToSchema)]
+pub struct MintRequest {
+    /// Human handle, unique: `zachs-1`, `agent-ravanan-3`.
+    pub id: String,
+    /// Who the token is for (the gn-auth user id it acts as).
+    pub subject: String,
+    /// Registry-declared scope; v1 mints `public`.
+    #[serde(default)]
+    pub scope: Option<String>,
+    /// Lifetime in days; omitted means `tokens::DEFAULT_TTL_DAYS`.
+    #[serde(default)]
+    pub ttl_days: Option<i64>,
+    #[serde(default)]
+    pub note: Option<String>,
+}
+
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct Minted {
+    /// Shown once, and only once: it is not stored anywhere.
+    pub token: String,
+    pub id: String,
+    pub subject: String,
+    pub scope: String,
+    pub prefix: String,
+    pub created_at: i64,
+    pub expires_at: Option<i64>,
+    pub status: String,
+}
+
+/// The localhost guard as middleware, applied to the whole token router
+/// in src/lib.rs.
+///
+/// A layer rather than a check inside each handler, deliberately: axum
+/// extracts a handler's arguments *before* its body runs, so a per-handler
+/// check would still answer a remote caller with a 415 for a malformed
+/// body. This refuses the request before anything is parsed, which is what
+/// "only responds to localhost" has to mean.
+pub async fn local_only(
+    request: axum::extract::Request,
+    next: axum::middleware::Next,
+) -> axum::response::Response {
+    use axum::response::IntoResponse;
+
+    let peer = request
+        .extensions()
+        .get::<ConnectInfo<SocketAddr>>()
+        .cloned();
+    let rid = request
+        .extensions()
+        .get::<crate::response::RequestInfo>()
+        .cloned()
+        .unwrap_or_else(|| crate::response::RequestInfo::new(None));
+    if let Err(error) = require_local(&peer.map(Extension), request.headers(), &rid, "tokens") {
+        return error.into_response();
+    }
+    next.run(request).await
+}
+
+/// The localhost guard, shared by every route in this module.
+fn require_local(
+    peer: &Option<Extension<ConnectInfo<SocketAddr>>>,
+    headers: &HeaderMap,
+    rid: &crate::response::RequestInfo,
+    operation: &str,
+) -> Result<(), ApiError> {
+    let local = peer
+        .as_ref()
+        .is_some_and(|Extension(ConnectInfo(address))| is_local(address));
+    if !local || via_proxy(headers) {
+        return Err(ApiError::new(
+            StatusCode::FORBIDDEN,
+            "not_local",
+            "Not authorized",
+            "Token administration only answers callers on this machine (127.0.x.x or ::1), \
+             directly and not through a proxy."
+                .to_string(),
+            operation,
+        )
+        .with_request_id(rid.clone()));
+    }
+    Ok(())
+}
+
+fn registry(config: &Config) -> Result<tokens::Registry, ApiError> {
+    tokens::registry(&config.api_tokens_db).map_err(|error| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "token_registry",
+            "Token registry unavailable",
+            error,
+            "tokens",
+        )
+    })
+}
+
+#[utoipa::path(get, path = "/tokens", summary = "List the short API tokens (localhost only)", description = "Answers only a caller on this machine (127.0.x.x or ::1, directly, not through a proxy); anything else is a 403. Never returns a token or its hash.", responses(
+    (status = 200, description = "Every registered token", body = Envelope<Vec<TokenView>>),
+    (status = 403, description = "The request did not come from localhost", body = ApiError)
+), security())]
+pub async fn list_tokens(
+    ctx: Ctx,
+    peer: Option<Extension<ConnectInfo<SocketAddr>>>,
+    headers: HeaderMap,
+) -> Result<Json<Envelope<Vec<TokenView>>>, ApiError> {
+    let rid = ctx.request_info();
+    // Defence in depth: the router layer has already refused non-local
+    // callers before anything was parsed (see `local_only`).
+    require_local(&peer, &headers, &rid, "list_tokens")?;
+    let config = Config::load();
+    let records = tokio::task::spawn_blocking(move || registry(&config).and_then(|r| {
+        r.list().map_err(|error| ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "token_registry",
+            "Token registry error",
+            error,
+            "list_tokens",
+        ))
+    }))
+    .await
+    .map_err(|error| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            error.to_string(),
+            "list_tokens",
+        )
+        .with_request_id(rid.clone())
+    })??;
+    Ok(Json(ctx.envelope(records.iter().map(TokenView::of).collect())))
+}
+
+#[utoipa::path(post, path = "/tokens", summary = "Mint a short API token (localhost only)", description = "Answers only a caller on this machine (127.0.x.x or ::1, directly, not through a proxy). The token is returned exactly once and only its SHA-256 is stored.", responses(
+    (status = 200, description = "The new token, shown once", body = Envelope<Minted>),
+    (status = 403, description = "The request did not come from localhost", body = ApiError),
+    (status = 409, description = "That id is already taken", body = ApiError)
+), security())]
+pub async fn mint_token(
+    ctx: Ctx,
+    peer: Option<Extension<ConnectInfo<SocketAddr>>>,
+    headers: HeaderMap,
+    Json(request): Json<MintRequest>,
+) -> Result<Json<Envelope<Minted>>, ApiError> {
+    let rid = ctx.request_info();
+    require_local(&peer, &headers, &rid, "mint_token")?;
+    let config = Config::load();
+    let scope = request.scope.unwrap_or_else(|| "public".to_string());
+    let minted = tokio::task::spawn_blocking(move || {
+        let registry = registry(&config)?;
+        let (secret, record) = registry
+            .mint(
+                request.id.trim(),
+                request.subject.trim(),
+                &scope,
+                request.ttl_days,
+                request.note.as_deref(),
+            )
+            .map_err(|error| {
+                // SQLite says "UNIQUE constraint failed" for a taken id; that
+                // is a 409, not a server error.
+                let status = if error.contains("UNIQUE") {
+                    StatusCode::CONFLICT
+                } else {
+                    StatusCode::INTERNAL_SERVER_ERROR
+                };
+                ApiError::new(
+                    status,
+                    "token_not_minted",
+                    "Could not mint the token",
+                    format!("{}: {error}", request.id),
+                    "mint_token",
+                )
+            })?;
+        let view = TokenView::of(&record);
+        Ok::<_, ApiError>(Minted {
+            token: secret,
+            id: view.id,
+            subject: view.subject,
+            scope: view.scope,
+            prefix: view.prefix,
+            created_at: view.created_at,
+            expires_at: view.expires_at,
+            status: view.status,
+        })
+    })
+    .await
+    .map_err(|error| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            error.to_string(),
+            "mint_token",
+        )
+        .with_request_id(rid.clone())
+    })??;
+    Ok(Json(ctx.envelope(minted)))
+}
+
+#[utoipa::path(delete, path = "/tokens/{id}", summary = "Revoke a short API token (localhost only)", description = "Answers only a caller on this machine. Revocation takes effect on the next request, without a restart.", params(("id" = String, Path, description = "The token's handle, e.g. zachs-1")), responses(
+    (status = 200, description = "The revoked token", body = Envelope<TokenView>),
+    (status = 403, description = "The request did not come from localhost", body = ApiError),
+    (status = 404, description = "No such token", body = ApiError)
+), security())]
+pub async fn revoke_token(
+    ctx: Ctx,
+    peer: Option<Extension<ConnectInfo<SocketAddr>>>,
+    headers: HeaderMap,
+    Path(id): Path<String>,
+) -> Result<Json<Envelope<TokenView>>, ApiError> {
+    let rid = ctx.request_info();
+    require_local(&peer, &headers, &rid, "revoke_token")?;
+    let config = Config::load();
+    let wanted = id.clone();
+    let revoked = tokio::task::spawn_blocking(move || {
+        let registry = registry(&config)?;
+        let changed = registry.revoke(&wanted).map_err(|error| {
+            ApiError::new(
+                StatusCode::INTERNAL_SERVER_ERROR,
+                "token_registry",
+                "Token registry error",
+                error,
+                "revoke_token",
+            )
+        })?;
+        if !changed {
+            return Err(ApiError::new(
+                StatusCode::NOT_FOUND,
+                "no_such_token",
+                "No such token",
+                format!("There is no active token with id {wanted}."),
+                "revoke_token",
+            ));
+        }
+        let record = registry
+            .list()
+            .map_err(|error| {
+                ApiError::new(
+                    StatusCode::INTERNAL_SERVER_ERROR,
+                    "token_registry",
+                    "Token registry error",
+                    error,
+                    "revoke_token",
+                )
+            })?
+            .into_iter()
+            .find(|record| record.id == wanted);
+        Ok::<_, ApiError>(record)
+    })
+    .await
+    .map_err(|error| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            error.to_string(),
+            "revoke_token",
+        )
+        .with_request_id(rid.clone())
+    })??;
+    match revoked {
+        Some(record) => Ok(Json(ctx.envelope(TokenView::of(&record)))),
+        None => Err(ApiError::new(
+            StatusCode::NOT_FOUND,
+            "no_such_token",
+            "No such token",
+            format!("There is no token with id {id}."),
+            "revoke_token",
+        )),
+    }
+}
+
+/// Who is this credential, and how long has it got? Works for both
+/// schemes: a JWT answers with its claims, an opaque token with its
+/// registry row. The credential is read from the `Authorization` header
+/// by [`AuthToken`] -- never from a query parameter.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct WhoAmI {
+    pub scheme: String,
+    pub subject: String,
+    pub scope: String,
+    /// Present for an opaque token, absent for a JWT.
+    pub id: Option<String>,
+    pub created_at: Option<i64>,
+    pub expires_at: Option<i64>,
+    pub last_used_at: Option<i64>,
+}
+
+#[utoipa::path(get, path = "/tokens/who", summary = "Describe the presented credential (localhost only)", description = "Answers only a caller on this machine (127.0.x.x or ::1, directly, not through a proxy), for either a gn-auth JWT or a gn4ai_ token, read from the Authorization header.", responses(
+    (status = 200, description = "The credential's identity and lifetime", body = Envelope<WhoAmI>),
+    (status = 401, description = "Missing or invalid credential", body = ApiError),
+    (status = 403, description = "The request did not come from localhost", body = ApiError)
+), security(("bearer" = [])))]
+pub async fn who_am_i(
+    ctx: Ctx,
+    peer: Option<Extension<ConnectInfo<SocketAddr>>>,
+    headers: HeaderMap,
+    token: AuthToken,
+) -> Result<Json<Envelope<WhoAmI>>, ApiError> {
+    let rid = ctx.request_info();
+    require_local(&peer, &headers, &rid, "who_am_i")?;
+    let mut who = WhoAmI {
+        scheme: token.scheme.as_str().to_string(),
+        subject: token.sub.clone(),
+        scope: token.scope.clone(),
+        id: token.id.clone(),
+        created_at: None,
+        expires_at: None,
+        last_used_at: None,
+    };
+    if token.scheme == crate::auth::Scheme::Opaque {
+        let config = Config::load();
+        let secret = token.raw.clone();
+        let record = tokio::task::spawn_blocking(move || {
+            registry(&config).and_then(|r| {
+                r.describe(&secret).map_err(|error| {
+                    ApiError::new(
+                        StatusCode::INTERNAL_SERVER_ERROR,
+                        "token_registry",
+                        "Token registry error",
+                        error,
+                        "who_am_i",
+                    )
+                })
+            })
+        })
+        .await
+        .map_err(|error| {
+            ApiError::new(
+                StatusCode::INTERNAL_SERVER_ERROR,
+                "internal_error",
+                "Internal error",
+                error.to_string(),
+                "who_am_i",
+            )
+            .with_request_id(rid.clone())
+        })??;
+        if let Some(record) = record {
+            who.created_at = Some(record.created_at);
+            who.expires_at = record.expires_at;
+            who.last_used_at = record.last_used_at;
+        }
+    }
+    Ok(Json(ctx.envelope(who)))
+}