diff --git a/docs/coder-loop.md b/docs/coder-loop.md index c5d4c2995..088c79697 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -142,6 +142,22 @@ The causes were in the loop, not only in prompt wording: run) is judged again with what it found, even when it wrote no code (`proof::round_answered`, `incidents::cn_proof_answer_judged`). + **The preview, wherever it is published.** The head commit's preview is + found where the team's host or CI already publishes it, never only from + a workflow CoderHelm recognizes (`preview_find`): the commit's + deployments and their newest status, deploy statuses, preview checks, + bot comments (edited in place, read row by row for a monorepo), a + description link, then the team's address template (Settings, + Repositories, Preview access; `{pr}`, `{branch}`, `{branch_slug}`, + `{sha}`, `{short_sha}`). Only what is tied to the head commit counts + first; the changed app's preview is picked when several apps publish + one; a preview still building is waited on, looked at every two minutes, + for at most an hour (`preview::settle`). A protected preview is opened + with the one secret the team saved there (a header, a query parameter or + a password), sealed, handed to the sandbox once and sent only to the + preview's own host (`preview_access`); a sign-in wall is said with where + to give that access. + **Two ways, end to end.** Before the pull request is called done, once its preview is up and its own end-to-end checks passed, the pull request watch runs each criterion's test (the one the criteria map names, else a diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 7c773dc64..bdfcb1d20 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -212,6 +212,8 @@ pub mod pr_steps; /// A repository's pull request template as the description's structure. pub mod pr_template; pub mod preview; +pub mod preview_access; +pub mod preview_find; /// What a fix must show before it is committed and pushed. pub mod push_gate; /// A bug reproduced on the base before code is planned, fixed in the diff --git a/services/common/src/preview.rs b/services/common/src/preview.rs index 5544cacaa..c7fa8342b 100644 --- a/services/common/src/preview.rs +++ b/services/common/src/preview.rs @@ -32,6 +32,9 @@ //! - [`routes`] picks the pages to capture from the repository's page files //! and the changed paths; [`capture_script`] is the sandbox script that //! captures them. +//! - Where the preview is and whether it is up for the head commit is +//! `crate::preview_find`'s: deployments, statuses, checks, bot comments, +//! the description and the team's address template, tied to the head. //! - [`State`] is what the run records ([`FIELD`]) and the description and //! the run page read. @@ -683,6 +686,15 @@ pub struct State { /// says (`crate::e2e::failure_read`), with whether this change caused /// it. pub failures: Vec, + /// Where the preview's address came from (`crate::preview_find`). + pub found: crate::preview_find::Found, + /// When this head's preview was first waited on (RFC 3339): the wait is + /// bounded by `preview_find::WAIT_BUDGET_MINS`. + pub waiting_since: String, + /// When the preview was last looked at (RFC 3339): a pending preview is + /// looked at again every `preview_find::POLL_SECS` even when nothing + /// else on the pull request changed. + pub looked_at: String, } impl State { @@ -740,41 +752,6 @@ pub fn progress(results: &[CheckResult], triggered: bool) -> Stage { Stage::Triggered } -/// A preview address in text (a check's output, a deployment, a comment): -/// the first https URL whose host names a preview. -pub fn url_in(text: &str) -> Option { - for (i, _) in text.match_indices("https://") { - let rest = &text[i..]; - let end = rest - .find(|c: char| { - c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | '<' | ']' | '`') - }) - .unwrap_or(rest.len()); - let url = rest[..end].trim_end_matches(['.', ',', ';']); - let host = url["https://".len()..].split('/').next().unwrap_or(""); - if host.to_ascii_lowercase().contains("preview") && !host.contains('@') { - return Some(url.to_string()); - } - } - None -} - -/// The preview address from the head's deployments: (environment, url) -/// pairs, a preview environment first, never a shared one. -pub fn url_from_deployments(deps: &[(String, String)]) -> Option { - let ok = |(env, url): &&(String, String)| { - url.starts_with("https://") && !is_shared_env_label(env) && role_of(env) != Role::Production - }; - deps.iter() - .filter(ok) - .find(|(env, url)| { - env.to_ascii_lowercase().contains("preview") - || url.to_ascii_lowercase().contains("preview") - }) - .or_else(|| deps.iter().find(ok)) - .map(|(_, u)| u.clone()) -} - // ── end-to-end specs ─────────────────────────────────────────────────────── /// The repository's end-to-end suite: the folder its runner's config is in. @@ -1115,12 +1092,37 @@ pub fn shot_name(page: &str, width: &str) -> String { format!("{slug}-{width}") } +/// The address pages are captured under: the preview's address without +/// its query or fragment and without a trailing `/`, its path kept (a +/// preview served under a path, `https://host/pr-12/`, keeps it). +pub fn capture_base(url: &str) -> String { + url.split(['?', '#']) + .next() + .unwrap_or(url) + .trim_end_matches('/') + .to_string() +} + +/// How long the capture waits between tries of a page that is still +/// warming up (404, 502, 503 or 504 on a fresh preview), and how many +/// tries it makes. +pub const WARM_TRIES: u32 = 3; +pub const WARM_WAIT_MS: u32 = 15_000; + /// The sandbox script that captures each page at both widths. It writes /// each image base64-encoded (`.png.b64`) and `shots.json` (each -/// page's status and title) to `$CODERHELM_OUT`; a page that doesn't load -/// is recorded with its status, never retried into a pass. -pub fn capture_script(base: &str, pages: &[String]) -> String { - let base = base.trim_end_matches('/'); +/// page's status, title and, when the browser was sent to another host, +/// that host) to `$CODERHELM_OUT`. A page still warming up is tried +/// [`WARM_TRIES`] times; one that doesn't load is recorded with its status, +/// never retried into a pass. +/// +/// `access` is how the preview is protected (`crate::preview_access`). Its +/// secret is never in the script: the sandbox hands the script its one-time +/// secret in `GH_TOKEN` (the channel every sandbox script's secret takes), +/// the script removes it from its environment at once, sends it only to the +/// preview's own host, and blanks it out of anything it writes. +pub fn capture_script(base: &str, pages: &[String], access: crate::preview_access::Kind) -> String { + let base = capture_base(base); let mut jobs = Vec::new(); for p in pages { for (width, (w, h)) in [("desktop", DESKTOP), ("phone", PHONE)] { @@ -1135,27 +1137,69 @@ pub fn capture_script(base: &str, pages: &[String]) -> String { } } let jobs = serde_json::to_string(&jobs).unwrap_or_else(|_| "[]".into()); + let base_js = serde_json::to_string(&base).unwrap_or_else(|_| "\"\"".into()); + let kind = serde_json::to_string(access.as_str()).unwrap_or_else(|_| "\"none\"".into()); format!( r#"import {{ chromium }} from 'playwright'; import {{ writeFileSync }} from 'node:fs'; const out = process.env.CODERHELM_OUT || '.'; +const secret = (process.env.GH_TOKEN || '').trim(); +delete process.env.GH_TOKEN; delete process.env.GITHUB_TOKEN; +const kind = {kind}; +const host = new URL({base_js}).host; +const hide = (s) => secret ? String(s).split(secret).join('***') : String(s); +const ctxOpts = {{}}; +const headers = {{}}; +if (kind === 'header' && secret) {{ + for (const line of secret.split('\n')) {{ + const i = line.indexOf(':'); + if (i > 0) headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim(); + }} +}} +if (kind === 'basic' && secret) {{ + const i = secret.indexOf(':'); + ctxOpts.httpCredentials = {{ username: secret.slice(0, i), password: secret.slice(i + 1), origin: 'https://' + host }}; +}} +const withQuery = (u) => (kind === 'query' && secret) ? u + (u.includes('?') ? '&' : '?') + secret : u; +const warming = (s) => [404, 502, 503, 504].includes(s); const jobs = {jobs}; const results = []; const browser = await chromium.launch(); for (const j of jobs) {{ - const page = await browser.newPage({{ viewport: {{ width: j.w, height: j.h }} }}); - let status = 0, title = '', error = ''; + const context = await browser.newContext({{ viewport: {{ width: j.w, height: j.h }}, ...ctxOpts }}); + if (Object.keys(headers).length) {{ + // The secret goes to the preview's own host only, never to a font, a + // script or an image another host serves. + await context.route('**/*', (route) => {{ + const req = route.request(); + let h = ''; + try {{ h = new URL(req.url()).host; }} catch (e) {{}} + if (h === host) route.continue({{ headers: {{ ...req.headers(), ...headers }} }}); + else route.continue(); + }}); + }} + const page = await context.newPage(); + let status = 0, title = '', error = '', left = ''; + for (let t = 1; t <= {WARM_TRIES}; t++) {{ + error = ''; + try {{ + const res = await page.goto(withQuery(j.url), {{ waitUntil: 'networkidle', timeout: 45000 }}); + status = res ? res.status() : 0; + }} catch (e) {{ status = 0; error = hide(String(e).slice(0, 300)); }} + if (!warming(status) && !(status === 0 && error) || t === {WARM_TRIES}) break; + await new Promise((r) => setTimeout(r, {WARM_WAIT_MS})); + }} try {{ - const res = await page.goto(j.url, {{ waitUntil: 'networkidle', timeout: 45000 }}); - status = res ? res.status() : 0; - title = await page.title(); - if (status > 0 && status < 400) {{ + const now = new URL(page.url()).host; + if (now && now !== host) left = now; + title = hide(await page.title()); + if (status > 0 && status < 400 && !left) {{ const png = await page.screenshot({{ fullPage: false }}); writeFileSync(`${{out}}/${{j.name}}.png.b64`, png.toString('base64')); }} - }} catch (e) {{ error = String(e).slice(0, 300); }} - results.push({{ page: j.page, width: j.width, name: j.name, status, title, error }}); - await page.close(); + }} catch (e) {{ error = error || hide(String(e).slice(0, 300)); }} + results.push({{ page: j.page, width: j.width, name: j.name, status, title, error, left }}); + await context.close(); }} await browser.close(); writeFileSync(`${{out}}/shots.json`, JSON.stringify(results)); @@ -1189,16 +1233,48 @@ pub struct Captured { pub status: u16, pub title: String, pub error: String, + /// The host the browser was sent to instead of the preview's (a + /// sign-in page), "" when it stayed. + pub left: String, +} + +impl Captured { + /// The page loaded on the preview itself. + pub fn shot(&self) -> bool { + (1..400).contains(&self.status) && self.left.is_empty() + } } -/// Why no page was captured, from the capture's report: a login wall, a -/// page that didn't load, or nothing at all. None when one was. -pub fn why_no_shot(report: &[Captured]) -> Option { - if report.iter().any(|c| (1..400).contains(&c.status)) { +/// Where a team gives CoderHelm a protected preview's access. +pub const ACCESS_SETTING: &str = "Settings, Repositories, Preview access"; + +/// Why no page was captured, from the capture's report: a sign-in wall +/// (the preview answered 401 or 403, or sent the browser to another host), +/// a page that didn't load, or nothing at all. None when one was. +/// `has_access`: the team saved the preview's access, so a wall means that +/// access was refused. +pub fn why_no_shot(report: &[Captured], has_access: bool) -> Option { + if report.iter().any(Captured::shot) { return None; } - if report.iter().any(|c| c.status == 401 || c.status == 403) { - return Some("the preview asks for a login, so its pages couldn't be captured".into()); + let wall = report + .iter() + .find(|c| c.status == 401 || c.status == 403 || !c.left.is_empty()); + if let Some(c) = wall { + let how = if c.left.is_empty() { + format!("it answered {}", c.status) + } else { + format!("it sent the browser to `{}`", c.left) + }; + return Some(if has_access { + format!( + "the preview refused the access saved in {ACCESS_SETTING} ({how}), so its pages couldn't be captured" + ) + } else { + format!( + "the preview asks for a sign-in ({how}), so its pages couldn't be captured; give CoderHelm its access in {ACCESS_SETTING}" + ) + }); } if let Some(c) = report.iter().find(|c| c.status >= 400) { return Some(format!( @@ -1597,29 +1673,6 @@ jobs: ); } - #[test] - fn a_preview_address_is_found_in_deployments_and_text() { - let deps = vec![ - ( - "staging".to_string(), - "https://staging.example.com".to_string(), - ), - ( - "pr-12".to_string(), - "https://pr-12.preview-web.example.com".to_string(), - ), - ]; - assert_eq!( - url_from_deployments(&deps).as_deref(), - Some("https://pr-12.preview-web.example.com") - ); - assert_eq!( - url_in("Deployed to https://pr-7.preview-web.example.com/ (ready).").as_deref(), - Some("https://pr-7.preview-web.example.com/") - ); - assert_eq!(url_in("see https://example.com/docs"), None); - } - #[test] fn a_visible_change_needs_an_e2e_spec_in_a_repo_with_a_suite() { let tree = s(&[ @@ -1666,21 +1719,66 @@ jobs: #[test] fn the_capture_script_takes_each_page_at_desktop_and_phone_width() { - let js = capture_script("https://pr-1.preview-web.example.com/", &s(&["/signup"])); + use crate::preview_access::Kind; + let js = capture_script( + "https://pr-1.preview-web.example.com/", + &s(&["/signup"]), + Kind::None, + ); assert!(js.contains("https://pr-1.preview-web.example.com/signup")); assert!(js.contains("signup-desktop") && js.contains("signup-phone")); assert!(js.contains("\"w\":390") && js.contains("\"w\":1280")); + // A preview served under a path keeps it; its query is dropped. + let js = capture_script( + "https://previews.example.com/pr-12/?x=1", + &s(&["/signup"]), + Kind::None, + ); + assert!(js.contains("https://previews.example.com/pr-12/signup")); let report = vec![Captured { status: 401, page: "/signup".into(), ..Default::default() }]; - assert!(why_no_shot(&report).unwrap().contains("login")); + let why = why_no_shot(&report, false).unwrap(); + assert!( + why.contains("sign-in") && why.contains(ACCESS_SETTING), + "{why}" + ); + assert!(why_no_shot(&report, true).unwrap().contains("refused")); + // Sent to a sign-in page on another host: a wall, never a shot. + let sent = vec![Captured { + status: 200, + left: "sso.example.org".into(), + ..Default::default() + }]; + assert!(why_no_shot(&sent, false) + .unwrap() + .contains("sso.example.org")); let ok = vec![Captured { status: 200, ..Default::default() }]; - assert_eq!(why_no_shot(&ok), None); + assert_eq!(why_no_shot(&ok, false), None); + } + + #[test] + fn a_protected_previews_secret_never_enters_the_script_and_goes_only_to_its_host() { + use crate::preview_access::Kind; + for kind in [Kind::Header, Kind::Query, Kind::Basic] { + let js = capture_script("https://pr-1.preview.example.com", &s(&["/"]), kind); + assert!(js.contains(&format!("const kind = \"{}\"", kind.as_str()))); + // Read once from the one-time secret, then removed from the + // environment, and blanked out of what is written. + assert!(js.contains("delete process.env.GH_TOKEN")); + assert!(js.contains("const hide =")); + } + let js = capture_script("https://pr-1.preview.example.com", &s(&["/"]), Kind::Header); + assert!(js.contains("if (h === host) route.continue({ headers:")); + assert!(js.contains("origin: 'https://' + host")); + // A page still warming up is tried again, a bounded number of times. + assert!(js.contains("[404, 502, 503, 504]")); + assert!(js.contains(&format!("t <= {WARM_TRIES}"))); } #[test] diff --git a/services/common/src/preview_access.rs b/services/common/src/preview_access.rs new file mode 100644 index 000000000..c705ee423 --- /dev/null +++ b/services/common/src/preview_access.rs @@ -0,0 +1,335 @@ +//! A repository's preview access: optional, per repository, one Settings +//! item (Settings, Repositories, Preview access). +//! +//! Most previews are found and opened with nothing set (`preview_find` +//! reads deployments, statuses, checks and comments). Two things only a +//! team can give, and they live here: +//! +//! - the preview's address as a template (`https://pr-{pr}.preview.example`), +//! for a host that publishes it nowhere CoderHelm can read +//! (`preview_find::expand`); +//! - how an automated browser gets through a protected preview, with one +//! secret the team stores: +//! - [`Kind::Header`]: one to four `Name: value` lines sent with every +//! request to the preview's host only (a protection bypass header, a +//! sign-in wall's service token pair); +//! - [`Kind::Query`]: `name=value` added to each page's address (a bypass +//! parameter that sets a cookie); +//! - [`Kind::Basic`]: `user:password` answered to the preview host's +//! password prompt. +//! +//! The secret is sealed by KMS bound to the team, the repository and this +//! purpose, never returned by the API, handed to the sandbox's capture +//! through its one-time secret object (never in the script, its environment +//! or its log) and only ever sent to the preview's own host. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; + +/// The settings-table sort key for a repository's preview access. +pub fn sk(repo: &str) -> String { + format!("PREVIEW_ACCESS#REPO#{repo}") +} + +/// Where the sealed secret is kept on the record. +pub const SECRET_ATTR: &str = "secret_sealed"; +const PURPOSE: &str = "preview-access"; +/// The longest secret kept. +pub const MAX_SECRET: usize = 2000; +/// Header lines a header secret may hold. +pub const MAX_HEADERS: usize = 4; + +/// How the preview is protected. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// Open, or only the address is set. + #[default] + None, + Header, + Query, + Basic, +} + +impl Kind { + pub fn parse(s: &str) -> Option { + match s.trim() { + "" | "none" => Some(Kind::None), + "header" => Some(Kind::Header), + "query" => Some(Kind::Query), + "basic" => Some(Kind::Basic), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Kind::None => "none", + Kind::Header => "header", + Kind::Query => "query", + Kind::Basic => "basic", + } + } +} + +/// A repository's preview access, without its secret. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PreviewAccess { + /// `owner/name`. + pub repo: String, + pub kind: Kind, + /// The preview's address template, "" when the preview publishes its + /// own address. + pub address: String, +} + +/// Headers a secret may not set: the browser owns them. +const OWNED_HEADERS: &[&str] = &[ + "host", + "content-length", + "connection", + "transfer-encoding", + "upgrade", + "te", + "trailer", + "keep-alive", +]; + +fn token_chars(s: &str, extra: &[char]) -> bool { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || extra.contains(&c)) +} + +/// Checks a secret's shape for its kind; the error is one sentence a person +/// can act on and never repeats the secret. +pub fn check_secret(kind: Kind, secret: &str) -> Result<(), String> { + if secret.len() > MAX_SECRET { + return Err("The secret is too long.".into()); + } + if secret + .chars() + .any(|c| c.is_control() && c != '\n' && c != '\r') + { + return Err("The secret can't hold control characters.".into()); + } + match kind { + Kind::None => Ok(()), + Kind::Header => { + let lines: Vec<&str> = secret + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .collect(); + if lines.is_empty() || lines.len() > MAX_HEADERS { + return Err(format!( + "Enter one to {MAX_HEADERS} lines, each `Header-Name: value`." + )); + } + for l in lines { + let Some((name, value)) = l.split_once(':') else { + return Err("Each line is `Header-Name: value`.".into()); + }; + let name = name.trim(); + if !token_chars(name, &['-', '_']) { + return Err(format!("`{name}` isn't a header name.")); + } + if OWNED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) { + return Err(format!("`{name}` is set by the browser itself.")); + } + if value.trim().is_empty() { + return Err(format!("The `{name}` header has no value.")); + } + } + Ok(()) + } + Kind::Query => { + let s = secret.trim(); + if s.contains(char::is_whitespace) || s.starts_with('?') || s.contains('#') { + return Err("Enter the parameters as `name=value` (join several with &).".into()); + } + for pair in s.split('&') { + let Some((name, value)) = pair.split_once('=') else { + return Err( + "Enter the parameters as `name=value` (join several with &).".into(), + ); + }; + if !token_chars(name, &['-', '_', '.']) || value.is_empty() { + return Err( + "Enter the parameters as `name=value` (join several with &).".into(), + ); + } + } + Ok(()) + } + Kind::Basic => match secret.trim().split_once(':') { + Some((user, pass)) if !user.is_empty() && !pass.is_empty() && !user.contains('\n') => { + Ok(()) + } + _ => Err("Enter the user name and password as `user:password`.".into()), + }, + } +} + +impl PreviewAccess { + /// Checks the access as a team entered it. + pub fn validate(&self) -> Result<(), String> { + if !self.repo.contains('/') || self.repo.len() > 200 { + return Err("Pick the repository this is for.".into()); + } + crate::preview_find::check_template(&self.address)?; + if self.kind == Kind::None && self.address.trim().is_empty() { + return Err( + "Set the preview's address, how it is protected, or both. With neither, remove it." + .into(), + ); + } + Ok(()) + } + + /// The record, without the secret. + pub fn item(&self, team_id: &str) -> HashMap { + let s = |v: &str| AttributeValue::S(v.to_string()); + HashMap::from([ + ("pk".to_string(), s(team_id)), + ("sk".to_string(), s(&sk(&self.repo))), + ("repo".to_string(), s(&self.repo)), + ("kind".to_string(), s(self.kind.as_str())), + ("address".to_string(), s(&self.address)), + ]) + } + + /// Reads a record. `None` when it isn't one. + pub fn from_item(item: &HashMap) -> Option { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let a = PreviewAccess { + repo: s("repo"), + kind: Kind::parse(&s("kind")).unwrap_or_default(), + address: s("address"), + }; + (!a.repo.is_empty()).then_some(a) + } + + /// The API's view: never the secret, only whether one is set. + pub fn view(&self, secret_set: bool) -> serde_json::Value { + serde_json::json!({ + "configured": true, + "repo": self.repo, + "kind": self.kind.as_str(), + "address": self.address, + "secret_set": secret_set, + }) + } +} + +/// The encryption context: the team, the repository and the purpose. +pub fn context(team_id: &str, repo: &str) -> HashMap { + HashMap::from([ + ("team".to_string(), team_id.to_string()), + ("repo".to_string(), repo.to_string()), + ("purpose".to_string(), PURPOSE.to_string()), + ]) +} + +/// Seals a secret for one team's repository. Returns text safe to store. +pub async fn seal( + cipher: &dyn crate::mcp_credentials::Cipher, + team_id: &str, + repo: &str, + secret: &str, +) -> Result { + use base64::Engine; + let blob = cipher + .encrypt(context(team_id, repo), secret.as_bytes()) + .await?; + Ok(base64::engine::general_purpose::STANDARD.encode(blob)) +} + +/// Opens a secret sealed for one team's repository. +pub async fn open( + cipher: &dyn crate::mcp_credentials::Cipher, + team_id: &str, + repo: &str, + sealed: &str, +) -> Result { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD + .decode(sealed) + .map_err(|_| "stored secret is not valid".to_string())?; + let plain = cipher.decrypt(context(team_id, repo), &bytes).await?; + String::from_utf8(plain).map_err(|_| "stored secret is not text".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn secrets_are_checked_for_their_kind_without_repeating_them() { + assert!(check_secret(Kind::Header, "X-Bypass-Token: s3cr3t").is_ok()); + assert!(check_secret( + Kind::Header, + "X-Client-Id: abc.access\nX-Client-Secret: def\n" + ) + .is_ok()); + let e = check_secret(Kind::Header, "no-colon-s3cr3t").unwrap_err(); + assert!(!e.contains("s3cr3t"), "{e}"); + assert!(check_secret(Kind::Header, "Host: evil.example").is_err()); + assert!(check_secret(Kind::Header, "A: 1\nB: 2\nC: 3\nD: 4\nE: 5").is_err()); + assert!(check_secret(Kind::Query, "bypass=abc123").is_ok()); + assert!(check_secret(Kind::Query, "bypass=abc&set-cookie=true").is_ok()); + assert!(check_secret(Kind::Query, "?bypass=abc").is_err()); + assert!(check_secret(Kind::Query, "abc").is_err()); + assert!(check_secret(Kind::Basic, "preview:hunter2").is_ok()); + assert!(check_secret(Kind::Basic, "hunter2").is_err()); + assert!(check_secret(Kind::Basic, &"x".repeat(MAX_SECRET + 1)).is_err()); + } + + #[test] + fn an_access_needs_an_address_or_a_protection_and_a_valid_template() { + let a = |kind, address: &str| PreviewAccess { + repo: "acme/web".into(), + kind, + address: address.into(), + }; + assert!(a(Kind::None, "").validate().is_err()); + assert!(a(Kind::Header, "").validate().is_ok()); + assert!(a(Kind::None, "https://pr-{pr}.preview.example.com") + .validate() + .is_ok()); + assert!(a(Kind::None, "https://staging.example.com") + .validate() + .is_err()); + } + + #[test] + fn the_record_round_trips_without_its_secret() { + let a = PreviewAccess { + repo: "acme/web".into(), + kind: Kind::Query, + address: "https://pr-{pr}.preview.example.com".into(), + }; + let item = a.item("team-1"); + assert!(!item.contains_key(SECRET_ATTR)); + assert_eq!(PreviewAccess::from_item(&item), Some(a.clone())); + let v = a.view(true); + assert_eq!(v["kind"], "query"); + assert_eq!(v["secret_set"], true); + assert!(v.get("secret").is_none()); + } + + #[test] + fn the_seal_is_bound_to_the_team_repository_and_purpose() { + let c = context("team-1", "acme/web"); + assert_eq!(c["purpose"], "preview-access"); + assert_eq!(c["repo"], "acme/web"); + } +} diff --git a/services/common/src/preview_find/fixtures/check_runs.json b/services/common/src/preview_find/fixtures/check_runs.json new file mode 100644 index 000000000..4caf74939 --- /dev/null +++ b/services/common/src/preview_find/fixtures/check_runs.json @@ -0,0 +1,18 @@ +{ + "total_count": 3, + "check_runs": [ + {"id": 11, "name": "Edge preview", "head_sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "status": "completed", "conclusion": "success", "started_at": "2026-11-17T10:00:10Z", + "details_url": "https://dash.edge-host.example/acme/pages/view/web/8c1d", + "output": {"title": "Deployed successfully", + "summary": "| Name | Status | Preview URL | Branch Preview URL |\n|---|---|---|---|\n| web | ✅ Deployment successful! | https://8c1d2e3f.web.edge-host.example | https://feature-signup-form.web.edge-host.example |", + "text": null}}, + {"id": 12, "name": "E2E on preview", "head_sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "status": "in_progress", "conclusion": null, "started_at": "2026-11-17T10:03:00Z", + "details_url": "https://github.com/acme/web/actions/runs/78/job/2", + "output": {"title": null, "summary": "Testing https://8c1d2e3f.web.edge-host.example", "text": null}}, + {"id": 13, "name": "unit tests", "head_sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "status": "completed", "conclusion": "success", "started_at": "2026-11-17T10:00:00Z", + "details_url": "https://github.com/acme/web/actions/runs/79/job/3", "output": {"summary": "", "text": null}} + ] +} diff --git a/services/common/src/preview_find/fixtures/comment_head.json b/services/common/src/preview_find/fixtures/comment_head.json new file mode 100644 index 000000000..7456bb4c7 --- /dev/null +++ b/services/common/src/preview_find/fixtures/comment_head.json @@ -0,0 +1,8 @@ +[ + {"id": 3, "user": {"login": "static-host[bot]", "type": "Bot"}, + "body": "### ✅ Deploy Preview for *acme-web* ready!\n\n| Name | Link |\n|:-:|------------------------|\n|🔨 Latest commit | 4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b |\n|🔍 Latest deploy log | https://app.static-host.example/sites/acme-web/deploys/65ab |\n|😎 Deploy Preview | [https://deploy-preview-12--acme-web.static-host.example](https://deploy-preview-12--acme-web.static-host.example) |", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-17T10:02:30Z"}, + {"id": 4, "user": {"login": "ci-bot[bot]", "type": "Bot"}, + "body": "\n🚀 Preview deployed to https://acme.pages.example/web/pr-preview/pr-12/\nBuilt from 4f2c9e1", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-17T10:04:00Z"} +] diff --git a/services/common/src/preview_find/fixtures/comments.json b/services/common/src/preview_find/fixtures/comments.json new file mode 100644 index 000000000..64162311c --- /dev/null +++ b/services/common/src/preview_find/fixtures/comments.json @@ -0,0 +1,10 @@ +[ + {"id": 1, "user": {"login": "someone", "type": "User"}, + "body": "Looks good, see https://pr-12.preview.example.com/old", "created_at": "2026-11-17T09:00:00Z", "updated_at": "2026-11-17T09:00:00Z"}, + {"id": 2, "user": {"login": "preview-host[bot]", "type": "Bot"}, + "body": "The latest updates on your projects.\n\n| Name | Status | Preview | Comments | Updated (UTC) |\n| :--- | :----- | :------ | :------- | :------ |\n| **admin** | ✅ Ready ([Inspect](https://console.host.example/team/admin/dpl_9)) | [Visit Preview](https://admin-git-feature-signup-form-team.host.example) | 💬 [**Add feedback**](https://host.example/feedback) | Nov 17, 2026 10:03am |\n| **web** | 🔄 Building ([Inspect](https://console.host.example/team/web/dpl_8)) | [Visit Preview](https://web-git-feature-signup-form-team.host.example) | 💬 [**Add feedback**](https://host.example/feedback) | Nov 17, 2026 10:02am |\n", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-17T10:03:30Z"}, + {"id": 3, "user": {"login": "static-host[bot]", "type": "Bot"}, + "body": "### ✅ Deploy Preview for *acme-web* ready!\n\n| Name | Link |\n|:-:|------------------------|\n|🔨 Latest commit | 0aa11bb22cc33dd44ee55ff6677889900aabbccd |\n|🔍 Latest deploy log | https://app.static-host.example/sites/acme-web/deploys/65aa |\n|😎 Deploy Preview | [https://deploy-preview-12--acme-web.static-host.example](https://deploy-preview-12--acme-web.static-host.example) |", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-16T15:05:00Z"} +] diff --git a/services/common/src/preview_find/fixtures/deployments.json b/services/common/src/preview_find/fixtures/deployments.json new file mode 100644 index 000000000..3429a4b69 --- /dev/null +++ b/services/common/src/preview_find/fixtures/deployments.json @@ -0,0 +1,55 @@ +[ + { + "deployment": { + "id": 9001, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "feature/signup-form", + "task": "deploy", "environment": "Preview – web", "original_environment": "Preview – web", + "transient_environment": false, "production_environment": false, "payload": {}, + "created_at": "2026-11-17T10:00:05Z" + }, + "statuses": [ + {"id": 3, "state": "success", "environment": "Preview – web", + "environment_url": "https://web-git-feature-signup-form-team.host.example", + "target_url": "https://console.host.example/team/web/dpl_abc", "log_url": "https://console.host.example/team/web/dpl_abc", + "created_at": "2026-11-17T10:02:40Z"}, + {"id": 2, "state": "in_progress", "environment": "Preview – web", "environment_url": "", "target_url": "https://console.host.example/team/web/dpl_abc", + "log_url": "https://console.host.example/team/web/dpl_abc", "created_at": "2026-11-17T10:00:20Z"}, + {"id": 1, "state": "pending", "environment": "Preview – web", "environment_url": "", "target_url": "", "log_url": "", + "created_at": "2026-11-17T10:00:06Z"} + ] + }, + { + "deployment": { + "id": 9002, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "feature/signup-form", + "task": "deploy", "environment": "Preview – admin", + "transient_environment": false, "production_environment": false, "payload": {}, + "created_at": "2026-11-17T10:00:05Z" + }, + "statuses": [ + {"id": 5, "state": "success", "environment_url": "https://admin-git-feature-signup-form-team.host.example", + "target_url": "", "log_url": "", "created_at": "2026-11-17T10:03:10Z"} + ] + }, + { + "deployment": { + "id": 8000, "sha": "0aa11bb22cc33dd44ee55ff6677889900aabbccd", "ref": "feature/signup-form", + "task": "deploy", "environment": "Preview – web", + "transient_environment": false, "production_environment": false, "payload": {}, + "created_at": "2026-11-17T09:00:00Z" + }, + "statuses": [ + {"id": 0, "state": "inactive", "environment_url": "https://web-old-commit-team.host.example", + "created_at": "2026-11-17T10:02:41Z"} + ] + }, + { + "deployment": { + "id": 7000, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "main", + "task": "deploy", "environment": "Production", + "transient_environment": false, "production_environment": true, "payload": {}, + "created_at": "2026-11-17T10:00:05Z" + }, + "statuses": [ + {"id": 9, "state": "success", "environment_url": "https://www.your-domain.example", "created_at": "2026-11-17T10:04:00Z"} + ] + } +] diff --git a/services/common/src/preview_find/fixtures/statuses.json b/services/common/src/preview_find/fixtures/statuses.json new file mode 100644 index 000000000..f28835394 --- /dev/null +++ b/services/common/src/preview_find/fixtures/statuses.json @@ -0,0 +1,12 @@ +{ + "state": "success", + "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "statuses": [ + {"context": "site/deploy-preview", "state": "success", "description": "Deploy Preview ready!", + "target_url": "https://deploy-preview-12--acme-web.static-host.example", "created_at": "2026-11-17T10:02:00Z"}, + {"context": "site/header-rules", "state": "success", "description": "No header rules processed", + "target_url": "https://app.static-host.example/sites/acme-web/deploys/65aa", "created_at": "2026-11-17T10:02:00Z"}, + {"context": "ci/build", "state": "success", "description": "Your tests passed", + "target_url": "https://ci.example.org/gh/acme/web/4411", "created_at": "2026-11-17T10:05:00Z"} + ] +} diff --git a/services/common/src/preview_find/fixtures/workflow_environment.json b/services/common/src/preview_find/fixtures/workflow_environment.json new file mode 100644 index 000000000..9e33de184 --- /dev/null +++ b/services/common/src/preview_find/fixtures/workflow_environment.json @@ -0,0 +1,13 @@ +[ + { + "deployment": { + "id": 501, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "refs/pull/12/merge", + "task": "deploy", "environment": "pr-12", "transient_environment": true, "production_environment": false + }, + "statuses": [ + {"id": 2, "state": "in_progress", "environment_url": "", "log_url": "https://github.com/acme/web/actions/runs/77/job/1", + "target_url": "https://github.com/acme/web/actions/runs/77/job/1", "created_at": "2026-11-17T10:01:00Z"}, + {"id": 1, "state": "queued", "created_at": "2026-11-17T10:00:30Z"} + ] + } +] diff --git a/services/common/src/preview_find/mod.rs b/services/common/src/preview_find/mod.rs new file mode 100644 index 000000000..bb22d60af --- /dev/null +++ b/services/common/src/preview_find/mod.rs @@ -0,0 +1,992 @@ +//! Where a pull request's preview lives, read from every place teams +//! publish it, tied to the head commit. +//! +//! A preview's address reaches a pull request in one of a handful of ways, +//! and a team uses whichever its host or its CI gives it: +//! +//! - a deployment on the head commit, its newest status carrying the +//! address (`environment_url`, else a `target_url` that isn't a log page); +//! hosting integrations and a workflow job's `environment: {name, url}` +//! both write these ([`deployments`]); +//! - a commit status whose context or description reads as a deploy, its +//! `target_url` the preview ([`statuses`]); +//! - a check run whose name or output reads as a preview deploy, the address +//! in its output or its details link ([`check_runs`]); +//! - a bot's comment on the pull request, usually edited in place on every +//! push, often a table with one row per app ([`comments`]); +//! - a link in the pull request's description ([`body`]); +//! - the team's own address template, filled in from the pull request's +//! number, branch and commit ([`expand`]). +//! +//! Each is read into [`Sighting`]s, and [`resolve`] gives the one answer: +//! +//! 1. Only what is tied to the head commit counts first: a deployment, +//! status or check run on that sha, a comment that names that sha (or, +//! naming none, was written after the commit). A deploy of an older +//! commit is never the preview of this one. +//! 2. When several apps publish previews (a monorepo), the one named after +//! the changed app is kept ([`app_score`]). +//! 3. Of what is up with an address, the most direct source wins +//! ([`Source`] order). A head deploy still building means wait; one that +//! failed or was taken down is said as such. +//! 4. Only when nothing on the head carries an address does an untied one +//! count: the description's link or the team's template. +//! +//! How long to wait is bounded ([`WAIT_BUDGET_MINS`]); nothing here reads +//! the clock, the caller passes the times. + +use serde::{Deserialize, Serialize}; + +/// How long a preview of one head is waited on before the wait is said to +/// have run out. +pub const WAIT_BUDGET_MINS: i64 = 60; +/// How long nothing at all on the head (no deployment, status, check, +/// comment or template) is waited on before there is said to be no preview: +/// hosting integrations start within a minute or two of a push. +pub const GRACE_MINS: i64 = 6; +/// How often a pending preview is looked at again when nothing else on the +/// pull request changed. +pub const POLL_SECS: i64 = 120; + +/// Where an address came from, most direct first: the order breaks ties +/// between two sightings that both say the head's preview is up. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Source { + #[default] + Deployment, + CheckRun, + CommitStatus, + Comment, + Body, + Template, +} + +impl Source { + /// How the source is named in a sentence. + pub fn phrase(self) -> &'static str { + match self { + Source::Deployment => "the head commit's deployment", + Source::CheckRun => "the preview check on the head commit", + Source::CommitStatus => "the deploy status on the head commit", + Source::Comment => "the preview comment on the pull request", + Source::Body => "the link in the pull request's description", + Source::Template => "the team's preview address template", + } + } +} + +/// What a sighting says of the preview. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Ready { + Up, + Building, + Failed, + /// Taken down, expired or replaced. + Gone, +} + +/// One place that says something about the head's preview. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sighting { + pub source: Source, + /// The environment, context, check or table row it names (an app in a + /// monorepo), "" when none. + pub name: String, + /// The address, "" when it says only how the deploy stands. + pub url: String, + pub ready: Ready, + /// Tied to the head commit. + pub tied: bool, +} + +/// The preview the change is checked on. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Found { + pub url: String, + pub source: Source, + /// The environment, check or app it was named under. + pub name: String, + /// Tied to the head commit (false: a description link or the template). + pub tied: bool, +} + +/// The answer [`resolve`] gives. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Answer { + Up(Found), + /// The head's preview is still on its way: what says so. + Building(String), + /// The head's preview failed or was taken down: what says so. + Failed(String), + Nothing, +} + +// ── words ───────────────────────────────────────────────────────────────── + +fn words(s: &str) -> Vec { + s.to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_string) + .collect() +} + +fn norm(s: &str) -> String { + s.chars() + .filter(|c| c.is_ascii_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect() +} + +/// Whether a check, status or environment name (with its description) +/// reads as a deploy of the pull request's own preview: it says preview, +/// deploy or review app, and never a shared environment or a cleanup. +pub fn reads_as_preview(name: &str, text: &str) -> bool { + use crate::preview::{role_of, Role}; + if matches!( + role_of(name), + Role::Production | Role::Staging | Role::Cleanup | Role::E2e + ) { + return false; + } + let both = format!("{name} {text}"); + let w = words(&both); + let low = both.to_ascii_lowercase(); + w.iter().any(|x| { + matches!( + x.as_str(), + "preview" | "previews" | "deploy" | "deployment" | "deployed" | "deploying" + ) + }) || low.contains("review app") + || low.contains("review-app") +} + +fn host_of(url: &str) -> &str { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")) + .unwrap_or(""); + rest.split(['/', '?', '#']).next().unwrap_or("") +} + +fn path_of(url: &str) -> &str { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")) + .unwrap_or(""); + match rest.find('/') { + Some(i) => rest[i..].split(['?', '#']).next().unwrap_or(""), + None => "", + } +} + +/// An address on the code host itself (a pull request, a run, a file), never +/// a preview. +pub fn is_code_host(url: &str) -> bool { + let h = host_of(url).to_ascii_lowercase(); + h == "github.com" || h.ends_with(".github.com") || h.ends_with(".githubusercontent.com") +} + +/// An address that is a log, dashboard or build page rather than the site: +/// its host starts with a console's name, or its path is a deploy, build or +/// run record. +pub fn is_console(url: &str) -> bool { + let h = host_of(url).to_ascii_lowercase(); + let first = h.split('.').next().unwrap_or(""); + if matches!( + first, + "app" | "dashboard" | "console" | "admin" | "ci" | "build" | "builds" | "logs" | "status" + ) && h.matches('.').count() >= 2 + { + return true; + } + path_of(url).to_ascii_lowercase().split('/').any(|seg| { + matches!( + seg, + "deploys" + | "deployments" + | "builds" + | "runs" + | "jobs" + | "pipelines" + | "logs" + | "inspect" + | "actions" + ) + }) +} + +fn is_image(url: &str) -> bool { + let p = path_of(url).to_ascii_lowercase(); + let h = host_of(url).to_ascii_lowercase(); + [".png", ".svg", ".gif", ".jpg", ".jpeg", ".webp", ".ico"] + .iter() + .any(|e| p.ends_with(e)) + || h.contains("badge") + || p.contains("/badge") +} + +/// An address that can be a site: https, a host with a dot, never the code +/// host, a console page or an image. +pub fn site_like(url: &str) -> bool { + let h = host_of(url); + url.starts_with("https://") + && h.contains('.') + && !h.contains('@') + && !is_code_host(url) + && !is_console(url) + && !is_image(url) +} + +/// Every https address in a text with the words around it: a markdown link's +/// text, else the line it sits on. +pub fn urls_in(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + for line in text.lines() { + for (i, _) in line.match_indices("https://") { + let rest = &line[i..]; + let end = rest + .find(|c: char| { + c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | '<' | ']' | '`' | '|') + }) + .unwrap_or(rest.len()); + let url = rest[..end].trim_end_matches(['.', ',', ';', ':']); + // `[text](url)`: the text says what it is. + let label = line[..i] + .strip_suffix("](") + .and_then(|before| before.rfind('[').map(|j| before[j + 1..].to_string())) + .unwrap_or_else(|| line.to_string()); + if !url.is_empty() && !out.iter().any(|(u, _): &(String, String)| u == url) { + out.push((url.to_string(), label)); + } + } + } + out +} + +/// Words that say an address is the preview. +fn labelled_preview(label: &str, url: &str) -> bool { + let w = words(label); + let says = w.iter().any(|x| { + matches!( + x.as_str(), + "preview" | "previews" | "visit" | "open" | "deployment" | "deployed" | "live" | "url" + ) + }); + let h = host_of(url).to_ascii_lowercase(); + says || h.contains("preview") + || h.split(['.', '-']).any(|p| { + p.strip_prefix("pr") + .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) + }) + || h.split('.').next().is_some_and(|l| l.contains("-pr-")) +} + +/// The preview address in a text. `named`: the text is a preview check's or +/// deploy status's own, so a site address counts even unlabelled; else it +/// must be labelled or shaped as a preview. +pub fn pick_url(text: &str, named: bool) -> Option { + let all: Vec<(String, String)> = urls_in(text) + .into_iter() + .filter(|(u, _)| site_like(u)) + .collect(); + all.iter() + .find(|(u, l)| labelled_preview(l, u)) + .or_else(|| if named { all.first() } else { None }) + .map(|(u, _)| u.clone()) +} + +// ── readers: each place a preview is published ───────────────────────────── + +fn s<'a>(v: &'a serde_json::Value, k: &str) -> &'a str { + v[k].as_str().unwrap_or("") +} + +fn same_sha(a: &str, head: &str) -> bool { + !a.is_empty() && !head.is_empty() && a.eq_ignore_ascii_case(head) +} + +/// The head's deployments, each with its statuses (as the deployments and +/// deployment statuses listings return them). A deployment to production +/// or to a shared environment is never a pull request's preview, unless it +/// says it is transient. +pub fn deployments( + list: &[(serde_json::Value, Vec)], + head: &str, +) -> Vec { + use crate::preview::{is_shared_env_label, role_of, Role}; + let mut out = Vec::new(); + for (d, statuses) in list { + if !same_sha(s(d, "sha"), head) { + continue; + } + let env = match s(d, "environment") { + "" => s(d, "original_environment"), + e => e, + }; + let transient = d["transient_environment"].as_bool().unwrap_or(false); + let shared = d["production_environment"].as_bool().unwrap_or(false) + || ((is_shared_env_label(env) + || matches!(role_of(env), Role::Production | Role::Staging)) + && !env.to_ascii_lowercase().contains("preview")); + if shared && !transient { + continue; + } + // The newest status says where it stands. + let mut sts: Vec<&serde_json::Value> = statuses.iter().collect(); + sts.sort_by(|a, b| { + s(b, "created_at") + .cmp(s(a, "created_at")) + .then(b["id"].as_u64().cmp(&a["id"].as_u64())) + }); + let newest = sts.first(); + let ready = match newest.map(|st| s(st, "state")) { + Some("success") => Ready::Up, + Some("failure" | "error") => Ready::Failed, + Some("inactive") => Ready::Gone, + // Created, queued, pending or in progress. + _ => Ready::Building, + }; + let url = newest + .map(|st| { + let env_url = s(st, "environment_url"); + let target = s(st, "target_url"); + let log = s(st, "log_url"); + if site_like(env_url) { + env_url.to_string() + } else if site_like(target) && target != log { + target.to_string() + } else { + String::new() + } + }) + .unwrap_or_default(); + out.push(Sighting { + source: Source::Deployment, + name: env.to_string(), + url, + ready, + tied: true, + }); + } + out +} + +/// The head's combined commit status: each context that reads as a deploy. +pub fn statuses(combined: &serde_json::Value, head: &str) -> Vec { + let sha = s(combined, "sha"); + if !sha.is_empty() && !same_sha(sha, head) { + return Vec::new(); + } + let mut out = Vec::new(); + for st in combined["statuses"].as_array().into_iter().flatten() { + let (ctx, desc) = (s(st, "context"), s(st, "description")); + if !reads_as_preview(ctx, desc) { + continue; + } + let ready = match s(st, "state") { + "success" => Ready::Up, + "failure" | "error" => Ready::Failed, + _ => Ready::Building, + }; + let target = s(st, "target_url"); + out.push(Sighting { + source: Source::CommitStatus, + name: ctx.to_string(), + url: if site_like(target) { + target.to_string() + } else { + String::new() + }, + ready, + tied: true, + }); + } + out +} + +/// The head's check runs (the check-runs listing): each that reads as a +/// preview deploy, its newest run per name. `covers` are the preview jobs +/// the repository's workflows run for the change (`preview::plan`). +pub fn check_runs( + runs: &serde_json::Value, + head: &str, + covers: &[crate::preview::Covering], +) -> Vec { + use crate::preview::{is_covering, role_of, Role}; + let mut newest: Vec<(&str, &serde_json::Value)> = Vec::new(); + for r in runs["check_runs"].as_array().into_iter().flatten() { + let sha = s(r, "head_sha"); + if !sha.is_empty() && !same_sha(sha, head) { + continue; + } + let name = s(r, "name"); + let out_text = format!( + "{} {}", + s(&r["output"], "title"), + s(&r["output"], "summary") + ); + let preview_job = covers + .iter() + .filter(|c| c.role == Some(Role::Preview)) + .any(|c| is_covering(std::slice::from_ref(c), name)); + if role_of(name) == Role::E2e || !(preview_job || reads_as_preview(name, &out_text)) { + continue; + } + if s(r, "conclusion") == "skipped" || s(r, "conclusion") == "neutral" { + continue; + } + match newest.iter_mut().find(|(n, _)| *n == name) { + Some(slot) if s(r, "started_at") > s(slot.1, "started_at") => slot.1 = r, + Some(_) => {} + None => newest.push((name, r)), + } + } + newest + .into_iter() + .map(|(name, r)| { + let ready = match (s(r, "status"), s(r, "conclusion")) { + ("completed", "success") => Ready::Up, + ("completed", _) => Ready::Failed, + _ => Ready::Building, + }; + let text = format!( + "{}\n{}\n{}", + s(&r["output"], "summary"), + s(&r["output"], "text"), + s(&r["output"], "title") + ); + let details = s(r, "details_url"); + let url = pick_url(&text, true) + .or_else(|| site_like(details).then(|| details.to_string())) + .unwrap_or_default(); + Sighting { + source: Source::CheckRun, + name: name.to_string(), + url, + ready, + tied: true, + } + }) + .collect() +} + +fn hexish(w: &str) -> bool { + // A commit's sha mixes digits and letters; a build number or a date + // is digits only. + (7..=40).contains(&w.len()) + && w.chars().all(|c| c.is_ascii_hexdigit()) + && w.chars().any(|c| c.is_ascii_digit()) + && w.chars().any(|c| c.is_ascii_alphabetic()) +} + +/// Whether a text names the head commit (its full sha or a prefix of seven +/// or more), names another commit, or names none. +fn names_commit(text: &str, head: &str) -> Option { + let head = head.to_ascii_lowercase(); + let mut other = false; + for w in text + .to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| hexish(w)) + { + if head.starts_with(w) { + return Some(true); + } + other = true; + } + other.then_some(false) +} + +/// The state a line or a comment says: failed, building, gone or up. +fn says(text: &str) -> Option { + let low = text.to_ascii_lowercase(); + let w = words(text); + let has = |xs: &[&str]| w.iter().any(|x| xs.contains(&x.as_str())); + if has(&[ + "failed", + "failure", + "error", + "errored", + "canceled", + "cancelled", + ]) || low.contains('❌') + { + return Some(Ready::Failed); + } + if has(&[ + "building", + "queued", + "pending", + "deploying", + "initializing", + "waiting", + ]) || low.contains("in progress") + || low.contains('⏳') + || low.contains('🔄') + { + return Some(Ready::Building); + } + if has(&["deleted", "removed", "expired", "inactive", "destroyed"]) || low.contains("torn down") + { + return Some(Ready::Gone); + } + if has(&[ + "ready", + "deployed", + "success", + "succeeded", + "live", + "available", + ]) || low.contains('✅') + { + return Some(Ready::Up); + } + None +} + +/// A table row's first cell, or "". +fn row_name(line: &str) -> String { + let t = line.trim(); + if !t.starts_with('|') { + return String::new(); + } + let cell = t.trim_matches('|').split('|').next().unwrap_or(""); + let clean: String = cell + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_' | '/' | '.')) + .collect(); + let clean = clean.trim(); + // A header row's or a label cell's words aren't an app. + if words(clean).iter().all(|w| { + matches!( + w.as_str(), + "name" + | "project" + | "app" + | "status" + | "preview" + | "deploy" + | "latest" + | "commit" + | "log" + | "updated" + | "url" + | "inspect" + | "visit" + ) + }) { + return String::new(); + } + clean.to_string() +} + +/// The bot comments on the pull request (the issue comments listing, oldest +/// first). A comment is tied to the head when it names the head commit, or +/// names none and was written or edited at or after `head_at` (the head +/// commit's time); one that names only another commit is an older deploy's. +/// Each line with a preview address is one sighting: a monorepo's table +/// gives one per app. +pub fn comments(list: &[serde_json::Value], head: &str, head_at: &str) -> Vec { + let mut bots: Vec<&serde_json::Value> = list + .iter() + .filter(|c| { + c["user"]["type"].as_str() == Some("Bot") + || c["user"]["login"] + .as_str() + .is_some_and(|l| l.ends_with("[bot]")) + }) + .collect(); + // The newest word first. + bots.sort_by(|a, b| { + let at = |c: &serde_json::Value| match s(c, "updated_at") { + "" => s(c, "created_at").to_string(), + u => u.to_string(), + }; + at(b).cmp(&at(a)) + }); + let mut out = Vec::new(); + for c in bots { + let body = s(c, "body"); + if !body.contains("https://") { + continue; + } + let updated = match s(c, "updated_at") { + "" => s(c, "created_at"), + u => u, + }; + let tied = match names_commit(body, head) { + Some(t) => t, + None => !head_at.is_empty() && updated >= head_at, + }; + let names_other = names_commit(body, head) == Some(false); + if names_other { + // An older commit's deploy: never this head's. + continue; + } + let whole = says(body); + for line in body.lines() { + let Some(url) = pick_url(line, false) else { + continue; + }; + out.push(Sighting { + source: Source::Comment, + name: row_name(line), + url, + ready: says(line).or(whole).unwrap_or(Ready::Up), + tied, + }); + } + } + out +} + +/// A preview link in the pull request's description: tied only when the +/// description names the head commit. +pub fn body(text: &str, head: &str) -> Vec { + let tied = names_commit(text, head) == Some(true); + text.lines() + .filter_map(|line| { + let url = pick_url(line, false)?; + Some(Sighting { + source: Source::Body, + name: row_name(line), + url, + ready: Ready::Up, + tied, + }) + }) + .collect() +} + +// ── the team's template ─────────────────────────────────────────────────── + +/// What an address template may name. +pub const PLACEHOLDERS: &[&str] = &[ + "{pr}", + "{branch}", + "{branch_slug}", + "{sha}", + "{short_sha}", + "{owner}", + "{repo}", +]; + +/// The pull request a template is filled in for. +#[derive(Debug, Clone, Copy, Default)] +pub struct Vars<'a> { + pub pr: u64, + pub branch: &'a str, + pub sha: &'a str, + pub owner: &'a str, + pub repo: &'a str, +} + +/// A branch name as hosts put it in an address: lowercase, every run of +/// other characters one `-`, no `-` at either end. +pub fn branch_slug(branch: &str) -> String { + let mut out = String::new(); + for c in branch.chars() { + if c.is_ascii_alphanumeric() { + out.push(c.to_ascii_lowercase()); + } else if !out.ends_with('-') { + out.push('-'); + } + } + out.trim_matches('-').to_string() +} + +fn braces(s: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut rest = s; + while let Some(i) = rest.find('{') { + match rest[i..].find('}') { + Some(j) => { + out.push(&rest[i..i + j + 1]); + rest = &rest[i + j + 1..]; + } + None => { + out.push(&rest[i..]); + break; + } + } + } + out +} + +/// Checks an address template as a team typed it; the error is one sentence +/// a person can act on. Empty is no template. +pub fn check_template(raw: &str) -> Result<(), String> { + let t = raw.trim(); + if t.is_empty() { + return Ok(()); + } + let rest = t + .strip_prefix("https://") + .ok_or("The preview address starts with https://.")?; + let host = rest.split(['/', '?', '#']).next().unwrap_or(""); + if host.is_empty() + || t.len() > 300 + || t.chars().any(|c| { + c.is_whitespace() || c.is_control() || matches!(c, '\'' | '"' | '`' | '\\' | '$' | ';') + }) + { + return Err( + "Enter the preview's address, like https://pr-{pr}.preview.your-domain.example.".into(), + ); + } + for b in braces(t) { + if !PLACEHOLDERS.contains(&b) { + return Err(format!( + "`{b}` isn't filled in; use {}.", + PLACEHOLDERS.join(", ") + )); + } + } + if !is_per_change(t) { + return Err( + "The address needs {pr}, {branch}, {branch_slug}, {sha} or {short_sha}, so each pull request gets its own preview." + .into(), + ); + } + Ok(()) +} + +/// Whether a template names something of the pull request, so it is that +/// pull request's own address (a fixed address is a shared environment). +pub fn is_per_change(t: &str) -> bool { + ["{pr}", "{branch}", "{branch_slug}", "{sha}", "{short_sha}"] + .iter() + .any(|p| t.contains(p)) +} + +/// A template filled in for a pull request. A host label longer than DNS +/// allows (63 characters) is cut to fit, as hosts cut a long branch's slug. +/// None when the template isn't valid or names a value the pull request +/// doesn't have. +pub fn expand(template: &str, v: Vars) -> Option { + let t = template.trim(); + check_template(t).ok()?; + if t.is_empty() { + return None; + } + let need = |p: &str, have: bool| !t.contains(p) || have; + if !(need("{pr}", v.pr > 0) + && need("{branch}", !v.branch.is_empty()) + && need("{branch_slug}", !v.branch.is_empty()) + && need("{sha}", !v.sha.is_empty()) + && need("{short_sha}", !v.sha.is_empty())) + { + return None; + } + let rest = &t["https://".len()..]; + let cut = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let (host_t, tail_t) = rest.split_at(cut); + let fill = |s: &str, host: bool| { + let branch = if host { + branch_slug(v.branch) + } else { + v.branch.to_string() + }; + s.replace("{pr}", &v.pr.to_string()) + .replace("{branch_slug}", &branch_slug(v.branch)) + .replace("{branch}", &branch) + .replace("{short_sha}", v.sha.get(..7).unwrap_or(v.sha)) + .replace("{sha}", v.sha) + .replace("{owner}", &branch_slug(v.owner)) + .replace("{repo}", &branch_slug(v.repo)) + }; + let host: Vec = fill(host_t, true) + .split('.') + .map(|l| { + if l.len() > 63 { + l[..63].trim_end_matches('-').to_string() + } else { + l.to_string() + } + }) + .collect(); + Some(format!("https://{}{}", host.join("."), fill(tail_t, false))) +} + +// ── which app, and the answer ───────────────────────────────────────────── + +/// Folders a monorepo keeps its apps under. +const APP_HOMES: &[&str] = &[ + "apps", + "packages", + "services", + "sites", + "projects", + "frontends", + "web", + "clients", +]; + +/// The app a changed path belongs to: the folder under a monorepo's apps +/// folder, else the path's first folder. +pub fn app_of(path: &str) -> Option { + let segs: Vec<&str> = path.split('/').collect(); + if segs.len() < 2 { + return None; + } + if APP_HOMES.contains(&segs[0]) && segs.len() >= 3 { + return Some(segs[1].to_string()); + } + Some(segs[0].to_string()) +} + +/// The apps a repository's tree has: each folder under a monorepo's apps +/// folder. +pub fn apps_of(tree: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for p in tree { + let segs: Vec<&str> = p.split('/').collect(); + if segs.len() >= 3 && APP_HOMES.contains(&segs[0]) { + let a = segs[1].to_string(); + if !out.contains(&a) { + out.push(a); + } + } + } + out +} + +fn names(name: &str, app: &str) -> bool { + let (n, a) = (norm(name), norm(app)); + a.len() >= 3 && n.contains(&a) +} + +/// How well a preview's name fits the change: it names a changed app (2), +/// names nothing known (0), names an app the change doesn't touch or reads +/// as a backend with no pages (-1). +pub fn app_score(name: &str, changed: &[String], apps: &[String]) -> i32 { + let changed_apps: Vec = changed.iter().filter_map(|p| app_of(p)).collect(); + if changed_apps.iter().any(|a| { + names(name, a) && (apps.is_empty() || apps.contains(a) || !APP_HOMES.contains(&a.as_str())) + }) { + return 2; + } + if apps + .iter() + .any(|a| names(name, a) && !changed_apps.contains(a)) + { + return -1; + } + let w = words(name); + if w.iter().any(|x| { + matches!( + x.as_str(), + "api" | "backend" | "server" | "graphql" | "worker" | "storybook" + ) + }) { + return -1; + } + 0 +} + +fn describe(s: &Sighting) -> String { + if s.name.is_empty() { + s.source.phrase().to_string() + } else { + format!("{} `{}`", s.source.phrase(), s.name) + } +} + +/// The one answer from every sighting: see the module's rules. +pub fn resolve(all: &[Sighting], changed: &[String], apps: &[String]) -> Answer { + fn pick<'a>( + group: Vec<&'a Sighting>, + changed: &[String], + apps: &[String], + ) -> Vec<&'a Sighting> { + let named: Vec = group + .iter() + .map(|s| { + if s.name.is_empty() { + 0 + } else { + app_score(&s.name, changed, apps) + } + }) + .collect(); + let best = named.iter().copied().max().unwrap_or(0); + group + .into_iter() + .zip(named) + .filter(|(_, sc)| *sc == best) + .map(|(s, _)| s) + .collect() + } + let up_with_url = |g: &[&Sighting]| -> Option { + g.iter() + .filter(|s| s.ready == Ready::Up && !s.url.is_empty()) + .min_by_key(|s| s.source) + .map(|s| Found { + url: s.url.clone(), + source: s.source, + name: s.name.clone(), + tied: s.tied, + }) + }; + let tied = pick(all.iter().filter(|s| s.tied).collect(), changed, apps); + if let Some(f) = up_with_url(&tied) { + return Answer::Up(f); + } + if let Some(b) = tied + .iter() + .filter(|s| s.ready == Ready::Building) + .min_by_key(|s| s.source) + { + return Answer::Building(describe(b)); + } + let up_without_url = tied.iter().any(|s| s.ready == Ready::Up); + if !up_without_url { + if let Some(f) = tied + .iter() + .filter(|s| matches!(s.ready, Ready::Failed | Ready::Gone)) + .min_by_key(|s| s.source) + { + let how = if f.ready == Ready::Failed { + "failed" + } else { + "was taken down" + }; + return Answer::Failed(format!("{} {how}", describe(f))); + } + } + let untied = pick(all.iter().filter(|s| !s.tied).collect(), changed, apps); + match up_with_url(&untied) { + Some(f) => Answer::Up(f), + None => Answer::Nothing, + } +} + +/// Minutes from `since` to `now` (RFC 3339), 0 when either can't be read. +pub fn minutes_between(since: &str, now: &str) -> i64 { + match ( + chrono::DateTime::parse_from_rfc3339(since), + chrono::DateTime::parse_from_rfc3339(now), + ) { + (Ok(a), Ok(b)) => (b - a).num_minutes().max(0), + _ => 0, + } +} + +/// Seconds from `since` to `now` (RFC 3339); a large number when `since` +/// can't be read, so a look is due. +pub fn seconds_between(since: &str, now: &str) -> i64 { + match ( + chrono::DateTime::parse_from_rfc3339(since), + chrono::DateTime::parse_from_rfc3339(now), + ) { + (Ok(a), Ok(b)) => (b - a).num_seconds(), + _ => i64::MAX, + } +} + +#[cfg(test)] +mod tests; diff --git a/services/common/src/preview_find/tests.rs b/services/common/src/preview_find/tests.rs new file mode 100644 index 000000000..cc7e4f966 --- /dev/null +++ b/services/common/src/preview_find/tests.rs @@ -0,0 +1,356 @@ +//! Replays of each route a preview's address is published on, with payloads +//! shaped like the code host's own listings and like real preview bots' +//! comments (names and hosts made up). + +use super::*; + +const HEAD: &str = "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b"; +/// The head commit's time: a comment edited after it speaks of it. +const HEAD_AT: &str = "2026-11-17T10:00:00Z"; + +fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() +} + +fn fixture(text: &str) -> serde_json::Value { + serde_json::from_str(text).expect("fixture is JSON") +} + +fn deployment_list(text: &str) -> Vec<(serde_json::Value, Vec)> { + fixture(text) + .as_array() + .unwrap() + .iter() + .map(|d| { + ( + d["deployment"].clone(), + d["statuses"].as_array().cloned().unwrap_or_default(), + ) + }) + .collect() +} + +fn changed_web() -> Vec { + s(&["apps/web/src/app/signup/page.tsx"]) +} + +fn apps() -> Vec { + s(&["web", "admin"]) +} + +#[test] +fn a_hosts_deployments_give_the_changed_apps_preview_of_the_head() { + let d = deployment_list(include_str!("fixtures/deployments.json")); + let seen = deployments(&d, HEAD); + // The older commit's deploy and the production deploy are never this + // head's preview. + assert_eq!(seen.len(), 2, "{seen:?}"); + assert!(seen.iter().all(|x| x.tied && x.ready == Ready::Up)); + // The newest status says where it stands, and its environment address + // is the site (the target is a console page). + let web = seen.iter().find(|x| x.name.contains("web")).unwrap(); + assert_eq!( + web.url, + "https://web-git-feature-signup-form-team.host.example" + ); + // A monorepo: the app the change touches, never another app's. + assert_eq!( + resolve(&seen, &changed_web(), &apps()), + Answer::Up(Found { + url: "https://web-git-feature-signup-form-team.host.example".into(), + source: Source::Deployment, + name: "Preview – web".into(), + tied: true, + }) + ); + let admin_change = s(&["apps/admin/src/pages/users.tsx"]); + match resolve(&seen, &admin_change, &apps()) { + Answer::Up(f) => assert!(f.url.starts_with("https://admin-"), "{f:?}"), + a => panic!("{a:?}"), + } +} + +#[test] +fn a_workflow_jobs_environment_still_building_is_waited_on() { + let d = deployment_list(include_str!("fixtures/workflow_environment.json")); + let seen = deployments(&d, HEAD); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].ready, Ready::Building); + // Its log link is a run on the code host, never the preview. + assert_eq!(seen[0].url, ""); + assert!(matches!( + resolve(&seen, &changed_web(), &apps()), + Answer::Building(w) if w.contains("pr-12") + )); +} + +#[test] +fn a_deploy_that_failed_or_was_taken_down_is_said_never_waited_on() { + let mk = |state: &str| { + vec![( + serde_json::json!({"sha": HEAD, "environment": "preview/feature-x", "transient_environment": true}), + vec![ + serde_json::json!({"id": 1, "state": state, "created_at": "2026-11-17T10:01:00Z"}), + ], + )] + }; + for (state, word) in [ + ("failure", "failed"), + ("error", "failed"), + ("inactive", "taken down"), + ] { + let seen = deployments(&mk(state), HEAD); + match resolve(&seen, &changed_web(), &[]) { + Answer::Failed(w) => assert!(w.contains(word), "{w}"), + a => panic!("{state}: {a:?}"), + } + } +} + +#[test] +fn a_deploy_status_on_the_head_gives_the_preview_and_never_a_ci_log() { + let seen = statuses(&fixture(include_str!("fixtures/statuses.json")), HEAD); + // The CI build's status and the host's rule-check status don't read as a + // deploy of the preview. + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!( + seen[0].url, + "https://deploy-preview-12--acme-web.static-host.example" + ); + assert!(matches!( + resolve(&seen, &changed_web(), &[]), + Answer::Up(f) if f.source == Source::CommitStatus + )); + // Another commit's combined status says nothing of this head. + assert!(statuses( + &fixture(include_str!("fixtures/statuses.json")), + "0aa11bb22cc" + ) + .is_empty()); +} + +#[test] +fn a_preview_check_runs_output_carries_the_address() { + let seen = check_runs( + &fixture(include_str!("fixtures/check_runs.json")), + HEAD, + &[], + ); + // The end-to-end check and the unit tests aren't the deploy. + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!(seen[0].url, "https://8c1d2e3f.web.edge-host.example"); + assert_eq!(seen[0].ready, Ready::Up); +} + +#[test] +fn a_preview_job_named_by_the_workflows_counts_even_when_its_name_doesnt_say_preview() { + let runs = serde_json::json!({"check_runs": [ + {"name": "Ship web", "head_sha": HEAD, "status": "completed", "conclusion": "success", + "output": {"summary": "Live at https://web-12.review.your-domain.example", "text": null}} + ]}); + assert!(check_runs(&runs, HEAD, &[]).is_empty()); + let covers = vec![crate::preview::Covering { + check: "Ship web".into(), + role: Some(crate::preview::Role::Preview), + workflow: ".github/workflows/preview.yml".into(), + }]; + let seen = check_runs(&runs, HEAD, &covers); + assert_eq!(seen[0].url, "https://web-12.review.your-domain.example"); +} + +#[test] +fn a_bot_comment_edited_in_place_is_read_row_by_row_and_an_older_commits_is_not() { + let list = fixture(include_str!("fixtures/comments.json")); + let seen = comments(list.as_array().unwrap(), HEAD, HEAD_AT); + // A person's comment and the comment that names an older commit give + // nothing; the table gives one row per app, never its console links. + assert_eq!(seen.len(), 2, "{seen:?}"); + let web = seen.iter().find(|x| x.name == "web").unwrap(); + assert_eq!(web.ready, Ready::Building); + let admin = seen.iter().find(|x| x.name == "admin").unwrap(); + assert_eq!(admin.ready, Ready::Up); + assert!(seen.iter().all(|x| x.tied && !is_console(&x.url))); + // The change is in the web app, still building: wait for it, never take + // the admin app's preview instead. + assert!(matches!( + resolve(&seen, &changed_web(), &apps()), + Answer::Building(w) if w.contains("web") + )); + // Before the head's time, an unnamed comment speaks of an older push. + let early = comments(list.as_array().unwrap(), HEAD, "2026-11-17T11:00:00Z"); + assert!(early.iter().all(|x| !x.tied)); +} + +#[test] +fn a_comment_naming_the_head_commit_gives_its_preview() { + let list = fixture(include_str!("fixtures/comment_head.json")); + let seen = comments(list.as_array().unwrap(), HEAD, HEAD_AT); + assert!( + seen.iter().all(|x| x.tied && x.ready == Ready::Up), + "{seen:?}" + ); + let urls: Vec<&str> = seen.iter().map(|x| x.url.as_str()).collect(); + assert!(urls.contains(&"https://deploy-preview-12--acme-web.static-host.example")); + assert!(urls.contains(&"https://acme.pages.example/web/pr-preview/pr-12/")); + assert!(!urls.iter().any(|u| u.contains("/deploys/"))); +} + +#[test] +fn a_description_link_counts_only_when_nothing_on_the_head_has_an_address() { + let link = body( + "## Preview\nPreview: https://pr-12.preview.your-domain.example\nDocs: https://docs.example.org/guide", + HEAD, + ); + assert_eq!(link.len(), 1); + assert!(!link[0].tied); + // A check on the head says the deploy passed but prints no address: + // the link is used. + let mut all = link.clone(); + all.push(Sighting { + source: Source::CheckRun, + name: "Deploy preview".into(), + url: String::new(), + ready: Ready::Up, + tied: true, + }); + assert!(matches!( + resolve(&all, &[], &[]), + Answer::Up(f) if f.source == Source::Body && !f.tied + )); + // The head's deploy still building: wait, the link may serve an older + // build. + all.push(Sighting { + source: Source::Deployment, + name: "pr-12".into(), + url: String::new(), + ready: Ready::Building, + tied: true, + }); + assert!(matches!(resolve(&all, &[], &[]), Answer::Building(_))); +} + +#[test] +fn the_most_direct_source_wins_between_answers_on_the_head() { + let mut all = deployments( + &deployment_list(include_str!("fixtures/deployments.json")), + HEAD, + ); + all.extend(statuses( + &fixture(include_str!("fixtures/statuses.json")), + HEAD, + )); + all.extend(body( + "Preview: https://pr-12.preview.your-domain.example", + HEAD, + )); + assert!(matches!( + resolve(&all, &changed_web(), &apps()), + Answer::Up(f) if f.source == Source::Deployment + )); + assert_eq!(resolve(&[], &changed_web(), &apps()), Answer::Nothing); +} + +#[test] +fn templates_fill_in_the_pull_request_as_hosts_name_previews() { + assert_eq!(branch_slug("Feature/Signup_Form!!"), "feature-signup-form"); + assert_eq!(branch_slug("--a//b--"), "a-b"); + let v = Vars { + pr: 12, + branch: "feature/signup-form", + sha: HEAD, + owner: "acme", + repo: "web", + }; + assert_eq!( + expand("https://pr-{pr}.preview.your-domain.example", v).as_deref(), + Some("https://pr-12.preview.your-domain.example") + ); + assert_eq!( + expand("https://{repo}-git-{branch_slug}-team.host.example", v).as_deref(), + Some("https://web-git-feature-signup-form-team.host.example") + ); + // In a path the branch keeps its slashes; in a host it is a slug. + assert_eq!( + expand("https://previews.your-domain.example/{branch}/", v).as_deref(), + Some("https://previews.your-domain.example/feature/signup-form/") + ); + assert_eq!( + expand("https://{short_sha}.web.edge-host.example", v).as_deref(), + Some("https://4f2c9e1.web.edge-host.example") + ); + // A host label longer than DNS allows is cut to 63 characters. + let long = Vars { + branch: "feature/a-very-long-branch-name-that-keeps-going-and-going-past-the-limit", + ..v + }; + let u = expand("https://{branch_slug}--site.static-host.example", long).unwrap(); + let label = u["https://".len()..].split('.').next().unwrap(); + assert!(label.len() <= 63 && !label.ends_with('-'), "{label}"); + // Nothing to fill a placeholder with: no address. + assert_eq!( + expand("https://pr-{pr}.x.example", Vars { pr: 0, ..v }), + None + ); +} + +#[test] +fn a_template_is_checked_as_the_team_types_it() { + assert!(check_template("").is_ok()); + assert!(check_template("https://pr-{pr}.preview.your-domain.example").is_ok()); + assert!(check_template("http://pr-{pr}.x.example").is_err()); + assert!(check_template("https://pr-{number}.x.example").is_err()); + // A fixed address is a shared environment, not a pull request's own. + assert!(check_template("https://staging.your-domain.example").is_err()); + assert!(check_template("https://x.example/$(id)/{pr}").is_err()); +} + +#[test] +fn addresses_are_read_from_text_with_what_labels_them() { + assert_eq!( + pick_url( + "[Visit Preview](https://web-abc.host.example) and https://docs.example.org", + false + ) + .as_deref(), + Some("https://web-abc.host.example") + ); + assert_eq!(pick_url("see https://docs.example.org/guide", false), None); + assert_eq!( + pick_url("see https://docs.example.org/guide", true).as_deref(), + Some("https://docs.example.org/guide") + ); + assert!(is_console( + "https://app.static-host.example/sites/x/deploys/1" + )); + assert!(is_console("https://ci.example.org/gh/acme/web/4411")); + assert!(!is_console( + "https://deploy-preview-12--acme-web.static-host.example" + )); + assert!(is_code_host("https://github.com/acme/web/actions/runs/1")); + assert!(!site_like("https://img.shields.io/badge/x.svg")); +} + +#[test] +fn the_app_a_preview_is_named_after_is_matched_to_the_changed_paths() { + let tree = s(&[ + "apps/web/package.json", + "apps/admin/package.json", + "packages/ui/src/a.ts", + ]); + assert_eq!(apps_of(&tree), s(&["web", "admin", "ui"])); + let a = apps_of(&tree); + assert_eq!(app_score("Preview – web", &changed_web(), &a), 2); + assert_eq!(app_score("Preview – admin", &changed_web(), &a), -1); + assert_eq!(app_score("api-pr-12", &changed_web(), &a), -1); + assert_eq!(app_score("Preview", &changed_web(), &a), 0); +} + +#[test] +fn time_between_reads_rfc3339_and_a_missing_time_is_due() { + assert_eq!( + minutes_between("2026-11-17T10:00:00Z", "2026-11-17T10:45:30Z"), + 45 + ); + assert_eq!(minutes_between("", "2026-11-17T10:45:30Z"), 0); + assert_eq!(seconds_between("", "2026-11-17T10:45:30Z"), i64::MAX); +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 6ffc07112..fc27eeb40 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -461,6 +461,12 @@ fn build_app(state: Arc) -> Router { ) .route("/runs/close", post(routes::run_close::close_runs)) .route("/repos", get(routes::api::list_repos)) + .route( + "/repos/:owner/:name/preview-access", + get(routes::preview_access::get) + .put(routes::preview_access::put) + .delete(routes::preview_access::delete), + ) .route( "/repos/:owner/:name/staging-cms", get(routes::staging_cms::get) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 653924dc4..81c890cc9 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -503,6 +503,10 @@ pub const CAPABILITIES: &[Capability] = &[ "graph::rebuild", "infrastructure::refresh_infrastructure", "infrastructure::refresh_repo_infrastructure", + // A repository's preview access (see routes::preview_access). + "preview_access::get", + "preview_access::put", + "preview_access::delete", // The staging-only CMS write connection (see routes::staging_cms). "staging_cms::get", "staging_cms::put", diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index c9dde8039..fd93e20fb 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -69,6 +69,7 @@ pub mod plan_chat_tools; pub mod plans; pub mod plugin_pkgs; pub mod plugins; +pub mod preview_access; pub mod repo_setup; pub mod review_lessons; pub mod reviewer; diff --git a/services/gateway/src/routes/preview_access.rs b/services/gateway/src/routes/preview_access.rs new file mode 100644 index 000000000..466da4a5f --- /dev/null +++ b/services/gateway/src/routes/preview_access.rs @@ -0,0 +1,251 @@ +//! A repository's preview access (Settings, Repositories, Preview access): +//! optional. The preview's address template, for a host that publishes it +//! nowhere CoderHelm reads, and how an automated browser gets through a +//! protected preview, with one secret the team stores. See +//! `common::preview_access` for the rules (the secret sealed, never +//! returned, sent only to the preview's own host). + +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{ + extract::{Path, State}, + http::StatusCode, + Extension, Json, +}; +use common::preview_access::{self, Kind, PreviewAccess}; +use serde_json::{json, Value}; +use tracing::error; + +use crate::models::Claims; +use crate::AppState; + +type Reply = Result, (StatusCode, Json)>; + +fn fail(status: StatusCode, message: &str) -> (StatusCode, Json) { + ( + status, + Json(json!({ "error": message, "code": crate::openapi::default_code(status) })), + ) +} + +fn internal(context: &str, e: String) -> (StatusCode, Json) { + error!(error = %e, "{context}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +fn repo_of(owner: &str, name: &str) -> Result)> { + let repo = format!("{owner}/{name}"); + let ok = repo.len() <= 200 + && !repo.contains("..") + && repo + .chars() + .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/'); + if ok { + Ok(repo) + } else { + Err(fail( + StatusCode::BAD_REQUEST, + "That isn't a repository name.", + )) + } +} + +fn forbidden() -> (StatusCode, Json) { + fail( + StatusCode::FORBIDDEN, + "Only admins can change a repository's preview access.", + ) +} + +/// What the request asks to keep, checked: the access, and the secret to +/// seal ("" keeps the one saved). `prior`: the kind saved before and +/// whether a secret is saved. +pub fn read_body( + repo: &str, + body: &Value, + prior: Option<(Kind, bool)>, +) -> Result<(PreviewAccess, String), String> { + let s = |k: &str| body[k].as_str().unwrap_or("").trim().to_string(); + let kind = Kind::parse(&s("kind")).ok_or( + "Pick how the preview is protected: none, a header, a query parameter or a password.", + )?; + let a = PreviewAccess { + repo: repo.to_string(), + kind, + address: s("address"), + }; + a.validate()?; + let secret = body["secret"].as_str().unwrap_or("").trim().to_string(); + if kind == Kind::None { + return Ok((a, String::new())); + } + if secret.is_empty() { + // A saved secret is kept only for the same kind: another kind's + // secret has another shape. + return match prior { + Some((k, true)) if k == kind => Ok((a, String::new())), + _ => Err("Enter the secret the preview takes.".into()), + }; + } + preview_access::check_secret(kind, &secret)?; + Ok((a, secret)) +} + +async fn read_item( + state: &AppState, + team_id: &str, + repo: &str, +) -> Result>, (StatusCode, Json)> { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(preview_access::sk(repo))) + .send() + .await + .map(|r| r.item) + .map_err(|e| internal("Failed to read the preview access", e.to_string())) +} + +fn sealed_of(item: &std::collections::HashMap) -> Option { + item.get(preview_access::SECRET_ATTR) + .and_then(|v| v.as_s().ok().cloned()) + .filter(|s| !s.is_empty()) +} + +/// GET /api/repos/:owner/:name/preview-access +pub async fn get( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + let item = read_item(&state, &claims.team_id, &repo).await?; + Ok(Json( + match item.as_ref().and_then(PreviewAccess::from_item) { + Some(a) => a.view(item.as_ref().and_then(sealed_of).is_some()), + None => json!({ "configured": false, "repo": repo }), + }, + )) +} + +/// PUT /api/repos/:owner/:name/preview-access +/// Body: `{kind, address?, secret?}`. The secret is required the first +/// time for a protected kind and kept when left out later. +pub async fn put( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + let prior = read_item(&state, &claims.team_id, &repo).await?; + let prior_sealed = prior.as_ref().and_then(sealed_of); + let prior_kind = prior + .as_ref() + .and_then(PreviewAccess::from_item) + .map(|a| (a.kind, prior_sealed.is_some())); + let (a, secret) = + read_body(&repo, &body, prior_kind).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let sealed = if a.kind == Kind::None { + None + } else if secret.is_empty() { + prior_sealed + } else { + let cipher = super::alerts::cipher(&state); + Some( + preview_access::seal(&cipher, &claims.team_id, &repo, &secret) + .await + .map_err(|e| internal("Failed to seal the preview access secret", e))?, + ) + }; + let mut item = a.item(&claims.team_id); + let secret_set = sealed.is_some(); + if let Some(s) = sealed { + item.insert(preview_access::SECRET_ATTR.into(), AttributeValue::S(s)); + } + item.insert("updated_by".into(), AttributeValue::S(claims.email.clone())); + item.insert( + "updated_at".into(), + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ); + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .set_item(Some(item)) + .send() + .await + .map_err(|e| internal("Failed to save the preview access", e.to_string()))?; + Ok(Json(a.view(secret_set))) +} + +/// DELETE /api/repos/:owner/:name/preview-access +pub async fn delete( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(claims.team_id.clone())) + .key("sk", AttributeValue::S(preview_access::sk(&repo))) + .send() + .await + .map_err(|e| internal("Failed to remove the preview access", e.to_string()))?; + Ok(Json(json!({ "configured": false, "repo": repo }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_protected_kind_needs_its_secret_the_first_time_and_keeps_it_after() { + let body = json!({"kind": "header", "secret": "X-Bypass: abc123"}); + let (a, secret) = read_body("acme/web", &body, None).unwrap(); + assert_eq!(a.kind, Kind::Header); + assert_eq!(secret, "X-Bypass: abc123"); + let keep = json!({"kind": "header"}); + assert!(read_body("acme/web", &keep, None).is_err()); + assert_eq!( + read_body("acme/web", &keep, Some((Kind::Header, true))) + .unwrap() + .1, + "" + ); + // Another kind's secret has another shape: a new one is asked for. + let other = json!({"kind": "basic"}); + assert!(read_body("acme/web", &other, Some((Kind::Header, true))).is_err()); + } + + #[test] + fn the_address_alone_is_enough_and_is_checked() { + let ok = json!({"kind": "none", "address": "https://pr-{pr}.preview.example.com"}); + let (a, secret) = read_body("acme/web", &ok, None).unwrap(); + assert_eq!(a.address, "https://pr-{pr}.preview.example.com"); + assert!(secret.is_empty()); + let fixed = json!({"kind": "none", "address": "https://staging.example.com"}); + assert!(read_body("acme/web", &fixed, None).is_err()); + let bad = json!({"kind": "header", "secret": "nocolon"}); + assert!(read_body("acme/web", &bad, None).is_err()); + assert!(read_body("acme/web", &json!({"kind": "magic"}), None).is_err()); + } + + #[test] + fn repository_names_are_checked() { + assert_eq!(repo_of("acme", "web").unwrap(), "acme/web"); + assert!(repo_of("acme", "..").is_err()); + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 449ceca56..aea185278 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3237,47 +3237,61 @@ impl GitHubClient { .await } - /// The address each deployment of `sha` reports, as (environment, url): - /// the newest status of each deployment that has one. - pub async fn deployment_urls( + /// The deployments on commit `sha`, each with its newest statuses (the + /// deployments listing filtered by sha, then each one's statuses), for + /// `common::preview_find::deployments`. Empty when the installation + /// can't read deployments. + pub async fn deployments_with_statuses( &self, owner: &str, repo: &str, sha: &str, - ) -> Result, Box> { - let deps = self - .get(&format!( - "{API_BASE}/repos/{owner}/{repo}/deployments?sha={sha}&per_page=10" - )) - .await?; + ) -> Result< + Vec<(serde_json::Value, Vec)>, + Box, + > { + let Some(deps) = self + .get_granted( + "deployments", + &format!("/repos/{owner}/{repo}/deployments?sha={sha}&per_page=20"), + ) + .await? + else { + return Ok(Vec::new()); + }; let mut out = Vec::new(); - for d in deps.as_array().into_iter().flatten().take(10) { - let (Some(id), env) = (d["id"].as_u64(), d["environment"].as_str().unwrap_or("")) - else { + for d in deps.as_array().into_iter().flatten().take(20) { + let Some(id) = d["id"].as_u64() else { continue; }; let st = self - .get(&format!( - "{API_BASE}/repos/{owner}/{repo}/deployments/{id}/statuses?per_page=5" - )) - .await?; - if let Some(url) = st - .as_array() - .into_iter() - .flatten() - .filter_map(|s| { - s["environment_url"] - .as_str() - .or_else(|| s["target_url"].as_str()) - }) - .find(|u| u.starts_with("https://")) - { - out.push((env.to_string(), url.to_string())); - } + .get_granted( + "deployments", + &format!("/repos/{owner}/{repo}/deployments/{id}/statuses?per_page=10"), + ) + .await? + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default(); + out.push((d.clone(), st)); } Ok(out) } + /// When commit `sha` was made (its committer's time, RFC 3339). + pub async fn commit_time( + &self, + owner: &str, + repo: &str, + sha: &str, + ) -> Result> { + let c = self.git_commit(owner, repo, sha).await?; + Ok(c["committer"]["date"] + .as_str() + .or_else(|| c["author"]["date"].as_str()) + .unwrap_or("") + .to_string()) + } + /// Points a ref outside `refs/heads/` (no workflow starts on it) at /// `sha`, creating it when it doesn't exist. Only for CoderHelm's own /// refs, such as the one its pull request screenshots are kept on. diff --git a/services/worker/src/passes/ci_repro.rs b/services/worker/src/passes/ci_repro.rs index 549b40b1b..e09f0d74b 100644 --- a/services/worker/src/passes/ci_repro.rs +++ b/services/worker/src/passes/ci_repro.rs @@ -427,7 +427,7 @@ pub(crate) async fn two_way( } /// The team's test address for the repository (Tests settings), as set. -async fn test_address(state: &WorkerState, team_id: &str, repo: &str) -> Option { +pub(crate) async fn test_address(state: &WorkerState, team_id: &str, repo: &str) -> Option { let st = common::e2e::store::Store::new(&state.dynamo, &state.config.tests_table_name); if !st.enabled() { return None; diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 1a7767d66..6d08b5578 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -308,8 +308,10 @@ pub fn decide_all(status: &str, seen: &Seen, marks: &Marks) -> Act { /// Whether the head's preview needs a look: the change's recorded state is /// of another head or not settled. A look that read nothing new (`fresh` -/// false) leaves a pending preview to the next change on the pull request. -pub fn preview_due(stored: &str, head: &str, fresh: bool) -> bool { +/// false) leaves a pending preview until `preview_find::POLL_SECS` after +/// its last look (`now`): a host's deploy finishing changes nothing else +/// on the pull request, and the wait is bounded (`preview::settle`). +pub fn preview_due(stored: &str, head: &str, fresh: bool, now: &str) -> bool { if head.is_empty() { return false; } @@ -319,7 +321,11 @@ pub fn preview_due(stored: &str, head: &str, fresh: bool) -> bool { Some(st) if super::preview::settled(&st, head) => false, // Ready: its pages are captured now, whatever else changed. Some(st) if st.stage == common::preview::Stage::Ready => true, - Some(_) => fresh, + Some(st) => { + fresh + || common::preview_find::seconds_between(&st.looked_at, now) + >= common::preview_find::POLL_SECS + } } } @@ -1005,10 +1011,14 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> }; let mut seen = seen; seen.preview_due = seen.open - && (preview_due(&c.preview, &seen.head, kept.is_none()) - || common::preview::State::from_json(&c.preview).is_some_and(|st| { - st.head == seen.head && super::preview::unread_failure(&st, &seen.failing) - })); + && (preview_due( + &c.preview, + &seen.head, + kept.is_none(), + &chrono::Utc::now().to_rfc3339(), + ) || common::preview::State::from_json(&c.preview).is_some_and(|st| { + st.head == seen.head && super::preview::unread_failure(&st, &seen.failing) + })); let mut act = resume_after_limit(&c.status, &seen, &c.marks, &c.limit_ended) .unwrap_or_else(|| decide_all(&c.status, &seen, &c.marks)); let mut performed = Performed::NotStarted; @@ -1398,7 +1408,8 @@ mod tests { #[test] fn an_unchecked_preview_is_picked_up_after_the_run_ended() { let mut seen = open(); - seen.preview_due = preview_due("", &seen.head, true); + let now = "2026-11-17T10:00:00Z"; + seen.preview_due = preview_due("", &seen.head, true, now); assert!(seen.preview_due); assert_eq!( decide_all("completed", &seen, &Marks::default()), @@ -1418,17 +1429,25 @@ mod tests { ..Default::default() } .to_json(); - assert!(!preview_due(&done, &seen.head, true)); - assert!(preview_due(&done, "another", false)); - // Pending and nothing new on the pull request: the next change. + assert!(!preview_due(&done, &seen.head, true, now)); + assert!(preview_due(&done, "another", false, now)); + // Pending and nothing new on the pull request: looked at again once + // a poll's time has passed since its last look. let pending = common::preview::State { head: seen.head.clone(), stage: common::preview::Stage::Deploying, + looked_at: "2026-11-17T09:59:30Z".into(), ..Default::default() } .to_json(); - assert!(!preview_due(&pending, &seen.head, false)); - assert!(preview_due(&pending, &seen.head, true)); + assert!(!preview_due(&pending, &seen.head, false, now)); + assert!(preview_due(&pending, &seen.head, true, now)); + assert!(preview_due( + &pending, + &seen.head, + false, + "2026-11-17T10:02:00Z" + )); // Never for a run still in flight. assert_eq!( decide_all("running", &seen, &Marks::default()), diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 3ee18abb0..8f8ee7721 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -15,14 +15,20 @@ //! the workflows need (only labels the team's settings allow, never a //! shared environment's), starts a workflow that counts labels only from //! a push with an empty commit on CoderHelm's own branch, and reads the -//! covering checks' results and the preview's address. +//! covering checks' results, and finds the head's preview wherever the +//! team's host or CI publishes it (`common::preview_find`: deployments, +//! deploy statuses, preview checks, bot comments, the description, the +//! team's address template), waiting a bounded time while it builds. //! - [`capture`] runs once the preview is up and its end-to-end checks //! passed, in a step of the watch: a failed capture says why in one line -//! and is never retried into a pass. +//! and is never retried into a pass. A protected preview is opened with +//! the access the team saved for the repository (`common::preview_access`). use aws_sdk_dynamodb::types::AttributeValue; use base64::Engine as _; use common::preview::{self as pv, CheckResult, Outcome, Shot, Stage, State}; +use common::preview_access::{self as pa, PreviewAccess}; +use common::preview_find::{self as pf, Answer}; use tracing::{info, warn}; use super::attr_s; @@ -113,12 +119,8 @@ fn outcome_of(run: &serde_json::Value) -> Outcome { } } -/// The covering checks' newest runs on the head, and the preview address -/// any of them printed. -fn covering_results( - runs: &serde_json::Value, - covers: &[pv::Covering], -) -> (Vec, Option) { +/// The covering checks' newest runs on the head. +fn covering_results(runs: &serde_json::Value, covers: &[pv::Covering]) -> Vec { // The newest run of each covering check that ran: a check skipped on // the draft and run once it was ready reads as run, and a later event // that skips it (another label added) doesn't undo a run. @@ -140,26 +142,193 @@ fn covering_results( None => newest.push((name, r)), } } - let mut out: Vec = Vec::new(); - let mut url = None; - for (name, r) in newest { - if url.is_none() { - url = [ - r["output"]["summary"].as_str(), - r["output"]["text"].as_str(), - r["details_url"].as_str(), - ] - .into_iter() - .flatten() - .find_map(pv::url_in); - } - out.push(CheckResult { + newest + .into_iter() + .map(|(name, r)| CheckResult { name: name.to_string(), outcome: outcome_of(r), url: r["html_url"].as_str().unwrap_or("").to_string(), + }) + .collect() +} + +/// The repository's preview access with its opened secret ("" when it has +/// none). None when the team saved none. +pub(crate) async fn load_access( + state: &WorkerState, + team_id: &str, + repo: &str, +) -> Option<(PreviewAccess, String)> { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&pa::sk(repo))) + .send() + .await + .ok()? + .item?; + let a = PreviewAccess::from_item(&item)?; + let sealed = item + .get(pa::SECRET_ATTR) + .and_then(|v| v.as_s().ok()) + .filter(|s| !s.is_empty()); + let secret = match sealed { + Some(sealed) if a.kind != pa::Kind::None => { + let kms = common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + }; + match pa::open(&kms, team_id, repo, sealed).await { + Ok(t) => t, + Err(e) => { + warn!(repo, error = %e, "Could not open the preview access secret"); + String::new() + } + } + } + _ => String::new(), + }; + Some((a, secret)) +} + +/// The team's preview address template for the repository: its preview +/// access, else a Tests settings test address that names the pull request. +async fn template_of( + state: &WorkerState, + team_id: &str, + repo: &str, + access: Option<&PreviewAccess>, +) -> Option { + if let Some(a) = access.map(|a| a.address.trim()).filter(|a| !a.is_empty()) { + return Some(a.to_string()); + } + super::ci_repro::test_address(state, team_id, repo) + .await + .filter(|t| pf::is_per_change(t)) +} + +/// Everything on the pull request that says where the head's preview is. +#[allow(clippy::too_many_arguments)] +async fn sightings( + gh: &GitHubClient, + p: Pr<'_>, + pr: &serde_json::Value, + head: &str, + branch: &str, + runs: &serde_json::Value, + covers: &[pv::Covering], + template: Option<&str>, +) -> Vec { + let mut all = Vec::new(); + match gh.deployments_with_statuses(p.owner, p.repo, head).await { + Ok(d) => all.extend(pf::deployments(&d, head)), + Err(e) => warn!(pr = p.number, error = %e, "Could not read the head's deployments"), + } + match gh.commit_statuses(p.owner, p.repo, head).await { + Ok(Some(c)) => all.extend(pf::statuses(&c, head)), + Ok(None) => {} + Err(e) => warn!(pr = p.number, error = %e, "Could not read the head's statuses"), + } + all.extend(pf::check_runs(runs, head, covers)); + let head_at = gh + .commit_time(p.owner, p.repo, head) + .await + .unwrap_or_default(); + match gh.list_issue_comments(p.owner, p.repo, p.number).await { + Ok(c) => all.extend(pf::comments(&c, head, &head_at)), + Err(e) => warn!(pr = p.number, error = %e, "Could not read the pull request's comments"), + } + all.extend(pf::body(pr["body"].as_str().unwrap_or(""), head)); + if let Some(url) = template.and_then(|t| { + pf::expand( + t, + pf::Vars { + pr: p.number, + branch, + sha: head, + owner: p.owner, + repo: p.repo, + }, + ) + }) { + all.push(pf::Sighting { + source: pf::Source::Template, + name: String::new(), + url, + ready: pf::Ready::Up, + tied: false, }); } - (out, url) + all +} + +/// Where the preview stands once the repository's own preview checks +/// (`from_checks`, None when no workflow covers the change) and what the +/// pull request publishes about the head's preview are put together, with +/// the wait bounded. Pure: every case is tested. +pub fn settle(st: &mut State, from_checks: Option, answer: &Answer, now: &str) { + let waited = pf::minutes_between(&st.waiting_since, now); + let mut waiting_on = String::new(); + match from_checks { + Some(stage) => st.stage = stage, + None => st.stage = Stage::Triggered, + } + match answer { + Answer::Up(f) => { + st.url = f.url.clone(); + st.found = f.clone(); + match from_checks { + // No workflow of the repository's covers it: the host's own + // preview of the head is up. + None => st.stage = Stage::Ready, + // The workflows couldn't be started, but the head has a + // preview: it is checked on that. + Some(Stage::Blocked) => { + st.stage = Stage::Ready; + st.why.clear(); + } + Some(_) => {} + } + } + Answer::Building(what) => { + waiting_on = what.clone(); + if from_checks.is_none() || st.stage == Stage::Ready { + st.stage = Stage::Deploying; + } + } + Answer::Failed(what) => { + if from_checks.is_none() + || matches!(st.stage, Stage::Ready | Stage::Deploying | Stage::Triggered) + { + st.stage = Stage::Failed; + st.why = format!("{what} for this commit, so its pages couldn't be captured"); + } + } + Answer::Nothing if from_checks.is_none() => { + if waited >= pf::GRACE_MINS { + st.stage = Stage::Blocked; + st.why = format!( + "nothing on this commit publishes a preview (no deployment, deploy status, preview check, bot comment or description link) and the team set no preview address in {}, so no page could be captured", + pv::ACCESS_SETTING + ); + } + } + Answer::Nothing => {} + } + if matches!(st.stage, Stage::Triggered | Stage::Deploying) && waited >= pf::WAIT_BUDGET_MINS { + let what = if waiting_on.is_empty() { + "its checks hadn't finished".to_string() + } else { + format!("{waiting_on} was still building") + }; + st.stage = Stage::Blocked; + st.why = format!( + "the preview of this commit wasn't up within {} minutes ({what}), so its pages couldn't be captured; a new push starts the wait again", + pf::WAIT_BUDGET_MINS + ); + } } /// The workflow files at `git_ref`, with their text. @@ -437,85 +606,101 @@ pub async fn advance( }); st.covers = plan.covers.clone(); st.draft_gated = plan.draft_gated.clone(); - if !plan.has_path() { - st.stage = Stage::Blocked; - st.why = - "the repository has no preview deploy for this change, so no page could be captured" - .into(); - save(state, p, &st).await; - return Some(st); - } - // Start what the workflows need: once per label per head. - let mut add = Vec::new(); - for l in &plan.add { - if st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) { - continue; - } - if super::review_pr::may_add_label(state, p.team_id, p.owner, p.repo, l).await { - add.push(l.clone()); + let now = chrono::Utc::now().to_rfc3339(); + st.looked_at = now.clone(); + st.waiting_since = same_head + .map(|s| s.waiting_since.clone()) + .filter(|w| !w.is_empty()) + .unwrap_or_else(|| now.clone()); + let mut from_checks = None; + if plan.has_path() { + // Start what the workflows need: once per label per head. + let mut add = Vec::new(); + for l in &plan.add { + if st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) { + continue; + } + if super::review_pr::may_add_label(state, p.team_id, p.owner, p.repo, l).await { + add.push(l.clone()); + } } - } - let mut blocked = plan.blocked.clone(); - if !add.is_empty() { - match gh.add_labels(p.owner, p.repo, p.number, &add).await { - Ok(_) => { - info!(pr = p.number, labels = ?add, "Added the labels that start the preview and its end-to-end checks"); - st.labels_added.extend(add.iter().cloned()); - if plan.needs_push && !draft && !branch.is_empty() { - let pushed = nudge(gh, p.owner, p.repo, &branch, &head).await; - info!( - pr = p.number, - pushed, "Pushed an empty commit so the labels count" - ); + let mut blocked = plan.blocked.clone(); + if !add.is_empty() { + match gh.add_labels(p.owner, p.repo, p.number, &add).await { + Ok(_) => { + info!(pr = p.number, labels = ?add, "Added the labels that start the preview and its end-to-end checks"); + st.labels_added.extend(add.iter().cloned()); + if plan.needs_push && !draft && !branch.is_empty() { + let pushed = nudge(gh, p.owner, p.repo, &branch, &head).await; + info!( + pr = p.number, + pushed, "Pushed an empty commit so the labels count" + ); + } + } + Err(e) => { + warn!(pr = p.number, error = %e, "Could not add the preview labels"); + blocked.push(format!( + "CoderHelm couldn't add {} ({})", + add.join(", "), + common::truncate_str(&e.to_string(), 120) + )); } - } - Err(e) => { - warn!(pr = p.number, error = %e, "Could not add the preview labels"); - blocked.push(format!( - "CoderHelm couldn't add {} ({})", - add.join(", "), - common::truncate_str(&e.to_string(), 120) - )); } } + let not_allowed: Vec<&String> = plan + .add + .iter() + .filter(|l| { + !st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) + && !on_pr.iter().any(|o| o.eq_ignore_ascii_case(l)) + }) + .collect(); + if !not_allowed.is_empty() && add.is_empty() { + blocked.push(format!( + "the team's label settings don't let CoderHelm add {}", + not_allowed + .iter() + .map(|l| format!("`{l}`")) + .collect::>() + .join(", ") + )); + } + st.checks = covering_results(&runs, &plan.covers); + let triggered = !st.labels_added.is_empty() || draft; + let mut stage = pv::progress(&st.checks, triggered); + let none_ran = st.checks.iter().all(|c| c.outcome == Outcome::Skipped); + if none_ran && !blocked.is_empty() && st.labels_added.is_empty() && !draft { + stage = Stage::Blocked; + st.why = blocked.join("; "); + } + from_checks = Some(stage); } - let not_allowed: Vec<&String> = plan - .add - .iter() - .filter(|l| { - !st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) - && !on_pr.iter().any(|o| o.eq_ignore_ascii_case(l)) - }) - .collect(); - if !not_allowed.is_empty() && add.is_empty() { - blocked.push(format!( - "the team's label settings don't let CoderHelm add {}", - not_allowed - .iter() - .map(|l| format!("`{l}`")) - .collect::>() - .join(", ") - )); - } - let (results, url) = covering_results(&runs, &plan.covers); - st.checks = results; - let triggered = !st.labels_added.is_empty() || draft; - st.stage = pv::progress(&st.checks, triggered); - let none_ran = st.checks.iter().all(|c| c.outcome == Outcome::Skipped); - if none_ran && !blocked.is_empty() && st.labels_added.is_empty() && !draft { - st.stage = Stage::Blocked; - st.why = blocked.join("; "); - } - st.url = match url { - Some(u) => u, - None if matches!(st.stage, Stage::Ready | Stage::Deploying) => gh - .deployment_urls(p.owner, p.repo, &head) - .await - .ok() - .and_then(|d| pv::url_from_deployments(&d)) - .unwrap_or_default(), - None => String::new(), - }; + // Where the head's preview is, wherever the team's host or CI + // publishes it. + let repo_full = format!("{}/{}", p.owner, p.repo); + let access = load_access(state, p.team_id, &repo_full).await; + let template = template_of( + state, + p.team_id, + &repo_full, + access.as_ref().map(|(a, _)| a), + ) + .await; + let seen = sightings( + gh, + p, + pr, + &head, + &branch, + &runs, + &plan.covers, + template.as_deref(), + ) + .await; + let answer = pf::resolve(&seen, &changed, &pf::apps_of(&tree)); + info!(pr = p.number, sightings = seen.len(), answer = ?answer, "Read where the head's preview is"); + settle(&mut st, from_checks, &answer, &now); // Captured on this head already: it stays checked. if st.stage == Stage::Ready { if let Some(prev) = same_head.filter(|s| !s.shots.is_empty() || s.stage == Stage::Checked) { @@ -544,7 +729,10 @@ pub async fn capture( } st.stage = Stage::Checked; if st.url.is_empty() { - st.why = "the preview's address wasn't in its deploy's output or deployments, so its pages couldn't be captured".into(); + st.why = format!( + "the preview's checks passed but nothing on this commit published its address (no deployment, deploy status, preview check, bot comment or description link) and no preview address is set in {}, so its pages couldn't be captured", + pv::ACCESS_SETTING + ); save(state, p, st).await; return; } @@ -553,7 +741,19 @@ pub async fn capture( .next() .unwrap_or("") .to_string(); - let base = format!("https://{host}"); + let base = pv::capture_base(&st.url); + let repo_full = format!("{}/{}", p.owner, p.repo); + let (kind, secret) = match load_access(state, p.team_id, &repo_full).await { + Some((a, s)) if a.kind != pa::Kind::None && !s.is_empty() => (a.kind, s), + _ => (pa::Kind::None, String::new()), + }; + let hide = |t: &str| { + if secret.is_empty() { + t.to_string() + } else { + t.replace(secret.as_str(), "***") + } + }; let tree: Vec = gh .get_tree(p.owner, p.repo, &st.head) .await @@ -561,7 +761,7 @@ pub async fn capture( .unwrap_or_default(); let changed = changed_of(gh, p).await; let pages = pv::routes(&tree, &changed); - let script = pv::capture_script(&base, &pages); + let script = pv::capture_script(&base, &pages, kind); let source = match super::skill_run::pack(&[("capture.mjs".to_string(), script)]) { Ok(b) => b, Err(e) => { @@ -592,7 +792,7 @@ pub async fn capture( key: &key, source, cmd: &cmd, - secret: None, + secret: (!secret.is_empty()).then_some(secret.as_str()), hosts, }, deadline, @@ -603,13 +803,16 @@ pub async fn capture( Ok(o) => { st.why = format!( "the capture didn't run in the sandbox ({})", - common::truncate_str(o.output.lines().next().unwrap_or(""), 120) + common::truncate_str(&hide(o.output.lines().next().unwrap_or("")), 120) ); save(state, p, st).await; return; } Err(e) => { - st.why = format!("the sandbox couldn't run the capture ({e})"); + st.why = format!( + "the sandbox couldn't run the capture ({})", + hide(&e.to_string()) + ); save(state, p, st).await; return; } @@ -620,7 +823,7 @@ pub async fn capture( .find(|(n, _)| n.ends_with("shots.json")) .and_then(|(_, b)| serde_json::from_str(b).ok()) .unwrap_or_default(); - if let Some(why) = pv::why_no_shot(&report) { + if let Some(why) = pv::why_no_shot(&report, kind != pa::Kind::None) { st.why = why; save(state, p, st).await; return; @@ -671,7 +874,7 @@ async fn keep_images( let short = head.get(..12).unwrap_or(head); let mut entries: Vec<(String, Option)> = Vec::new(); let mut shots: Vec<(Shot, String)> = Vec::new(); - for c in report.iter().filter(|c| (1..400).contains(&c.status)) { + for c in report.iter().filter(|c| c.shot()) { let Some((_, b64)) = files .iter() .find(|(n, _)| n.ends_with(&format!("{}.png.b64", c.name))) @@ -735,7 +938,7 @@ mod tests { use super::*; #[test] - fn covering_runs_are_read_with_the_preview_address_they_print() { + fn covering_runs_are_read_newest_first() { let runs = serde_json::json!({"check_runs": [ {"name": "Deploy Preview Web App", "status": "completed", "conclusion": "success", "html_url": "https://github.com/o/r/runs/1", @@ -754,11 +957,10 @@ mod tests { ..Default::default() }, ]; - let (r, url) = covering_results(&runs, &covers); + let r = covering_results(&runs, &covers); assert_eq!(r.len(), 2); assert_eq!(r[0].outcome, Outcome::Passed); assert_eq!(r[1].outcome, Outcome::Running); - assert_eq!(url.as_deref(), Some("https://pr-9.preview-web.example.com")); assert_eq!(pv::progress(&r, true), Stage::Deploying); } @@ -776,7 +978,7 @@ mod tests { check: "E2E on preview".into(), ..Default::default() }]; - let (r, _) = covering_results(&runs, &covers); + let r = covering_results(&runs, &covers); assert_eq!(r.len(), 1); assert_eq!(r[0].outcome, Outcome::Passed); } @@ -797,4 +999,117 @@ mod tests { }; assert!(!settled(&pending, "abc")); } + + const T0: &str = "2026-11-17T10:00:00Z"; + + fn waiting() -> State { + State { + head: "abc".into(), + waiting_since: T0.into(), + ..Default::default() + } + } + + fn up(source: pf::Source) -> Answer { + Answer::Up(pf::Found { + url: "https://pr-12.preview.example.com".into(), + source, + name: String::new(), + tied: true, + }) + } + + #[test] + fn a_hosts_own_preview_counts_when_no_workflow_covers_the_change() { + let mut st = waiting(); + settle( + &mut st, + None, + &up(pf::Source::Deployment), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Ready); + assert_eq!(st.url, "https://pr-12.preview.example.com"); + assert_eq!(st.found.source, pf::Source::Deployment); + let mut st = waiting(); + settle( + &mut st, + None, + &Answer::Building("the deployment".into()), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Deploying); + assert!(st.pending()); + } + + #[test] + fn a_preview_still_building_after_its_checks_passed_is_waited_on() { + let mut st = waiting(); + settle( + &mut st, + Some(Stage::Ready), + &Answer::Building("the deployment `pr-12`".into()), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Deploying); + // The workflows couldn't start, but the head has its preview. + let mut st = waiting(); + st.why = "the label isn't allowed".into(); + settle( + &mut st, + Some(Stage::Blocked), + &up(pf::Source::Comment), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Ready); + assert!(st.why.is_empty()); + } + + #[test] + fn a_failed_head_deploy_is_said_with_where_it_was_read() { + let mut st = waiting(); + settle( + &mut st, + None, + &Answer::Failed("the head commit's deployment `Preview` failed".into()), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Failed); + assert!(st.why.contains("deployment `Preview` failed"), "{}", st.why); + } + + #[test] + fn the_wait_is_bounded() { + // Nothing at all on the head: a short grace, then no preview. + let mut st = waiting(); + settle(&mut st, None, &Answer::Nothing, "2026-11-17T10:02:00Z"); + assert_eq!(st.stage, Stage::Triggered); + let mut st = waiting(); + settle(&mut st, None, &Answer::Nothing, "2026-11-17T10:07:00Z"); + assert_eq!(st.stage, Stage::Blocked); + assert!(st.why.contains(pv::ACCESS_SETTING), "{}", st.why); + // Building for longer than the budget: said, never waited on for ever. + let mut st = waiting(); + settle( + &mut st, + None, + &Answer::Building("the deploy status `site/deploy-preview`".into()), + "2026-11-17T11:00:00Z", + ); + assert_eq!(st.stage, Stage::Blocked); + assert!( + st.why.contains("60 minutes") && st.why.contains("still building"), + "{}", + st.why + ); + let mut st = waiting(); + settle( + &mut st, + Some(Stage::Deploying), + &Answer::Nothing, + "2026-11-17T11:05:00Z", + ); + assert_eq!(st.stage, Stage::Blocked); + assert!(st.why.contains("checks hadn't finished")); + } }