diff --git a/app/database/migrations/0001_01_01_000000_create_users_table.rs b/app/database/migrations/0001_01_01_000000_create_users_table.rs index a6bc3567..549723ab 100644 --- a/app/database/migrations/0001_01_01_000000_create_users_table.rs +++ b/app/database/migrations/0001_01_01_000000_create_users_table.rs @@ -1,7 +1,7 @@ use laravel::db::AnyTransaction; -/// People, and their sessions. Everyone signs in through a forge (GitHub or GitLab): `password` stays empty, and the -/// forge accounts are in `identities`. +/// People, and their sessions. Everyone signs in through a forge (GitHub or GitLab), whose accounts are in +/// `identities`: no passwords, no "remember me" tokens. pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("users", |table| { @@ -10,8 +10,6 @@ pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { table.string("name"); table.string("email").unique(); table.timestamp("email_verified_at").nullable(); - table.string("password").default(""); - table.remember_token(); table.text("avatar_url").nullable(); // VisualCI's own team: the admin MCP endpoint and staff pages table.boolean("staff").default(false); diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 7780bf8e..62c53f28 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,6 +8,8 @@ //! //! Nobody found: `401`. +pub mod sign_in; + use axum::extract::FromRequestParts; use axum::http::request::Parts; use laravel::auth::Auth; @@ -234,3 +236,12 @@ pub async fn whoami(principal: Principal) -> laravel::Result` when the sign-in came from an MCP client's authorization. + pub via: String, +} + +/// Someone signed in, with what the forge says they can reach: their memberships follow it. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct SignedIn { + pub user_id: i64, + pub forge: ForgeKind, + pub site: String, + pub repositories: Vec<(Repository, Permission)>, +} + +const RETURN_TO: &str = "auth.return_to"; +const LINKING: &str = "auth.linking"; + +#[laravel::query] +pub struct StartQuery { + return_to: Option, +} + +fn provider(forge: &str) -> laravel::Result { + match ForgeKind::parse(forge) { + Some(ForgeKind::Github) => Ok(Provider::GITHUB), + // GitLab sign-in comes with the GitLab provider (social login's custom providers) + _ => Err(laravel::abort(404)), + } +} + +/// A path on this site to return to, never another site's URL. +fn safe_return(to: &str) -> Option { + (to.starts_with('/') && !to.starts_with("//") && !to.contains('\\')).then(|| to.to_string()) +} + +/// `GET /auth/{forge}`: off to the forge. +pub async fn start( + Params(forge): Params, + Query(q): Query, + session: Session, +) -> laravel::Result { + let provider = provider(&forge)?; + match q.return_to.as_deref().and_then(safe_return) { + Some(to) => session.put(RETURN_TO, to), + None => { + let _: Option = session.pull(RETURN_TO); + } + } + let _: Option = session.pull(LINKING); + social::redirect(provider) +} + +/// `POST /auth/{forge}/link`: link another forge account to the signed-in user. A JSON POST, which a page on another +/// site can't make with the session cookie. Returns where to go. +pub async fn link( + Params(forge): Params, + _user: laravel::auth::Authenticated, + session: Session, +) -> laravel::Result> { + let provider = provider(&forge)?; + session.put(LINKING, true); + let redirect = laravel::http::Response::new(social::redirect(provider)?).into_http(); + let url = redirect.headers().get(axum::http::header::LOCATION).and_then(|v| v.to_str().ok()).unwrap_or_default(); + Ok(Json(serde_json::json!({ "url": url }))) +} + +/// `GET /auth/{forge}/callback`: back from the forge. +pub async fn callback( + Params(forge): Params, + auth: Auth, + sign_ups: laravel::config::Section, + session: Session, +) -> laravel::Result { + let provider = provider(&forge)?; + let return_to: Option = session.pull(RETURN_TO); + let linking: bool = session.pull(LINKING).unwrap_or(false); + let profile = match social::user(provider).await { + Ok(profile) => profile, + Err(social::Error::Denied) => { + return Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/")))); + } + Err(e) => return Err(e.into()), + }; + let sign_in = forge::github::sign_in(&profile).await?; + let current = auth.user().await?; + let link_to = current.as_ref().filter(|_| linking); + let via = return_to.as_deref().and_then(mcp_client).map_or_else(|| "web".to_string(), |c| format!("mcp: {c}")); + + if sign_ups.waitlist && is_new_person(&sign_in.identity, link_to).await? { + record_waitlist(&sign_in.identity, &via).await?; + return Ok(waitlist_page(&sign_in.identity)); + } + let (user, created) = user_for_sign_in(&sign_in.identity, link_to).await?; + if created { + SignedUp { user_id: user.id, via: via.clone() }.dispatch().await?; + } + SignedIn { + user_id: user.id, + forge: sign_in.identity.forge, + site: sign_in.identity.site.clone(), + repositories: sign_in.repositories, + } + .dispatch() + .await?; + auth.login(&user).await?; + Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/")))) +} + +/// `GET /auth/session`: whether this browser is signed in, for visualci.com's static pages ("Open app" instead of +/// "Sign in"). Only what that button needs: no email, no IDs. +pub async fn session(auth: Auth) -> laravel::Result> { + let user = auth.user().await?; + Ok(Json(serde_json::json!({ "signed_in": user.is_some(), "name": user.map(|u| u.name) }))) +} + +/// `POST /auth/logout`. +pub async fn logout(auth: Auth) -> laravel::Result> { + auth.logout().await?; + Ok(Json(serde_json::json!({ "ok": true }))) +} + +/// The MCP client an authorization's return address names (`/oauth/authorize?client_id=…`). +fn mcp_client(return_to: &str) -> Option { + let (path, query) = return_to.split_once('?')?; + (path == "/oauth/authorize") + .then(|| query.split('&').find_map(|kv| kv.strip_prefix("client_id=")).map(str::to_string)) + .flatten() +} + +/// Sign-ups: closed (`VISUALCI_WAITLIST=true`) until VisualCI opens, when someone new goes on the waitlist instead. +#[derive(Clone, laravel::config::Section)] +pub struct SignUps { + #[env("VISUALCI_WAITLIST", default = false)] + pub waitlist: bool, +} + +/// The user who owns this forge identity, if anyone. +async fn identity_owner(id: &Identity) -> laravel::Result> { + let (forge, site, forge_id) = (id.forge.as_str(), id.site.as_str(), id.id.as_str()); + db::query!("SELECT user_id FROM identities WHERE forge = {forge} AND site = {site} AND forge_user_id = {forge_id}") + .scalar::() + .await +} + +async fn user_by_email(id: &Identity) -> laravel::Result> { + for address in id.trusted_emails() { + if let Some(user) = User::query().filter(db::raw!("lower(email) = {address}")).first().await? { + return Ok(Some(user)); + } + } + Ok(None) +} + +/// Whether this sign-in would make a new account. +async fn is_new_person(id: &Identity, link_to: Option<&User>) -> laravel::Result { + Ok(link_to.is_none() && identity_owner(id).await?.is_none() && user_by_email(id).await?.is_none()) +} + +/// The user a sign-in belongs to, and whether it was made just now. An identity that's already someone else's can't +/// be linked to the signed-in user. +async fn user_for_sign_in(id: &Identity, link_to: Option<&User>) -> laravel::Result<(User, bool)> { + if let Some(owner) = identity_owner(id).await? { + if link_to.is_some_and(|u| u.id != owner) { + return Err(laravel::abort_with( + 409, + format!("that {} account is already linked to another VisualCI user", id.forge.label()), + )); + } + let user = User::find(owner).await?.ok_or_else(|| laravel::abort(404))?; + // The same identity identity_owner found: a GitHub and a GitLab account can have the same number for an ID + let (login, forge, site, forge_id) = (id.login.as_str(), id.forge.as_str(), id.site.as_str(), id.id.as_str()); + db::query!( + "UPDATE identities SET login = {login}, updated_at = now() \ + WHERE forge = {forge} AND site = {site} AND forge_user_id = {forge_id}" + ) + .update() + .await?; + return Ok((user, false)); + } + let (user, created) = match link_to.cloned() { + Some(u) => (u, false), + None => match user_by_email(id).await? { + Some(u) => (u, false), + None => (new_user(id).await?, true), + }, + }; + let (user_id, forge, site, forge_id, login) = + (user.id, id.forge.as_str(), id.site.as_str(), id.id.as_str(), id.login.as_str()); + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({user_id}, {forge}, {site}, {forge_id}, {login}, now(), now())" + ) + .insert() + .await?; + Ok((user, created)) +} + +async fn new_user(id: &Identity) -> laravel::Result { + // An account with no trusted address gets a placeholder unique to the forge account + let email = id + .trusted_emails() + .first() + .cloned() + .unwrap_or_else(|| format!("{}+{}@users.noreply.{}.visualci.com", id.id, id.login, id.forge.as_str())); + let verified = (!id.trusted_emails().is_empty()).then(laravel::now); + create!(User { + pid: laravel::str::uuid7(), + name: id.name.clone().unwrap_or_else(|| id.login.clone()), + email: email, + email_verified_at: verified, + avatar_url: id.avatar_url.clone(), + staff: false, + }) + .await +} + +async fn record_waitlist(id: &Identity, source: &str) -> laravel::Result<()> { + let (forge, site, forge_id, login) = (id.forge.as_str(), id.site.as_str(), id.id.as_str(), id.login.as_str()); + let (name, email) = (id.name.clone(), id.trusted_emails().first().cloned()); + db::query!( + "INSERT INTO waitlist (forge, site, forge_user_id, login, name, email, source, created_at, updated_at) \ + VALUES ({forge}, {site}, {forge_id}, {login}, {name}, {email}, {source}, now(), now()) \ + ON CONFLICT (forge, site, forge_user_id) DO UPDATE SET login = EXCLUDED.login, \ + name = COALESCE(EXCLUDED.name, waitlist.name), email = COALESCE(EXCLUDED.email, waitlist.email), \ + updated_at = now()" + ) + .statement() + .await?; + Ok(()) +} + +/// The one page someone on the waitlist sees. +fn waitlist_page(id: &Identity) -> laravel::http::Response { + let escape = |s: &str| s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """); + let line = match id.trusted_emails().first() { + Some(email) => format!("VisualCI opens in about 48 hours. We'll email you at {}.", escape(email)), + None => "VisualCI opens in about 48 hours.".to_string(), + }; + let html = format!( + "VisualCI

{line}

" + ); + laravel::http::Response::new(laravel::view::Html::raw(html)) +} diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs new file mode 100644 index 00000000..b0dcb84f --- /dev/null +++ b/app/src/forge/github.rs @@ -0,0 +1,108 @@ +//! GitHub, as a sign-in sees it (ported from today's server). Laravel's social login does the OAuth dance with the +//! GitHub App's client ID and hands over the person's token; with it, [`sign_in`] reads every verified email address +//! and the repositories the person can reach through the app's installations, with their permission on each. + +use laravel::http::client; +use serde::Deserialize; +use serde_json::Value; + +use super::{ForgeKind, Identity, Permission, Repository, SignIn}; + +const API: &str = "https://api.github.com"; + +/// Everything a GitHub sign-in learns, from the profile Laravel's social login fetched and the person's token. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result { + let token = profile.token.access.as_str(); + // The GitHub username: the profile's nickname, or the `/user` payload's `login` + let login = + profile.nickname.clone().or_else(|| profile.raw["login"].as_str().map(str::to_string)).unwrap_or_default(); + Ok(SignIn { + identity: Identity { + forge: ForgeKind::Github, + id: profile.id.clone(), + login, + name: profile.name.clone(), + avatar_url: profile.avatar.clone(), + verified_emails: verified_emails(token).await?, + site: String::new(), + }, + repositories: repositories(token).await?, + }) +} + +/// The person's verified addresses, primary first, lowercased. +async fn verified_emails(token: &str) -> laravel::Result> { + #[derive(Deserialize)] + struct Email { + email: String, + primary: bool, + verified: bool, + } + let response = client::get(format!("{API}/user/emails")).token(token).accept_json().await?; + if !response.successful() { + // Without the email scope the list isn't readable: the sign-in still works, with no verified address + return Ok(Vec::new()); + } + let mut emails: Vec = response.json().unwrap_or_default(); + emails.retain(|e| e.verified); + emails.sort_by_key(|e| !e.primary); + Ok(emails.into_iter().map(|e| e.email.to_lowercase()).collect()) +} + +/// Every repository the GitHub App can see through its installations that the person has a permission on. +async fn repositories(token: &str) -> laravel::Result> { + let mut out = Vec::new(); + for installation in all_pages(token, "/user/installations", "installations").await? { + let Some(installation) = installation["id"].as_i64() else { continue }; + let path = format!("/user/installations/{installation}/repositories"); + for repo in all_pages(token, &path, "repositories").await? { + let (Some(repository), Some(permission)) = + (repo["full_name"].as_str().and_then(Repository::parse), permission_from_flags(&repo["permissions"])) + else { + continue; + }; + out.push((repository.with_id(repo["id"].as_i64().map(|i| i.to_string())), permission)); + } + } + Ok(out) +} + +/// Every item of a paged list (`key` in each page's object), 100 a page, up to 50 pages. +async fn all_pages(token: &str, path: &str, key: &str) -> laravel::Result> { + let mut items = Vec::new(); + for page in 1..=50 { + let response = client::get(format!("{API}{path}")) + .token(token) + .accept_json() + .query([("per_page", 100), ("page", page)]) + .await?; + if !response.successful() { + return Err(laravel::Error::msg(format!("GitHub {path}: HTTP {}", response.status()))); + } + let body: Value = response.json()?; + let list = body[key].as_array().cloned().unwrap_or_default(); + let done = list.len() < 100; + items.extend(list); + if done { + break; + } + } + Ok(items) +} + +/// The highest permission GitHub's flags give (`{"admin": false, "push": true, …}`). +fn permission_from_flags(flags: &Value) -> Option { + [ + ("admin", Permission::Admin), + ("maintain", Permission::Maintain), + ("push", Permission::Write), + ("triage", Permission::Triage), + ("pull", Permission::Read), + ] + .into_iter() + .find(|(flag, _)| flags[*flag] == true) + .map(|(_, p)| p) +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs new file mode 100644 index 00000000..dc2a5e65 --- /dev/null +++ b/app/src/forge/mod.rs @@ -0,0 +1,241 @@ +//! Forges: where a project's repository lives (GitHub and GitLab), ported from today's server (sc-8900, the forge +//! side). These are the forge-neutral types: kinds, permissions, repository URLs, and what a sign-in learns. Each +//! forge's API calls are in its own module. + +pub mod github; + +use crate::auth::Role; + +/// A forge's name as stored (`projects.forge`, `identities.forge`, `memberships.source`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ForgeKind { + Github, + Gitlab, +} + +impl ForgeKind { + pub const ALL: [Self; 2] = [Self::Github, Self::Gitlab]; + + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Github => "github", + Self::Gitlab => "gitlab", + } + } + + #[must_use] + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|k| k.as_str() == s) + } + + /// The forge's name for people. + #[must_use] + pub const fn label(self) -> &'static str { + match self { + Self::Github => "GitHub", + Self::Gitlab => "GitLab", + } + } +} + +/// A person's permission on a repository, in the forge's own terms (GitHub's five levels; other forges map theirs). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Permission { + Read, + Triage, + Write, + Maintain, + Admin, +} + +impl Permission { + /// The VisualCI role it gives: admin or maintain → admin, write → member (review and approve), triage or read → + /// read. + #[must_use] + pub const fn role(self) -> Role { + match self { + Self::Admin | Self::Maintain => Role::Admin, + Self::Write => Role::Member, + Self::Triage | Self::Read => Role::Read, + } + } +} + +/// A repository on a forge, named by its web URL (`https://github.com/acme/web`, `https://gitlab.com/acme/web/app`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Repository { + pub forge: ForgeKind, + /// `https://github.com/acme/web`: no trailing slash or `.git`. + pub url: String, + /// The forge's own path for it: `acme/web` (GitLab: `group/subgroup/project`, nested groups and all). + pub path: String, + /// The forge's permanent ID for it, when known (a webhook delivery carries it). A renamed or transferred + /// repository keeps it, and a new repository that takes the old name gets another. + pub id: Option, +} + +/// GitLab instances other than gitlab.com whose project URLs parse as GitLab repositories (base URLs without a +/// trailing slash: `https://gitlab.example.com`, `http://docspring-dev.hs:5196`). +static GITLAB_INSTANCES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); + +/// Recognise a GitLab instance's project URLs. +pub fn register_gitlab_instance(base_url: &str) { + let base = base_url.trim().trim_end_matches('/').to_ascii_lowercase(); + if base.is_empty() || base == "https://gitlab.com" { + return; + } + if let Ok(mut list) = GITLAB_INSTANCES.write() + && !list.contains(&base) + { + list.push(base); + } +} + +/// The registered GitLab instance a URL is on, with the rest of its path. +fn on_gitlab_instance(input: &str) -> Option<(String, String)> { + let list = GITLAB_INSTANCES.read().ok()?; + let lower = input.to_ascii_lowercase(); + list.iter().find_map(|base| { + let rest = lower.strip_prefix(base.as_str())?.strip_prefix('/')?; + Some((base.clone(), input[input.len() - rest.len()..].to_string())) + }) +} + +impl Repository { + /// The same repository, with the forge's ID for it. + #[must_use] + pub fn with_id(mut self, id: Option) -> Self { + self.id = id; + self + } + + /// A repository from its web or clone URL (`https://github.com/acme/web`, `…/web.git`, + /// `git@github.com:acme/web.git`, `https://gitlab.com/acme/web/app`), or GitHub's `owner/name`. `None` for a + /// forge VisualCI doesn't know yet. + #[must_use] + pub fn parse(input: &str) -> Option { + let s = input.trim().trim_end_matches('/'); + let s = s.strip_suffix(".git").unwrap_or(s); + if let Some((base, path)) = on_gitlab_instance(s) { + let parts: Vec<&str> = path.split('/').collect(); + let valid = |p: &str| { + !p.is_empty() + && p != "." + && p != ".." + && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) + }; + if !(2..=21).contains(&parts.len()) || parts.contains(&"-") || !parts.iter().all(|p| valid(p)) { + return None; + } + let path = parts.join("/"); + return Some(Self { forge: ForgeKind::Gitlab, url: format!("{base}/{path}"), path, id: None }); + } + let (host, path) = if let Some(rest) = s.strip_prefix("git@") { + rest.split_once(':')? + } else if let Some(rest) = s.strip_prefix("https://").or_else(|| s.strip_prefix("http://")) { + let rest = rest.rsplit_once('@').map_or(rest, |(_, r)| r); + rest.split_once('/')? + } else { + ("github.com", s) + }; + let host = host.to_ascii_lowercase(); + let (forge, host) = match host.as_str() { + "github.com" | "www.github.com" => (ForgeKind::Github, "github.com"), + "gitlab.com" | "www.gitlab.com" => (ForgeKind::Gitlab, "gitlab.com"), + _ => return None, + }; + let parts: Vec<&str> = path.split('/').collect(); + let valid = |p: &str| { + !p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) + }; + // GitHub: owner/name. GitLab: a project in a group and up to 20 levels of subgroups; `-` starts GitLab's own + // pages (`…/-/merge_requests/1`), never a group or project. + let shape = match forge { + ForgeKind::Github => parts.len() == 2, + ForgeKind::Gitlab => (2..=21).contains(&parts.len()) && !parts.contains(&"-"), + }; + if !shape || !parts.iter().all(|p| valid(p)) { + return None; + } + let path = parts.join("/"); + Some(Self { forge, url: format!("https://{host}/{path}"), path, id: None }) + } + + /// A GitLab project's web URL on any host: gitlab.com, or a self-managed instance at the root of its host + /// (`https://gitlab.example.com/group/sub/project`). For URLs already known to be GitLab's (a project linked to + /// GitLab, a GitLab webhook's payload, a host an organization registered). + #[must_use] + pub fn parse_gitlab(input: &str) -> Option { + let s = input.trim().trim_end_matches('/'); + let s = s.strip_suffix(".git").unwrap_or(s); + let (scheme, rest) = s.split_once("://").filter(|(scheme, _)| matches!(*scheme, "https" | "http"))?; + let (host, path) = rest.split_once('/')?; + let host = host.rsplit_once('@').map_or(host, |(_, h)| h).to_ascii_lowercase(); + if host.is_empty() || host.contains(['/', ' ']) { + return None; + } + let parts: Vec<&str> = path.split('/').collect(); + let valid = |p: &str| { + !p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) + }; + if !(2..=21).contains(&parts.len()) || parts.contains(&"-") || !parts.iter().all(|p| valid(p)) { + return None; + } + let path = parts.join("/"); + let scheme = if host == "gitlab.com" || host == "www.gitlab.com" { "https" } else { scheme }; + let host = host.strip_prefix("www.").filter(|h| *h == "gitlab.com").unwrap_or(&host); + Some(Self { forge: ForgeKind::Gitlab, url: format!("{scheme}://{host}/{path}"), path, id: None }) + } + + /// The base URL of the site the repository is on: `https://gitlab.example.com`. + #[must_use] + pub fn site_url(&self) -> &str { + let after_scheme = self.url.find("://").map_or(0, |i| i + 3); + self.url[after_scheme..].find('/').map_or(self.url.as_str(), |i| &self.url[..after_scheme + i]) + } +} + +/// What the forge says about a repository: whether it's public, and its licence (for open source projects). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Visibility { + /// The forge's permanent ID for the repository. + pub id: Option, + pub public: bool, + /// The SPDX id of the licence the forge detected, if any. + pub licence: Option, +} + +/// Someone who signed in with a forge. +#[derive(Debug, Clone)] +pub struct Identity { + pub forge: ForgeKind, + /// The forge's permanent user ID. + pub id: String, + pub login: String, + pub name: Option, + pub avatar_url: Option, + /// Verified addresses, primary first, lowercased. + pub verified_emails: Vec, + /// Where the account lives: '' for github.com and gitlab.com, a self-managed GitLab's base URL otherwise. + pub site: String, +} + +impl Identity { + /// The addresses this sign-in proves the person owns. Only github.com, gitlab.com and the server's configured + /// GitLab count: a self-managed instance is added by any organization's admin and says whatever it likes about its + /// accounts, so its addresses never find an existing account, become a new account's address, or accept an + /// invitation. + #[must_use] + pub fn trusted_emails(&self) -> &[String] { + if self.site.is_empty() { &self.verified_emails } else { &[] } + } +} + +/// What a sign-in learns: who it is and what they can reach. +#[derive(Debug, Clone)] +pub struct SignIn { + pub identity: Identity, + /// Every repository the forge app can see that this person has a permission on. + pub repositories: Vec<(Repository, Permission)>, +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 0c096a64..f37c18c3 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,6 +1,7 @@ //! VisualCI's server on Laravel Rust. Who owns which module, and the seams between them, are in sc-8900. pub mod auth; +pub mod forge; pub mod http; pub mod models; #[path = "../database/seeders/mod.rs"] @@ -14,9 +15,9 @@ pub fn configure() -> ApplicationBuilder { Application::configure() .with_migrations(laravel::db::migrations!("database/migrations")) .with_auth(|auth, _| { - auth.session::>(); + auth.session::(); }) .with_routing(|routing, _| { - routing.api(http::api::routes).health("/up"); + routing.web(auth::routes).api(http::api::routes).health("/up"); }) } diff --git a/app/src/models/mod.rs b/app/src/models/mod.rs index 10805441..aa0156ff 100644 --- a/app/src/models/mod.rs +++ b/app/src/models/mod.rs @@ -4,4 +4,4 @@ mod tokens; mod user; pub use tokens::{ProjectToken, UserToken, token_hash}; -pub use user::User; +pub use user::{User, Users}; diff --git a/app/src/models/user.rs b/app/src/models/user.rs index bc20b977..d3e3a7bd 100644 --- a/app/src/models/user.rs +++ b/app/src/models/user.rs @@ -1,26 +1,63 @@ -use laravel::auth::{Authenticatable, RememberToken}; +use laravel::auth::Authenticatable; use laravel::hash::PasswordHash; use laravel::model::model; use laravel::str::Uuid; use laravel::time::Timestamp; -/// A person. Everyone signs in through a forge (their forge accounts are `Identity` rows), and MCP clients act for -/// them once they approve a connection. +/// A person. Everyone signs in through a forge (GitHub or GitLab, their `identities`): there are no passwords and no +/// "remember me" tokens, so the session is the only way a browser stays signed in. MCP clients act for them once they +/// approve a connection. #[model] -#[derive(Authenticatable)] pub struct User { pub id: i64, pub pid: Uuid, pub name: String, pub email: String, pub email_verified_at: Option, - #[serde(skip)] - pub password: PasswordHash, - #[serde(skip)] - pub remember_token: Option, pub avatar_url: Option, pub staff: bool, pub signup_via: Option, pub created_at: Timestamp, pub updated_at: Timestamp, } + +impl Authenticatable for User { + type Id = i64; + + fn auth_id(&self) -> i64 { + self.id + } + + fn auth_password(&self) -> Option<&PasswordHash> { + None + } + + fn remember_token(&self) -> Option<&str> { + None + } +} + +/// The session guard's users: found by ID. 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> { + User::find(*id).await + } + + async fn find_for_login(&self, _login: &str) -> laravel::Result> { + Ok(None) + } + + async fn update_password(&self, _user: &User, _password: &PasswordHash) -> laravel::Result<()> { + Err(laravel::Error::msg("VisualCI has no passwords: people sign in with GitHub or GitLab")) + } + + async fn update_remember_token(&self, _user: &User, _token: &str) -> laravel::Result<()> { + Ok(()) + } +} diff --git a/app/tests/auth.rs b/app/tests/auth.rs index 60b401f4..ba1f25f1 100644 --- a/app/tests/auth.rs +++ b/app/tests/auth.rs @@ -7,7 +7,7 @@ use laravel::model::create; use laravel::testing::prelude::*; async fn user(email: &str) -> laravel::Result { - create!(User { pid: laravel::str::uuid7(), name: "Ada", email: email, password: "", staff: false }).await + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: email, staff: false }).await } /// The memberships table belongs to the domain migrations (sc-8900); until they land, the test makes a stand-in. diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs new file mode 100644 index 00000000..528101d4 --- /dev/null +++ b/app/tests/sign_in.rs @@ -0,0 +1,144 @@ +//! Signing in with GitHub (Laravel's social login and GitHub's API, both faked): a new person gets an account and +//! its identity, a returning one is found by their GitHub ID, an existing account by a verified email, and with +//! sign-ups closed a new person goes on the waitlist instead. + +use app::models::User; +use laravel::auth::social::{self, Provider}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +/// GitHub's API as a sign-in reads it: one verified address and one repository the person can push to. +fn github() -> client::HttpFake { + client::fake() + .with( + "api.github.com/user/emails*", + json!([ + { "email": "Ada@Example.com", "primary": true, "verified": true }, + { "email": "old@example.com", "primary": false, "verified": false }, + ]), + ) + .with( + "api.github.com/user/installations/*/repositories*", + json!({ "repositories": [ + { "id": 9, "full_name": "acme/web", "permissions": { "admin": false, "push": true, "pull": true } }, + ] }), + ) + .with("api.github.com/user/installations*", json!({ "installations": [{ "id": 1 }] })) +} + +fn ada() -> social::FakeUser { + social::User::fake("gh-1").name("Ada Lovelace").raw(json!({ "login": "ada" })).verified_email("ada@example.com") +} + +async fn identities_of(user_id: i64) -> laravel::Result { + Ok(db::query!("SELECT count(*) FROM identities WHERE user_id = {user_id}").scalar::().await?.unwrap_or(0)) +} + +#[laravel::test] +async fn a_new_person_gets_an_account_and_returns_where_they_started(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + + let start = app.get("/auth/github?return_to=/acme/web/builds/3").await; + start.assert_redirect(); + let done = app.get("/auth/github/callback").with_cookies_from(&start).await; + done.assert_redirect_to("/acme/web/builds/3"); + + let user = User::first_where(User::email.eq("ada@example.com")).await?.expect("an account"); + assert_eq!(user.name, "Ada Lovelace"); + assert!(user.email_verified_at.is_some()); + assert_eq!(identities_of(user.id).await?, 1); + app.get("/auth/session") + .with_cookies_from(&done) + .await + .assert_ok() + .assert_json_path("signed_in", true) + .assert_json_path("name", "Ada Lovelace"); + + // Again: the same account, found by the GitHub ID + let again = app.get("/auth/github/callback").await; + again.assert_redirect_to("/"); + assert_eq!(User::query().count().await?, 1); + Ok(()) +} + +#[laravel::test] +async fn an_existing_account_is_found_by_a_verified_email(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let existing = + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + + app.get("/auth/github/callback").await.assert_redirect_to("/"); + assert_eq!(User::query().count().await?, 1, "no second account"); + assert_eq!(identities_of(existing.id).await?, 1, "the GitHub account is linked to it"); + Ok(()) +} + +#[laravel::test] +async fn an_unsafe_return_address_is_ignored(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let start = app.get("/auth/github?return_to=//evil.example/x").await; + app.get("/auth/github/callback").with_cookies_from(&start).await.assert_redirect_to("/"); + Ok(()) +} + +#[laravel::test] +async fn an_unknown_forge_is_not_found(app: Application) -> laravel::Result<()> { + app.get("/auth/bitbucket").await.assert_status(404); + Ok(()) +} + +fn closed() -> Application { + app::testing::configure().with_env("VISUALCI_WAITLIST", "true").create() +} + +#[laravel::test(app = closed)] +async fn with_sign_ups_closed_someone_new_goes_on_the_waitlist(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let r = app.get("/auth/github/callback").await; + r.assert_ok().assert_see("VisualCI opens in about 48 hours. We'll email you at ada@example.com."); + assert!(User::first_where(User::email.eq("ada@example.com")).await?.is_none(), "no account"); + let rows = db::query!("SELECT login, email, source FROM waitlist").select().await?; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].try_get::("login")?, "ada"); + assert_eq!(rows[0].try_get::("source")?, "web"); + app.get("/auth/session").with_cookies_from(&r).await.assert_json_path("signed_in", false); + + Ok(()) +} + +#[laravel::test(app = closed)] +async fn with_sign_ups_closed_someone_with_an_account_still_signs_in(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let existing = + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + + app.get("/auth/github/callback").await.assert_redirect_to("/"); + assert_eq!(identities_of(existing.id).await?, 1); + assert_eq!(db::query!("SELECT count(*) FROM waitlist").scalar::().await?, Some(0)); + Ok(()) +} + +#[laravel::test] +async fn signing_out_from_another_site_is_refused(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let signed_in = app.get("/auth/github/callback").await; + // A form on another site posting to /auth/logout: no same-origin Sec-Fetch-Site and no CSRF token + app.post("/auth/logout") + .with_cookies_from(&signed_in) + .header("sec-fetch-site", "cross-site") + .header("content-type", "application/x-www-form-urlencoded") + .await + .assert_status(419); + app.get("/auth/session").with_cookies_from(&signed_in).await.assert_json_path("signed_in", true); + // From the app itself it works + app.post("/auth/logout").with_cookies_from(&signed_in).header("sec-fetch-site", "same-origin").await.assert_ok(); + Ok(()) +}