From f5e8776b0bedf21071bc25646ccbba94586f78d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86ndra=20Rininsland?= Date: Mon, 7 Sep 2026 01:23:04 +0100 Subject: [PATCH] Add POST /invite-codes/disable, authenticated by Cloudflare Access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The vetting tool needs to disable an invite code when it blocks the applicant that code was issued to. A code already sitting in someone's inbox outlives the decision to bar them, so blocking without revoking leaves a working way in (NorthskySocial/invite-vetting#38). /disable-invite-codes already does this, but authenticates with the browser session cookie and an OTP check. A service holding a Cloudflare Access token cannot satisfy that extractor, so the endpoint is unreachable from another Worker. This mirrors /invite-codes/issue, which exists as the machine-facing counterpart to /create-invite-codes for exactly the same reason. The browser-facing route is left alone. Disabling is unconditional and idempotent. A redeemed code cannot be redeemed again, so disabling it is a no-op rather than something to check for first — and checking would mean trusting a use-count read taken a moment before the write. An empty request is rejected rather than reported as success: disabling nothing and returning 200 reads to the caller exactly like a code having been revoked, which is the one outcome that must not be indistinguishable from failure here. Co-Authored-By: Claude Opus 5 --- src/apis/mod.rs | 2 + src/apis/revoke_invite_codes.rs | 187 ++++++++++++++++++++++++++++++++ src/main.rs | 9 +- 3 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 src/apis/revoke_invite_codes.rs diff --git a/src/apis/mod.rs b/src/apis/mod.rs index 6638a12..b7e9cc9 100644 --- a/src/apis/mod.rs +++ b/src/apis/mod.rs @@ -12,6 +12,7 @@ pub mod issue_invite_code; pub mod list_admins; pub mod login; pub mod remove_admin; +pub mod revoke_invite_codes; pub mod validate_otp; pub mod verify_otp; @@ -25,6 +26,7 @@ pub use issue_invite_code::*; pub use list_admins::*; pub use login::*; pub use remove_admin::*; +pub use revoke_invite_codes::*; pub use validate_otp::*; pub use verify_otp::*; diff --git a/src/apis/revoke_invite_codes.rs b/src/apis/revoke_invite_codes.rs new file mode 100644 index 0000000..90876ce --- /dev/null +++ b/src/apis/revoke_invite_codes.rs @@ -0,0 +1,187 @@ +use crate::DISABLE_INVITE_CODES; +use crate::config::Config; +use crate::error::AppError; +use crate::user::{AccessClient, DisableInviteCodeSchema}; +use axum::{Json, extract::State, response::IntoResponse}; + +/// Disable invite codes, for a caller authenticated by Cloudflare Access. +/// +/// `/disable-invite-codes` does the same thing but authenticates with the +/// browser session cookie, so a service holding an Access token cannot reach +/// it. The vetting tool needs to disable a code when it blocks the applicant +/// it was issued to: a code already in someone's inbox outlives the decision +/// to bar them, and blocking without revoking leaves a working way in. +/// +/// This mirrors `/invite-codes/issue`, which is the machine-facing counterpart +/// to `/create-invite-codes` for the same reason. +/// +/// Disabling is unconditional and idempotent. A code that has already been +/// redeemed cannot be redeemed again, so disabling it is a no-op rather than +/// something to check for first — and checking would mean trusting a +/// use-count read taken a moment before the write. +#[tracing::instrument(skip(config, client, body), fields(caller = %client.0.subject()))] +#[utoipa::path( + post, + path = "/invite-codes/disable", + request_body = DisableInviteCodeSchema, + responses( + (status = 200, description = "Invite codes disabled"), + (status = 400, description = "Nothing to disable"), + (status = 401, description = "Not authenticated by Cloudflare Access"), + (status = 502, description = "PDS error") + ), + security( + ("cloudflare_access" = []) + ) +)] +pub async fn revoke_invite_codes_handler( + State(config): State, + client: AccessClient, + Json(body): Json, +) -> Result { + // An empty request would disable nothing while reporting success, which + // reads to the caller exactly like a code having been revoked. + if body.codes.is_empty() && body.accounts.is_empty() { + return Err(AppError::BadRequest( + "codes or accounts must be non-empty".to_string(), + )); + } + + let res = reqwest::Client::new() + .post(config.pds_endpoint.clone() + DISABLE_INVITE_CODES) + .header("Content-Type", "application/json") + .basic_auth("admin", Some(config.pds_admin_password.clone())) + .json(&body) + .send() + .await?; + + if !res.status().is_success() { + let status = res.status(); + let error_body = res.text().await.unwrap_or_default(); + return Err(AppError::PdsError(format!( + "PDS returned error {status}: {error_body}" + ))); + } + + Ok(Json(())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::DbConn; + use crate::state::AppState; + use axum::{ + Router, + body::Body, + http::{Request, StatusCode}, + routing::post, + }; + use tower::ServiceExt; + + fn state(access: Option) -> AppState { + let manager = deadpool_diesel::sqlite::Manager::new( + "file:revoke_invite_test?mode=memory&cache=shared", + deadpool_diesel::Runtime::Tokio1, + ); + let pool = deadpool_diesel::sqlite::Pool::builder(manager) + .build() + .expect("Failed to create test pool"); + + AppState { + db_pool: DbConn(pool), + config: Config { + pds_admin_password: "pds_password".to_string(), + pds_endpoint: "http://localhost".to_string(), + access, + }, + } + } + + fn app(access: Option) -> Router { + Router::new() + .route("/invite-codes/disable", post(revoke_invite_codes_handler)) + .with_state(state(access)) + } + + fn request(body: &str, header: Option<(&str, &str)>) -> Request { + let mut builder = Request::builder() + .method("POST") + .uri("/invite-codes/disable") + .header("content-type", "application/json"); + + if let Some((name, value)) = header { + builder = builder.header(name, value); + } + + builder.body(Body::from(body.to_string())).unwrap() + } + + fn access_config() -> crate::access::AccessConfig { + crate::access::AccessConfig::new( + "https://team.cloudflareaccess.com".to_string(), + "aud-tag".to_string(), + vec![], + ) + } + + const BODY: &str = r#"{"codes":["northsky-social-aaaaa-bbbbb"],"accounts":[]}"#; + + #[tokio::test] + async fn rejects_a_request_without_an_access_assertion() { + let resp = app(Some(access_config())) + .oneshot(request(BODY, None)) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn rejects_a_forged_access_assertion() { + // A caller reaching the origin directly can set any header it likes; + // only a signature from the team's Access keys is trusted. + let resp = app(Some(access_config())) + .oneshot(request( + BODY, + Some(("cf-access-jwt-assertion", "totally.made.up")), + )) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn refuses_every_request_when_access_is_not_configured() { + // Fail closed: an unconfigured auth path must not become an open one. + let resp = app(None) + .oneshot(request(BODY, Some(("cf-access-jwt-assertion", "anything")))) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn does_not_reach_the_pds_before_authenticating() { + // pds_endpoint points at localhost with nothing listening, so a 401 + // here also proves no PDS call was attempted. + let resp = app(Some(access_config())) + .oneshot(request(BODY, None)) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + } + + #[test] + fn an_empty_request_is_rejected_rather_than_reported_as_success() { + // Disabling nothing and returning 200 reads to the caller exactly like + // a code having been revoked, which is the one outcome that must never + // be indistinguishable from failure here. + let parsed: DisableInviteCodeSchema = + serde_json::from_str(r#"{"codes":[],"accounts":[]}"#).unwrap(); + assert!(parsed.codes.is_empty() && parsed.accounts.is_empty()); + } +} diff --git a/src/main.rs b/src/main.rs index 9fa30f7..bd3ce8c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,8 +9,8 @@ use invite_code_manager::access::AccessConfig; use invite_code_manager::apis::{ add_admin_handler, create_invite_codes_handler, disable_invite_codes_handler, generate_otp_handler, get_invite_codes_handler, healthcheck_handler, issue_invite_code_handler, - list_admins_handler, login_user, remove_admin_handler, validate_otp_handler, - verify_otp_handler, + list_admins_handler, login_user, remove_admin_handler, revoke_invite_codes_handler, + validate_otp_handler, verify_otp_handler, }; use invite_code_manager::config::Config; use invite_code_manager::state::AppState; @@ -39,6 +39,7 @@ use utoipa_swagger_ui::SwaggerUi; invite_code_manager::apis::issue_invite_code::issue_invite_code_handler, invite_code_manager::apis::get_invite_codes::get_invite_codes_handler, invite_code_manager::apis::disable_invite_codes::disable_invite_codes_handler, + invite_code_manager::apis::revoke_invite_codes::revoke_invite_codes_handler, ), components( schemas( @@ -251,6 +252,10 @@ async fn main() { .route("/invite-codes/issue", post(issue_invite_code_handler)) .route("/invite-codes", get(get_invite_codes_handler)) .route("/disable-invite-codes", post(disable_invite_codes_handler)) + // Machine-facing counterpart, authenticated by Cloudflare Access rather + // than the browser session, exactly as /invite-codes/issue is to + // /create-invite-codes. + .route("/invite-codes/disable", post(revoke_invite_codes_handler)) .with_state(app_state) .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi()));