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:
@@ -1,6 +1,9 @@
|
||||
//! Who is asking: the backend's session (cookie or Bearer token) and the
|
||||
//! member behind it. Reading needs no login; writing needs a nickname.
|
||||
//! Every request of a member also keeps the online dot fresh.
|
||||
//!
|
||||
//! An admin's MCP client (docs/mcp.md) may send its OAuth token instead: it
|
||||
//! reads as that admin and may moderate, but never writes as a member.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -68,6 +71,8 @@ pub struct Viewer {
|
||||
pub topics: Vec<i16>,
|
||||
/// The members they muted.
|
||||
pub mutes: Vec<Uuid>,
|
||||
/// An admin's MCP client (an OAuth token, not a session): moderation only.
|
||||
pub via_token: bool,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
@@ -89,6 +94,9 @@ impl Viewer {
|
||||
}
|
||||
|
||||
pub fn require_user(&self) -> Result<&User, ApiError> {
|
||||
if self.via_token {
|
||||
return Err(ApiError::Forbidden("Claude-ból a fórumban csak moderálni lehet.".into()));
|
||||
}
|
||||
self.user.as_ref().ok_or(ApiError::Unauthorized)
|
||||
}
|
||||
|
||||
@@ -108,7 +116,7 @@ impl Viewer {
|
||||
}
|
||||
|
||||
pub fn require_moderator(&self) -> Result<&User, ApiError> {
|
||||
let user = self.require_user()?;
|
||||
let user = self.user.as_ref().ok_or(ApiError::Unauthorized)?;
|
||||
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
|
||||
}
|
||||
}
|
||||
@@ -127,7 +135,15 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else {
|
||||
// An admin's MCP client: the admin, without the member's side.
|
||||
return Ok(match db::user_by_oauth_token(&state.db, &token).await? {
|
||||
Some((_, user)) if user.has_role(Role::Admin) => {
|
||||
Viewer { user: Some(user), via_token: true, ..Viewer::default() }
|
||||
}
|
||||
_ => Viewer::default(),
|
||||
});
|
||||
};
|
||||
let member = load_member(&state.db, user.id).await?;
|
||||
if member.is_some() {
|
||||
// At most once a minute per member: the online dot.
|
||||
@@ -154,7 +170,7 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
Ok(Viewer { user: Some(user), member, topics, mutes })
|
||||
Ok(Viewer { user: Some(user), member, topics, mutes, via_token: false })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1703,3 +1703,71 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap();
|
||||
assert_eq!(left, 1);
|
||||
}
|
||||
|
||||
/// An admin's MCP client (docs/mcp.md): it moderates with its OAuth token,
|
||||
/// and never writes as a member.
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn an_admins_mcp_client_moderates_only(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||
let admin = app.member("admin@example.com", "Gondnok", &["user", "admin"]).await;
|
||||
let thread = app.thread(&anna, "belso-utak", "Energiák").await;
|
||||
let post = app.reply(&bea, thread, "Energetikai gyógyítás, írj!", None).await["id"].as_i64().unwrap();
|
||||
app.call("POST", &format!("/v1/forum/posts/{post}/report"), Some(&anna), json!({"kind": "ad"})).await;
|
||||
|
||||
// The token the backend gave Claude after the admin's approval.
|
||||
let token = db::new_token();
|
||||
let grant = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO oauth_clients (id, name, redirect_uris) VALUES ('claude', 'Claude', '{}')")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope) VALUES ($1, 'claude', $2, 'admin')")
|
||||
.bind(grant)
|
||||
.bind(admin.id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \
|
||||
VALUES ($1, $2, $3, now() + interval '1 hour', $4, now() + interval '30 days')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(grant)
|
||||
.bind(db::token_hash(&token))
|
||||
.bind(db::token_hash(&db::new_token()))
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let claude = User { id: admin.id, token };
|
||||
|
||||
// Moderation: the reports, closing one, a ban, the log (under the admin's name).
|
||||
let list = app.get("/v1/forum/mod/reports", Some(&claude)).await;
|
||||
let id = list["reports"][0]["id"].as_i64().unwrap();
|
||||
let (status, _) =
|
||||
app.call("POST", &format!("/v1/forum/mod/reports/{id}"), Some(&claude), json!({"action": "dismiss"})).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
let (status, _) = app
|
||||
.call("POST", "/v1/forum/members/holdfeny/ban", Some(&claude), json!({"hours": 24, "reason": "hirdetés"}))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let log = app.get("/v1/forum/mod/log", Some(&claude)).await;
|
||||
assert_eq!((&log["entries"][0]["action"], &log["entries"][0]["actor"]), (&json!("ban"), &json!("Gondnok")));
|
||||
assert_eq!(app.get(&format!("/v1/forum/threads/{thread}"), Some(&claude)).await["thread"]["id"], thread);
|
||||
|
||||
// Never as a member: no reply, reaction, report or new thread.
|
||||
let reply = json!({"body": "Claude írta."});
|
||||
let (status, _) = app.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&claude), reply).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) =
|
||||
app.call("PUT", &format!("/v1/forum/posts/{post}/reaction"), Some(&claude), json!({"kind": "heart"})).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) =
|
||||
app.call("POST", &format!("/v1/forum/posts/{post}/report"), Some(&claude), json!({"kind": "ad"})).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
|
||||
// A revoked connection is nobody.
|
||||
sqlx::query("UPDATE oauth_grants SET revoked_at = now()").execute(&app.pool).await.unwrap();
|
||||
assert_eq!(app.call("GET", "/v1/forum/mod/reports", Some(&claude), Value::Null).await.0, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user