Admin tools for Claude: an MCP server, connected with an admin's approval
- services/mcp: the MCP server at /mcp (Streamable HTTP, stateless): the admin's reading tools, the daily tasks and the forum's moderation; every tool calls the site's API with the caller's token, and members' e-mail addresses and names are masked in the answers. - Backend: OAuth 2.1 for MCP clients (registration with Claude's or a local return address only, PKCE, rotating refresh tokens, revocation); the admin guards accept the token for reading and the writes in MCP_WRITES only. - Forum: an admin's token reaches the moderator endpoints only. - Frontend: the approval page (/oauth/engedely), Admin → Claude to revoke a connection, the authorization server's metadata at its standard address. - Deploy: the mcp service in compose, Caddy, CI; the worker removes old codes, tokens and clients. docs/mcp.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -20,6 +20,7 @@ service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
deunicode.workspace = true
|
||||
argon2.workspace = true
|
||||
base64.workspace = true
|
||||
password-hash = { version = "0.5", features = ["getrandom"] }
|
||||
axum.workspace = true
|
||||
axum-extra.workspace = true
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
//! HttpOnly cookie (`sf_session`) and in the login response body (for
|
||||
//! non-browser clients, sent back as `Authorization: Bearer <token>`); the
|
||||
//! database keeps only its SHA-256 hash, so sessions can be revoked.
|
||||
//!
|
||||
//! The admin endpoints also accept the OAuth access token of an MCP client
|
||||
//! that an admin connected (docs/mcp.md): for reading, and for the few
|
||||
//! writes in [`MCP_WRITES`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -12,7 +16,8 @@ use std::time::{Duration, Instant};
|
||||
use argon2::Argon2;
|
||||
use argon2::password_hash::rand_core::OsRng;
|
||||
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::extract::{FromRequestParts, MatchedPath};
|
||||
use axum::http::Method;
|
||||
use axum::http::header::{AUTHORIZATION, USER_AGENT};
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
|
||||
@@ -36,7 +41,11 @@ pub const MAX_PASSWORD_LEN: usize = 256;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthUser {
|
||||
pub user: User,
|
||||
/// The session; with an MCP client's token, the id of its connection.
|
||||
pub session_id: Uuid,
|
||||
/// Set when an MCP client's OAuth token was sent instead of a session
|
||||
/// (only the admin guards accept one).
|
||||
pub oauth: Option<db::OauthAccess>,
|
||||
}
|
||||
|
||||
impl AuthUser {
|
||||
@@ -68,19 +77,72 @@ impl FromRequestParts<Arc<AppState>> for AuthUser {
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let token = session_token(parts).ok_or(ApiError::Unauthorized)?;
|
||||
let (session_id, user) = db::user_by_session(&state.db, &token).await?.ok_or(ApiError::Unauthorized)?;
|
||||
Ok(AuthUser { user, session_id })
|
||||
Ok(AuthUser { user, session_id, oauth: None })
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard: a logged-in user with the admin role (401 / 403 otherwise).
|
||||
/// The admin writes an MCP client's token may make (method, route), besides
|
||||
/// reading: the daily tasks of docs/mcp.md. Every other write needs a session.
|
||||
pub const MCP_WRITES: [(Method, &str); 11] = [
|
||||
(Method::POST, "/v1/admin/promo-codes"),
|
||||
(Method::POST, "/v1/admin/promo-codes/{id}/revoke"),
|
||||
(Method::PATCH, "/v1/admin/feedback/{id}"),
|
||||
(Method::POST, "/v1/admin/ratings/reviewed"),
|
||||
(Method::POST, "/v1/admin/jobs/restart"),
|
||||
(Method::DELETE, "/v1/admin/errors"),
|
||||
(Method::DELETE, "/v1/admin/errors/{id}"),
|
||||
(Method::POST, "/v1/admin/invitations"),
|
||||
(Method::POST, "/v1/admin/invitations/{id}/resend"),
|
||||
(Method::POST, "/v1/admin/analyses/{id}/regenerate"),
|
||||
(Method::POST, "/v1/admin/questions/{id}/regenerate"),
|
||||
];
|
||||
|
||||
/// The user of an MCP client's OAuth access token (`Authorization: Bearer`).
|
||||
pub async fn oauth_user(parts: &Parts, state: &AppState) -> Result<Option<AuthUser>, ApiError> {
|
||||
let Some(token) = parts
|
||||
.headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let found = db::user_by_oauth_token(&state.db, token).await?;
|
||||
Ok(found.map(|(access, user)| AuthUser { user, session_id: access.grant_id, oauth: Some(access) }))
|
||||
}
|
||||
|
||||
/// A session, or else an MCP client's token.
|
||||
async fn session_or_token(parts: &mut Parts, state: &Arc<AppState>) -> Result<AuthUser, ApiError> {
|
||||
match AuthUser::from_request_parts(parts, state).await {
|
||||
Err(ApiError::Unauthorized) => oauth_user(parts, state).await?.ok_or(ApiError::Unauthorized),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// With an MCP client's token: reading, and the writes of [`MCP_WRITES`].
|
||||
fn token_may(user: &AuthUser, parts: &Parts) -> Result<(), ApiError> {
|
||||
if user.oauth.is_none() || parts.method == Method::GET || parts.method == Method::HEAD {
|
||||
return Ok(());
|
||||
}
|
||||
let route = parts.extensions.get::<MatchedPath>().map(MatchedPath::as_str);
|
||||
if MCP_WRITES.iter().any(|(method, path)| *method == parts.method && Some(*path) == route) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(ApiError::Forbidden("Ezt Claude-ból nem lehet, csak az admin oldalon.".into()))
|
||||
}
|
||||
|
||||
/// Guard: a logged-in user with the admin role (401 / 403 otherwise), or an
|
||||
/// MCP client an admin connected.
|
||||
pub struct AdminUser(pub AuthUser);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for AdminUser {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
let user = session_or_token(parts, state).await?;
|
||||
user.require(Role::Admin)?;
|
||||
token_may(&user, parts)?;
|
||||
Ok(AdminUser(user))
|
||||
}
|
||||
}
|
||||
@@ -98,11 +160,12 @@ impl FromRequestParts<Arc<AppState>> for CelebrityEditor {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
if user.user.has_role(Role::Creator) {
|
||||
let user = session_or_token(parts, state).await?;
|
||||
if user.oauth.is_none() && user.user.has_role(Role::Creator) {
|
||||
return Ok(CelebrityEditor(user));
|
||||
}
|
||||
user.require(Role::Admin)?;
|
||||
token_may(&user, parts)?;
|
||||
Ok(CelebrityEditor(user))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,8 +117,23 @@ pub struct Config {
|
||||
/// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it
|
||||
/// is missing (development; in production it is made in the console).
|
||||
pub storage_create_bucket: bool,
|
||||
/// `OAUTH_REDIRECT_URIS`: comma-separated return addresses an MCP client
|
||||
/// may register (docs/mcp.md); a trailing `*` stands for any port (and
|
||||
/// path). Default: Claude's callbacks and local ones for Claude Code.
|
||||
pub oauth_redirect_uris: Vec<String>,
|
||||
/// `MCP_RESOURCE_URL`: the MCP server's address, the audience of the
|
||||
/// tokens (default `PUBLIC_BASE_URL` + `/mcp`).
|
||||
pub mcp_resource_url: String,
|
||||
}
|
||||
|
||||
/// The default `OAUTH_REDIRECT_URIS`.
|
||||
pub const DEFAULT_OAUTH_REDIRECT_URIS: [&str; 4] = [
|
||||
"https://claude.ai/api/mcp/auth_callback",
|
||||
"https://claude.com/api/mcp/auth_callback",
|
||||
"http://localhost:*",
|
||||
"http://127.0.0.1:*",
|
||||
];
|
||||
|
||||
/// `STRIPE_SECRET_KEY` (`sk_test_…` or `sk_live_…`), `STRIPE_WEBHOOK_SECRET`
|
||||
/// (`whsec_…`, from the webhook endpoint in the Stripe dashboard) and
|
||||
/// `STRIPE_API_URL` (default `https://api.stripe.com`, tests change it).
|
||||
@@ -182,7 +197,6 @@ impl Config {
|
||||
let config = Self {
|
||||
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
|
||||
horoscope_api_url: var("HOROSCOPE_API_URL").unwrap_or_else(|| "http://localhost:8080".into()),
|
||||
public_base_url,
|
||||
cors_allowed_origins,
|
||||
cookie_secure: parsed("COOKIE_SECURE", true)?,
|
||||
cookie_domain: var("COOKIE_DOMAIN"),
|
||||
@@ -250,6 +264,14 @@ impl Config {
|
||||
}),
|
||||
},
|
||||
storage_create_bucket: parsed("S3_CREATE_BUCKET", false)?,
|
||||
oauth_redirect_uris: match list("OAUTH_REDIRECT_URIS") {
|
||||
uris if uris.is_empty() => DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(),
|
||||
uris => uris,
|
||||
},
|
||||
mcp_resource_url: var("MCP_RESOURCE_URL")
|
||||
.map(|u| u.trim_end_matches('/').to_string())
|
||||
.unwrap_or_else(|| format!("{public_base_url}/mcp")),
|
||||
public_base_url,
|
||||
};
|
||||
if config.session_ttl_days < 1 {
|
||||
bail!("SESSION_TTL_DAYS must be at least 1");
|
||||
@@ -300,6 +322,8 @@ impl Config {
|
||||
secret_key: "test-secret".into(),
|
||||
}),
|
||||
storage_create_bucket: false,
|
||||
oauth_redirect_uris: DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(),
|
||||
mcp_resource_url: "https://sorsfonalak.test/mcp".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,8 @@ pub struct AppState {
|
||||
pub storage: Option<storage::Storage>,
|
||||
/// The sky by date, the same for everyone (see `routes::sky`).
|
||||
pub sky: routes::sky::SkyCache,
|
||||
/// MCP client registrations and token requests, per visitor address.
|
||||
pub oauth_limiter: LoginLimiter,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -80,6 +82,7 @@ impl AppState {
|
||||
stripe: stripe::Client::default(),
|
||||
storage: config.storage.clone().map(storage::Storage::new),
|
||||
sky: Default::default(),
|
||||
oauth_limiter: LoginLimiter::new(60, Duration::from_secs(60 * 60)),
|
||||
db,
|
||||
config,
|
||||
}
|
||||
|
||||
@@ -138,6 +138,7 @@ pub async fn change_password(
|
||||
.bind(auth.session_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
db::revoke_oauth_grants(&mut *tx, auth.id()).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
@@ -509,6 +509,7 @@ async fn social_login(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(id).execute(&mut *tx).await?;
|
||||
db::revoke_oauth_grants(&mut *tx, id).await?;
|
||||
tracing::warn!(user = %id, provider, "unconfirmed password account taken over by its address's owner");
|
||||
}
|
||||
// The provider has verified the address, so it counts as verified here too.
|
||||
@@ -595,6 +596,8 @@ pub async fn logout(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResu
|
||||
/// Ends every session of the user (all devices).
|
||||
pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(auth.id()).execute(&state.db).await?;
|
||||
// The MCP clients connected by the user too (docs/mcp.md).
|
||||
db::revoke_oauth_grants(&state.db, auth.id()).await?;
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
@@ -659,6 +662,7 @@ pub async fn set_password_with_link(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
|
||||
db::revoke_oauth_grants(&mut *tx, user_id).await?;
|
||||
let mut user = load_user(&mut tx, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -21,6 +21,7 @@ mod invoices_user;
|
||||
mod jobs;
|
||||
mod models;
|
||||
mod notifications;
|
||||
mod oauth;
|
||||
pub(crate) mod payments;
|
||||
mod promo;
|
||||
mod prompts;
|
||||
@@ -88,6 +89,15 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/auth/logout-all", post(auth::logout_all))
|
||||
.route("/v1/auth/password-reset", post(auth::request_password_reset))
|
||||
.route("/v1/auth/set-password", post(auth::set_password_with_link))
|
||||
// MCP clients (docs/mcp.md): OAuth for the admin tools.
|
||||
.route("/v1/oauth/metadata", get(oauth::metadata))
|
||||
.route("/v1/oauth/register", post(oauth::register))
|
||||
.route("/v1/oauth/authorize", get(oauth::authorize_check).post(oauth::authorize))
|
||||
.route("/v1/oauth/token", post(oauth::token))
|
||||
.route("/v1/oauth/revoke", post(oauth::revoke))
|
||||
.route("/v1/oauth/whoami", get(oauth::whoami))
|
||||
.route("/v1/admin/oauth/grants", get(oauth::admin_grants))
|
||||
.route("/v1/admin/oauth/grants/{id}", delete(oauth::admin_revoke_grant))
|
||||
// own account (GDPR export and deletion included)
|
||||
.route("/v1/me", get(account::me).patch(account::update_me).delete(account::delete_me))
|
||||
.route("/v1/me/password", post(account::change_password))
|
||||
|
||||
@@ -0,0 +1,748 @@
|
||||
//! OAuth 2.1 for the MCP server (docs/mcp.md). Claude registers itself as a
|
||||
//! client (only with an allowed return address), an admin approves the
|
||||
//! connection on the site (`/oauth/engedely`, which calls `authorize`), and
|
||||
//! Claude trades the code for an access token (an hour) and a refresh token
|
||||
//! (30 days, a new one at every refresh). The admin guards accept the access
|
||||
//! token (see `auth::MCP_WRITES`); the MCP server checks it with `whoami`.
|
||||
//!
|
||||
//! The endpoints Claude calls (`register`, `token`, `revoke`) answer OAuth's
|
||||
//! own error format; the ones the site calls answer the API's.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::rejection::{FormRejection, JsonRejection};
|
||||
use axum::extract::{FromRequestParts, Path, Query, State};
|
||||
use axum::http::header::{AUTHORIZATION, CACHE_CONTROL, PRAGMA};
|
||||
use axum::http::request::Parts;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{Form, Json};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
|
||||
use db::Role;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St, client_ip};
|
||||
use crate::AppState;
|
||||
use crate::auth::{AuthUser, oauth_user};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
/// What a connection may do: the admin tools (the guards narrow it further).
|
||||
pub const SCOPE: &str = "admin";
|
||||
const ACCESS_TTL: Duration = Duration::hours(1);
|
||||
const REFRESH_TTL: Duration = Duration::days(30);
|
||||
const CODE_TTL: Duration = Duration::minutes(10);
|
||||
const MAX_REDIRECT_URIS: usize = 5;
|
||||
const AUTH_METHODS: [&str; 3] = ["none", "client_secret_post", "client_secret_basic"];
|
||||
|
||||
// --- errors in OAuth's format -----------------------------------------------------
|
||||
|
||||
/// `{"error", "error_description"}` (RFC 6749 5.2, RFC 7591 3.2.2).
|
||||
#[derive(Debug)]
|
||||
pub struct OauthError {
|
||||
status: StatusCode,
|
||||
error: &'static str,
|
||||
description: String,
|
||||
}
|
||||
|
||||
impl OauthError {
|
||||
fn new(error: &'static str, description: impl Into<String>) -> Self {
|
||||
let status = if error == "invalid_client" { StatusCode::UNAUTHORIZED } else { StatusCode::BAD_REQUEST };
|
||||
Self { status, error, description: description.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for OauthError {
|
||||
fn into_response(self) -> Response {
|
||||
if self.status.is_server_error() {
|
||||
tracing::error!(error = %self.description, "oauth request failed");
|
||||
}
|
||||
let body = Json(json!({ "error": self.error, "error_description": self.description }));
|
||||
(self.status, [(CACHE_CONTROL, "no-store")], body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for OauthError {
|
||||
fn from(e: sqlx::Error) -> Self {
|
||||
Self { status: StatusCode::INTERNAL_SERVER_ERROR, error: "server_error", description: format!("database: {e}") }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ApiError> for OauthError {
|
||||
fn from(e: ApiError) -> Self {
|
||||
match e {
|
||||
ApiError::TooManyRequests => {
|
||||
Self { status: StatusCode::TOO_MANY_REQUESTS, error: "too_many_requests", description: e.to_string() }
|
||||
}
|
||||
other => Self {
|
||||
status: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error: "server_error",
|
||||
description: other.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for OauthError {
|
||||
fn from(rejection: JsonRejection) -> Self {
|
||||
Self::new("invalid_client_metadata", rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FormRejection> for OauthError {
|
||||
fn from(rejection: FormRejection) -> Self {
|
||||
Self::new("invalid_request", rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
// --- metadata (RFC 8414) ------------------------------------------------------------
|
||||
|
||||
/// The authorization server's metadata, served by the frontend at
|
||||
/// `/.well-known/oauth-authorization-server`.
|
||||
pub async fn metadata(State(state): St) -> Json<Value> {
|
||||
let base = &state.config.public_base_url;
|
||||
Json(json!({
|
||||
"issuer": base,
|
||||
"authorization_endpoint": format!("{base}/oauth/engedely"),
|
||||
"token_endpoint": format!("{base}/api/v1/oauth/token"),
|
||||
"registration_endpoint": format!("{base}/api/v1/oauth/register"),
|
||||
"revocation_endpoint": format!("{base}/api/v1/oauth/revoke"),
|
||||
"response_types_supported": ["code"],
|
||||
"response_modes_supported": ["query"],
|
||||
"grant_types_supported": ["authorization_code", "refresh_token"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
"token_endpoint_auth_methods_supported": AUTH_METHODS,
|
||||
"revocation_endpoint_auth_methods_supported": AUTH_METHODS,
|
||||
"scopes_supported": [SCOPE],
|
||||
"authorization_response_iss_parameter_supported": true,
|
||||
}))
|
||||
}
|
||||
|
||||
// --- client registration (RFC 7591) ---------------------------------------------------
|
||||
|
||||
/// Whether a client may register `uri` as its return address: one of the
|
||||
/// configured ones, where a trailing `*` stands for a port and any path.
|
||||
pub fn redirect_allowed(uri: &str, patterns: &[String]) -> bool {
|
||||
if uri.len() > 500 || uri.contains('#') || uri.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return false;
|
||||
}
|
||||
patterns.iter().any(|pattern| match pattern.strip_suffix('*') {
|
||||
None => uri == pattern,
|
||||
Some(prefix) => uri.strip_prefix(prefix).is_some_and(|rest| {
|
||||
let port = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
|
||||
!port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit())
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Registration {
|
||||
#[serde(default)]
|
||||
redirect_uris: Vec<String>,
|
||||
client_name: Option<String>,
|
||||
token_endpoint_auth_method: Option<String>,
|
||||
grant_types: Option<Vec<String>>,
|
||||
response_types: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Json(req), _): WithRejection<Json<Registration>, OauthError>,
|
||||
) -> Result<Response, OauthError> {
|
||||
state.oauth_limiter.hit(&format!("register:{}", client_ip(&headers).unwrap_or_default()))?;
|
||||
if req.redirect_uris.is_empty() || req.redirect_uris.len() > MAX_REDIRECT_URIS {
|
||||
return Err(OauthError::new("invalid_redirect_uri", "Give one to five redirect_uris."));
|
||||
}
|
||||
if let Some(bad) = req.redirect_uris.iter().find(|u| !redirect_allowed(u, &state.config.oauth_redirect_uris)) {
|
||||
return Err(OauthError::new("invalid_redirect_uri", format!("This redirect_uri is not allowed: {bad}")));
|
||||
}
|
||||
let grant_types = req.grant_types.unwrap_or_else(|| vec!["authorization_code".into()]);
|
||||
if grant_types.iter().any(|g| g != "authorization_code" && g != "refresh_token") {
|
||||
return Err(OauthError::new("invalid_client_metadata", "Only authorization_code and refresh_token."));
|
||||
}
|
||||
let response_types = req.response_types.unwrap_or_else(|| vec!["code".into()]);
|
||||
if response_types.iter().any(|r| r != "code") {
|
||||
return Err(OauthError::new("invalid_client_metadata", "Only the code response type."));
|
||||
}
|
||||
// RFC 7591's default is client_secret_basic.
|
||||
let method = req.token_endpoint_auth_method.unwrap_or_else(|| "client_secret_basic".into());
|
||||
if !AUTH_METHODS.contains(&method.as_str()) {
|
||||
return Err(OauthError::new("invalid_client_metadata", "Unsupported token_endpoint_auth_method."));
|
||||
}
|
||||
let name: String = req
|
||||
.client_name
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(100)
|
||||
.collect::<String>()
|
||||
.trim()
|
||||
.to_string();
|
||||
let name = if name.is_empty() { "MCP-kliens".to_string() } else { name };
|
||||
|
||||
let client_id = db::random_token(16);
|
||||
let secret = (method != "none").then(db::new_token);
|
||||
sqlx::query("INSERT INTO oauth_clients (id, name, redirect_uris, secret_hash) VALUES ($1, $2, $3, $4)")
|
||||
.bind(&client_id)
|
||||
.bind(&name)
|
||||
.bind(&req.redirect_uris)
|
||||
.bind(secret.as_deref().map(db::token_hash))
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(client = %client_id, name = %name, "oauth client registered");
|
||||
let mut body = json!({
|
||||
"client_id": client_id,
|
||||
"client_id_issued_at": OffsetDateTime::now_utc().unix_timestamp(),
|
||||
"client_name": name,
|
||||
"redirect_uris": req.redirect_uris,
|
||||
"grant_types": grant_types,
|
||||
"response_types": response_types,
|
||||
"token_endpoint_auth_method": method,
|
||||
});
|
||||
if let Some(secret) = secret {
|
||||
body["client_secret"] = json!(secret);
|
||||
body["client_secret_expires_at"] = json!(0);
|
||||
}
|
||||
Ok((StatusCode::CREATED, [(CACHE_CONTROL, "no-store")], Json(body)).into_response())
|
||||
}
|
||||
|
||||
// --- approval (the site's /oauth/engedely page) -----------------------------------------
|
||||
|
||||
/// The authorization request's parameters, as the client put them on the
|
||||
/// approval page's address (and the page sends them on).
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AuthorizeParams {
|
||||
response_type: Option<String>,
|
||||
client_id: Option<String>,
|
||||
redirect_uri: Option<String>,
|
||||
code_challenge: Option<String>,
|
||||
code_challenge_method: Option<String>,
|
||||
scope: Option<String>,
|
||||
state: Option<String>,
|
||||
resource: Option<String>,
|
||||
/// POST only: the admin said no.
|
||||
#[serde(default)]
|
||||
deny: bool,
|
||||
}
|
||||
|
||||
/// A checked authorization request.
|
||||
struct Checked {
|
||||
client_id: String,
|
||||
client_name: String,
|
||||
redirect_uri: String,
|
||||
code_challenge: String,
|
||||
state: Option<String>,
|
||||
}
|
||||
|
||||
fn bad(message: &str) -> ApiError {
|
||||
ApiError::BadRequest(message.to_string())
|
||||
}
|
||||
|
||||
/// The same address with or without a trailing slash.
|
||||
fn same_resource(a: &str, b: &str) -> bool {
|
||||
a.trim_end_matches('/') == b.trim_end_matches('/')
|
||||
}
|
||||
|
||||
async fn check(state: &AppState, p: &AuthorizeParams) -> ApiResult<Checked> {
|
||||
let client_id = p.client_id.as_deref().ok_or_else(|| bad("Hiányzik az alkalmazás azonosítója."))?;
|
||||
let client: Option<(String, Vec<String>)> =
|
||||
sqlx::query_as("SELECT name, redirect_uris FROM oauth_clients WHERE id = $1")
|
||||
.bind(client_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (client_name, redirect_uris) = client.ok_or_else(|| bad("Ismeretlen alkalmazás. Kapcsold össze újra."))?;
|
||||
let redirect_uri = match &p.redirect_uri {
|
||||
Some(uri) if redirect_uris.contains(uri) => uri.clone(),
|
||||
None if redirect_uris.len() == 1 => redirect_uris[0].clone(),
|
||||
_ => return Err(bad("Ez a visszatérési cím nincs az alkalmazásnál bejegyezve.")),
|
||||
};
|
||||
if p.response_type.as_deref() != Some("code") {
|
||||
return Err(bad("Csak a „code” válaszforma támogatott."));
|
||||
}
|
||||
if p.code_challenge_method.as_deref() != Some("S256") {
|
||||
return Err(bad("PKCE (S256) kell."));
|
||||
}
|
||||
let code_challenge = p.code_challenge.clone().unwrap_or_default();
|
||||
if !(43..=128).contains(&code_challenge.len()) {
|
||||
return Err(bad("Hibás PKCE-kód."));
|
||||
}
|
||||
if let Some(resource) = &p.resource
|
||||
&& !same_resource(resource, &state.config.mcp_resource_url)
|
||||
{
|
||||
return Err(bad("Ismeretlen erőforrás."));
|
||||
}
|
||||
if p.state.as_deref().is_some_and(|s| s.len() > 1000) {
|
||||
return Err(bad("Túl hosszú state."));
|
||||
}
|
||||
Ok(Checked { client_id: client_id.to_string(), client_name, redirect_uri, code_challenge, state: p.state.clone() })
|
||||
}
|
||||
|
||||
/// The approval page asks what it is approving (no login needed for this).
|
||||
pub async fn authorize_check(
|
||||
State(state): St,
|
||||
WithRejection(Query(p), _): WithRejection<Query<AuthorizeParams>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let c = check(&state, &p).await?;
|
||||
let host = reqwest::Url::parse(&c.redirect_uri).ok().and_then(|u| u.host_str().map(str::to_string));
|
||||
Ok(Json(json!({
|
||||
"client_name": c.client_name,
|
||||
"redirect_uri": c.redirect_uri,
|
||||
"redirect_host": host,
|
||||
"scope": SCOPE,
|
||||
"resource": state.config.mcp_resource_url,
|
||||
// `requested` is what the client asked for; the connection gets `scope`.
|
||||
"requested_scope": p.scope,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The client's return address with the answer's parameters.
|
||||
fn answer(redirect_uri: &str, pairs: &[(&str, &str)]) -> ApiResult<String> {
|
||||
let mut url = reqwest::Url::parse(redirect_uri).map_err(|_| bad("Hibás visszatérési cím."))?;
|
||||
{
|
||||
let mut query = url.query_pairs_mut();
|
||||
for (key, value) in pairs {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
Ok(url.to_string())
|
||||
}
|
||||
|
||||
/// The admin approved (or refused) the connection: the address to send the
|
||||
/// browser back to the client with a code (or an error). A session only:
|
||||
/// an MCP client's token cannot make new tokens.
|
||||
pub async fn authorize(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(p), _): Body<AuthorizeParams>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
if !auth.user.has_role(Role::Admin) {
|
||||
return Err(ApiError::Forbidden("Ehhez admin fiók kell.".into()));
|
||||
}
|
||||
let c = check(&state, &p).await?;
|
||||
let iss = state.config.public_base_url.as_str();
|
||||
let mut pairs: Vec<(&str, &str)> = Vec::new();
|
||||
let code = db::new_token();
|
||||
if p.deny {
|
||||
pairs.push(("error", "access_denied"));
|
||||
} else {
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(db::token_hash(&code))
|
||||
.bind(&c.client_id)
|
||||
.bind(auth.id())
|
||||
.bind(&c.redirect_uri)
|
||||
.bind(&c.code_challenge)
|
||||
.bind(SCOPE)
|
||||
.bind(&state.config.mcp_resource_url)
|
||||
.bind(OffsetDateTime::now_utc() + CODE_TTL)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(client = %c.client_id, user = %auth.id(), "oauth connection approved");
|
||||
pairs.push(("code", &code));
|
||||
}
|
||||
if let Some(s) = &c.state {
|
||||
pairs.push(("state", s));
|
||||
}
|
||||
pairs.push(("iss", iss));
|
||||
Ok(Json(json!({ "redirect_to": answer(&c.redirect_uri, &pairs)? })))
|
||||
}
|
||||
|
||||
// --- tokens ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenRequest {
|
||||
grant_type: Option<String>,
|
||||
code: Option<String>,
|
||||
redirect_uri: Option<String>,
|
||||
code_verifier: Option<String>,
|
||||
refresh_token: Option<String>,
|
||||
client_id: Option<String>,
|
||||
client_secret: Option<String>,
|
||||
resource: Option<String>,
|
||||
}
|
||||
|
||||
/// The client of a token or revocation request: HTTP Basic, the form's
|
||||
/// `client_id` and `client_secret`, or a public client's `client_id` alone.
|
||||
async fn client_of(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
client_id: Option<&str>,
|
||||
client_secret: Option<&str>,
|
||||
) -> Result<String, OauthError> {
|
||||
let basic = headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Basic "))
|
||||
.and_then(|b| STANDARD.decode(b.trim()).ok())
|
||||
.and_then(|b| String::from_utf8(b).ok())
|
||||
.and_then(|s| s.split_once(':').map(|(id, secret)| (id.to_string(), secret.to_string())));
|
||||
let (id, secret) = match basic {
|
||||
Some((id, secret)) => (id, Some(secret)),
|
||||
None => (
|
||||
client_id.ok_or_else(|| OauthError::new("invalid_client", "Unknown client."))?.to_string(),
|
||||
client_secret.map(str::to_string),
|
||||
),
|
||||
};
|
||||
let row: Option<(Option<Vec<u8>>,)> = sqlx::query_as("SELECT secret_hash FROM oauth_clients WHERE id = $1")
|
||||
.bind(&id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
match row {
|
||||
None => return Err(OauthError::new("invalid_client", "Unknown client.")),
|
||||
Some((Some(hash),)) if secret.as_deref().map(db::token_hash).as_ref() != Some(&hash) => {
|
||||
return Err(OauthError::new("invalid_client", "Wrong client secret."));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
sqlx::query("UPDATE oauth_clients SET last_used_at = now() WHERE id = $1").bind(&id).execute(&state.db).await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// PKCE: the verifier's SHA-256, base64url, is the challenge (RFC 7636).
|
||||
fn pkce_ok(verifier: &str, challenge: &str) -> bool {
|
||||
(43..=128).contains(&verifier.len())
|
||||
&& verifier.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
|
||||
&& URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) == challenge
|
||||
}
|
||||
|
||||
/// A new access and refresh token for a connection.
|
||||
async fn issue(tx: &mut sqlx::PgConnection, grant_id: Uuid) -> Result<Response, OauthError> {
|
||||
let (access, refresh) = (db::new_token(), db::new_token());
|
||||
let now = OffsetDateTime::now_utc();
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(grant_id)
|
||||
.bind(db::token_hash(&access))
|
||||
.bind(now + ACCESS_TTL)
|
||||
.bind(db::token_hash(&refresh))
|
||||
.bind(now + REFRESH_TTL)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let body = json!({
|
||||
"access_token": access,
|
||||
"token_type": "Bearer",
|
||||
"expires_in": ACCESS_TTL.whole_seconds(),
|
||||
"refresh_token": refresh,
|
||||
"scope": SCOPE,
|
||||
});
|
||||
Ok((StatusCode::OK, [(CACHE_CONTROL, "no-store"), (PRAGMA, "no-cache")], Json(body)).into_response())
|
||||
}
|
||||
|
||||
async fn revoke_grant(tx: &mut sqlx::PgConnection, grant_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL")
|
||||
.bind(grant_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn still_admin(tx: &mut sqlx::PgConnection, user_id: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT 'admin' = ANY(roles) FROM users WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map(|r| r.unwrap_or(false))
|
||||
}
|
||||
|
||||
fn invalid_grant(description: &str) -> OauthError {
|
||||
OauthError::new("invalid_grant", description)
|
||||
}
|
||||
|
||||
pub async fn token(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Form(req), _): WithRejection<Form<TokenRequest>, OauthError>,
|
||||
) -> Result<Response, OauthError> {
|
||||
state.oauth_limiter.hit(&format!("token:{}", client_ip(&headers).unwrap_or_default()))?;
|
||||
let client = client_of(&state, &headers, req.client_id.as_deref(), req.client_secret.as_deref()).await?;
|
||||
match req.grant_type.as_deref() {
|
||||
Some("authorization_code") => code_grant(&state, &client, &req).await,
|
||||
Some("refresh_token") => refresh_grant(&state, &client, &req).await,
|
||||
_ => Err(OauthError::new("unsupported_grant_type", "Use authorization_code or refresh_token.")),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct CodeRow {
|
||||
client_id: String,
|
||||
user_id: Uuid,
|
||||
redirect_uri: String,
|
||||
code_challenge: String,
|
||||
scope: String,
|
||||
resource: Option<String>,
|
||||
expires_at: OffsetDateTime,
|
||||
used_at: Option<OffsetDateTime>,
|
||||
grant_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
async fn code_grant(state: &AppState, client: &str, req: &TokenRequest) -> Result<Response, OauthError> {
|
||||
let code = req.code.as_deref().ok_or_else(|| OauthError::new("invalid_request", "The code is missing."))?;
|
||||
let verifier = req
|
||||
.code_verifier
|
||||
.as_deref()
|
||||
.ok_or_else(|| OauthError::new("invalid_request", "The code_verifier is missing."))?;
|
||||
let code_hash = db::token_hash(code);
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: Option<CodeRow> = sqlx::query_as(
|
||||
"SELECT client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at, used_at, grant_id \
|
||||
FROM oauth_codes WHERE code_hash = $1 FOR UPDATE",
|
||||
)
|
||||
.bind(&code_hash)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(row) = row.filter(|r| r.client_id == client) else { return Err(invalid_grant("Unknown code.")) };
|
||||
if row.used_at.is_some() {
|
||||
// A code sent twice may have been stolen: the connection made with it ends.
|
||||
if let Some(grant_id) = row.grant_id {
|
||||
revoke_grant(&mut tx, grant_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::warn!(client, grant = %grant_id, "oauth code used twice: connection revoked");
|
||||
}
|
||||
return Err(invalid_grant("The code was already used."));
|
||||
}
|
||||
if row.expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(invalid_grant("The code has expired."));
|
||||
}
|
||||
if req.redirect_uri.as_deref() != Some(row.redirect_uri.as_str()) {
|
||||
return Err(invalid_grant("The redirect_uri does not match."));
|
||||
}
|
||||
if !pkce_ok(verifier, &row.code_challenge) {
|
||||
return Err(invalid_grant("Wrong code_verifier."));
|
||||
}
|
||||
if let (Some(asked), Some(granted)) = (&req.resource, &row.resource)
|
||||
&& !same_resource(asked, granted)
|
||||
{
|
||||
return Err(OauthError::new("invalid_target", "Unknown resource."));
|
||||
}
|
||||
if !still_admin(&mut tx, row.user_id).await? {
|
||||
return Err(invalid_grant("The approver is no longer an admin."));
|
||||
}
|
||||
let grant_id = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope, resource) VALUES ($1, $2, $3, $4, $5)")
|
||||
.bind(grant_id)
|
||||
.bind(client)
|
||||
.bind(row.user_id)
|
||||
.bind(&row.scope)
|
||||
.bind(&row.resource)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE oauth_codes SET used_at = now(), grant_id = $2 WHERE code_hash = $1")
|
||||
.bind(&code_hash)
|
||||
.bind(grant_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let response = issue(&mut tx, grant_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(client, grant = %grant_id, user = %row.user_id, "oauth connection made");
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct RefreshRow {
|
||||
id: Uuid,
|
||||
grant_id: Uuid,
|
||||
client_id: String,
|
||||
user_id: Uuid,
|
||||
refresh_expires_at: OffsetDateTime,
|
||||
refreshed_at: Option<OffsetDateTime>,
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
async fn refresh_grant(state: &AppState, client: &str, req: &TokenRequest) -> Result<Response, OauthError> {
|
||||
let refresh = req
|
||||
.refresh_token
|
||||
.as_deref()
|
||||
.ok_or_else(|| OauthError::new("invalid_request", "The refresh_token is missing."))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: Option<RefreshRow> = sqlx::query_as(
|
||||
"SELECT t.id, t.grant_id, g.client_id, g.user_id, t.refresh_expires_at, t.refreshed_at, g.revoked_at \
|
||||
FROM oauth_tokens t JOIN oauth_grants g ON g.id = t.grant_id \
|
||||
WHERE t.refresh_hash = $1 FOR UPDATE OF t, g",
|
||||
)
|
||||
.bind(db::token_hash(refresh))
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(row) = row.filter(|r| r.client_id == client) else { return Err(invalid_grant("Unknown refresh token.")) };
|
||||
if row.revoked_at.is_some() {
|
||||
return Err(invalid_grant("The connection was revoked."));
|
||||
}
|
||||
if row.refreshed_at.is_some() {
|
||||
// An old refresh token again: it may have been stolen, so the connection ends.
|
||||
revoke_grant(&mut tx, row.grant_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::warn!(client, grant = %row.grant_id, "oauth refresh token reused: connection revoked");
|
||||
return Err(invalid_grant("The refresh token was already used."));
|
||||
}
|
||||
if row.refresh_expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(invalid_grant("The refresh token has expired."));
|
||||
}
|
||||
if !still_admin(&mut tx, row.user_id).await? {
|
||||
return Err(invalid_grant("The approver is no longer an admin."));
|
||||
}
|
||||
sqlx::query("UPDATE oauth_tokens SET refreshed_at = now() WHERE id = $1").bind(row.id).execute(&mut *tx).await?;
|
||||
let response = issue(&mut tx, row.grant_id).await?;
|
||||
tx.commit().await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RevokeRequest {
|
||||
token: Option<String>,
|
||||
client_id: Option<String>,
|
||||
client_secret: Option<String>,
|
||||
}
|
||||
|
||||
/// RFC 7009: either token of a connection ends the whole connection.
|
||||
pub async fn revoke(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Form(req), _): WithRejection<Form<RevokeRequest>, OauthError>,
|
||||
) -> Result<StatusCode, OauthError> {
|
||||
let client = client_of(&state, &headers, req.client_id.as_deref(), req.client_secret.as_deref()).await?;
|
||||
if let Some(token) = req.token {
|
||||
let hash = db::token_hash(&token);
|
||||
sqlx::query(
|
||||
"UPDATE oauth_grants g SET revoked_at = now() FROM oauth_tokens t \
|
||||
WHERE t.grant_id = g.id AND g.client_id = $2 AND g.revoked_at IS NULL \
|
||||
AND (t.access_hash = $1 OR t.refresh_hash = $1)",
|
||||
)
|
||||
.bind(hash)
|
||||
.bind(&client)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
}
|
||||
Ok(StatusCode::OK)
|
||||
}
|
||||
|
||||
// --- the MCP server's check -------------------------------------------------------------
|
||||
|
||||
/// Guard: an MCP client's access token of an admin (not a session).
|
||||
pub struct McpClient(AuthUser);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for McpClient {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = oauth_user(parts, state).await?.ok_or(ApiError::Unauthorized)?;
|
||||
user.require(Role::Admin)?;
|
||||
Ok(McpClient(user))
|
||||
}
|
||||
}
|
||||
|
||||
/// Who the token belongs to and what it is for (the MCP server checks the
|
||||
/// resource; no personal data).
|
||||
pub async fn whoami(McpClient(user): McpClient) -> Json<Value> {
|
||||
let access = user.oauth.as_ref();
|
||||
Json(json!({
|
||||
"user_id": user.id(),
|
||||
"roles": user.user.roles,
|
||||
"grant_id": access.map(|a| a.grant_id),
|
||||
"scope": access.map(|a| a.scope.as_str()),
|
||||
"resource": access.and_then(|a| a.resource.as_deref()),
|
||||
}))
|
||||
}
|
||||
|
||||
// --- the admin's list of connections -------------------------------------------------------
|
||||
|
||||
/// A connection: id, client name, its return addresses, the admin's e-mail, made, last used.
|
||||
type GrantRow = (Uuid, String, Vec<String>, String, OffsetDateTime, Option<OffsetDateTime>);
|
||||
|
||||
/// The connections in use (a session only: a client cannot see or end them).
|
||||
pub async fn admin_grants(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
auth.require(Role::Admin)?;
|
||||
let rows: Vec<GrantRow> = sqlx::query_as(
|
||||
"SELECT g.id, c.name, c.redirect_uris, u.email, g.created_at, g.last_used_at \
|
||||
FROM oauth_grants g JOIN oauth_clients c ON c.id = g.client_id JOIN users u ON u.id = g.user_id \
|
||||
WHERE g.revoked_at IS NULL \
|
||||
AND EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.grant_id = g.id AND t.refresh_expires_at > now()) \
|
||||
ORDER BY g.created_at DESC",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let grants: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, client, uris, email, created, used)| {
|
||||
let host =
|
||||
uris.first().and_then(|u| reqwest::Url::parse(u).ok()).and_then(|u| u.host_str().map(String::from));
|
||||
json!({
|
||||
"id": id,
|
||||
"client_name": client,
|
||||
"redirect_host": host,
|
||||
"user_email": email,
|
||||
"created_at": rfc3339(created),
|
||||
"last_used_at": rfc3339_opt(used),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "grants": grants })))
|
||||
}
|
||||
|
||||
pub async fn admin_revoke_grant(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): super::IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
auth.require(Role::Admin)?;
|
||||
let done = sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL")
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if done.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("connection"));
|
||||
}
|
||||
tracing::info!(grant = %id, by = %auth.id(), "oauth connection revoked by an admin");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn redirect_addresses() {
|
||||
let allowed: Vec<String> = crate::config::DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec();
|
||||
for ok in [
|
||||
"https://claude.ai/api/mcp/auth_callback",
|
||||
"https://claude.com/api/mcp/auth_callback",
|
||||
"http://localhost:53682/callback",
|
||||
"http://127.0.0.1:8080",
|
||||
"http://localhost:3000/cb?x=1",
|
||||
] {
|
||||
assert!(redirect_allowed(ok, &allowed), "{ok}");
|
||||
}
|
||||
for no in [
|
||||
"https://claude.ai/api/mcp/auth_callback/x",
|
||||
"https://evil.example/api/mcp/auth_callback",
|
||||
"http://localhost:80@evil.example/",
|
||||
"http://localhost.evil.example:80/",
|
||||
"http://localhost:/cb",
|
||||
"http://localhost:123456/",
|
||||
"https://claude.ai/api/mcp/auth_callback#frag",
|
||||
"javascript:alert(1)",
|
||||
] {
|
||||
assert!(!redirect_allowed(no, &allowed), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkce() {
|
||||
// A verifier and its challenge (base64url of the SHA-256).
|
||||
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWZOEjXk";
|
||||
assert!(pkce_ok(verifier, "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII"));
|
||||
assert!(!pkce_ok(verifier, "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reIX"));
|
||||
assert!(!pkce_ok("short", "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII"));
|
||||
}
|
||||
}
|
||||
@@ -363,6 +363,19 @@ impl TestApp {
|
||||
(status, headers, resp.into_body().collect().await.unwrap().to_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// A form POST (OAuth's token and revocation endpoints), with extra headers.
|
||||
async fn form(&self, uri: &str, body: &str, headers: &[(&str, &str)]) -> Response {
|
||||
let mut req =
|
||||
Request::builder().method("POST").uri(uri).header("content-type", "application/x-www-form-urlencoded");
|
||||
for (name, value) in headers {
|
||||
req = req.header(*name, *value);
|
||||
}
|
||||
let resp = self.router.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
|
||||
let (status, headers) = (resp.status(), resp.headers().clone());
|
||||
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||
Response { status, body: serde_json::from_slice(&bytes).unwrap_or(Value::Null), headers }
|
||||
}
|
||||
|
||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
||||
self.call_with(method, uri, token, body, &[]).await
|
||||
}
|
||||
@@ -1125,7 +1138,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||
/// logged-in user, so other apps cannot use them.
|
||||
const PUBLIC_ROUTES: [&str; 26] = [
|
||||
const PUBLIC_ROUTES: [&str; 31] = [
|
||||
"/healthz",
|
||||
// Stripe calls it; the signature proves it.
|
||||
"/v1/payments/stripe/webhook",
|
||||
@@ -1157,6 +1170,13 @@ const PUBLIC_ROUTES: [&str; 26] = [
|
||||
// The sky by date, the same for everyone (the moon and retrograde calendars).
|
||||
"/v1/public/sky",
|
||||
"/v1/public/sky/events",
|
||||
// OAuth for the MCP clients (docs/mcp.md): Claude calls these before it has
|
||||
// a token; approving (POST authorize) needs an admin's session.
|
||||
"/v1/oauth/metadata",
|
||||
"/v1/oauth/register",
|
||||
"/v1/oauth/authorize",
|
||||
"/v1/oauth/token",
|
||||
"/v1/oauth/revoke",
|
||||
];
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -4422,3 +4442,244 @@ async fn admin_statistics_and_where_members_came_from(pool: PgPool) {
|
||||
assert!(all["previous"].is_null());
|
||||
assert_eq!(all["period"]["signups"], 3);
|
||||
}
|
||||
|
||||
// --- MCP clients through OAuth (docs/mcp.md) ---------------------------------------------
|
||||
|
||||
const MCP_CALLBACK: &str = "https://claude.ai/api/mcp/auth_callback";
|
||||
const MCP_CALLBACK_ENC: &str = "https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback";
|
||||
// A PKCE verifier and its challenge.
|
||||
const PKCE_VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWZOEjXk";
|
||||
const PKCE_CHALLENGE: &str = "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII";
|
||||
|
||||
fn mcp_approval(client: &str) -> Value {
|
||||
json!({
|
||||
"response_type": "code", "client_id": client, "redirect_uri": MCP_CALLBACK,
|
||||
"code_challenge": PKCE_CHALLENGE, "code_challenge_method": "S256",
|
||||
"state": "xyz", "resource": "https://sorsfonalak.test/mcp", "scope": "admin",
|
||||
})
|
||||
}
|
||||
|
||||
/// The admin approves; returns the code from the address Claude gets back.
|
||||
async fn mcp_code(app: &TestApp, session: &str, client: &str) -> String {
|
||||
let r = app.post("/v1/oauth/authorize", Some(session), mcp_approval(client)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let to = r.body["redirect_to"].as_str().unwrap();
|
||||
assert!(to.starts_with(&format!("{MCP_CALLBACK}?code=")), "{to}");
|
||||
assert!(to.ends_with("&state=xyz&iss=https%3A%2F%2Fsorsfonalak.test"), "{to}");
|
||||
to.split("code=").nth(1).unwrap().split('&').next().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn mcp_exchange(client: &str, code: &str, verifier: &str) -> String {
|
||||
format!(
|
||||
"grant_type=authorization_code&code={code}&redirect_uri={MCP_CALLBACK_ENC}&client_id={client}\
|
||||
&code_verifier={verifier}&resource=https%3A%2F%2Fsorsfonalak.test%2Fmcp"
|
||||
)
|
||||
}
|
||||
|
||||
/// A new connection: (access token, refresh token).
|
||||
async fn mcp_connect(app: &TestApp, session: &str, client: &str) -> (String, String) {
|
||||
let code = mcp_code(app, session, client).await;
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(client, &code, PKCE_VERIFIER), &[]).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
(r.body["access_token"].as_str().unwrap().into(), r.body["refresh_token"].as_str().unwrap().into())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn mcp_clients_connect_through_oauth(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let anna_id = app.get("/v1/me", Some(&anna)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
|
||||
let meta = app.get("/v1/oauth/metadata", None).await.body;
|
||||
assert_eq!(
|
||||
(&meta["issuer"], &meta["token_endpoint"], &meta["authorization_endpoint"]),
|
||||
(
|
||||
&json!("https://sorsfonalak.test"),
|
||||
&json!("https://sorsfonalak.test/api/v1/oauth/token"),
|
||||
&json!("https://sorsfonalak.test/oauth/engedely")
|
||||
)
|
||||
);
|
||||
|
||||
// Registration: only Claude's (or a local) return address.
|
||||
let r = app.post("/v1/oauth/register", None, json!({"redirect_uris": ["https://evil.example/cb"]})).await;
|
||||
assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::BAD_REQUEST, Some("invalid_redirect_uri")));
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/oauth/register",
|
||||
None,
|
||||
json!({"client_name": "Claude", "redirect_uris": [MCP_CALLBACK], "token_endpoint_auth_method": "none",
|
||||
"grant_types": ["authorization_code", "refresh_token"], "logo_uri": "https://claude.ai/x.png"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert!(r.body.get("client_secret").is_none());
|
||||
let client = r.body["client_id"].as_str().unwrap().to_string();
|
||||
|
||||
// The approval page's question; a return address the client did not register.
|
||||
let query = format!(
|
||||
"response_type=code&client_id={client}&redirect_uri={MCP_CALLBACK_ENC}&code_challenge={PKCE_CHALLENGE}\
|
||||
&code_challenge_method=S256&state=xyz"
|
||||
);
|
||||
let r = app.get(&format!("/v1/oauth/authorize?{query}"), None).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["client_name"], &r.body["redirect_host"]),
|
||||
(StatusCode::OK, &json!("Claude"), &json!("claude.ai"))
|
||||
);
|
||||
let other = query.replace("claude.ai", "claude.com");
|
||||
assert_eq!(app.get(&format!("/v1/oauth/authorize?{other}"), None).await.status, StatusCode::BAD_REQUEST);
|
||||
let plain = query.replace("S256", "plain");
|
||||
assert_eq!(app.get(&format!("/v1/oauth/authorize?{plain}"), None).await.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// Approving needs a login and the admin role; a refusal goes back too.
|
||||
assert_eq!(app.post("/v1/oauth/authorize", None, mcp_approval(&client)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.post("/v1/oauth/authorize", Some(&anna), mcp_approval(&client)).await.status, StatusCode::FORBIDDEN);
|
||||
let mut deny = mcp_approval(&client);
|
||||
deny["deny"] = json!(true);
|
||||
let r = app.post("/v1/oauth/authorize", Some(&admin), deny).await;
|
||||
assert_eq!(
|
||||
r.body["redirect_to"],
|
||||
json!(format!("{MCP_CALLBACK}?error=access_denied&state=xyz&iss=https%3A%2F%2Fsorsfonalak.test"))
|
||||
);
|
||||
|
||||
// The code: a wrong verifier or return address does not use it up.
|
||||
let code = mcp_code(&app, &admin, &client).await;
|
||||
let wrong = mcp_exchange(&client, &code, &"a".repeat(43));
|
||||
let r = app.form("/v1/oauth/token", &wrong, &[]).await;
|
||||
assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::BAD_REQUEST, Some("invalid_grant")));
|
||||
let elsewhere = mcp_exchange(&client, &code, PKCE_VERIFIER).replace("claude.ai", "claude.com");
|
||||
assert_eq!(app.form("/v1/oauth/token", &elsewhere, &[]).await.body["error"], "invalid_grant");
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["token_type"], &r.body["expires_in"]),
|
||||
(StatusCode::OK, &json!("Bearer"), &json!(3600)),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
assert_eq!(r.headers["cache-control"], "no-store");
|
||||
let (access, refresh) =
|
||||
(r.body["access_token"].as_str().unwrap().to_string(), r.body["refresh_token"].as_str().unwrap().to_string());
|
||||
|
||||
// What the token is for, and what it may do.
|
||||
let r = app.get("/v1/oauth/whoami", Some(&access)).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["resource"], &r.body["scope"]),
|
||||
(StatusCode::OK, &json!("https://sorsfonalak.test/mcp"), &json!("admin"))
|
||||
);
|
||||
assert!(r.body.get("email").is_none());
|
||||
assert_eq!(app.get("/v1/oauth/whoami", Some(&admin)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/admin/stats?days=7", Some(&access)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/admin/users?q=anna", Some(&access)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/admin/celebrities", Some(&access)).await.status, StatusCode::OK);
|
||||
let r = app.post("/v1/admin/promo-codes", Some(&access), json!({"package": "single", "count": 1})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!(app.post("/v1/admin/jobs/restart", Some(&access), json!({})).await.status, StatusCode::OK);
|
||||
// Not a daily task: only on the admin page.
|
||||
let roles = json!({"roles": ["user", "admin"]});
|
||||
let r = app.call("PATCH", &format!("/v1/admin/users/{anna_id}"), Some(&access), Some(roles)).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let units = json!({"unit": "natal", "delta": 5});
|
||||
let r = app.post(&format!("/v1/admin/users/{anna_id}/credits"), Some(&access), units).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
// Not an admin page: no session, no new tokens, no list of connections.
|
||||
assert_eq!(app.get("/v1/me", Some(&access)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(
|
||||
app.post("/v1/oauth/authorize", Some(&access), mcp_approval(&client)).await.status,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
assert_eq!(app.get("/v1/admin/oauth/grants", Some(&access)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let grants = app.get("/v1/admin/oauth/grants", Some(&admin)).await.body["grants"].clone();
|
||||
assert_eq!((grants.as_array().unwrap().len(), &grants[0]["client_name"]), (1, &json!("Claude")));
|
||||
|
||||
// A refresh makes a new pair; the old refresh token again ends the connection.
|
||||
let again = format!("grant_type=refresh_token&refresh_token={refresh}&client_id={client}");
|
||||
let r = app.form("/v1/oauth/token", &again, &[]).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let access2 = r.body["access_token"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access2)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.form("/v1/oauth/token", &again, &[]).await.body["error"], "invalid_grant");
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access2)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access)).await.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// A code used twice ends the connection made with it.
|
||||
let code = mcp_code(&app, &admin, &client).await;
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await;
|
||||
let access3 = r.body["access_token"].as_str().unwrap().to_string();
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await;
|
||||
assert_eq!(r.body["error"], "invalid_grant");
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access3)).await.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// An expired code.
|
||||
let code = mcp_code(&app, &admin, &client).await;
|
||||
sqlx::query("UPDATE oauth_codes SET expires_at = now() - interval '1 second' WHERE used_at IS NULL")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await.body["error"],
|
||||
"invalid_grant"
|
||||
);
|
||||
|
||||
// Ended by the admin on the site, by the client, by logging out everywhere.
|
||||
let (access4, _) = mcp_connect(&app, &admin, &client).await;
|
||||
let grants = app.get("/v1/admin/oauth/grants", Some(&admin)).await.body["grants"].clone();
|
||||
assert_eq!(grants.as_array().unwrap().len(), 1);
|
||||
let id = grants[0]["id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
app.call("DELETE", &format!("/v1/admin/oauth/grants/{id}"), Some(&admin), None).await.status,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access4)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let (access5, refresh5) = mcp_connect(&app, &admin, &client).await;
|
||||
let r = app.form("/v1/oauth/revoke", &format!("token={refresh5}&client_id={client}"), &[]).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access5)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let (access6, _) = mcp_connect(&app, &admin, &client).await;
|
||||
assert_eq!(app.post("/v1/auth/logout-all", Some(&admin), json!({})).await.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access6)).await.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// An admin no more: the token is refused.
|
||||
sqlx::query("UPDATE users SET roles = array_append(roles, 'admin') WHERE email = 'anna@example.com'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let (anna_access, anna_refresh) = mcp_connect(&app, &anna, &client).await;
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&anna_access)).await.status, StatusCode::OK);
|
||||
sqlx::query("UPDATE users SET roles = array_remove(roles, 'admin') WHERE email = 'anna@example.com'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&anna_access)).await.status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.get("/v1/oauth/whoami", Some(&anna_access)).await.status, StatusCode::FORBIDDEN);
|
||||
let again = format!("grant_type=refresh_token&refresh_token={anna_refresh}&client_id={client}");
|
||||
assert_eq!(app.form("/v1/oauth/token", &again, &[]).await.body["error"], "invalid_grant");
|
||||
|
||||
// A client with a secret must send it (in the form or with HTTP Basic).
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/oauth/register",
|
||||
None,
|
||||
json!({"client_name": "Claude Code", "redirect_uris": ["http://localhost:53682/callback"]}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["token_endpoint_auth_method"]), (StatusCode::CREATED, &json!("client_secret_basic")));
|
||||
let (local, secret) =
|
||||
(r.body["client_id"].as_str().unwrap().to_string(), r.body["client_secret"].as_str().unwrap().to_string());
|
||||
let login = json!({"email": "admin@example.com", "password": "titkos-jelszo-123"});
|
||||
let admin = app.post("/v1/auth/login", None, login).await.body["session"]["token"].as_str().unwrap().to_string();
|
||||
let mut approval = mcp_approval(&local);
|
||||
approval["redirect_uri"] = json!("http://localhost:53682/callback");
|
||||
let r = app.post("/v1/oauth/authorize", Some(&admin), approval).await;
|
||||
let to = r.body["redirect_to"].as_str().unwrap();
|
||||
let code = to.split("code=").nth(1).unwrap().split('&').next().unwrap();
|
||||
let exchange = format!(
|
||||
"grant_type=authorization_code&code={code}&redirect_uri=http%3A%2F%2Flocalhost%3A53682%2Fcallback\
|
||||
&code_verifier={PKCE_VERIFIER}"
|
||||
);
|
||||
let r = app.form("/v1/oauth/token", &format!("{exchange}&client_id={local}"), &[]).await;
|
||||
assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::UNAUTHORIZED, Some("invalid_client")));
|
||||
use base64::Engine;
|
||||
let basic = format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(format!("{local}:{secret}")));
|
||||
let r = app.form("/v1/oauth/token", &exchange, &[("authorization", &basic)]).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user