Skip to content

Commit a2ffb80

Browse files
authored
app/: GitHub sign-in at today's URLs, with the waitlist (sc-8900) (#52)
* app/: GitHub sign-in (sc-8900, the auth side): /auth/{forge}?return_to=, /auth/{forge}/callback, /auth/{forge}/link, /auth/session and /auth/logout at today's URLs; Laravel's social login plus GitHub's API for every verified email and the installations' repositories; finds the person by identity, the signed-in user when linking, or a verified email, else makes an account (SignedUp) or, with VISUALCI_WAITLIST=true, a waitlist row and one line; SignedIn carries the repositories for memberships; users have no password or remember token (a provider of our own); forge types ported * Review fixes: a returning identity's login is updated by forge, site and ID (a GitHub and a GitLab ID can be the same number); a test that a cross-site POST to /auth/logout is refused (Laravel's web-group CSRF check: 419) while the app's own works
1 parent 1125f51 commit a2ffb80

10 files changed

Lines changed: 826 additions & 16 deletions

File tree

‎app/database/migrations/0001_01_01_000000_create_users_table.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use laravel::db::AnyTransaction;
22

3-
/// People, and their sessions. Everyone signs in through a forge (GitHub or GitLab): `password` stays empty, and the
4-
/// forge accounts are in `identities`.
3+
/// People, and their sessions. Everyone signs in through a forge (GitHub or GitLab), whose accounts are in
4+
/// `identities`: no passwords, no "remember me" tokens.
55
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
66
tx.schema()
77
.create("users", |table| {
@@ -10,8 +10,6 @@ pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
1010
table.string("name");
1111
table.string("email").unique();
1212
table.timestamp("email_verified_at").nullable();
13-
table.string("password").default("");
14-
table.remember_token();
1513
table.text("avatar_url").nullable();
1614
// VisualCI's own team: the admin MCP endpoint and staff pages
1715
table.boolean("staff").default(false);

‎app/src/auth/mod.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
//!
99
//! Nobody found: `401`.
1010
11+
pub mod sign_in;
12+
1113
use axum::extract::FromRequestParts;
1214
use axum::http::request::Parts;
1315
use laravel::auth::Auth;
@@ -234,3 +236,12 @@ pub async fn whoami(principal: Principal) -> laravel::Result<axum::Json<serde_js
234236
};
235237
Ok(axum::Json(serde_json::json!({ "principal": who, "client": client })))
236238
}
239+
240+
/// The sign-in routes, on the `web` group (they need the session).
241+
pub fn routes(route: &mut laravel::prelude::Router) {
242+
route.get("/auth/{forge}", sign_in::start);
243+
route.post("/auth/{forge}/link", sign_in::link);
244+
route.get("/auth/{forge}/callback", sign_in::callback);
245+
route.get("/auth/session", sign_in::session);
246+
route.post("/auth/logout", sign_in::logout);
247+
}

‎app/src/auth/sign_in.rs‎

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
//! Signing in with a forge, ported from today's server (sc-8900, the auth side), at the same URLs so the web app's
2+
//! links keep working: `GET /auth/{forge}?return_to=…` starts it, `GET /auth/{forge}/callback` finishes it,
3+
//! `POST /auth/logout` ends the session.
4+
//!
5+
//! The callback finds the person by their forge identity, else (when they asked to link it) the signed-in user, else
6+
//! an account with one of their verified email addresses, else makes an account: or, with sign-ups closed
7+
//! (`VISUALCI_WAITLIST=true`), puts them on the waitlist and shows one line instead. A new account fires
8+
//! [`SignedUp`] (the domain side gives it its own organization); every sign-in fires [`SignedIn`] with the
9+
//! repositories the forge says they can reach, for their memberships.
10+
11+
use laravel::auth::Auth;
12+
use laravel::auth::social::{self, Provider};
13+
use laravel::db;
14+
use laravel::model::create;
15+
use laravel::prelude::*;
16+
use laravel::session::Session;
17+
18+
use crate::forge::{self, ForgeKind, Identity, Permission, Repository};
19+
use crate::models::User;
20+
21+
/// Someone signed up: a new account. The domain side gives it its own organization and project.
22+
#[derive(laravel::event::Event, Clone, Debug)]
23+
pub struct SignedUp {
24+
pub user_id: i64,
25+
/// `web`, or `mcp: <client id>` when the sign-in came from an MCP client's authorization.
26+
pub via: String,
27+
}
28+
29+
/// Someone signed in, with what the forge says they can reach: their memberships follow it.
30+
#[derive(laravel::event::Event, Clone, Debug)]
31+
pub struct SignedIn {
32+
pub user_id: i64,
33+
pub forge: ForgeKind,
34+
pub site: String,
35+
pub repositories: Vec<(Repository, Permission)>,
36+
}
37+
38+
const RETURN_TO: &str = "auth.return_to";
39+
const LINKING: &str = "auth.linking";
40+
41+
#[laravel::query]
42+
pub struct StartQuery {
43+
return_to: Option<String>,
44+
}
45+
46+
fn provider(forge: &str) -> laravel::Result<Provider> {
47+
match ForgeKind::parse(forge) {
48+
Some(ForgeKind::Github) => Ok(Provider::GITHUB),
49+
// GitLab sign-in comes with the GitLab provider (social login's custom providers)
50+
_ => Err(laravel::abort(404)),
51+
}
52+
}
53+
54+
/// A path on this site to return to, never another site's URL.
55+
fn safe_return(to: &str) -> Option<String> {
56+
(to.starts_with('/') && !to.starts_with("//") && !to.contains('\\')).then(|| to.to_string())
57+
}
58+
59+
/// `GET /auth/{forge}`: off to the forge.
60+
pub async fn start(
61+
Params(forge): Params<String>,
62+
Query(q): Query<StartQuery>,
63+
session: Session,
64+
) -> laravel::Result<Redirect> {
65+
let provider = provider(&forge)?;
66+
match q.return_to.as_deref().and_then(safe_return) {
67+
Some(to) => session.put(RETURN_TO, to),
68+
None => {
69+
let _: Option<String> = session.pull(RETURN_TO);
70+
}
71+
}
72+
let _: Option<bool> = session.pull(LINKING);
73+
social::redirect(provider)
74+
}
75+
76+
/// `POST /auth/{forge}/link`: link another forge account to the signed-in user. A JSON POST, which a page on another
77+
/// site can't make with the session cookie. Returns where to go.
78+
pub async fn link(
79+
Params(forge): Params<String>,
80+
_user: laravel::auth::Authenticated<User>,
81+
session: Session,
82+
) -> laravel::Result<Json<serde_json::Value>> {
83+
let provider = provider(&forge)?;
84+
session.put(LINKING, true);
85+
let redirect = laravel::http::Response::new(social::redirect(provider)?).into_http();
86+
let url = redirect.headers().get(axum::http::header::LOCATION).and_then(|v| v.to_str().ok()).unwrap_or_default();
87+
Ok(Json(serde_json::json!({ "url": url })))
88+
}
89+
90+
/// `GET /auth/{forge}/callback`: back from the forge.
91+
pub async fn callback(
92+
Params(forge): Params<String>,
93+
auth: Auth<User>,
94+
sign_ups: laravel::config::Section<SignUps>,
95+
session: Session,
96+
) -> laravel::Result<laravel::http::Response> {
97+
let provider = provider(&forge)?;
98+
let return_to: Option<String> = session.pull(RETURN_TO);
99+
let linking: bool = session.pull(LINKING).unwrap_or(false);
100+
let profile = match social::user(provider).await {
101+
Ok(profile) => profile,
102+
Err(social::Error::Denied) => {
103+
return Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/"))));
104+
}
105+
Err(e) => return Err(e.into()),
106+
};
107+
let sign_in = forge::github::sign_in(&profile).await?;
108+
let current = auth.user().await?;
109+
let link_to = current.as_ref().filter(|_| linking);
110+
let via = return_to.as_deref().and_then(mcp_client).map_or_else(|| "web".to_string(), |c| format!("mcp: {c}"));
111+
112+
if sign_ups.waitlist && is_new_person(&sign_in.identity, link_to).await? {
113+
record_waitlist(&sign_in.identity, &via).await?;
114+
return Ok(waitlist_page(&sign_in.identity));
115+
}
116+
let (user, created) = user_for_sign_in(&sign_in.identity, link_to).await?;
117+
if created {
118+
SignedUp { user_id: user.id, via: via.clone() }.dispatch().await?;
119+
}
120+
SignedIn {
121+
user_id: user.id,
122+
forge: sign_in.identity.forge,
123+
site: sign_in.identity.site.clone(),
124+
repositories: sign_in.repositories,
125+
}
126+
.dispatch()
127+
.await?;
128+
auth.login(&user).await?;
129+
Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/"))))
130+
}
131+
132+
/// `GET /auth/session`: whether this browser is signed in, for visualci.com's static pages ("Open app" instead of
133+
/// "Sign in"). Only what that button needs: no email, no IDs.
134+
pub async fn session(auth: Auth<User>) -> laravel::Result<Json<serde_json::Value>> {
135+
let user = auth.user().await?;
136+
Ok(Json(serde_json::json!({ "signed_in": user.is_some(), "name": user.map(|u| u.name) })))
137+
}
138+
139+
/// `POST /auth/logout`.
140+
pub async fn logout(auth: Auth<User>) -> laravel::Result<Json<serde_json::Value>> {
141+
auth.logout().await?;
142+
Ok(Json(serde_json::json!({ "ok": true })))
143+
}
144+
145+
/// The MCP client an authorization's return address names (`/oauth/authorize?client_id=…`).
146+
fn mcp_client(return_to: &str) -> Option<String> {
147+
let (path, query) = return_to.split_once('?')?;
148+
(path == "/oauth/authorize")
149+
.then(|| query.split('&').find_map(|kv| kv.strip_prefix("client_id=")).map(str::to_string))
150+
.flatten()
151+
}
152+
153+
/// Sign-ups: closed (`VISUALCI_WAITLIST=true`) until VisualCI opens, when someone new goes on the waitlist instead.
154+
#[derive(Clone, laravel::config::Section)]
155+
pub struct SignUps {
156+
#[env("VISUALCI_WAITLIST", default = false)]
157+
pub waitlist: bool,
158+
}
159+
160+
/// The user who owns this forge identity, if anyone.
161+
async fn identity_owner(id: &Identity) -> laravel::Result<Option<i64>> {
162+
let (forge, site, forge_id) = (id.forge.as_str(), id.site.as_str(), id.id.as_str());
163+
db::query!("SELECT user_id FROM identities WHERE forge = {forge} AND site = {site} AND forge_user_id = {forge_id}")
164+
.scalar::<i64>()
165+
.await
166+
}
167+
168+
async fn user_by_email(id: &Identity) -> laravel::Result<Option<User>> {
169+
for address in id.trusted_emails() {
170+
if let Some(user) = User::query().filter(db::raw!("lower(email) = {address}")).first().await? {
171+
return Ok(Some(user));
172+
}
173+
}
174+
Ok(None)
175+
}
176+
177+
/// Whether this sign-in would make a new account.
178+
async fn is_new_person(id: &Identity, link_to: Option<&User>) -> laravel::Result<bool> {
179+
Ok(link_to.is_none() && identity_owner(id).await?.is_none() && user_by_email(id).await?.is_none())
180+
}
181+
182+
/// The user a sign-in belongs to, and whether it was made just now. An identity that's already someone else's can't
183+
/// be linked to the signed-in user.
184+
async fn user_for_sign_in(id: &Identity, link_to: Option<&User>) -> laravel::Result<(User, bool)> {
185+
if let Some(owner) = identity_owner(id).await? {
186+
if link_to.is_some_and(|u| u.id != owner) {
187+
return Err(laravel::abort_with(
188+
409,
189+
format!("that {} account is already linked to another VisualCI user", id.forge.label()),
190+
));
191+
}
192+
let user = User::find(owner).await?.ok_or_else(|| laravel::abort(404))?;
193+
// The same identity identity_owner found: a GitHub and a GitLab account can have the same number for an ID
194+
let (login, forge, site, forge_id) = (id.login.as_str(), id.forge.as_str(), id.site.as_str(), id.id.as_str());
195+
db::query!(
196+
"UPDATE identities SET login = {login}, updated_at = now() \
197+
WHERE forge = {forge} AND site = {site} AND forge_user_id = {forge_id}"
198+
)
199+
.update()
200+
.await?;
201+
return Ok((user, false));
202+
}
203+
let (user, created) = match link_to.cloned() {
204+
Some(u) => (u, false),
205+
None => match user_by_email(id).await? {
206+
Some(u) => (u, false),
207+
None => (new_user(id).await?, true),
208+
},
209+
};
210+
let (user_id, forge, site, forge_id, login) =
211+
(user.id, id.forge.as_str(), id.site.as_str(), id.id.as_str(), id.login.as_str());
212+
db::query!(
213+
"INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \
214+
VALUES ({user_id}, {forge}, {site}, {forge_id}, {login}, now(), now())"
215+
)
216+
.insert()
217+
.await?;
218+
Ok((user, created))
219+
}
220+
221+
async fn new_user(id: &Identity) -> laravel::Result<User> {
222+
// An account with no trusted address gets a placeholder unique to the forge account
223+
let email = id
224+
.trusted_emails()
225+
.first()
226+
.cloned()
227+
.unwrap_or_else(|| format!("{}+{}@users.noreply.{}.visualci.com", id.id, id.login, id.forge.as_str()));
228+
let verified = (!id.trusted_emails().is_empty()).then(laravel::now);
229+
create!(User {
230+
pid: laravel::str::uuid7(),
231+
name: id.name.clone().unwrap_or_else(|| id.login.clone()),
232+
email: email,
233+
email_verified_at: verified,
234+
avatar_url: id.avatar_url.clone(),
235+
staff: false,
236+
})
237+
.await
238+
}
239+
240+
async fn record_waitlist(id: &Identity, source: &str) -> laravel::Result<()> {
241+
let (forge, site, forge_id, login) = (id.forge.as_str(), id.site.as_str(), id.id.as_str(), id.login.as_str());
242+
let (name, email) = (id.name.clone(), id.trusted_emails().first().cloned());
243+
db::query!(
244+
"INSERT INTO waitlist (forge, site, forge_user_id, login, name, email, source, created_at, updated_at) \
245+
VALUES ({forge}, {site}, {forge_id}, {login}, {name}, {email}, {source}, now(), now()) \
246+
ON CONFLICT (forge, site, forge_user_id) DO UPDATE SET login = EXCLUDED.login, \
247+
name = COALESCE(EXCLUDED.name, waitlist.name), email = COALESCE(EXCLUDED.email, waitlist.email), \
248+
updated_at = now()"
249+
)
250+
.statement()
251+
.await?;
252+
Ok(())
253+
}
254+
255+
/// The one page someone on the waitlist sees.
256+
fn waitlist_page(id: &Identity) -> laravel::http::Response {
257+
let escape = |s: &str| s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;");
258+
let line = match id.trusted_emails().first() {
259+
Some(email) => format!("VisualCI opens in about 48 hours. We'll email you at {}.", escape(email)),
260+
None => "VisualCI opens in about 48 hours.".to_string(),
261+
};
262+
let html = format!(
263+
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
264+
content=\"width=device-width, initial-scale=1\"><title>VisualCI</title><style>body{{font:16px/1.5 \
265+
system-ui,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;padding:16px;color:#1a1a1a;\
266+
background:#fff}}@media (prefers-color-scheme:dark){{body{{color:#eee;background:#111}}}}p{{max-width:32rem;\
267+
margin:0}}</style></head><body><p>{line}</p></body></html>"
268+
);
269+
laravel::http::Response::new(laravel::view::Html::raw(html))
270+
}

0 commit comments

Comments
 (0)