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
1 change: 0 additions & 1 deletion app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ tracing = "0.1"
# 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]
regex = "1"
Expand Down
20 changes: 19 additions & 1 deletion app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ impl Principal {
}

/// Their role in the project's organization, or `None` when they have none. A project token is a member of its
/// own project and nothing else.
/// own project and nothing else, as on today's server: CI uploads and finalizes, and an agent holding the token
/// may review (`review` needs a member).
///
/// # Errors
/// On a database error.
Expand Down Expand Up @@ -183,12 +184,28 @@ impl Principal {
/// On a database error.
pub async fn from_token(token: &str) -> laravel::Result<Option<Self>> {
let hash = token_hash(token);
// When a token was last used, for the tokens pages: written at most once a minute per token, so a busy CI job
// doesn't write on every request
if token.starts_with("vci_") {
let Some(t) = ProjectToken::first_where(ProjectToken::token_hash.eq(&hash)).await? else { return Ok(None) };
let id = t.id;
db::query!(
"UPDATE project_tokens SET last_used_at = now() WHERE id = {id} \
AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute')"
)
.update()
.await?;
return Ok(Some(Self::Project { project_id: t.project_id, token_id: t.id, token_name: t.name }));
}
if token.starts_with("vcu_") {
let Some(t) = UserToken::first_where(UserToken::token_hash.eq(&hash)).await? else { return Ok(None) };
let id = t.id;
db::query!(
"UPDATE user_tokens SET last_used_at = now() WHERE id = {id} \
AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute')"
)
.update()
.await?;
let Some(user) = User::find(t.user_id).await? else { return Ok(None) };
return Ok(Some(Self::User { user: Box::new(user), via: Via::Token { token_id: t.id, name: t.name } }));
}
Expand Down Expand Up @@ -245,5 +262,6 @@ pub fn routes(route: &mut laravel::prelude::Router) {
route.post("/auth/{forge}/link", sign_in::link);
route.get("/auth/{forge}/callback", sign_in::callback);
route.get("/auth/session", sign_in::session);
route.get("/auth/providers", sign_in::providers);
route.post("/auth/logout", sign_in::logout);
}
143 changes: 132 additions & 11 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,16 @@ fn safe_return(to: &str) -> Option<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 = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
pub async fn login_page(apps: laravel::config::Section<ForgeApps>) -> laravel::http::Response {
let forges = apps.forges();
let gitlab =
if forges.contains(&"gitlab") { "<p><a href=\"/auth/gitlab\">Sign in with GitLab</a></p>" } else { "" };
let head = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\"><title>Sign in · 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}}\
p{margin:0 0 8px}</style></head><body><main><p><a href=\"/auth/github\">Sign in with GitHub</a></p>\
<p><a href=\"/auth/gitlab\">Sign in with GitLab</a></p></main></body></html>";
p{margin:0 0 8px}</style></head><body><main><p><a href=\"/auth/github\">Sign in with GitHub</a></p>";
let page = format!("{head}{gitlab}</main></body></html>");
laravel::http::Response::new(laravel::view::Html::raw(page))
}

Expand Down Expand Up @@ -113,6 +116,7 @@ pub async fn callback(
auth: Auth<User>,
sign_ups: laravel::config::Section<SignUps>,
gitlab: laravel::config::Section<forge::gitlab::GitlabConfig>,
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
session: Session,
) -> laravel::Result<laravel::http::Response> {
let provider = provider(&forge)?;
Expand Down Expand Up @@ -158,20 +162,137 @@ pub async fn callback(
// needs a route for its fallback)
None => Redirect::to(session.pull::<String>("url.intended").unwrap_or_else(|| "/".to_string())),
};
Ok(laravel::http::Response::new(back))
Ok(laravel::http::Response::new(back).with_cookie(signed_in_hint(&hosts, true)))
}

/// `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>> {
/// "Sign in"): the name and avatar for the button, and the organization when there's just one, so the button goes
/// straight to it. The site reads it with credentials, so it answers CORS for the site's own origin alone
/// (`VISUALCI_SITE_URL`, exactly), never a reflected one, and is never cached.
pub async fn session(
auth: Auth<User>,
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
headers: axum::http::HeaderMap,
) -> laravel::Result<laravel::http::Response> {
let user = auth.user().await?;
Ok(Json(serde_json::json!({ "signed_in": user.is_some(), "name": user.map(|u| u.name) })))
// The site's hint follows the answer: renewed while signed in, cleared once the session has gone.
let hinted = headers
.get_all(axum::http::header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.any(|c| c.trim() == format!("{SIGNED_IN_HINT}=1"));
let hint = match (&user, hinted) {
(Some(_), _) => Some(signed_in_hint(&hosts, true)),
(None, true) => Some(signed_in_hint(&hosts, false)),
(None, false) => None,
};
let body = match user {
Some(user) => {
let user_id = user.id;
let orgs = db::query!(
"SELECT o.slug FROM organizations o JOIN memberships m ON m.organization_id = o.id \
WHERE m.user_id = {user_id} ORDER BY o.slug LIMIT 2"
)
.select_as::<String>()
.await
.unwrap_or_default();
let org = (orgs.len() == 1).then(|| orgs[0].clone());
serde_json::json!({ "signed_in": true, "name": user.name, "avatar_url": user.avatar_url, "org": org })
}
None => serde_json::json!({ "signed_in": false }),
};
let mut response = laravel::http::Response::new(Json(body))
.with_header("cache-control", "no-store")
.with_header("vary", "Origin, Cookie");
if let Some(hint) = hint {
response = response.with_cookie(hint);
}
let site = hosts.site.as_deref().map(|s| s.trim_end_matches('/').to_string());
if let (Some(origin), Some(site)) = (headers.get(axum::http::header::ORIGIN).and_then(|o| o.to_str().ok()), site)
&& origin == site
{
response = response
.with_header("access-control-allow-origin", origin.to_string())
.with_header("access-control-allow-credentials", "true");
}
Ok(response)
}

/// `POST /auth/logout`.
pub async fn logout(auth: Auth<User>) -> laravel::Result<Json<serde_json::Value>> {
/// The forges a person can sign in with here: those whose OAuth application is configured.
#[derive(Clone, laravel::config::Section)]
pub struct ForgeApps {
#[env("GITHUB_CLIENT_ID")]
pub github: Option<String>,
#[env("GITHUB_CLIENT_SECRET")]
pub github_secret: Option<String>,
#[env("GITLAB_CLIENT_ID")]
pub gitlab: Option<String>,
#[env("GITLAB_CLIENT_SECRET")]
pub gitlab_secret: Option<String>,
}

impl ForgeApps {
/// The forges whose OAuth application has both its ID and its secret.
#[must_use]
pub fn forges(&self) -> Vec<&'static str> {
let set = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.trim().is_empty());
let mut forges = Vec::new();
if set(&self.github) && set(&self.github_secret) {
forges.push("github");
}
if set(&self.gitlab) && set(&self.gitlab_secret) {
forges.push("gitlab");
}
forges
}
}

/// `GET /auth/providers`: the sign-in buttons the web app shows.
pub async fn providers(apps: laravel::config::Section<ForgeApps>) -> Json<serde_json::Value> {
Json(serde_json::json!({ "forges": apps.forges(), "dev_login": false }))
}

/// `POST /auth/logout`: the session ends, and so does the site's hint.
pub async fn logout(
auth: Auth<User>,
hosts: laravel::config::Section<crate::http::hosts::HostUrls>,
) -> laravel::Result<laravel::http::Response> {
auth.logout().await?;
Ok(Json(serde_json::json!({ "ok": true })))
Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, false)))
}

/// The cookie visualci.com's static pages read to show "Open app" instead of "Sign in": `1` while signed in. It says
/// nothing else, so it's readable by the site's script (not `HttpOnly`) and not encrypted (`EncryptCookies` passes it
/// through). On the site's domain when the app is one of its subdomains (`Domain=visualci.com`), host-only otherwise.
pub const SIGNED_IN_HINT: &str = "vci_signed_in";
/// How long the hint lasts: today's session's 30 days, renewed by every `/auth/session`.
const HINT_DAYS: i64 = 30;

/// The hint, set (`on`) or cleared.
pub fn signed_in_hint(hosts: &crate::http::hosts::HostUrls, on: bool) -> laravel::cookie::Cookie {
use laravel::time::ToSpan;
let host = |url: &Option<String>| {
let url = url.as_deref()?.trim();
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let host = rest.split(['/', ':']).next()?.to_ascii_lowercase();
(!host.is_empty()).then_some(host)
};
let domain = match (host(&hosts.site), host(&hosts.app)) {
(Some(site), Some(app)) if app.ends_with(&format!(".{site}")) => Some(site),
_ => None,
};
let production = laravel::config().app.env.is_production();
let mut cookie = laravel::cookie::Cookie::new(SIGNED_IN_HINT, if on { "1" } else { "" })
.path("/")
.http_only(false)
.secure(production)
.same_site(laravel::cookie::SameSite::Lax)
.max_age(if on { HINT_DAYS.days() } else { 0.seconds() });
if let Some(domain) = domain {
cookie = cookie.domain(domain);
}
cookie
}

/// The MCP client an authorization's return address names (`/oauth/authorize?client_id=…`).
Expand Down
2 changes: 2 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub fn configure() -> ApplicationBuilder {
})
.with_middleware(|middleware, _| {
middleware.prepend(http::hosts::route_by_host);
// The site's signed-in hint is read by its script: plain, not encrypted
middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT]));
})
.with_routing(|routing, _| {
routing.web(auth::routes).api(http::api::routes).health("/up");
Expand Down
5 changes: 5 additions & 0 deletions app/tests/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ async fn tokens_name_their_user_or_project(app: Application) -> laravel::Result<
.assert_ok()
.assert_json_path("principal.project_id", docs_id)
.assert_json_path("client.source", "project_token");
let used: Option<bool> =
db::query!("SELECT last_used_at IS NOT NULL FROM project_tokens WHERE token_hash = {jh}").scalar().await?;
assert_eq!(used, Some(true), "a token's use is recorded");
app.get("/api/v1/whoami").header("authorization", "Bearer vci_nope").await.assert_status(401);
app.get("/api/v1/whoami").await.assert_status(401);
Ok(())
Expand All @@ -77,6 +80,8 @@ async fn roles_come_from_memberships_and_a_project_token_is_a_member_of_its_proj
assert!(!ada.can(Role::Admin, &mine).await?);
assert!(!ada.can(Role::Read, &theirs).await?);

// As on today's server: a project token is a member of its own project, so CI (or an agent with the token) can
// upload, finalize and review, but not change settings
let ci = Principal::Project { project_id: mine.id, token_id: 1, token_name: "CI".into() };
assert!(ci.can(Role::Member, &mine).await? && !ci.can(Role::Admin, &mine).await?);
let sibling = ProjectRef { id: mine.id + 1000, organization_id: acme.id };
Expand Down
67 changes: 66 additions & 1 deletion app/tests/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ async fn a_new_person_gets_an_account_and_returns_where_they_started(app: Applic
start.assert_redirect();
let done = app.get("/auth/github/callback").with_cookies_from(&start).await;
done.assert_redirect_to("/acme/web/builds/3");
// The site's hint: plain, so its script can read it
done.assert_cookie("vci_signed_in", "1");

let user = User::first_where(User::email.eq("ada@example.com")).await?.expect("an account");
assert_eq!(user.name, "Ada Lovelace");
Expand Down Expand Up @@ -215,8 +217,71 @@ async fn an_mcp_client_finds_the_oauth_server_and_its_consent_page_asks_for_sign
app.get("/.well-known/oauth-authorization-server")
.await
.assert_ok()
.assert_json_path("authorization_endpoint", "http://localhost/oauth/authorize");
.assert_json_path("authorization_endpoint", "https://app.visualci.test/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");
}

fn with_site() -> Application {
app::testing::configure().with_env("VISUALCI_SITE_URL", "https://visualci.test").create()
}

#[laravel::test(app = with_site)]
async fn the_session_answers_cors_for_the_site_alone(app: Application) {
let site = app.get("/auth/session").header("origin", "https://visualci.test").await;
site.assert_ok().assert_header("access-control-allow-origin", "https://visualci.test");
site.assert_header("access-control-allow-credentials", "true");
let outside = app.get("/auth/session").header("origin", "https://evil.example").await;
outside.assert_ok().assert_header_missing("access-control-allow-origin");
}

fn with_github() -> Application {
app::testing::configure().with_envs([("GITHUB_CLIENT_ID", "id"), ("GITHUB_CLIENT_SECRET", "secret")]).create()
}

#[laravel::test(app = with_github)]
async fn providers_are_the_configured_forges(app: Application) {
app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": ["github"], "dev_login": false }));
}

fn with_site_and_app() -> Application {
app::testing::configure()
.with_envs([("VISUALCI_SITE_URL", "https://visualci.test"), ("VISUALCI_APP_URL", "https://app.visualci.test")])
.create()
}

#[laravel::test(app = with_site_and_app)]
async fn the_sites_hint_follows_the_session(app: Application) -> laravel::Result<()> {
// A hint left over from a session that has gone is cleared; no hint and no session sends none.
app.get("/auth/session").cookie("vci_signed_in", "1").await.assert_ok().assert_cookie_expired("vci_signed_in");
app.get("/auth/session").await.assert_ok().assert_cookie_missing("vci_signed_in");
let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?;
let renewed = app.get("/auth/session").acting_as(&ada).await;
renewed.assert_ok().assert_cookie("vci_signed_in", "1");
assert!(
renewed
.headers()
.get_all("set-cookie")
.iter()
.any(|v| v.to_str().unwrap_or("").contains("Domain=visualci.test")),
"shared with the site's domain"
);
app.post("/auth/logout")
.acting_as(&ada)
.header("sec-fetch-site", "same-origin")
.await
.assert_ok()
.assert_cookie_expired("vci_signed_in");
Ok(())
}

fn with_github_id_only() -> Application {
app::testing::configure().with_envs([("GITHUB_CLIENT_ID", "id"), ("GITLAB_CLIENT_ID", "id")]).create()
}

#[laravel::test(app = with_github_id_only)]
async fn a_forge_without_its_secret_is_not_offered(app: Application) {
app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": [], "dev_login": false }));
app.get("/login").await.assert_ok().assert_dont_see("GitLab");
}
Loading