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
Original file line number Diff line number Diff line change
@@ -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| {
Expand All @@ -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);
Expand Down
11 changes: 11 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
//!
//! Nobody found: `401`.

pub mod sign_in;

use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use laravel::auth::Auth;
Expand Down Expand Up @@ -234,3 +236,12 @@ pub async fn whoami(principal: Principal) -> laravel::Result<axum::Json<serde_js
};
Ok(axum::Json(serde_json::json!({ "principal": who, "client": client })))
}

/// The sign-in routes, on the `web` group (they need the session).
pub fn routes(route: &mut laravel::prelude::Router) {
route.get("/auth/{forge}", sign_in::start);
route.post("/auth/{forge}/link", sign_in::link);
route.get("/auth/{forge}/callback", sign_in::callback);
route.get("/auth/session", sign_in::session);
route.post("/auth/logout", sign_in::logout);
}
270 changes: 270 additions & 0 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
//! Signing in with a forge, ported from today's server (sc-8900, the auth side), at the same URLs so the web app's
//! links keep working: `GET /auth/{forge}?return_to=…` starts it, `GET /auth/{forge}/callback` finishes it,
//! `POST /auth/logout` ends the session.
//!
//! The callback finds the person by their forge identity, else (when they asked to link it) the signed-in user, else
//! an account with one of their verified email addresses, else makes an account: or, with sign-ups closed
//! (`VISUALCI_WAITLIST=true`), puts them on the waitlist and shows one line instead. A new account fires
//! [`SignedUp`] (the domain side gives it its own organization); every sign-in fires [`SignedIn`] with the
//! repositories the forge says they can reach, for their memberships.

use laravel::auth::Auth;
use laravel::auth::social::{self, Provider};
use laravel::db;
use laravel::model::create;
use laravel::prelude::*;
use laravel::session::Session;

use crate::forge::{self, ForgeKind, Identity, Permission, Repository};
use crate::models::User;

/// Someone signed up: a new account. The domain side gives it its own organization and project.
#[derive(laravel::event::Event, Clone, Debug)]
pub struct SignedUp {
pub user_id: i64,
/// `web`, or `mcp: <client id>` 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<String>,
}

fn provider(forge: &str) -> laravel::Result<Provider> {
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<String> {
(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<String>,
Query(q): Query<StartQuery>,
session: Session,
) -> laravel::Result<Redirect> {
let provider = provider(&forge)?;
match q.return_to.as_deref().and_then(safe_return) {
Some(to) => session.put(RETURN_TO, to),
None => {
let _: Option<String> = session.pull(RETURN_TO);
}
}
let _: Option<bool> = 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<String>,
_user: laravel::auth::Authenticated<User>,
session: Session,
) -> laravel::Result<Json<serde_json::Value>> {
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<String>,
auth: Auth<User>,
sign_ups: laravel::config::Section<SignUps>,
session: Session,
) -> laravel::Result<laravel::http::Response> {
let provider = provider(&forge)?;
let return_to: Option<String> = 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<User>) -> laravel::Result<Json<serde_json::Value>> {
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<User>) -> laravel::Result<Json<serde_json::Value>> {
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<String> {
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<Option<i64>> {
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::<i64>()
.await
}

async fn user_by_email(id: &Identity) -> laravel::Result<Option<User>> {
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<bool> {
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<User> {
// 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('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;");
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!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\"><title>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}}}}p{{max-width:32rem;\
margin:0}}</style></head><body><p>{line}</p></body></html>"
);
laravel::http::Response::new(laravel::view::Html::raw(html))
}
Loading
Loading