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
24 changes: 24 additions & 0 deletions app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//! A GitHub sign-in's installations and repositories are listed after it, by a queued job (`forge::sign_in_sync`), not
//! in the callback (4 Dec 2026: the callback took 6.3 s listing them before it redirected).
//!
//! - `users.github_sync_requested_at`: when their last GitHub sign-in asked for the listing.
//! - `users.github_synced_at`: when the job that last finished started; the listing is still coming while it's older
//! than the request.
//! - `users.github_sync_error`: why the last listing failed, if it did.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r"
ALTER TABLE users
ADD COLUMN github_sync_requested_at TIMESTAMPTZ,
ADD COLUMN github_synced_at TIMESTAMPTZ,
ADD COLUMN github_sync_error TEXT;
-- The listings still coming, for /status
CREATE INDEX users_github_sync_waiting ON users (github_sync_requested_at)
WHERE github_synced_at IS NULL OR github_synced_at < github_sync_requested_at;
";
70 changes: 62 additions & 8 deletions app/src/auth/installations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
//! through the organization's installations, from their last GitHub sign-in, with no GitHub call. `POST` with
//! `repository_ids` makes the chosen ones into projects through a queued job; `GET
//! /api/ui/orgs/{org}/repository-imports/{id}` is its progress.
//! - `POST /api/ui/github/sync` lists what their GitHub sign-in reaches again, after a listing failed: 202, or 409
//! `sign_in_again` when the token from their sign-in has expired.

use laravel::auth::{Auth, Authenticated};
use laravel::prelude::*;
Expand All @@ -22,6 +24,7 @@ use laravel::session::Session;
use crate::config::GithubApp;
use crate::forge::github_app;
use crate::forge::installations::{self, SetUp};
use crate::forge::sign_in_sync::{self, State};
use crate::models::User;

pub fn routes(route: &mut Router) {
Expand All @@ -31,6 +34,7 @@ pub fn routes(route: &mut Router) {
route.get("/api/ui/orgs/{org}/repositories", picker);
route.post("/api/ui/orgs/{org}/repositories", import);
route.get("/api/ui/orgs/{org}/repository-imports/{id}", import_progress);
route.post("/api/ui/github/sync", sync_again);
}

/// The session key holding the `state` sent to GitHub with an install.
Expand Down Expand Up @@ -61,13 +65,15 @@ pub async fn install(session: Session) -> Redirect {

/// Back to this page after signing in with GitHub. The ID is digits and the state letters and digits, so both are
/// safe in the URL as they are.
fn through_sign_in(installation_id: &str, state: Option<&str>) -> Redirect {
fn sign_in_url(installation_id: &str, state: Option<&str>) -> String {
let state = state
.filter(|s| s.bytes().all(|b| b.is_ascii_alphanumeric()))
.map_or(String::new(), |s| format!("%26state%3D{s}"));
Redirect::to(format!(
"/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}{state}%26refreshed%3D1"
))
format!("/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}{state}%26refreshed%3D1")
}

fn through_sign_in(installation_id: &str, state: Option<&str>) -> Redirect {
Redirect::to(sign_in_url(installation_id, state))
}

/// `GET /github/setup`: GitHub's redirect after someone installs the App.
Expand All @@ -90,7 +96,23 @@ pub async fn setup_page(
let Some(user) = auth.user().await? else {
return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref())));
};
let known = installations::reachable(user.id, &id).await?;
let mut known = installations::reachable(user.id, &id).await?;
// Back from the sign-in that refreshes their installations: its listing runs after it (`sign_in_sync`), so wait
// for it while it hasn't found this one yet
if q.refreshed.is_some() && !(known && installations::knows_repositories(user.id, &id).await?) {
match sign_in_sync::state(user.id).await? {
State::Syncing => return Ok(waiting_page()),
State::Failed | State::SignInAgain => {
return Ok(page_with(
"Couldn't read your GitHub repositories",
"GitHub didn't list your installations of the VisualCI GitHub App this time.",
None,
Some((&sign_in_url(&id, q.state.as_deref()), "Try again")),
));
}
State::Done => known = installations::reachable(user.id, &id).await?,
}
}
// Reachable only through the `installation` webhook (they installed it): sign in once more for its repositories
if known && q.refreshed.is_none() && !installations::knows_repositories(user.id, &id).await? {
return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref())));
Expand Down Expand Up @@ -142,16 +164,30 @@ pub async fn setup(

/// A one-message page, in the sign-in page's style.
fn page(title: &str, message: &str) -> laravel::http::Response {
page_with(title, message, None, None)
}

/// The page shown while the listing after their sign-in runs: it loads itself again every second.
fn waiting_page() -> laravel::http::Response {
page_with("Finding your GitHub repositories…", "This takes a few seconds.", Some(1), None)
}

/// A one-message page that may load itself again after `refresh` seconds, and may link somewhere other than the app.
fn page_with(title: &str, message: &str, refresh: Option<u32>, link: Option<(&str, &str)>) -> laravel::http::Response {
let esc = |s: &str| s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;");
let refresh = refresh.map_or(String::new(), |s| format!("<meta http-equiv=\"refresh\" content=\"{s}\">"));
let (href, label) = link.unwrap_or(("/", "Go to VisualCI"));
let html = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\"><title>{t} · VisualCI</title><style>body{{font:16px/1.5 \
content=\"width=device-width, initial-scale=1\">{refresh}<title>{t} · 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}}}}\
main{{max-width:34rem}}h1{{font-size:1.25rem;margin:0 0 8px}}p{{margin:0 0 12px}}</style></head><body><main>\
<h1>{t}</h1><p>{m}</p><p><a href=\"/\">Go to VisualCI</a></p></main></body></html>",
<h1>{t}</h1><p>{m}</p><p><a href=\"{h}\">{l}</a></p></main></body></html>",
t = esc(title),
m = esc(message)
m = esc(message),
h = esc(href),
l = esc(label)
);
laravel::http::Response::new(laravel::view::Html::raw(html))
}
Expand Down Expand Up @@ -222,3 +258,21 @@ pub async fn import_progress(
}
Ok(Json(state))
}

/// `POST /api/ui/github/sync`: list what their GitHub sign-in reaches again (the picker's "Try again"). 409 with
/// `sign_in_again` when the token from their sign-in has expired, so they sign in again instead.
pub async fn sync_again(Authenticated(user): Authenticated<User>) -> laravel::Result<laravel::http::Response> {
if crate::forge::github::user_token(user.id).await.is_none() {
return Ok(laravel::http::Response::new(Json(serde_json::json!({
"error": "sign_in_again",
"message": "Sign in with GitHub again to list your repositories",
})))
.with_status(409));
}
let limit = laravel::rate_limit::Limit::per_minute(6);
if laravel::rate_limit::attempt(&format!("github-sync:{}", user.id), limit).await?.is_err() {
return Err(laravel::abort_with(429, "too many tries: try again in a minute"));
}
sign_in_sync::request(user.id).await?;
Ok(laravel::http::Response::new(Json(serde_json::json!({ "sync": "syncing" }))).with_status(202))
}
18 changes: 10 additions & 8 deletions app/src/auth/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> laravel
let complete = steps.last().is_some_and(|(_, done)| *done);
// The person's installations of the App (an offer to set one up that isn't yet), and what setting up this
// organization's installations did (the repositories they couldn't add, and why)
let offers = match &subject {
Some(pid) => {
let user_id: Option<i64> = db::query!("SELECT id FROM users WHERE pid = {pid}::uuid").scalar().await?;
match user_id {
Some(id) => crate::forge::installations::offers(id).await?,
None => Vec::new(),
}
let user_id: Option<i64> = match &subject {
Some(pid) => db::query!("SELECT id FROM users WHERE pid = {pid}::uuid").scalar().await?,
None => None,
};
let (offers, github_sync) = match user_id {
Some(id) => {
(crate::forge::installations::offers(id).await?, crate::forge::sign_in_sync::state(id).await?.as_str())
}
None => Vec::new(),
None => (Vec::new(), "done"),
};
let set_up = db::query!(
"SELECT installation_id, account_login, setup_result::text AS result FROM github_installations \
Expand All @@ -86,6 +86,8 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> laravel
"dismissed": row.try_get::<Option<bool>>("dismissed")?.unwrap_or(false),
"install_url": "/github/install",
"installations": offers,
// How the listing after their last GitHub sign-in is going (`sign_in_sync::State`): the offers above wait for it
"github_sync": github_sync,
"github": set_up,
}))
}
Expand Down
68 changes: 46 additions & 22 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
//! 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.
//! [`SignedUp`] (the domain side gives it its own organization). A GitLab sign-in fires [`SignedIn`] with the
//! repositories the forge says they can reach, for their memberships; a GitHub sign-in redirects at once, and a queued
//! job lists what it reaches and fires it (`forge::sign_in_sync`). The log line `sign-in callback` gives each one's
//! time and GitHub calls.

use laravel::auth::Auth;
use laravel::auth::social::{self, Provider};
Expand Down Expand Up @@ -159,6 +161,8 @@ pub async fn callback(
hosts: laravel::config::Section<crate::config::HostUrls>,
session: Session,
) -> laravel::Result<laravel::http::Response> {
// From GitHub's redirect to ours, the code exchange and `/user` included
let started = std::time::Instant::now();
let provider = provider(&forge)?;
let return_to: Option<String> = session.pull(RETURN_TO);
let linking: bool = session.pull(LINKING).unwrap_or(false);
Expand All @@ -169,36 +173,47 @@ pub async fn callback(
}
Err(e) => return Err(e.into()),
};
let sign_in = match ForgeKind::parse(&forge) {
Some(ForgeKind::Gitlab) => forge::gitlab::sign_in(&gitlab.url, &profile).await?,
_ => forge::github::sign_in(&profile).await?,
let kind = ForgeKind::parse(&forge).unwrap_or(ForgeKind::Github);
// Who they are. A GitHub sign-in reads nothing more here (their verified addresses only when no account has this
// GitHub account yet): what it can reach is listed after it, by a queued job (`forge::sign_in_sync`)
let (identity, gitlab_repositories) = match kind {
ForgeKind::Gitlab => {
let sign_in = forge::gitlab::sign_in(&gitlab.url, &profile).await?;
(sign_in.identity, Some(sign_in.repositories))
}
ForgeKind::Github => {
let mut identity = forge::github::identity(&profile);
if identity_owner(&identity).await?.is_none() {
identity.verified_emails = forge::github::verified_emails(&profile.token.access).await?;
}
(identity, None)
}
};
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.closed() && is_new_person(&sign_in.identity, link_to).await? {
record_waitlist(&sign_in.identity, &via).await?;
return Ok(waitlist_page(&sign_in.identity));
if sign_ups.closed() && is_new_person(&identity, link_to).await? {
record_waitlist(&identity, &via).await?;
return Ok(waitlist_page(&identity));
}
let (user, created) = user_for_sign_in(&sign_in.identity, link_to).await?;
let (user, created) = user_for_sign_in(&identity, link_to).await?;
if created {
SignedUp { user_id: user.id, via: via.clone() }.dispatch().await?;
}
// The GitHub App's installations they can reach, for the setup page and the checklist's offers
if sign_in.identity.forge == ForgeKind::Github {
forge::installations::remember(user.id, &sign_in.installations, &sign_in.reachable).await?;
forge::installations::remember_listings(user.id, &sign_in.listings).await?;
forge::github::remember_user_token(user.id, &profile.token).await;
}
SignedIn {
user_id: user.id,
forge: sign_in.identity.forge,
site: sign_in.identity.site.clone(),
repositories: sign_in.repositories,
match gitlab_repositories {
Some(repositories) => {
SignedIn { user_id: user.id, forge: identity.forge, site: identity.site.clone(), repositories }
.dispatch()
.await?;
}
None => {
// Their token, for the job and the picker's search; then the job lists what it reaches. What an earlier
// sign-in listed stays until it has
forge::github::remember_user_token(user.id, &profile.token).await;
forge::sign_in_sync::request(user.id).await?;
}
}
.dispatch()
.await?;
auth.login(&user).await?;
// 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
Expand All @@ -213,6 +228,15 @@ pub async fn callback(
.unwrap_or_else(|| "/".to_string()),
),
};
tracing::info!(
forge = kind.as_str(),
user_id = user.id,
created,
elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
// Besides the code exchange and `/user`, which the framework's own client makes
github_calls = forge::calls::so_far(),
"sign-in callback"
);
Ok(laravel::http::Response::new(back).with_cookie(signed_in_hint(&hosts, true)))
}

Expand Down
21 changes: 14 additions & 7 deletions app/src/forge/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,36 @@ tokio::task_local! {
/// The most GitHub calls a request may make unless [`BUDGETS`] names it.
pub const DEFAULT_BUDGET: u32 = 5;

/// A sign-in: the person's verified addresses, one page of their installations ([`super::github::SIGN_IN_INSTALLATIONS`])
/// and at most [`super::github::SIGN_IN_REPOSITORY_PAGES`] pages of repositories across them.
pub const SIGN_IN_BUDGET: u32 = 2 + super::github::SIGN_IN_REPOSITORY_PAGES;
/// A sign-in's callback: the person's verified addresses, only when no account has their GitHub account yet. With the
/// code exchange and `/user`, which the framework's client makes uncounted, that's three at most. What they can reach
/// is listed by a queued job after it (`sign_in_sync`; 4 Dec 2026: listing it in the callback took 6.3 s).
pub const SIGN_IN_BUDGET: u32 = 1;

/// The listing after a sign-in (`sign_in_sync`): one page of installations
/// ([`super::github::SIGN_IN_INSTALLATIONS`]) and at most [`super::github::SIGN_IN_REPOSITORY_PAGES`] pages of
/// repositories.
pub const SIGN_IN_SYNC_BUDGET: u32 = 1 + super::github::SIGN_IN_REPOSITORY_PAGES;

/// Linking a repository checks it live (`link::link_repository`): the installation that reaches it, the person's
/// permission (a token, their login, collaborator and permission), its ID, then its visibility and licence
/// (`open_source::refresh`: a token, its path by ID, the repository).
pub const LINK_BUDGET: u32 = 10;

/// Requests allowed more than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and why. Each is
/// still a fixed number, whatever the size of the organization.
/// Requests allowed more (or fewer) than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and
/// why. Each is still a fixed number, whatever the size of the organization.
pub const BUDGETS: &[(&str, &str, u32, &str)] = &[
(
"GET",
"/auth/github/callback",
SIGN_IN_BUDGET,
"a sign-in lists the person's installations and repositories, a page at a time, up to fixed caps",
"a sign-in reads the person's verified addresses when no account has their GitHub account yet; the rest is a \
queued job",
),
("PATCH", "/api/ui/orgs/*/projects/*", LINK_BUDGET, "updating a project may link its repository, checked live"),
("POST", "/mcp", LINK_BUDGET, "the update_project tool may link a repository, checked live"),
];

/// The most GitHub calls `method path` may make, and why when it's more than [`DEFAULT_BUDGET`].
/// The most GitHub calls `method path` may make, and why when [`BUDGETS`] names it.
#[must_use]
pub fn budget(method: &str, path: &str) -> (u32, Option<&'static str>) {
BUDGETS
Expand Down
Loading
Loading