diff --git a/.gitignore b/.gitignore index ab4a962c..9b9cb6ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -/target +target/ **/node_modules /tmp .env diff --git a/app/Cargo.lock b/app/Cargo.lock index 6ed23918..481bb6d7 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -2822,9 +2822,9 @@ dependencies = [ [[package]] name = "oauth-provider-laravel" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef48df94542f862f18f6cb65afc7e208d6f7b198e7488a45a606934bbf69b27a" +checksum = "dd8b9a71814d8f022adafed725f98a7f766e81ee555137d350b5254a9a68e353" dependencies = [ "async-trait", "axum", @@ -4537,6 +4537,7 @@ dependencies = [ "hex", "image", "laravel-rust", + "oauth-provider", "oauth-provider-laravel", "reqwest 0.12.28", "rusty-s3", @@ -4545,6 +4546,7 @@ dependencies = [ "sha2 0.10.9", "snapshot-diff", "tokio", + "tracing", "visualci-core", ] diff --git a/app/Cargo.toml b/app/Cargo.toml index 67d58e3d..7c8baf16 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -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" @@ -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] diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 62c53f28..614ff811 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,6 +8,7 @@ //! //! Nobody found: `401`. +pub mod oauth; pub mod sign_in; use axum::extract::FromRequestParts; @@ -239,6 +240,7 @@ pub async fn whoami(principal: Principal) -> laravel::Result/mcp`; the consent page is on the app host, where the session is (`OAUTH_AUTHORIZATION_ENDPOINT` = +//! `/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::()`. +pub type Tokens = OAuthTokens; + +/// The service provider `configure()` registers. +#[must_use] +pub fn provider() -> OAuthServiceProvider { + OAuthServiceProvider::::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| 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 = 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(()) +} diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 8086b092..6df25cc8 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -63,6 +63,19 @@ fn safe_return(to: &str) -> Option { .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 = "Sign in ยท VisualCI

Sign in with GitHub

\ +

Sign in with GitLab

"; + laravel::http::Response::new(laravel::view::Html::raw(page)) +} + /// `GET /auth/{forge}`: off to the forge. pub async fn start( Params(forge): Params, @@ -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::("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 diff --git a/app/src/lib.rs b/app/src/lib.rs index 41e5beb6..90699f87 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -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::(); }) @@ -25,6 +28,15 @@ pub fn configure() -> ApplicationBuilder { url: config.section::().url.clone(), }); }) + .booted(async |app| { + let config = app.config(); + auth::oauth::check( + config.section::(), + config.section::(), + config.app.env.is_production(), + )?; + Ok(()) + }) .with_middleware(|middleware, _| { middleware.prepend(http::hosts::route_by_host); }) diff --git a/app/src/models/user.rs b/app/src/models/user.rs index d3e3a7bd..5449a087 100644 --- a/app/src/models/user.rs +++ b/app/src/models/user.rs @@ -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> { @@ -37,7 +39,7 @@ 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; @@ -45,8 +47,8 @@ pub struct Users; impl laravel::auth::UserProvider for Users { type User = User; - async fn find(&self, id: &i64) -> laravel::Result> { - User::find(*id).await + async fn find(&self, pid: &Uuid) -> laravel::Result> { + User::first_where(User::pid.eq(*pid)).await } async fn find_for_login(&self, _login: &str) -> laravel::Result> { diff --git a/app/tests/oauth.rs b/app/tests/oauth.rs new file mode 100644 index 00000000..06bae4ee --- /dev/null +++ b/app/tests/oauth.rs @@ -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"); +} diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index 45416b06..1886db3b 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -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"); +}