diff --git a/README.md b/README.md index 5106e992..6cf1d450 100644 --- a/README.md +++ b/README.md @@ -1034,7 +1034,7 @@ public_url = "https://claudear.example.com" #### Identity API -Unless noted, these endpoints need a dashboard session cookie and return 401 without one. Every `POST`, `PUT` and `DELETE` also needs an `x-csrf-token` header matching the `claudear_csrf` cookie, which the dashboard sets on every response. The one exception is `PUT /api/directory` sent with an `Authorization: Bearer` API token: it is the only dashboard endpoint that accepts Bearer, and with Bearer it needs no CSRF header. Writes are rate-limited per user and return 429 over the limit. +Unless noted, these endpoints need a dashboard session cookie and return 401 without one. Every `POST`, `PUT` and `DELETE` also needs an `x-csrf-token` header matching the `claudear_csrf` cookie, which the dashboard sets on every response. Two endpoints also accept an `Authorization: Bearer` API token: `GET /api/identities`, so a service can read the handles it mentions people by, and `PUT /api/directory`, which with Bearer needs no CSRF header. Writes are rate-limited per user and return 429 over the limit. Every non-2xx response from the users, identities, invite and directory endpoints, including 401 and 403 rejections, is JSON with a human-readable `error`, plus `violations` when specific fields are at fault (most 400 and 409 responses): @@ -1047,7 +1047,7 @@ Typical messages are `"Not authenticated"`, `"Invalid or expired token"` (a bad | Endpoint | Who | Result | |----------|-----|--------| -| `GET /api/identities` | Any logged-in user | `UserIdentities[]` for every user; non-admins get others redacted | +| `GET /api/identities` | Any logged-in user, by session or Bearer | `UserIdentities[]` for every user; non-admins get others redacted | | `GET /api/users/{id}/identities` | Any logged-in user | `UserIdentities`; redacted for a non-admin reading someone else. 404 if the user does not exist | | `PUT /api/users/{id}/identities` | Admin, or self | Sparse update; returns `UserIdentities`. 400 invalid values, 403 not admin and not self or a non-admin sending `slug`, 404 no such user, 409 a handle or slug belongs to another person | | `DELETE /api/users/{id}/identities` | Admin, or self | Drops the console identities (revert to config); returns the now-effective `UserIdentities`. An admin removes the row entirely. A non-admin whose row has an admin-set `slug` other than the config key their login email matches keeps that slug and loses only the identities; otherwise their row is removed too, which keeps the same person key. 403, 404 as above | diff --git a/crates/claudear-engine/src/api/auth.rs b/crates/claudear-engine/src/api/auth.rs index 6185f314..75781b4e 100644 --- a/crates/claudear-engine/src/api/auth.rs +++ b/crates/claudear-engine/src/api/auth.rs @@ -148,15 +148,15 @@ impl FromRequestParts for AdminUser { } } -/// An admin authenticated by `Authorization: Bearer ` or, when that header -/// is absent, by session. With the header present the cookie is never consulted, which -/// is what makes the CSRF exemption for Bearer requests safe. Failed Bearer attempts -/// spend the client address's bearer limit; once it is spent every Bearer attempt from -/// that address is refused before the token is looked up. +/// A user authenticated by `Authorization: Bearer ` or, when that header is +/// absent, by session. With the header present the cookie is never consulted, which is +/// what makes the CSRF exemption for Bearer requests safe. Failed Bearer attempts spend +/// the client address's bearer limit; once it is spent every Bearer attempt from that +/// address is refused before the token is looked up. #[derive(Debug, Clone)] -pub(crate) struct AdminCaller(pub AuthUser); +pub(crate) struct Caller(pub AuthUser); -impl FromRequestParts for AdminCaller { +impl FromRequestParts for Caller { type Rejection = ApiError; async fn from_request_parts( @@ -164,8 +164,7 @@ impl FromRequestParts for AdminCaller { state: &ApiState, ) -> Result { let Some(authorization) = parts.headers.get(header::AUTHORIZATION) else { - let AdminUser(user) = AdminUser::from_request_parts(parts, state).await?; - return Ok(Self(user)); + return Ok(Self(AuthUser::from_request_parts(parts, state).await?)); }; let address = extract_client_ip(&parts.headers); if state.limiters.bearer.exhausted(&address) { @@ -191,6 +190,22 @@ impl FromRequestParts for AdminCaller { return Err(ApiError::invalid_token()); }; user.identify(); + Ok(Self(user)) + } +} + +/// A [`Caller`] whose role is admin. +#[derive(Debug, Clone)] +pub(crate) struct AdminCaller(pub AuthUser); + +impl FromRequestParts for AdminCaller { + type Rejection = ApiError; + + async fn from_request_parts( + parts: &mut Parts, + state: &ApiState, + ) -> Result { + let Caller(user) = Caller::from_request_parts(parts, state).await?; if !user.is_admin() { return Err(ApiError::admin_required()); } diff --git a/crates/claudear-engine/src/api/identities.rs b/crates/claudear-engine/src/api/identities.rs index 2e30dc07..f5a941d3 100644 --- a/crates/claudear-engine/src/api/identities.rs +++ b/crates/claudear-engine/src/api/identities.rs @@ -5,7 +5,7 @@ //! the sensitive notification targets redacted. A handle that already belongs to a //! different person is rejected, and every write reloads the shared registry. -use super::auth::AuthUser; +use super::auth::{AuthUser, Caller}; use super::error::ApiError; use super::routes::ApiState; use crate::registry; @@ -372,9 +372,10 @@ fn configured_person(registry: &UserRegistry, login_email: &str) -> Option<(Stri .filter(|(key, _)| registry.origin(key) == Some(IdentityOrigin::Config)) } -/// GET /api/identities +/// GET /api/identities. Also takes a Bearer API token, so a service can read the handles +/// it mentions people by; a non-admin token sees the same redacted view as a non-admin session. pub(crate) async fn list_identities_handler( - actor: AuthUser, + Caller(actor): Caller, State(state): State, ) -> Result>, ApiError> { let users = state.tracker.list_users().map_err(ApiError::storage)?; diff --git a/crates/claudear-engine/src/api/routes.rs b/crates/claudear-engine/src/api/routes.rs index aad7a2fb..edf55d72 100644 --- a/crates/claudear-engine/src/api/routes.rs +++ b/crates/claudear-engine/src/api/routes.rs @@ -9420,6 +9420,34 @@ mod tests { let other = find_person(&people, harness.other.id); assert_eq!(other["login_email"], OTHER_EMAIL); assert_eq!(other["identities"]["sms_number"], SMS_NUMBER); + + // A viewer's API token reads the same redacted view, which keeps the handles + // a service mentions people by. + let secret = "cldr_identities-reader-token"; + harness + .tracker + .create_api_token( + harness.viewer.id, + "identities read", + &crate::api::tokens::hash_secret(secret), + &secret[.."cldr_".len() + 8], + None, + ) + .expect("create api token"); + let (status, people) = harness + .send( + Request::builder() + .uri("/api/identities") + .header("authorization", format!("Bearer {secret}")) + .body(Body::empty()) + .expect("request"), + ) + .await; + assert_eq!(status, StatusCode::OK); + let other = find_person(&people, harness.other.id); + assert_redacted(other); + assert_eq!(other["identities"]["github_usernames"], json!(["other-gh"])); + assert_eq!(other["identities"]["discord_id"], OTHER_DISCORD_ID); } #[tokio::test]