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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/target
target/
**/node_modules
/tmp
.env
Expand Down
6 changes: 4 additions & 2 deletions app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja
# The same axum Laravel Rust runs on, for extractors (auth::Principal)
axum = "0.8"
hex = "0.4"
oauth-provider-laravel = { version = "0.1", features = ["postgres"] }
oauth-provider = "0.1.3"
oauth-provider-laravel = { version = "=0.1.1", features = ["postgres"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
Expand All @@ -38,6 +39,7 @@ rusty-s3 = "0.12"
# VisualCI's own crates, shared with the CLI.
visualci-core = { path = "../crates/visualci-core" }
snapshot-diff = { path = "../crates/snapshot-diff" }
tracing = "0.1"

[dev-dependencies]

Expand Down
2 changes: 2 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//!
//! Nobody found: `401`.

pub mod oauth;
pub mod sign_in;

use axum::extract::FromRequestParts;
Expand Down Expand Up @@ -239,6 +240,7 @@ pub async fn whoami(principal: Principal) -> laravel::Result<axum::Json<serde_js

/// The sign-in routes, on the `web` group (they need the session).
pub fn routes(route: &mut laravel::prelude::Router) {
route.get("/login", sign_in::login_page);
route.get("/auth/{forge}", sign_in::start);
route.post("/auth/{forge}/link", sign_in::link);
route.get("/auth/{forge}/callback", sign_in::callback);
Expand Down
71 changes: 71 additions & 0 deletions app/src/auth/oauth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//! VisualCI's OAuth server for MCP clients (sc-8900, the auth side), on oauth-provider-laravel: the endpoints MCP
//! clients discover and call, the consent page (behind sign-in: `GET /login` sends a signed-out person to GitHub or
//! GitLab and back), and the `RequireToken` middleware and `OAuthTokens` guard the MCP routes use (`Tokens`).
//!
//! Configured as today's server is: the service is "VisualCI", and what it issues is prefixed `vca_` (access tokens),
//! `vcr_` (refresh) and `vcs_` (client secrets), distinct from personal (`vcu_`) and project (`vci_`) tokens, so secret
//! scanners can tell them apart. With routing by hostname, the issuer is the MCP host (`OAUTH_ISSUER` =
//! `VISUALCI_MCP_URL`), which serves the metadata, registration and token endpoints, and tokens are for
//! `<mcp url>/mcp`; the consent page is on the app host, where the session is (`OAUTH_AUTHORIZATION_ENDPOINT` =
//! `<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`.

use oauth_provider_laravel::{OAuthServiceProvider, OAuthTokens};

use oauth_provider_laravel::OAuthConfig;

use crate::http::hosts::HostUrls;
use crate::models::Users;

/// The guard MCP routes put behind `RequireToken`: `Authenticate::via::<Tokens>()`.
pub type Tokens = OAuthTokens<Users>;

/// The service provider `configure()` registers.
#[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(),
})
})
}

/// 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.
///
/// # Errors
/// In production, when the OAuth URLs don't match the hosts.
pub fn check(oauth: &OAuthConfig, hosts: &HostUrls, production: bool) -> laravel::Result<()> {
let trim =
|s: &Option<String>| s.as_deref().map(|u| u.trim().trim_end_matches('/').to_string()).filter(|u| !u.is_empty());
let (Some(app), Some(mcp)) = (trim(&hosts.app), trim(&hosts.mcp)) else { return Ok(()) };
let mut wrong = Vec::new();
if trim(&oauth.issuer).as_deref() != Some(mcp.as_str()) {
wrong.push(format!("OAUTH_ISSUER must be {mcp}"));
}
let consent = format!("{app}/oauth/authorize");
if trim(&oauth.authorization_endpoint).as_deref() != Some(consent.as_str()) {
wrong.push(format!("OAUTH_AUTHORIZATION_ENDPOINT must be {consent}"));
}
let resource = format!("{mcp}/mcp");
let resources: Vec<String> = oauth.resources.iter().map(|r| r.trim().trim_end_matches('/').to_string()).collect();
if !resources.is_empty() && !resources.contains(&resource) {
wrong.push(format!("OAUTH_RESOURCES must include {resource}"));
}
if wrong.is_empty() {
return Ok(());
}
let message = format!("MCP clients can't connect: {}", wrong.join("; "));
if production {
return Err(laravel::Error::msg(message));
}
tracing::warn!("{message}");
Ok(())
}
23 changes: 22 additions & 1 deletion app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ fn safe_return(to: &str) -> Option<String> {
.then(|| to.to_string())
}

/// `GET /login`: where a page that needs a signed-in person (an MCP client's consent page) sends someone who isn't,
/// and where they come back from afterwards (sign-in returns to the page they were sent from). One line per forge.
#[laravel::auth::page(login)]
pub async fn login_page() -> laravel::http::Response {
let page = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\"><title>Sign in · VisualCI</title><style>body{font:16px/1.5 \
system-ui,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;padding:16px;color:#1a1a1a;\
background:#fff}@media (prefers-color-scheme:dark){body{color:#eee;background:#111}a{color:#9cf}}\
p{margin:0 0 8px}</style></head><body><main><p><a href=\"/auth/github\">Sign in with GitHub</a></p>\
<p><a href=\"/auth/gitlab\">Sign in with GitLab</a></p></main></body></html>";
laravel::http::Response::new(laravel::view::Html::raw(page))
}

/// `GET /auth/{forge}`: off to the forge.
pub async fn start(
Params(forge): Params<String>,
Expand Down Expand Up @@ -137,7 +150,15 @@ pub async fn callback(
.dispatch()
.await?;
auth.login(&user).await?;
Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/"))))
// Back where they started: the return address they came with, else the page that sent them to sign in (an MCP
// client's consent page), else the app
let back = match return_to {
Some(to) => Redirect::to(to),
// Laravel's `Authenticate` keeps the page it sent them from under this key (`Redirect::intended`, which
// needs a route for its fallback)
None => Redirect::to(session.pull::<String>("url.intended").unwrap_or_else(|| "/".to_string())),
};
Ok(laravel::http::Response::new(back))
}

/// `GET /auth/session`: whether this browser is signed in, for visualci.com's static pages ("Open app" instead of
Expand Down
12 changes: 12 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ use laravel::foundation::ApplicationBuilder;
pub fn configure() -> ApplicationBuilder {
Application::configure()
.with_migrations(laravel::db::migrations!("database/migrations"))
.with_providers(|providers| {
providers.add(auth::oauth::provider());
})
.with_auth(|auth, _| {
auth.session::<models::Users>();
})
Expand All @@ -25,6 +28,15 @@ pub fn configure() -> ApplicationBuilder {
url: config.section::<forge::gitlab::GitlabConfig>().url.clone(),
});
})
.booted(async |app| {
let config = app.config();
auth::oauth::check(
config.section::<oauth_provider_laravel::OAuthConfig>(),
config.section::<http::hosts::HostUrls>(),
config.app.env.is_production(),
)?;
Ok(())
})
.with_middleware(|middleware, _| {
middleware.prepend(http::hosts::route_by_host);
})
Expand Down
14 changes: 8 additions & 6 deletions app/src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ pub struct User {
pub updated_at: Timestamp,
}

/// People are known outside the database by their pid (a UUID), never by their row ID: the session holds it, and so
/// does every OAuth token an MCP client gets (its subject), as today's server does.
impl Authenticatable for User {
type Id = i64;
type Id = Uuid;

fn auth_id(&self) -> i64 {
self.id
fn auth_id(&self) -> Uuid {
self.pid
}

fn auth_password(&self) -> Option<&PasswordHash> {
Expand All @@ -37,16 +39,16 @@ impl Authenticatable for User {
}
}

/// The session guard's users: found by ID. There's no password login, so nothing is ever found by a login name, and
/// The session guard's users: found by pid. There's no password login, so nothing is ever found by a login name, and
/// passwords and "remember me" tokens are never stored.
#[laravel::container::singleton]
pub struct Users;

impl laravel::auth::UserProvider for Users {
type User = User;

async fn find(&self, id: &i64) -> laravel::Result<Option<User>> {
User::find(*id).await
async fn find(&self, pid: &Uuid) -> laravel::Result<Option<User>> {
User::first_where(User::pid.eq(*pid)).await
}

async fn find_for_login(&self, _login: &str) -> laravel::Result<Option<User>> {
Expand Down
88 changes: 88 additions & 0 deletions app/tests/oauth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
//! MCP clients connect with every host configured: the MCP host is the issuer (metadata, registration, tokens) and
//! the consent page is on the app host, where the session is. A production boot stops when the OAuth URLs don't match
//! the hosts.

use app::auth::oauth::check;
use app::http::hosts::HostUrls;
use laravel::testing::prelude::*;
use oauth_provider_laravel::OAuthConfig;

fn hosts() -> Application {
app::testing::configure()
.with_envs([
("VISUALCI_SITE_URL", "https://visualci.test"),
("VISUALCI_APP_URL", "https://app.visualci.test"),
("VISUALCI_API_URL", "https://api.visualci.test"),
("VISUALCI_MCP_URL", "https://mcp.visualci.test"),
("OAUTH_ISSUER", "https://mcp.visualci.test"),
("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"),
])
.create()
}

#[laravel::test(app = hosts)]
async fn mcp_clients_find_each_endpoint_on_its_own_host(app: Application) {
let metadata = app.get("/.well-known/oauth-authorization-server").header("host", "mcp.visualci.test").await;
metadata
.assert_ok()
.assert_json_path("issuer", "https://mcp.visualci.test")
.assert_json_path("authorization_endpoint", "https://app.visualci.test/oauth/authorize")
.assert_json_path("token_endpoint", "https://mcp.visualci.test/oauth/token");
app.get("/.well-known/oauth-protected-resource/mcp")
.header("host", "mcp.visualci.test")
.await
.assert_ok()
.assert_json_path("resource", "https://mcp.visualci.test/mcp");
let registered = app
.post("/oauth/register")
.header("host", "mcp.visualci.test")
.json(json!({
"client_name": "Test Client", "redirect_uris": ["http://127.0.0.1:33418/callback"],
"token_endpoint_auth_method": "none",
}))
.await;
registered.assert_status(201);
let client_id = registered.json()["client_id"].as_str().unwrap().to_string();
let authorize = format!(
"/oauth/authorize?response_type=code&client_id={client_id}&redirect_uri=http%3A%2F%2F127.0.0.1%3A33418%2Fcallback\
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&scope=mcp\
&resource=https%3A%2F%2Fmcp.visualci.test%2Fmcp&state=s"
);
// On the app host, a signed-out person is sent to sign in first; the MCP host doesn't serve the page at all.
let consent = app.get(&authorize).header("host", "app.visualci.test").await;
assert!(consent.status().is_redirection(), "sign in first: {}", consent.status());
app.get(&authorize).header("host", "mcp.visualci.test").await.assert_status(404);
}

fn config(issuer: &str, endpoint: &str) -> OAuthConfig {
OAuthConfig {
issuer: Some(issuer.into()),
authorization_endpoint: Some(endpoint.into()),
resources: Vec::new(),
scopes: Vec::new(),
service_name: None,
token_prefix: None,
dynamic_registration: true,
metadata_documents: true,
connection: None,
allow_http: false,
}
}

#[test]
fn production_stops_when_the_oauth_urls_miss_the_hosts() {
let hosts = HostUrls {
site: Some("https://visualci.test".into()),
app: Some("https://app.visualci.test".into()),
api: Some("https://api.visualci.test".into()),
mcp: Some("https://mcp.visualci.test".into()),
session_cookie: "visualci_session".into(),
};
let right = config("https://mcp.visualci.test", "https://app.visualci.test/oauth/authorize");
assert!(check(&right, &hosts, true).is_ok());
let on_app = config("https://app.visualci.test", "https://app.visualci.test/oauth/authorize");
assert!(check(&on_app, &hosts, true).is_err());
let consent_on_mcp = config("https://mcp.visualci.test", "https://mcp.visualci.test/oauth/authorize");
assert!(check(&consent_on_mcp, &hosts, true).is_err());
assert!(check(&consent_on_mcp, &hosts, false).is_ok(), "only logged outside production");
}
11 changes: 11 additions & 0 deletions app/tests/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,14 @@ async fn a_self_managed_gitlabs_addresses_match_no_account(app: Application) ->
assert_eq!(site.as_deref(), Some("https://gitlab.example.com"));
Ok(())
}

#[laravel::test]
async fn an_mcp_client_finds_the_oauth_server_and_its_consent_page_asks_for_sign_in(app: Application) {
app.get("/.well-known/oauth-authorization-server")
.await
.assert_ok()
.assert_json_path("authorization_endpoint", "http://localhost/oauth/authorize");
let page = app.get("/oauth/authorize?client_id=x&response_type=code").header("accept", "text/html").await;
page.assert_redirect_to("/login");
app.get("/login").with_cookies_from(&page).await.assert_ok().assert_see("Sign in with GitHub");
}
Loading