Skip to content

Commit dab7601

Browse files
committed
app/: the account page's connected apps (sc-8900): GET /api/ui/me/connections lists the MCP clients connected to the signed-in person's account; DELETE /api/ui/me/connections?client_id= revokes every token that app holds for them, and no one else's
1 parent 555ff9a commit dab7601

3 files changed

Lines changed: 152 additions & 5 deletions

File tree

‎app/src/auth/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,7 @@ pub fn routes(route: &mut laravel::prelude::Router) {
271271
invitations::routes(route);
272272
orgs::routes(route);
273273
me::routes(route);
274+
oauth::routes(route);
274275
device::routes(route);
275276
staff::routes(route);
276277
route.get("/auth/{forge}", sign_in::start);

‎app/src/auth/oauth.rs‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,18 @@
1313
//! Only the `mcp` scope for now. Today's `admin` scope, for the staff-only `/mcp/admin` endpoint, must be granted to
1414
//! staff alone, and the package's consent step grants what a client asks for: it comes with a consent hook that checks
1515
//! `users.staff`.
16+
//!
17+
//! The account page lists the apps connected to the person's account (`GET /api/ui/me/connections`) and disconnects
18+
//! one (`DELETE /api/ui/me/connections?client_id=`), which revokes every token that app holds for them.
1619
17-
use oauth_provider_laravel::{OAuthServiceProvider, OAuthTokens};
18-
19-
use oauth_provider_laravel::OAuthConfig;
20+
use laravel::auth::Authenticated;
21+
use laravel::container::Inject;
22+
use laravel::prelude::*;
23+
use oauth_provider_laravel::{OAuth, OAuthConfig, OAuthServiceProvider, OAuthTokens};
24+
use serde_json::{Value, json};
2025

2126
use crate::http::hosts::HostUrls;
22-
use crate::models::Users;
27+
use crate::models::{User, Users};
2328

2429
/// The guard MCP routes put behind `RequireToken`: `Authenticate::via::<Tokens>()`.
2530
pub type Tokens = OAuthTokens<Users>;
@@ -69,3 +74,48 @@ pub fn check(oauth: &OAuthConfig, hosts: &HostUrls, production: bool) -> laravel
6974
tracing::warn!("{message}");
7075
Ok(())
7176
}
77+
78+
pub fn routes(route: &mut Router) {
79+
route.get("/api/ui/me/connections", connections);
80+
route.delete("/api/ui/me/connections", disconnect);
81+
}
82+
83+
/// `GET /api/ui/me/connections`: the apps (MCP clients) connected to the signed-in person's account, newest first:
84+
/// each one's `client_id`, name, whether it's a client VisualCI knows (`verified`), when it connected and when it last
85+
/// used a token. Only the person's own.
86+
pub async fn connections(
87+
Authenticated(user): Authenticated<User>,
88+
oauth: Inject<OAuth>,
89+
) -> laravel::Result<Json<Value>> {
90+
let list = oauth.connections(&oauth_provider_laravel::subject(&user)).await?;
91+
let apps: Vec<Value> = list
92+
.into_iter()
93+
.map(|c| {
94+
json!({
95+
"client_id": c.client_id,
96+
"name": c.name,
97+
"verified": oauth.config().known(&c.client_id).is_some(),
98+
"connected_at": c.connected_at.to_rfc3339(),
99+
"last_used_at": c.last_used_at.map(|t| t.to_rfc3339()),
100+
})
101+
})
102+
.collect();
103+
Ok(Json(json!({ "connections": apps })))
104+
}
105+
106+
#[laravel::query]
107+
pub struct DisconnectQuery {
108+
client_id: String,
109+
}
110+
111+
/// `DELETE /api/ui/me/connections?client_id=`: ends every connection of one app to the signed-in person's account.
112+
/// Its access and refresh tokens stop working at once; `revoked` counts them. Another person's connections to the same
113+
/// app are untouched.
114+
pub async fn disconnect(
115+
Authenticated(user): Authenticated<User>,
116+
oauth: Inject<OAuth>,
117+
Query(q): Query<DisconnectQuery>,
118+
) -> laravel::Result<Json<Value>> {
119+
let revoked = oauth.disconnect(&oauth_provider_laravel::subject(&user), &q.client_id).await?;
120+
Ok(Json(json!({ "revoked": revoked })))
121+
}

‎app/tests/oauth.rs‎

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
55
use app::auth::oauth::check;
66
use app::http::hosts::HostUrls;
7+
use app::models::User;
8+
use laravel::model::create;
79
use laravel::testing::prelude::*;
8-
use oauth_provider_laravel::OAuthConfig;
10+
use oauth_provider_laravel::{OAuth, OAuthConfig};
911

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

59+
const REDIRECT: &str = "http://127.0.0.1:33418/callback";
60+
const RESOURCE: &str = "https://mcp.visualci.test/mcp";
61+
const VERIFIER: &str = "visualci-test-verifier-0123456789-abcdefghijklmnopqrstuvwxyz";
62+
const CHALLENGE: &str = "v8yzKoHOTGkBq15_ikEfQ4vLdOS_IW3B3JIsz5GmKUc";
63+
64+
async fn person(name: &str, email: &str) -> laravel::Result<User> {
65+
create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await
66+
}
67+
68+
/// `user` connects the app `client_id` as an MCP client would (consent, then the code for tokens); returns its
69+
/// access token.
70+
async fn connect(oauth: &OAuth, client_id: &str, user: &User) -> String {
71+
let provider = oauth.provider();
72+
let params = [
73+
("response_type", "code"),
74+
("client_id", client_id),
75+
("redirect_uri", REDIRECT),
76+
("code_challenge", CHALLENGE),
77+
("code_challenge_method", "S256"),
78+
("scope", "mcp"),
79+
("resource", RESOURCE),
80+
("state", "s"),
81+
]
82+
.into_iter()
83+
.map(|(k, v)| (k.to_string(), v.to_string()))
84+
.collect();
85+
let request = provider.authorization(&params).await.expect("a valid authorization request");
86+
let back = provider
87+
.approve(&request, &oauth_provider_laravel::subject(user), &["mcp".to_string()])
88+
.await
89+
.expect("approved");
90+
let code = url::Url::parse(&back).unwrap().query_pairs().find(|(k, _)| k == "code").unwrap().1.into_owned();
91+
let body = url::form_urlencoded::Serializer::new(String::new())
92+
.extend_pairs([
93+
("grant_type", "authorization_code"),
94+
("code", code.as_str()),
95+
("code_verifier", VERIFIER),
96+
("client_id", client_id),
97+
("redirect_uri", REDIRECT),
98+
("resource", RESOURCE),
99+
])
100+
.finish();
101+
let issued = provider
102+
.token(body.as_bytes(), Some("application/x-www-form-urlencoded"), None)
103+
.await
104+
.expect("tokens for the code");
105+
issued.access_token
106+
}
107+
108+
#[laravel::test(app = hosts)]
109+
async fn the_account_page_lists_and_disconnects_ones_own_apps(app: Application) -> laravel::Result<()> {
110+
let oauth = laravel::container::resolve::<OAuth>().await?;
111+
let registered = app
112+
.post("/oauth/register")
113+
.header("host", "mcp.visualci.test")
114+
.json(
115+
json!({ "client_name": "Test Client", "redirect_uris": [REDIRECT], "token_endpoint_auth_method": "none" }),
116+
)
117+
.await;
118+
registered.assert_status(201);
119+
let client_id = registered.json()["client_id"].as_str().unwrap().to_string();
120+
let (ada, bea) = (person("Ada", "ada@example.com").await?, person("Bea", "bea@example.com").await?);
121+
let ada_token = connect(&oauth, &client_id, &ada).await;
122+
let bea_token = connect(&oauth, &client_id, &bea).await;
123+
let host = "app.visualci.test";
124+
125+
let listed = app.get("/api/ui/me/connections").header("host", host).acting_as(&ada).await;
126+
listed.assert_ok().assert_json_path("connections.0.client_id", client_id.as_str());
127+
listed.assert_json_path("connections.0.name", "Test Client").assert_json_path("connections.0.verified", false);
128+
assert_eq!(listed.json()["connections"].as_array().map(Vec::len), Some(1), "{}", listed.json());
129+
// Signed out: nothing
130+
app.get("/api/ui/me/connections")
131+
.header("host", host)
132+
.header("accept", "application/json")
133+
.await
134+
.assert_status(401);
135+
136+
let gone = app
137+
.delete(format!("/api/ui/me/connections?client_id={client_id}"))
138+
.header("host", host)
139+
.header("sec-fetch-site", "same-origin")
140+
.acting_as(&ada)
141+
.await;
142+
gone.assert_ok().assert_json_path("revoked", 1);
143+
let provider = oauth.provider();
144+
assert!(provider.verify(&ada_token, RESOURCE).await.unwrap().is_err(), "Ada's token stops working");
145+
assert!(provider.verify(&bea_token, RESOURCE).await.unwrap().is_ok(), "Bea's connection is hers");
146+
let listed = app.get("/api/ui/me/connections").header("host", host).acting_as(&ada).await;
147+
assert_eq!(listed.assert_ok().json()["connections"].as_array().map(Vec::len), Some(0));
148+
let bea_listed = app.get("/api/ui/me/connections").header("host", host).acting_as(&bea).await;
149+
assert_eq!(bea_listed.json()["connections"].as_array().map(Vec::len), Some(1));
150+
Ok(())
151+
}
152+
57153
fn config(issuer: &str, endpoint: &str) -> OAuthConfig {
58154
OAuthConfig {
59155
issuer: Some(issuer.into()),

0 commit comments

Comments
 (0)