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
1 change: 1 addition & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ pub fn routes(route: &mut laravel::prelude::Router) {
invitations::routes(route);
orgs::routes(route);
me::routes(route);
oauth::routes(route);
device::routes(route);
staff::routes(route);
route.get("/auth/{forge}", sign_in::start);
Expand Down
58 changes: 54 additions & 4 deletions app/src/auth/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@
//! 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`.
//!
//! 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 oauth_provider_laravel::{OAuthServiceProvider, OAuthTokens};

use oauth_provider_laravel::OAuthConfig;
use laravel::auth::Authenticated;
use laravel::container::Inject;
use laravel::prelude::*;
use oauth_provider_laravel::{OAuth, OAuthConfig, OAuthServiceProvider, OAuthTokens};
use serde_json::{Value, json};

use crate::http::hosts::HostUrls;
use crate::models::Users;
use crate::models::{User, Users};

/// The guard MCP routes put behind `RequireToken`: `Authenticate::via::<Tokens>()`.
pub type Tokens = OAuthTokens<Users>;
Expand Down Expand Up @@ -69,3 +74,48 @@ pub fn check(oauth: &OAuthConfig, hosts: &HostUrls, production: bool) -> laravel
tracing::warn!("{message}");
Ok(())
}

pub fn routes(route: &mut Router) {
route.get("/api/ui/me/connections", connections);
route.delete("/api/ui/me/connections", disconnect);
}

/// `GET /api/ui/me/connections`: the apps (MCP clients) connected to the signed-in person's account, newest first:
/// each one's `client_id`, name, whether it's a client VisualCI knows (`verified`), when it connected and when it last
/// used a token. Only the person's own.
pub async fn connections(
Authenticated(user): Authenticated<User>,
oauth: Inject<OAuth>,
) -> laravel::Result<Json<Value>> {
let list = oauth.connections(&oauth_provider_laravel::subject(&user)).await?;
let apps: Vec<Value> = list
.into_iter()
.map(|c| {
json!({
"client_id": c.client_id,
"name": c.name,
"verified": oauth.config().known(&c.client_id).is_some(),
"connected_at": c.connected_at.to_rfc3339(),
"last_used_at": c.last_used_at.map(|t| t.to_rfc3339()),
})
})
.collect();
Ok(Json(json!({ "connections": apps })))
}

#[laravel::query]
pub struct DisconnectQuery {
client_id: String,
}

/// `DELETE /api/ui/me/connections?client_id=`: ends every connection of one app to the signed-in person's account.
/// Its access and refresh tokens stop working at once; `revoked` counts them. Another person's connections to the same
/// app are untouched.
pub async fn disconnect(
Authenticated(user): Authenticated<User>,
oauth: Inject<OAuth>,
Query(q): Query<DisconnectQuery>,
) -> laravel::Result<Json<Value>> {
let revoked = oauth.disconnect(&oauth_provider_laravel::subject(&user), &q.client_id).await?;
Ok(Json(json!({ "revoked": revoked })))
}
98 changes: 97 additions & 1 deletion app/tests/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

use app::auth::oauth::check;
use app::http::hosts::HostUrls;
use app::models::User;
use laravel::model::create;
use laravel::testing::prelude::*;
use oauth_provider_laravel::OAuthConfig;
use oauth_provider_laravel::{OAuth, OAuthConfig};

fn hosts() -> Application {
app::testing::configure()
Expand Down Expand Up @@ -54,6 +56,100 @@ async fn mcp_clients_find_each_endpoint_on_its_own_host(app: Application) {
app.get(&authorize).header("host", "mcp.visualci.test").await.assert_status(404);
}

const REDIRECT: &str = "http://127.0.0.1:33418/callback";
const RESOURCE: &str = "https://mcp.visualci.test/mcp";
const VERIFIER: &str = "visualci-test-verifier-0123456789-abcdefghijklmnopqrstuvwxyz";
const CHALLENGE: &str = "v8yzKoHOTGkBq15_ikEfQ4vLdOS_IW3B3JIsz5GmKUc";

async fn person(name: &str, email: &str) -> laravel::Result<User> {
create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await
}

/// `user` connects the app `client_id` as an MCP client would (consent, then the code for tokens); returns its
/// access token.
async fn connect(oauth: &OAuth, client_id: &str, user: &User) -> String {
let provider = oauth.provider();
let params = [
("response_type", "code"),
("client_id", client_id),
("redirect_uri", REDIRECT),
("code_challenge", CHALLENGE),
("code_challenge_method", "S256"),
("scope", "mcp"),
("resource", RESOURCE),
("state", "s"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let request = provider.authorization(&params).await.expect("a valid authorization request");
let back = provider
.approve(&request, &oauth_provider_laravel::subject(user), &["mcp".to_string()])
.await
.expect("approved");
let code = url::Url::parse(&back).unwrap().query_pairs().find(|(k, _)| k == "code").unwrap().1.into_owned();
let body = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs([
("grant_type", "authorization_code"),
("code", code.as_str()),
("code_verifier", VERIFIER),
("client_id", client_id),
("redirect_uri", REDIRECT),
("resource", RESOURCE),
])
.finish();
let issued = provider
.token(body.as_bytes(), Some("application/x-www-form-urlencoded"), None)
.await
.expect("tokens for the code");
issued.access_token
}

#[laravel::test(app = hosts)]
async fn the_account_page_lists_and_disconnects_ones_own_apps(app: Application) -> laravel::Result<()> {
let oauth = laravel::container::resolve::<OAuth>().await?;
let registered = app
.post("/oauth/register")
.header("host", "mcp.visualci.test")
.json(
json!({ "client_name": "Test Client", "redirect_uris": [REDIRECT], "token_endpoint_auth_method": "none" }),
)
.await;
registered.assert_status(201);
let client_id = registered.json()["client_id"].as_str().unwrap().to_string();
let (ada, bea) = (person("Ada", "ada@example.com").await?, person("Bea", "bea@example.com").await?);
let ada_token = connect(&oauth, &client_id, &ada).await;
let bea_token = connect(&oauth, &client_id, &bea).await;
let host = "app.visualci.test";

let listed = app.get("/api/ui/me/connections").header("host", host).acting_as(&ada).await;
listed.assert_ok().assert_json_path("connections.0.client_id", client_id.as_str());
listed.assert_json_path("connections.0.name", "Test Client").assert_json_path("connections.0.verified", false);
assert_eq!(listed.json()["connections"].as_array().map(Vec::len), Some(1), "{}", listed.json());
// Signed out: nothing
app.get("/api/ui/me/connections")
.header("host", host)
.header("accept", "application/json")
.await
.assert_status(401);

let gone = app
.delete(format!("/api/ui/me/connections?client_id={client_id}"))
.header("host", host)
.header("sec-fetch-site", "same-origin")
.acting_as(&ada)
.await;
gone.assert_ok().assert_json_path("revoked", 1);
let provider = oauth.provider();
assert!(provider.verify(&ada_token, RESOURCE).await.unwrap().is_err(), "Ada's token stops working");
assert!(provider.verify(&bea_token, RESOURCE).await.unwrap().is_ok(), "Bea's connection is hers");
let listed = app.get("/api/ui/me/connections").header("host", host).acting_as(&ada).await;
assert_eq!(listed.assert_ok().json()["connections"].as_array().map(Vec::len), Some(0));
let bea_listed = app.get("/api/ui/me/connections").header("host", host).acting_as(&bea).await;
assert_eq!(bea_listed.json()["connections"].as_array().map(Vec::len), Some(1));
Ok(())
}

fn config(issuer: &str, endpoint: &str) -> OAuthConfig {
OAuthConfig {
issuer: Some(issuer.into()),
Expand Down
Loading