Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand All @@ -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 |
Expand Down
33 changes: 24 additions & 9 deletions crates/claudear-engine/src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,24 +148,23 @@ impl FromRequestParts<ApiState> for AdminUser {
}
}

/// An admin authenticated by `Authorization: Bearer <api token>` 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 <api token>` 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<ApiState> for AdminCaller {
impl FromRequestParts<ApiState> for Caller {
type Rejection = ApiError;

async fn from_request_parts(
parts: &mut Parts,
state: &ApiState,
) -> Result<Self, Self::Rejection> {
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) {
Expand All @@ -191,6 +190,22 @@ impl FromRequestParts<ApiState> 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<ApiState> for AdminCaller {
type Rejection = ApiError;

async fn from_request_parts(
parts: &mut Parts,
state: &ApiState,
) -> Result<Self, Self::Rejection> {
let Caller(user) = Caller::from_request_parts(parts, state).await?;
if !user.is_admin() {
return Err(ApiError::admin_required());
}
Expand Down
7 changes: 4 additions & 3 deletions crates/claudear-engine/src/api/identities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<ApiState>,
) -> Result<Json<Vec<UserIdentities>>, ApiError> {
let users = state.tracker.list_users().map_err(ApiError::storage)?;
Expand Down
28 changes: 28 additions & 0 deletions crates/claudear-engine/src/api/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading