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
36 changes: 35 additions & 1 deletion app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ pub enum Via {
OAuth { client_id: String },
/// One of their personal tokens.
Token { token_id: i64, name: String },
/// The admin MCP endpoint (`/mcp/admin`): a staff member's OAuth token with the `admin` scope. They act as an
/// admin of every organization there, and nowhere else ([`crate::mcp::admin`]).
Admin { client_id: String },
}

/// What acted, for attributing a review or an upload (`reviews.source`, `client_id`, `token_name`): "Claude Code for
Expand Down Expand Up @@ -128,7 +131,7 @@ impl Principal {
pub fn client(&self) -> Client {
match self {
Self::User { via: Via::Session, .. } => Client { source: "web", client_id: None, token_name: None },
Self::User { via: Via::OAuth { client_id }, .. } => {
Self::User { via: Via::OAuth { client_id } | Via::Admin { client_id }, .. } => {
Client { source: "mcp", client_id: Some(client_id.clone()), token_name: None }
}
Self::User { via: Via::Token { name, .. }, .. } => {
Expand All @@ -149,6 +152,8 @@ impl Principal {
pub async fn role_in(&self, project: &impl InProject) -> laravel::Result<Option<Role>> {
match self {
Self::Project { project_id, .. } => Ok((*project_id == project.project_id()).then_some(Role::Member)),
// Staff on the admin endpoint read every organization, as an admin would.
Self::User { user, via: Via::Admin { .. } } if user.staff => Ok(Some(Role::Admin)),
Self::User { user, .. } => {
let (org, user_id) = (project.organization_id(), user.id);
let role: Option<String> =
Expand Down Expand Up @@ -220,6 +225,35 @@ impl Principal {
}
Ok(None)
}

/// The person an MCP client's OAuth access token (`vca_…`) acts for, when it's live for `resource` and has
/// `scope`: `Ok(Err(refusal))` says why not (unknown, expired, for another resource, missing the scope, or its
/// person is gone), for the endpoint's challenge.
///
/// # Errors
/// When the token store or the database can't be read.
pub async fn from_oauth(
token: &str,
resource: &str,
scope: &str,
) -> laravel::Result<Result<(User, String), oauth_provider::Refusal>> {
let oauth = laravel::container::resolve::<oauth_provider_laravel::OAuth>().await?;
let verified = match oauth.provider().verify(token, resource).await {
Ok(Ok(verified)) => verified,
Ok(Err(refusal)) => return Ok(Err(refusal)),
Err(e) => return Err(laravel::Error::msg(format!("checking an OAuth access token: {e}"))),
};
if let Err(refusal) = verified.require(&[scope]) {
return Ok(Err(refusal));
}
let Ok(pid) = verified.subject.parse::<laravel::str::Uuid>() else {
return Ok(Err(oauth_provider::Refusal::Invalid("The token's person no longer exists.".into())));
};
match User::first_where(User::pid.eq(pid)).await? {
Some(user) => Ok(Ok((user, verified.client_id))),
None => Ok(Err(oauth_provider::Refusal::Invalid("The token's person no longer exists.".into()))),
}
}
}

impl laravel::auth::Authorizable for Principal {}
Expand Down
172 changes: 162 additions & 10 deletions app/src/auth/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,19 @@
//! `<VISUALCI_APP_URL>/oauth/authorize`). [`check`] stops a production boot when they don't say so. A token's
//! subject is the person's pid, never their row ID.
//!
//! Only the `mcp` scope for now. Today's `admin` scope, for the staff-only `/mcp/admin` endpoint, must be granted to
//! staff alone, and the package's consent step grants what a client asks for: it comes with a consent hook that checks
//! `users.staff`.
//! Two scopes, each for one resource: `mcp` for `<mcp url>/mcp`, and `admin` for the staff-only `<mcp url>/mcp/admin`
//! ([`crate::mcp::admin`]). Each resource's metadata advertises only its own scope, so clients don't ask everyone for
//! `admin`. The package's consent step grants what a client asks for, so [`consent_scopes`] (in the `web` group,
//! after the session) decides first: the consent page asks for what's granted, and an approval asking for more is
//! refused. What's granted is as today's server's `granted_scopes` did: `admin` alone on the admin resource and
//! only for staff (anyone else gets a refusal page), and `mcp` alone everywhere else, whatever was asked for.
//!
//! The account page lists the apps connected to the person's account (`GET /api/ui/me/connections`) and disconnects
//! one (`DELETE /api/ui/me/connections?client_id=`), which revokes every token that app holds for them.

use laravel::auth::Authenticated;
use laravel::auth::{Auth, Authenticated};
use laravel::container::Inject;
use laravel::http::{Next, Request, Response, middleware};
use laravel::prelude::*;
use oauth_provider_laravel::{OAuth, OAuthConfig, OAuthServiceProvider, OAuthTokens};
use serde_json::{Value, json};
Expand All @@ -29,18 +33,166 @@ use crate::models::{User, Users};
/// The guard MCP routes put behind `RequireToken`: `Authenticate::via::<Tokens>()`.
pub type Tokens = OAuthTokens<Users>;

/// The service provider `configure()` registers.
/// The scope `/mcp` needs.
pub const MCP_SCOPE: &str = "mcp";
/// The scope `/mcp/admin` needs: only staff can grant it ([`granted_scopes`]).
pub const ADMIN_SCOPE: &str = "admin";

/// The service provider `configure()` registers. Every MCP resource (`<url>/mcp`, from `OAUTH_RESOURCES` or the
/// default) gets its admin endpoint (`<url>/mcp/admin`) as a resource too, each advertising only its own scope.
#[must_use]
pub fn provider() -> OAuthServiceProvider<Users> {
OAuthServiceProvider::<Users>::new().configure(|config| {
config.with_service_name("VisualCI").with_scopes(&["mcp"]).with_prefixes(oauth_provider::Prefixes {
access: "vca_".into(),
refresh: "vcr_".into(),
client_secret: "vcs_".into(),
})
let mut config = config.with_service_name("VisualCI").with_scopes(&[MCP_SCOPE, ADMIN_SCOPE]).with_prefixes(
oauth_provider::Prefixes { access: "vca_".into(), refresh: "vcr_".into(), client_secret: "vcs_".into() },
);
let mcp: Vec<String> = config.resources.iter().filter(|r| r.ends_with("/mcp")).cloned().collect();
for resource in mcp {
let admin = format!("{resource}/admin");
if !config.resources.contains(&admin) {
config.resources.push(admin.clone());
}
config = config.with_resource_scopes(&resource, &[MCP_SCOPE]).with_resource_scopes(&admin, &[ADMIN_SCOPE]);
}
config
})
}

/// Why someone who isn't staff can't connect to the admin endpoint.
pub const ADMIN_REFUSAL: &str = "Admin access to all organizations is only for VisualCI staff.";

/// The scopes to grant for a request to `resource`: `admin` alone on an admin resource (`.../mcp/admin`), and only for
/// staff (`Err` says why not); `mcp` everywhere else, whatever else was asked for.
///
/// # Errors
/// [`ADMIN_REFUSAL`], for someone who isn't staff asking for the admin resource.
pub fn granted_scopes(resource: &str, staff: bool) -> Result<Vec<String>, &'static str> {
if is_admin_resource(resource) {
if staff { Ok(vec![ADMIN_SCOPE.to_string()]) } else { Err(ADMIN_REFUSAL) }
} else {
Ok(vec![MCP_SCOPE.to_string()])
}
}

fn is_admin_resource(resource: &str) -> bool {
resource.trim_end_matches('/').ends_with("/mcp/admin")
}

/// The consent step's hook, in the `web` group after the session, on the authorization endpoint: `GET` shows the
/// consent page with the request's `scope` replaced by what [`granted_scopes`] grants the signed-in person, so the
/// page shows it and its form carries it; `POST` (the approval, which grants the posted `scope`) is refused unless it
/// posts exactly that. Someone who isn't staff asking for the admin endpoint gets a `403` page saying why. Anything
/// the package would refuse anyway (a bad request, a signed-out person) passes through untouched for it to answer.
///
/// The approval is checked rather than rewritten: the session middleware may have read its body already, and the
/// package reads that copy.
#[middleware]
pub async fn consent_scopes(auth: Auth<User>, oauth: Inject<OAuth>, request: Request, next: Next) -> Response {
let endpoint = url::Url::parse(&oauth.config().authorization_endpoint)
.map_or_else(|_| "/oauth/authorize".to_string(), |u| u.path().to_string());
let get = request.method() == laravel::http::Method::GET;
if request.path() != endpoint || !(get || request.method() == laravel::http::Method::POST) {
return next.run(request).await;
}
let Ok(Some(user)) = auth.user().await else { return next.run(request).await };
let (mut parts, body) = request.into_http().into_parts();
let (raw, body) = if get {
(parts.uri.query().unwrap_or_default().to_string(), body)
} else {
match axum::body::to_bytes(body, 64 * 1024).await {
Ok(bytes) => (String::from_utf8_lossy(&bytes).into_owned(), axum::body::Body::from(bytes)),
Err(_) => {
return Response::new("The form is too large.")
.with_status(laravel::http::StatusCode::PAYLOAD_TOO_LARGE);
}
}
};
let refused = |why: &str| {
Response::new(laravel::view("oauth::error", laravel::view::data! { message => why, status => 403 }))
.with_status(laravel::http::StatusCode::FORBIDDEN)
.with_header("cache-control", "private, no-store")
};
let granted = match oauth_provider::parse_params(&raw) {
Ok(params) => match oauth.provider().authorization(&params).await {
Ok(req) => match granted_scopes(&req.resource, user.staff) {
Ok(granted) => Some((granted.join(" "), req.scopes.join(" "), req.redirect_uri.clone())),
Err(why) => return refused(why),
},
Err(_) => None,
},
Err(_) => None,
};
let Some((granted, asked, redirect_uri)) = granted else {
// An approval the OAuth server can't read as a valid request grants nothing: refused here too, whatever the
// package would answer
if !get {
return refused("This connection request isn't valid any more. Start connecting the app again.");
}
return next.run(Request::from_http(axum::http::Request::from_parts(parts, body))).await;
};
let admin = granted == ADMIN_SCOPE;
if get {
let pairs: Vec<(String, String)> = url::form_urlencoded::parse(raw.as_bytes())
.filter(|(k, _)| k != "scope")
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.chain([("scope".to_string(), granted)])
.collect();
let query = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(&pairs).finish();
// Laravel's `Request::uri` reads the original URI when routing kept one: change both.
if let Ok(uri) = format!("{}?{query}", parts.uri.path()).parse::<axum::http::Uri>() {
parts.uri = uri;
}
if let Some(original) = parts.extensions.get_mut::<axum::extract::OriginalUri>()
&& let Ok(uri) = format!("{}?{query}", original.0.path()).parse()
{
original.0 = uri;
}
} else if asked != granted {
return refused(&format!(
"The app asked for \"{asked}\", and this account can grant \"{granted}\" here. Start connecting it again."
));
}
let response = next.run(Request::from_http(axum::http::Request::from_parts(parts, body))).await;
if get && admin { admin_warning(response, &redirect_uri).await } else { response }
}

/// The admin consent page's warning, under its heading: what admin access lets the app do, and the host the person is
/// sent back to, so a staff member can see a client that isn't theirs before allowing it. It uses the consent page's
/// own `warning` and `muted` styles.
async fn admin_warning(response: Response, redirect_uri: &str) -> Response {
let (mut parts, body) = response.into_http().into_parts();
let Ok(bytes) = axum::body::to_bytes(body, 1024 * 1024).await else {
return Response::new("The consent page couldn't be shown.")
.with_status(laravel::http::StatusCode::INTERNAL_SERVER_ERROR);
};
let html = String::from_utf8_lossy(&bytes).into_owned();
let page = match html.split_once("</h1>") {
Some((head, rest)) if parts.status.is_success() => format!("{head}</h1>\n{}{rest}", admin_notice(redirect_uri)),
_ => html,
};
parts.headers.remove(axum::http::header::CONTENT_LENGTH);
Response::from_http(axum::http::Response::from_parts(parts, axum::body::Body::from(page)))
}

/// The notice itself, escaped.
#[must_use]
pub fn admin_notice(redirect_uri: &str) -> String {
let host = url::Url::parse(redirect_uri)
.ok()
.and_then(|u| u.host_str().map(|h| u.port().map_or_else(|| h.to_string(), |p| format!("{h}:{p}"))))
.unwrap_or_else(|| redirect_uri.to_string());
let escape = |s: &str| {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&#39;")
};
format!(
" <p class=\"warning\" role=\"alert\"><strong>Admin access.</strong> This app could read every \
organization's data, change plans, re-run builds and resolve customers' emails and feedback, as you. Every \
call is recorded.</p>\n <p>After you allow it, you're sent to <strong><code>{}</code></strong>. Allow it \
only if you started this connection, from an app you run on that address.</p>\n",
escape(&host)
)
}

/// At boot: with routing by hostname, the issuer must be the MCP host and the consent page the app host's
/// `/oauth/authorize`, or MCP clients can't connect (their metadata would send them to a host that doesn't serve
/// those paths). Production fails to boot when they differ; elsewhere a mismatch is only logged.
Expand Down
63 changes: 48 additions & 15 deletions app/src/auth/staff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,31 +103,56 @@ pub async fn resolve(
Valid(p): Valid<ResolveInput>,
) -> laravel::Result<Json<Value>> {
staff_only(&user)?;
let done: Option<i64> = match p.action.as_str() {
"retry" => {
let action = match p.action.as_str() {
"retry" => Resolve::Retry,
"dismiss" => Resolve::Dismiss,
_ => return Err(laravel::abort_with(422, "action is retry or dismiss")),
};
let done = resolve_failed(id, action).await?;
if !done {
return Err(laravel::abort(404));
}
tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email");
Ok(Json(json!({ "id": id })))
}

/// What staff do with a failed email: send it again from scratch, or dismiss it as handled.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Resolve {
Retry,
Dismiss,
}

/// Retry (back to pending, its attempts reset, and the delivery job queued) or dismiss a failed email nobody has
/// dismissed yet. Either way it stops counting in `/status`'s `emails_failed_unresolved`. `false` when there's no
/// such email.
///
/// # Errors
/// On a database or queue error.
pub async fn resolve_failed(id: i64, action: Resolve) -> laravel::Result<bool> {
let done: Option<i64> = match action {
Resolve::Retry => {
db::query!(
"UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \
WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id"
)
.scalar()
.await?
}
"dismiss" => {
Resolve::Dismiss => {
db::query!(
"UPDATE emails SET dismissed_at = now(), updated_at = now() \
WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id"
)
.scalar()
.await?
}
_ => return Err(laravel::abort_with(422, "action is retry or dismiss")),
};
done.ok_or_else(|| laravel::abort(404))?;
tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email");
if p.action == "retry" {
if done.is_some() && action == Resolve::Retry {
DeliverEmails.dispatch().await?;
}
Ok(Json(json!({ "id": id })))
Ok(done.is_some())
}

#[laravel::query]
Expand All @@ -143,7 +168,18 @@ pub async fn feedback(
Query(q): Query<FeedbackQuery>,
) -> laravel::Result<Json<Value>> {
staff_only(&user)?;
let before = q.before;
let items = feedback_page(q.before, 100, false).await?;
Ok(Json(json!({ "feedback": items })))
}

/// Customers' feedback for staff, newest first: at most `limit` (1 to 100) older than `before`, only the unhandled
/// ones when asked, each with who sent it and whether someone handled it. The staff page and the admin MCP server's
/// `list_feedback` and `get_feedback` read it.
///
/// # Errors
/// On a database error.
pub async fn feedback_page(before: Option<i64>, limit: i64, unhandled: bool) -> laravel::Result<Vec<Value>> {
let limit = limit.clamp(1, 100);
let rows = db::query!(
"SELECT json_build_object('id', f.id, 'pid', f.pid::text, 'title', f.title, 'kind', f.kind, \
'description', f.description, 'impact', f.impact, 'task', f.task, 'tool', f.tool, 'error', f.error, \
Expand All @@ -157,13 +193,10 @@ pub async fn feedback(
'handled_by', h.email, 'handled_note', f.handled_note)::text AS j \
FROM feedback f LEFT JOIN users u ON u.id = f.user_id LEFT JOIN users h ON h.id = f.handled_by \
LEFT JOIN projects p ON p.id = f.project_id LEFT JOIN organizations o ON o.id = p.organization_id \
WHERE ({before}::bigint IS NULL OR f.id < {before}) ORDER BY f.id DESC LIMIT 100"
WHERE ({before}::bigint IS NULL OR f.id < {before}) AND (NOT {unhandled} OR f.handled_at IS NULL) \
ORDER BY f.id DESC LIMIT {limit}"
)
.select()
.await?;
let items = rows
.iter()
.map(|r| Ok(serde_json::from_str::<Value>(&r.try_get::<String>("j")?)?))
.collect::<laravel::Result<Vec<_>>>()?;
Ok(Json(json!({ "feedback": items })))
rows.iter().map(|r| Ok(serde_json::from_str::<Value>(&r.try_get::<String>("j")?)?)).collect()
}
6 changes: 6 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ pub fn configure() -> ApplicationBuilder {
// The development sign-in (refused in production and unless VISUALCI_DEV_LOGIN is on) is posted by CI's screenshot
// scripts, which send no Sec-Fetch-Site and hold no CSRF token yet
middleware.replace(laravel::http::middleware::PreventRequestForgery::new().except(["auth/dev-login"]));
// The OAuth consent step grants `admin` to staff alone, on the admin endpoint alone (needs the session)
middleware.web(|web| {
web.append(auth::oauth::consent_scopes);
});
// Outermost, so every response gets the security headers, the host check's 404s included
middleware.prepend(http::security::security_headers);
})
Expand All @@ -92,6 +96,8 @@ pub fn configure() -> ApplicationBuilder {
// MCP clients: a person's OAuth token (the guard joins with the OAuth server, #57) or a personal
// or project token.
route.any("/mcp", mcp::handle);
// Staff's ops agents: an OAuth token with the `admin` scope, for a staff user (mcp::admin)
route.any("/mcp/admin", mcp::admin::handle);
// GitHub sends deliveries of up to 25 MB
route
.post("/webhooks/github", forge::webhooks::github)
Expand Down
Loading
Loading