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
77 changes: 77 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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' || '' }}
Expand Down
29 changes: 26 additions & 3 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down Expand Up @@ -435,10 +435,33 @@ fn mcp_client(return_to: &str) -> Option<String> {
}

/// 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<bool>,
}

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.
Expand Down
8 changes: 5 additions & 3 deletions app/src/forge/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -41,7 +43,7 @@ async fn verified_emails(token: &str) -> laravel::Result<Vec<String>> {
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());
Expand Down Expand Up @@ -74,7 +76,7 @@ async fn repositories(token: &str) -> laravel::Result<Vec<(Repository, Permissio
async fn all_pages(token: &str, path: &str, key: &str) -> laravel::Result<Vec<Value>> {
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)])
Expand Down
17 changes: 11 additions & 6 deletions app/src/forge/github_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -83,7 +85,7 @@ fn app_jwt(app: &GithubApp) -> laravel::Result<String> {

/// GET a GitHub API path as JSON; `None` on 404.
async fn get(token: &str, path: &str) -> laravel::Result<Option<Value>> {
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")
Expand All @@ -102,7 +104,7 @@ async fn get(token: &str, path: &str) -> laravel::Result<Option<Value>> {
/// # Errors
/// When the App isn't configured, or GitHub refuses its credentials.
pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result<String> {
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")
Expand All @@ -126,7 +128,10 @@ pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result<b
}

/// Where people install the App on their repositories.
pub const INSTALL_URL: &str = "https://github.com/apps/visualci-com/installations/new";
#[must_use]
pub fn install_url() -> 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.
///
Expand Down Expand Up @@ -158,7 +163,7 @@ pub const RATE_LIMIT_RESERVE: i64 = 500;
pub async fn collaborators(token: &str, repo: &str) -> laravel::Result<Vec<(String, Permission)>> {
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")
Expand Down Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion app/src/forge/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))?;
Expand Down
35 changes: 35 additions & 0 deletions app/src/forge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,41 @@ pub struct Repository {
/// trailing slash: `https://gitlab.example.com`, `http://docspring-dev.hs:5196`).
static GITLAB_INSTANCES: std::sync::RwLock<Vec<String>> = 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();
Expand Down
4 changes: 2 additions & 2 deletions app/src/forge/outbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ fn trusted(base: &str) -> bool {
let base = base.trim_end_matches('/');
let gitlab =
laravel::config().get::<super::gitlab::GitlabConfig>().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))
}

Expand Down
16 changes: 9 additions & 7 deletions app/src/forge/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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));
}
Expand Down Expand Up @@ -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 } => {
Expand All @@ -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>| {
Expand Down
38 changes: 38 additions & 0 deletions app/src/http/app_shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<meta charset>`, 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('&', "&amp;").replace('"', "&quot;").replace('<', "&lt;").replace('>', "&gt;");
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!("<meta name=\"visualci-{name}-url\" content=\"{}\" />", attribute(url))
})
.collect();
let lower = html.to_ascii_lowercase();
match lower.find("<meta charset").and_then(|at| html[at..].find('>').map(|end| at + end + 1)) {
Some(after) => format!("{}{tags}{}", &html[..after], &html[after..]),
None => html.replacen("<head>", &format!("<head>{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\"><script>".into()),
};
let page = with_hosts("<!doctype html><html><head><meta charset=\"UTF-8\" /><title>x</title>", &hosts);
assert!(page.starts_with(
"<!doctype html><html><head><meta charset=\"UTF-8\" /><meta name=\"visualci-site-url\" \
content=\"https://visualci.test\" /><meta name=\"visualci-app-url\" content=\"https://app.visualci.test\" />"
));
assert!(page.contains("content=\"https://mcp.visualci.test&quot;&gt;&lt;script&gt;\""), "{page}");
assert!(page.ends_with("<title>x</title>"));
}

#[test]
fn file_paths_are_told_apart_from_pages() {
for page in ["/", "/docspring/billing", "/account", "/docs.html", "/a.b/c"] {
Expand Down
2 changes: 2 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ pub fn configure() -> ApplicationBuilder {
config.app.env.is_production(),
)?;
http::hosts::check(config.section::<http::hosts::HostUrls>(), config.app.env.is_production())?;
forge::check_github(config)?;
config.section::<auth::sign_in::SignUps>().check(config.app.env.is_production())?;
billing::check(config.section::<billing::Stripe>(), config.app.env.is_production())?;
http::security::check(config, config.app.env.is_production())?;
config.section::<auth::sign_in::DevLogin>().check(&config.app.env)?;
Expand Down
Loading
Loading