diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 76d33968..cc99e4d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -244,6 +244,83 @@ jobs: path: tmp/visual retention-days: 7 + # The journeys (scripts/journeys/run.sh): VisualCI as production runs it, on four .test hosts behind Caddy with + # TLS and a GitHub stub, clicked through in a browser. Each step's screenshot goes to VisualCI as the `journeys` + # build (its own check, "VisualCI: journeys"). + journeys: + runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} + environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} + timeout-minutes: 30 + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: loco + POSTGRES_PASSWORD: loco + POSTGRES_DB: visualci_journeys + ports: ["55433:5432"] + options: --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10 + env: + VISUALCI_SITE_URL: https://visualci.test + VISUALCI_APP_URL: https://app.visualci.test + VISUALCI_API_URL: https://api.visualci.test + VISUALCI_MCP_URL: https://mcp.visualci.test + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 101 + - run: echo "127.0.0.1 visualci.test app.visualci.test api.visualci.test mcp.visualci.test github.test" | sudo tee -a /etc/hosts + - run: | + docker run -d --name s3 -p 59000:9000 \ + -e RUSTFS_ACCESS_KEY=visualci -e RUSTFS_SECRET_KEY=visualci-dev-secret rustfs/rustfs:1.0.6 + for _ in $(seq 1 30); do curl -s -o /dev/null http://127.0.0.1:59000/ && break; sleep 1; done + - uses: kunobi-ninja/kache-action@061011817fd04b0e460f79d6bb3c115b1fc8f029 # v1 + with: + version: "2.4.0" + cache-key-prefix: kache-${{ github.job }} + save-cache: ${{ github.ref == 'refs/heads/main' }} + pr-comment: false + s3-bucket: ${{ vars.KACHE_BUCKET }} + s3-endpoint: ${{ vars.KACHE_ENDPOINT }} + s3-region: auto + s3-prefix: visualci + s3-access-key-id: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_ACCESS_KEY_ID || secrets.KACHE_RO_ACCESS_KEY_ID }} + s3-secret-access-key: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_SECRET_ACCESS_KEY || secrets.KACHE_RO_SECRET_ACCESS_KEY }} + - run: cargo build --locked -p visualci-cli + - run: cargo build --locked --bin visualci-app + working-directory: app + - uses: pnpm/action-setup@v4 + with: + package_json_file: server/frontend/package.json + - uses: actions/setup-node@v4 + with: + node-version: "24" + # The site and the app's page, built for the .test hosts (scripts/hosts.mjs reads VISUALCI_*_URL) + - run: pnpm install --frozen-lockfile && pnpm build && node scripts/site.mjs + working-directory: server/frontend + env: + GITHUB_TOKEN: ${{ github.token }} + - run: pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium + working-directory: scripts/screenshots + - run: scripts/journeys/run.sh + env: + DATABASE_URL: postgres://loco:loco@127.0.0.1:55433/visualci_journeys + # The screenshots go up even when a journey failed: its last one shows where it stopped. + - if: ${{ !cancelled() }} + uses: ./clients/github-action + with: + token: ${{ secrets.VISUALCI_TOKEN }} + cli: target/debug/visualci + name: journeys + upload: | + tmp/journeys/screenshots --prefix journeys/ --platform chrome-linux + - if: failure() + uses: actions/upload-artifact@v4 + with: + name: journeys + path: tmp/journeys + retention-days: 7 + clients: runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index dc84328e..073be0d0 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -175,7 +175,7 @@ pub async fn callback( 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? { + 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)); } @@ -435,10 +435,33 @@ fn mcp_client(return_to: &str) -> Option { } /// Sign-ups: closed (`VISUALCI_WAITLIST=true`) until VisualCI opens, when someone new goes on the waitlist instead. +/// Production sets it explicitly, either way, or refuses to boot ([`SignUps::check`]): a dropped setting would open +/// sign-ups by surprise. Elsewhere it's open unless set. #[derive(Clone, laravel::config::Section)] pub struct SignUps { - #[env("VISUALCI_WAITLIST", default = false)] - pub waitlist: bool, + #[env("VISUALCI_WAITLIST")] + waitlist: Option, +} + +impl SignUps { + /// Whether someone new goes on the waitlist instead of getting an account. + #[must_use] + pub fn closed(&self) -> bool { + self.waitlist.unwrap_or(false) + } + + /// Boot check: production says whether sign-ups are open. + /// + /// # Errors + /// In production, when `VISUALCI_WAITLIST` isn't set. + pub fn check(&self, production: bool) -> laravel::Result<()> { + if production && self.waitlist.is_none() { + return Err(laravel::Error::msg( + "VISUALCI_WAITLIST isn't set: production needs it explicitly (true keeps sign-ups closed, false opens them)", + )); + } + Ok(()) + } } /// The user who owns this forge identity, if anyone. diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs index b0dcb84f..db2dd42a 100644 --- a/app/src/forge/github.rs +++ b/app/src/forge/github.rs @@ -8,7 +8,9 @@ use serde_json::Value; use super::{ForgeKind, Identity, Permission, Repository, SignIn}; -const API: &str = "https://api.github.com"; +fn api() -> String { + super::github_api() +} /// Everything a GitHub sign-in learns, from the profile Laravel's social login fetched and the person's token. /// @@ -41,7 +43,7 @@ async fn verified_emails(token: &str) -> laravel::Result> { primary: bool, verified: bool, } - let response = client::get(format!("{API}/user/emails")).token(token).accept_json().await?; + let response = client::get(format!("{}/user/emails", api())).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()); @@ -74,7 +76,7 @@ async fn repositories(token: &str) -> laravel::Result laravel::Result> { let mut items = Vec::new(); for page in 1..=50 { - let response = client::get(format!("{API}{path}")) + let response = client::get(format!("{}{path}", api())) .token(token) .accept_json() .query([("per_page", 100), ("page", page)]) diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index be3c22ef..e5dac173 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -7,7 +7,9 @@ use serde_json::Value; use super::Permission; -const API: &str = "https://api.github.com"; +fn api() -> String { + super::github_api() +} /// The App (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`: its PEM key, base64-encoded to fit one line) and its /// webhook's secret (`GITHUB_WEBHOOK_SECRET`). Without the secret, the webhook answers 404. @@ -83,7 +85,7 @@ fn app_jwt(app: &GithubApp) -> laravel::Result { /// GET a GitHub API path as JSON; `None` on 404. async fn get(token: &str, path: &str) -> laravel::Result> { - let response = client::get(format!("{API}{path}")) + let response = client::get(format!("{}{path}", api())) .token(token) .header("accept", "application/vnd.github+json") .header("user-agent", "visualci") @@ -102,7 +104,7 @@ async fn get(token: &str, path: &str) -> laravel::Result> { /// # Errors /// When the App isn't configured, or GitHub refuses its credentials. pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result { - let response = client::post(format!("{API}/app/installations/{installation}/access_tokens")) + let response = client::post(format!("{}/app/installations/{installation}/access_tokens", api())) .token(app_jwt(app)?) .header("accept", "application/vnd.github+json") .header("user-agent", "visualci") @@ -126,7 +128,10 @@ pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result String { + format!("{}/apps/visualci-com/installations/new", super::github_web()) +} /// The App's installation that reaches a repository (`owner/name`), if it's installed there. /// @@ -158,7 +163,7 @@ pub const RATE_LIMIT_RESERVE: i64 = 500; pub async fn collaborators(token: &str, repo: &str) -> laravel::Result> { let mut out = Vec::new(); for page in 1..=50 { - let response = client::get(format!("{API}/repos/{repo}/collaborators")) + let response = client::get(format!("{}/repos/{repo}/collaborators", api())) .token(token) .header("accept", "application/vnd.github+json") .header("user-agent", "visualci") @@ -288,7 +293,7 @@ pub async fn permission( let Some(user) = get(&token, &format!("/user/{id}")).await? else { return Ok(None) }; let Some(login) = user["login"].as_str() else { return Ok(None) }; // 204 when they're a collaborator (directly, through a team, or by the organization's base permission), 404 not - let collaborator = client::get(format!("{API}/repos/{repo}/collaborators/{login}")) + let collaborator = client::get(format!("{}/repos/{repo}/collaborators/{login}", api())) .token(&token) .header("accept", "application/vnd.github+json") .header("user-agent", "visualci") diff --git a/app/src/forge/link.rs b/app/src/forge/link.rs index 929387d4..e98f514e 100644 --- a/app/src/forge/link.rs +++ b/app/src/forge/link.rs @@ -78,7 +78,7 @@ pub async fn link_repository( return Err(bad(format!( "VisualCI can't reach {} on {label} yet: install the VisualCI GitHub App on it at {}, then link it", repository.path, - github_app::INSTALL_URL + github_app::install_url() ))); }; let forge_user = identity("").await?.ok_or_else(|| signed_out(label, &repository))?; diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index aee525e7..3020d40f 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -90,6 +90,41 @@ pub struct Repository { /// trailing slash: `https://gitlab.example.com`, `http://docspring-dev.hs:5196`). static GITLAB_INSTANCES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); +/// GitHub's web address: the framework's `GITHUB_URL` (its social login signs in there), github.com unless the +/// journeys point it at their stub (refused in production, [`check_github`]). +#[must_use] +pub fn github_web() -> String { + laravel::config().social.github_url.trim().trim_end_matches('/').to_string() +} + +/// GitHub's API, as the framework's social login finds it: api.github.com for github.com, else the server's `/api/v3`. +#[must_use] +pub fn github_api() -> String { + let web = github_web(); + if web.eq_ignore_ascii_case("https://github.com") { + "https://api.github.com".to_string() + } else { + format!("{web}/api/v3") + } +} + +/// Boot check: only testing and local may point `GITHUB_URL` anywhere but github.com (the journeys' GitHub stub), so +/// production can never sign people in against another server. +/// +/// # Errors +/// When `GITHUB_URL` isn't github.com outside testing and local. +pub fn check_github(config: &laravel::config::Config) -> laravel::Result<()> { + let web = config.social.github_url.trim().trim_end_matches('/'); + let development = + matches!(config.app.env, laravel::config::app::Environment::Local | laravel::config::app::Environment::Testing); + if web.eq_ignore_ascii_case("https://github.com") || development { + return Ok(()); + } + Err(laravel::Error::msg(format!( + "GITHUB_URL is {web}: only testing and local may use a GitHub other than github.com" + ))) +} + /// 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(); diff --git a/app/src/forge/outbound.rs b/app/src/forge/outbound.rs index da89713d..8a6cb1fe 100644 --- a/app/src/forge/outbound.rs +++ b/app/src/forge/outbound.rs @@ -102,8 +102,8 @@ fn trusted(base: &str) -> bool { let base = base.trim_end_matches('/'); let gitlab = laravel::config().get::().map(|g| g.url.trim_end_matches('/').to_string()); - base.eq_ignore_ascii_case("https://api.github.com") - || base.eq_ignore_ascii_case("https://github.com") + base.eq_ignore_ascii_case(&super::github_api()) + || base.eq_ignore_ascii_case(&super::github_web()) || gitlab.is_some_and(|g| base.eq_ignore_ascii_case(&g)) } diff --git a/app/src/forge/report.rs b/app/src/forge/report.rs index 7f1e63a2..20809fc8 100644 --- a/app/src/forge/report.rs +++ b/app/src/forge/report.rs @@ -11,7 +11,9 @@ use super::outbound::{self, Reply}; use super::{ForgeKind, Repository}; use crate::models::Project; -const GITHUB: &str = "https://api.github.com"; +fn github() -> String { + super::github_api() +} /// A check on a pull request's commit. #[derive(Debug, Clone, PartialEq, Eq)] @@ -166,13 +168,13 @@ pub async fn report_check( Target::Github { app, installation } => { let token = github_app::installation_token(app, installation).await?; let request = match existing { - Some(id) => client::patch(format!("{GITHUB}/repos/{path}/check-runs/{id}")), - None => client::post(format!("{GITHUB}/repos/{path}/check-runs")), + Some(id) => client::patch(format!("{}/repos/{path}/check-runs/{id}", github())), + None => client::post(format!("{}/repos/{path}/check-runs", github())), }; let request = request.token(token).header("accept", "application/vnd.github+json").header("user-agent", "visualci"); let request = request.json(github_check_run(check)); - let reply = outbound::exchange(request, GITHUB).await?; + let reply = outbound::exchange(request, &github()).await?; if !reply.successful() { return Err(refused("GitHub check run", &reply)); } @@ -221,8 +223,8 @@ pub async fn upsert_comment( let (token, comments, one, what) = match target { Target::Github { app, installation } => ( github_app::installation_token(app, installation).await?, - format!("{GITHUB}/repos/{path}/issues/{pr_number}/comments"), - format!("{GITHUB}/repos/{path}/issues/comments"), + format!("{}/repos/{path}/issues/{pr_number}/comments", github()), + format!("{}/repos/{path}/issues/comments", github()), "GitHub PR comment", ), Target::Gitlab { base, token } => { @@ -231,7 +233,7 @@ pub async fn upsert_comment( } }; let (github, base) = match target { - Target::Github { .. } => (true, GITHUB.to_string()), + Target::Github { .. } => (true, github()), Target::Gitlab { base, .. } => (false, base.clone()), }; let send = async |request: client::PendingRequest, body: Option<&str>| { diff --git a/app/src/http/app_shell.rs b/app/src/http/app_shell.rs index 0950eacc..a05e3d49 100644 --- a/app/src/http/app_shell.rs +++ b/app/src/http/app_shell.rs @@ -49,13 +49,51 @@ pub async fn app_shell( .await .map_err(|_| laravel::abort(404))?, }; + let html = if configured { with_hosts(&html, &hosts) } else { html }; Ok(laravel::http::Response::new(laravel::view::Html::raw(html)).with_header("cache-control", "no-cache")) } +/// The page with the four hosts as meta tags after its ``, which the frontend reads +/// (server/frontend/src/lib/hosts.ts; the site's prerendered pages get the same tags from scripts/hosts.mjs). Meta +/// tags change none of the script hashes the security policy was built from. +#[must_use] +pub fn with_hosts(html: &str, hosts: &HostUrls) -> String { + let attribute = |v: &str| v.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">"); + let tags: String = [("site", &hosts.site), ("app", &hosts.app), ("api", &hosts.api), ("mcp", &hosts.mcp)] + .into_iter() + .map(|(name, url)| { + let url = url.as_deref().unwrap_or_default().trim().trim_end_matches('/'); + format!("", attribute(url)) + }) + .collect(); + let lower = html.to_ascii_lowercase(); + match lower.find("').map(|end| at + end + 1)) { + Some(after) => format!("{}{tags}{}", &html[..after], &html[after..]), + None => html.replacen("", &format!("{tags}"), 1), + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn the_page_carries_the_hosts_after_its_charset() { + let hosts = HostUrls { + site: Some("https://visualci.test".into()), + app: Some("https://app.visualci.test/".into()), + api: Some("https://api.visualci.test".into()), + mcp: Some("https://mcp.visualci.test\">