diff --git a/docs/self-host/config-reference.md b/docs/self-host/config-reference.md index 5b9269ef4..71cd2b548 100644 --- a/docs/self-host/config-reference.md +++ b/docs/self-host/config-reference.md @@ -128,6 +128,7 @@ The CDK app turns the config into environment variables on the gateway, streamin |---|---| | `APP_URL`, `API_URL` | Your hostname, when you have one | | `PUBLIC_URL_PARAMETER` | The SSM parameter that holds the CloudFront URL, when you have no domain | +| `SELF_HOSTED` | `1` on every self-hosted install: links never fall back to CoderHelm's hosted addresses, and support goes to `SUPPORT_INBOX` | | `SITE_URL` | `siteUrl` | | `CODERHELM_ACCOUNT_ID` | `account` (the account teams' read-only roles trust) | | `LOG_READER_TEMPLATE_URL` | `logReaderTemplateUrl` | diff --git a/docs/self-host/email.md b/docs/self-host/email.md index 4c03f0d69..a6290b3e2 100644 --- a/docs/self-host/email.md +++ b/docs/self-host/email.md @@ -34,3 +34,9 @@ and deploy again. Turning it on before the identity is verified makes the deploy ## Templates The email templates are created by the email stack with your URLs filled in. `email.logoUrl` and `email.privacyUrl` change the header logo and the footer link. + +## Links in emails and messages + +Every link CoderHelm sends from your install points at your install: emails (run results, invites, approvals, the weekly summary and its unsubscribe link), Slack and Teams cards, Jira comments and GitHub comments all use your own address. The header logo loads from your install (`/favicon.svg`) unless you set `email.logoUrl`, so opening an email never calls CoderHelm's servers. Support and "reply to unsubscribe" go to `email.supportInbox` (by default `email.from`), never to CoderHelm support. The only coderhelm.com links left are the public docs on docs.coderhelm.com. + +If the install doesn't know its own address (no `APP_URL` and `API_URL`, and the CloudFront address not yet readable from SSM), links stay relative rather than pointing anywhere else, the services log an error at start, and **Settings, then Setup** fails **Web address answers** until a deploy sets it. diff --git a/infra/lib/service-env.ts b/infra/lib/service-env.ts index 7c85a2038..b1a73f950 100644 --- a/infra/lib/service-env.ts +++ b/infra/lib/service-env.ts @@ -31,6 +31,9 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record // Self-hosted installs: which release this is (Settings → System), and // the updater the system routes ask. The hosted deployment has neither. if (cfg.layout === "single-origin") { + // A self-hosted install: its links never fall back to the hosted + // addresses, and support goes to its own inbox (public_urls.rs). + env.SELF_HOSTED = "1"; Object.assign(env, stampEnvironment(releaseStamp(cfg))); // Whether "Sign in with Google" is on (Settings, then Setup checks it). env.GOOGLE_SIGN_IN = cfg.integrations.googleSignIn ? "true" : "false"; diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 4c478b926..34175d96b 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -324,6 +324,10 @@ test("the manifest landing: self-host only, may write only this install's secret const api = t["coderhelm-prod-api"]; const gw = envOf(api, "coderhelm-prod-gateway"); assert.equal(gw.SETUP_ENDPOINTS, "1"); + // Every service knows it is self-hosted, so no link falls back to the hosted addresses. + for (const [stack, fn] of [["coderhelm-prod-api", "coderhelm-prod-gateway"], ["coderhelm-prod-worker", "coderhelm-prod-worker"]] as const) { + assert.equal(envOf(t[stack], fn).SELF_HOSTED, "1", fn); + } const policies = JSON.stringify(api.findResources("AWS::IAM::Policy")); assert.ok(policies.includes("SetupStoresGithubAppKeys")); assert.ok(policies.includes("secret:coderhelm/prod/secrets-??????"), "only this install's secret"); @@ -338,6 +342,7 @@ test("the manifest landing: self-host only, may write only this install's secret const hostedCfg = loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }); const hosted = synth(hostedCfg, zoneContext("654654210434", "us-east-1", "coderhelm.com")); assert.equal(envOf(hosted["coderhelm-prod-api"], "coderhelm-prod-gateway").SETUP_ENDPOINTS, undefined); + assert.equal(envOf(hosted["coderhelm-prod-api"], "coderhelm-prod-gateway").SELF_HOSTED, undefined); assert.ok(!JSON.stringify(hosted["coderhelm-prod-api"].findResources("AWS::IAM::Policy")).includes("SetupStoresGithubAppKeys")); // The install guide reads launch/latest.json from the public bucket in the browser. hosted["coderhelm-prod-log-analyzer"].hasResourceProperties("AWS::S3::Bucket", { diff --git a/lambda/log-analyzer/handler.py b/lambda/log-analyzer/handler.py index 907bf58c7..9a02b7e50 100644 --- a/lambda/log-analyzer/handler.py +++ b/lambda/log-analyzer/handler.py @@ -39,7 +39,9 @@ MODEL_ID = os.environ.get("MODEL_ID", "claude-sonnet-4-6") CODERHELM_ACCOUNT_ID = os.environ["CODERHELM_ACCOUNT_ID"] LOOKBACK_HOURS = int(os.environ.get("LOOKBACK_HOURS", "24")) -DASHBOARD_URL = os.environ.get("DASHBOARD_URL", "https://app.coderhelm.com") +# This deployment's dashboard (the deploy always sets it); never the hosted +# dashboard, which a self-hosted install's teams can't sign in to. +DASHBOARD_URL = os.environ["DASHBOARD_URL"].rstrip("/") # Team usage counters (empty: usage isn't counted). ANALYTICS_TABLE = os.environ.get("ANALYTICS_TABLE_NAME", "") diff --git a/lambda/tests/test_log_analyzer.py b/lambda/tests/test_log_analyzer.py index 24e780b48..41c555664 100644 --- a/lambda/tests/test_log_analyzer.py +++ b/lambda/tests/test_log_analyzer.py @@ -17,6 +17,7 @@ def load_handler(model_id): os.environ.update( CODERHELM_ACCOUNT_ID="000000000000", + DASHBOARD_URL="https://coderhelm.example.com", MODEL_ID=model_id, AWS_DEFAULT_REGION="us-east-1", ) diff --git a/services/common/src/agent_policy/mod.rs b/services/common/src/agent_policy/mod.rs index 8c5462e1b..b01d431e1 100644 --- a/services/common/src/agent_policy/mod.rs +++ b/services/common/src/agent_policy/mod.rs @@ -68,7 +68,11 @@ pub fn next_id() -> String { .to_string() } -/// Where the dashboard lives (links in Slack, Teams and email). -pub const DASHBOARD_URL: &str = "https://app.coderhelm.com"; -/// Where the gateway answers signed approval links. -pub const API_URL: &str = "https://api.coderhelm.com"; +/// Where this install's dashboard lives (links in Slack, Teams and email). +pub fn dashboard_url() -> &'static str { + crate::public_urls::app_url_from_env() +} +/// Where this install's gateway answers signed approval links. +pub fn api_url() -> &'static str { + crate::public_urls::api_url_from_env() +} diff --git a/services/common/src/agent_policy/notify.rs b/services/common/src/agent_policy/notify.rs index 88680e7bc..543b14d61 100644 --- a/services/common/src/agent_policy/notify.rs +++ b/services/common/src/agent_policy/notify.rs @@ -11,7 +11,7 @@ use crate::notify::{Block, Button, Message, Size, Text, Tone}; use super::approvals::Approval; use super::links::{self, Channel, LinkClaims}; use super::signin::Prompt; -use super::{API_URL, DASHBOARD_URL}; +use super::{api_url, dashboard_url}; /// A signed link to an approval for a channel (or a person, for email). pub fn approval_link( @@ -36,7 +36,8 @@ pub fn approval_link( }, ); format!( - "{API_URL}/agent-approvals/link?t={}&do={}", + "{}/agent-approvals/link?t={}&do={}", + api_url(), urlencoding::encode(&token), urlencoding::encode(action) ) @@ -45,7 +46,8 @@ pub fn approval_link( /// The dashboard page for an approval (signed in). pub fn approval_page(a: &Approval) -> String { format!( - "{DASHBOARD_URL}/settings/agents?approval={}", + "{}/settings/agents?approval={}", + dashboard_url(), urlencoding::encode(&a.id) ) } @@ -134,7 +136,7 @@ pub fn sign_in_message(p: &Prompt, run_id: &str) -> Message { } else { "Connect" }, - format!("{DASHBOARD_URL}{}", p.link_path), + format!("{}{}", dashboard_url(), p.link_path), )], full_width: false, } @@ -196,6 +198,52 @@ mod tests { } } + /// A self-hosted install's approval cards and sign-in prompts link to + /// the install, in every channel, never to the hosted service. + #[test] + fn a_self_hosted_install_links_to_itself() { + use crate::public_urls::{hosted_mentions, pretend_self_hosted, EXAMPLE_SELF_HOST}; + pretend_self_hosted(); + let a = card(); + let p = super::super::signin::prompt( + "figma", + "Figma", + super::super::signin::Need::Personal, + true, + "read this file", + ); + let messages = [ + approval_message("s3cret", "TEAM#1", &a, Channel::Slack), + approval_message("s3cret", "TEAM#1", &a, Channel::Teams), + sign_in_message(&p, "run-1"), + ]; + let mut out = vec![ + approval_page(&a), + approval_link( + "s3cret", + "TEAM#1", + &a, + Channel::Email, + "ada@example.org", + "approve", + ), + ]; + for m in &messages { + for b in &m.buttons { + assert!(b.url.starts_with(EXAMPLE_SELF_HOST), "{}", b.url); + } + for kind in crate::notify::ChannelKind::ALL { + out.push(kind.render(m).to_string()); + } + } + crate::public_urls::override_for_this_thread(None); + for o in &out { + assert_eq!(hosted_mentions(o), Vec::::new(), "{o}"); + } + assert!(out[0].starts_with(EXAMPLE_SELF_HOST)); + assert!(out[1].starts_with(EXAMPLE_SELF_HOST)); + } + #[test] fn sign_in_messages_link_to_the_dashboard() { let p = super::super::signin::prompt( diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e13d7d026..778dc1a3e 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -95,6 +95,8 @@ pub mod rewards; pub mod run_fail; /// Run statuses; which ones a person set; closing and reopening a run. pub mod run_status; +#[cfg(test)] +mod selfhost_links; pub mod skill_apply; pub mod skill_compat; pub mod skills; diff --git a/services/common/src/mcp_remote/oauth.rs b/services/common/src/mcp_remote/oauth.rs index f316b3b55..b1ce7ce5c 100644 --- a/services/common/src/mcp_remote/oauth.rs +++ b/services/common/src/mcp_remote/oauth.rs @@ -189,7 +189,9 @@ pub fn registration_request(a: &AuthServer, redirect_uri: &str, scopes: &[String }; let mut body = serde_json::json!({ "client_name": CLIENT_NAME, - "client_uri": "https://coderhelm.com", + // The install that asks: the callback's origin (a self-hosted + // install's own address, never the hosted site). + "client_uri": origin_of(redirect_uri), "redirect_uris": [redirect_uri], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], @@ -207,6 +209,14 @@ pub fn registration_request(a: &AuthServer, redirect_uri: &str, scopes: &[String .header("Accept", "application/json") } +/// `https://host[:port]` of a URL, or the URL itself when it has no host. +fn origin_of(u: &str) -> String { + match url::Url::parse(u) { + Ok(p) if p.host_str().is_some() => p.origin().ascii_serialization(), + _ => u.to_string(), + } +} + /// Reads a registration reply. pub fn parse_registration(r: &HttpResponse) -> Result { let doc = r.json().unwrap_or_default(); @@ -615,6 +625,7 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(r.body.as_ref().unwrap()).unwrap(); assert_eq!(body["token_endpoint_auth_method"], "none"); assert_eq!(body["redirect_uris"], j!(["https://x.example.com/cb"])); + assert_eq!(body["client_uri"], "https://x.example.com"); assert_eq!( body["grant_types"], j!(["authorization_code", "refresh_token"]) diff --git a/services/common/src/public_urls.rs b/services/common/src/public_urls.rs index 14968f74c..bec18aef8 100644 --- a/services/common/src/public_urls.rs +++ b/services/common/src/public_urls.rs @@ -9,8 +9,15 @@ //! It only exists once the deploy finishes, so a read that fails is tried //! again (at most every 30 seconds) on later requests. //! -//! With neither (local runs, tests) the stage decides, as it always did. +//! With neither (local runs, tests) the stage decides, as it always did, on +//! the hosted deployment only. A self-hosted install never falls back to the +//! hosted addresses: until its own address is known its links are relative +//! (`/runs/...`), it logs an error at start, and Setup checks fail +//! ([`problem`]). Links that belong to an install (runs, reviews, settings, +//! approvals, unsubscribing) must come from here; `tests/no_hosted_urls.rs` +//! refuses hardcoded hosted addresses anywhere else. +use std::cell::RefCell; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -30,6 +37,10 @@ const RETRY_AFTER: Duration = Duration::from_secs(30); /// The marketing site the hosted deployment links to when SITE_URL is unset. const HOSTED_SITE: &str = "https://coderhelm.com"; +/// The hosted deployment's support inbox and platform admin (defaults only +/// there; a self-hosted install uses its own). +const HOSTED_SUPPORT: &str = "support@coderhelm.com"; +const HOSTED_ADMIN: &str = "admin@coderhelm.com"; fn clean(u: &str) -> String { u.trim().trim_end_matches('/').to_string() @@ -59,7 +70,90 @@ pub fn from_single(url: &str) -> Option { } } +/// What a test sets for its own thread instead of the environment: the +/// install's URLs, its marketing site, and whether it is self-hosted. +#[derive(Debug, Clone)] +pub struct Override { + pub urls: Option, + pub site: Option, + pub self_hosted: bool, +} + +/// A thread's override as stored: the URLs, the site, self-hosted or not. +type Stored = (Option<&'static Urls>, Option<&'static str>, bool); + +thread_local! { + static OVERRIDE: RefCell> = const { RefCell::new(None) }; +} + +/// Sets (or with `None` clears) this thread's [`Override`]. For tests that +/// render messages as a given deployment would; the services never call it. +/// Each call leaks its two short strings, which only tests can afford. +#[doc(hidden)] +pub fn override_for_this_thread(o: Option) { + let v = o.map(|o| { + let urls: Option<&'static Urls> = o.urls.map(|u| &*Box::leak(Box::new(u))); + let site: Option<&'static str> = o.site.map(|s| &*Box::leak(s.into_boxed_str())); + (urls, site, o.self_hosted) + }); + OVERRIDE.with(|c| *c.borrow_mut() = v); +} + +/// The address tests render a self-hosted install's messages with. +#[doc(hidden)] +pub const EXAMPLE_SELF_HOST: &str = "https://coderhelm.example.com"; + +/// Makes this thread a self-hosted install at [`EXAMPLE_SELF_HOST`] with no +/// marketing site (tests only; see [`override_for_this_thread`]). +#[doc(hidden)] +pub fn pretend_self_hosted() { + override_for_this_thread(Some(Override { + urls: from_single(EXAMPLE_SELF_HOST), + site: None, + self_hosted: true, + })); +} + +/// The public resources a self-hosted install may still link to: CoderHelm's +/// docs. Everything else on coderhelm.com is the hosted service. +pub const PUBLIC_HOSTS: &[&str] = &["docs.coderhelm.com"]; + +/// Every coderhelm.com host (or address at it) in `text` other than +/// [`PUBLIC_HOSTS`]: what a self-hosted install's messages must not contain. +pub fn hosted_mentions(text: &str) -> Vec { + let lower = text.to_ascii_lowercase(); + let mut out = Vec::new(); + let mut from = 0; + while let Some(i) = lower[from..].find("coderhelm.com") { + let at = from + i; + let end = at + "coderhelm.com".len(); + let start = lower[..at] + .rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '.' || c == '-')) + .map_or(0, |j| j + 1); + let host = &lower[start..end]; + let next = lower[end..].chars().next(); + let whole = !next.is_some_and(|c| c.is_ascii_alphanumeric() || c == '-'); + if whole && !PUBLIC_HOSTS.contains(&host) { + let ctx_start = lower[..start] + .char_indices() + .rev() + .nth(30) + .map_or(0, |(j, _)| j); + out.push(text[ctx_start..end].to_string()); + } + from = end; + } + out +} + +fn overridden() -> Option { + OVERRIDE.with(|c| *c.borrow()) +} + fn current() -> Option<&'static Urls> { + if let Some((urls, _, _)) = overridden() { + return urls; + } if let Some(u) = URLS.get() { return Some(u); } @@ -71,6 +165,49 @@ fn current() -> Option<&'static Urls> { pub async fn init(client: ssm::Client) { let _ = SSM.set(client); ensure().await; + if let Some(p) = problem() { + tracing::error!(problem = %p, "This install's address is unknown: links in emails, chat and GitHub are relative until it is set"); + } +} + +/// Whether this deployment is a self-hosted install. The deploy sets +/// `SELF_HOSTED`; installs deployed before it are told apart by what only a +/// self-hosted install carries (its setup endpoints, the SSM parameter for +/// its CloudFront address, its release stamp). +pub fn self_hosted() -> bool { + if let Some((_, _, s)) = overridden() { + return s; + } + self_hosted_from(|k| std::env::var(k).ok()) +} + +/// [`self_hosted`]'s rule, on a given environment. +pub fn self_hosted_from(get: impl Fn(&str) -> Option) -> bool { + let on = |k: &str| get(k).is_some_and(|v| matches!(v.trim(), "1" | "true")); + let set = |k: &str| get(k).is_some_and(|v| !v.trim().is_empty()); + on("SELF_HOSTED") + || on("SETUP_ENDPOINTS") + || set("PUBLIC_URL_PARAMETER") + || set("CODERHELM_CONFIG_FINGERPRINT") +} + +/// Why a self-hosted install's links can't be built yet, or `None` when they +/// can (or on the hosted deployment, which has its own defaults). +pub fn problem() -> Option { + if current().is_some() || !self_hosted() { + return None; + } + Some(problem_text(std::env::var("PUBLIC_URL_PARAMETER").ok())) +} + +/// [`problem`]'s words, given the SSM parameter's name (if any). +pub fn problem_text(parameter: Option) -> String { + match parameter.filter(|p| !p.trim().is_empty()) { + Some(p) => format!( + "The install's address isn't readable from the SSM parameter {p} yet. Links in emails, chat and GitHub stay relative until it is. The web stack writes it at the end of a deploy: finish the deploy, or run the doctor." + ), + None => "APP_URL and API_URL aren't set, and there is no PUBLIC_URL_PARAMETER, so this install doesn't know its own address. Links in emails, chat and GitHub stay relative until it does. Deploy again with the installer, which sets them.".to_string(), + } } /// Reads the URL from SSM if it isn't known yet (cheap once it is). @@ -127,18 +264,26 @@ pub fn stage_api_url(stage: &str) -> &'static str { } } -/// The dashboard's base URL, e.g. `https://app.example.com` (no trailing slash). +/// The dashboard's base URL, e.g. `https://app.example.com` (no trailing +/// slash). On a self-hosted install whose address isn't known yet, "" (links +/// stay relative), never the hosted dashboard. pub fn app_url(stage: &str) -> &'static str { - current() - .map(|u| u.app.as_str()) - .unwrap_or_else(|| stage_app_url(stage)) + match current() { + Some(u) => u.app.as_str(), + None if self_hosted() => "", + None => stage_app_url(stage), + } } -/// The API's base URL (webhooks, OAuth callbacks, unsubscribe links). +/// The API's base URL (webhooks, OAuth callbacks, unsubscribe links). On a +/// self-hosted install whose address isn't known yet, "", never the hosted +/// API. pub fn api_url(stage: &str) -> &'static str { - current() - .map(|u| u.api.as_str()) - .unwrap_or_else(|| stage_api_url(stage)) + match current() { + Some(u) => u.api.as_str(), + None if self_hosted() => "", + None => stage_api_url(stage), + } } /// The stage as the services read it (prod when unset, like their configs). @@ -178,20 +323,62 @@ pub fn log_reader_template_url() -> String { /// The marketing site linked from email footers: SITE_URL, none when it is /// empty, and the hosted site when it is unset. pub fn site_url() -> Option<&'static str> { + if let Some((_, site, _)) = overridden() { + return site; + } static SITE: OnceLock> = OnceLock::new(); SITE.get_or_init(|| site_from(std::env::var("SITE_URL").ok())) .as_deref() } -/// [`site_url`]'s rule, on a given value. +/// [`site_url`]'s rule, on a given value: unset means the hosted site, on +/// the hosted deployment only (a self-hosted install links to no site). pub fn site_from(v: Option) -> Option { match v { + None if self_hosted() => None, None => Some(HOSTED_SITE.to_string()), Some(s) if s.trim().is_empty() => None, Some(s) => Some(clean(&s)), } } +/// Where support questions (and unsubscribe requests by mail) go: +/// SUPPORT_INBOX; else, on a self-hosted install, the address its email is +/// sent from (its own admins, never CoderHelm support); else the hosted +/// support inbox. +pub fn support_inbox() -> String { + support_inbox_from( + std::env::var("SUPPORT_INBOX").ok(), + std::env::var("SES_FROM_ADDRESS").ok(), + self_hosted(), + ) +} + +/// [`support_inbox`]'s rule, on given values ("" when a self-hosted install +/// has neither). +pub fn support_inbox_from( + inbox: Option, + from: Option, + self_hosted: bool, +) -> String { + let set = |v: Option| v.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + match (set(inbox), self_hosted) { + (Some(i), _) => i, + (None, true) => set(from).unwrap_or_default(), + (None, false) => HOSTED_SUPPORT.to_string(), + } +} + +/// Who may administer the whole install when PLATFORM_ADMIN_EMAILS is unset: +/// the hosted admin on the hosted deployment, nobody on a self-hosted one. +pub fn default_platform_admins() -> &'static str { + if self_hosted() { + "" + } else { + HOSTED_ADMIN + } +} + /// The host part of a URL (`app.example.com`), for display. pub fn host_of(url: &str) -> &str { let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url); @@ -245,6 +432,103 @@ mod tests { ); } + #[test] + fn self_hosted_is_told_apart() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |k: &str| { + pairs + .iter() + .find(|(n, _)| *n == k) + .map(|(_, v)| v.to_string()) + } + }; + assert!(!self_hosted_from(env(&[]))); + assert!(!self_hosted_from(env(&[( + "APP_URL", + "https://app.coderhelm.com" + )]))); + assert!(self_hosted_from(env(&[("SELF_HOSTED", "1")]))); + assert!(self_hosted_from(env(&[("SETUP_ENDPOINTS", "1")]))); + assert!(self_hosted_from(env(&[( + "PUBLIC_URL_PARAMETER", + "/coderhelm/prod/public-url" + )]))); + assert!(self_hosted_from(env(&[( + "CODERHELM_CONFIG_FINGERPRINT", + "abc" + )]))); + assert!(!self_hosted_from(env(&[ + ("SELF_HOSTED", "0"), + ("PUBLIC_URL_PARAMETER", "") + ]))); + } + + #[test] + fn a_self_hosted_install_never_falls_back_to_the_hosted_addresses() { + override_for_this_thread(Some(Override { + urls: None, + site: None, + self_hosted: true, + })); + assert_eq!(app_url("prod"), ""); + assert_eq!(api_url("prod"), ""); + assert_eq!(app_url_from_env(), ""); + assert!(problem().is_some()); + assert_eq!(site_from(None), None); + override_for_this_thread(Some(Override { + urls: from_single("https://coderhelm.example.com/"), + site: None, + self_hosted: true, + })); + assert_eq!(app_url("prod"), "https://coderhelm.example.com"); + assert_eq!(api_url("prod"), "https://coderhelm.example.com"); + assert!(problem().is_none()); + override_for_this_thread(None); + } + + #[test] + fn the_problem_names_what_is_missing() { + assert!(problem_text(None).contains("APP_URL and API_URL")); + assert!(problem_text(Some("/p".into())).contains("SSM parameter /p")); + } + + #[test] + fn support_goes_to_the_install_on_self_host() { + let s = |v: &str| Some(v.to_string()); + assert_eq!( + support_inbox_from(s("help@example.org"), s("noreply@example.org"), true), + "help@example.org" + ); + assert_eq!( + support_inbox_from(None, s("noreply@example.org"), true), + "noreply@example.org" + ); + assert_eq!(support_inbox_from(s(" "), None, true), ""); + assert_eq!( + support_inbox_from(None, s("noreply@example.org"), false), + "support@coderhelm.com" + ); + } + + #[test] + fn hosted_mentions_spare_the_docs_only() { + assert!(hosted_mentions( + "see https://docs.coderhelm.com/api and https://coderhelm.example.com/runs" + ) + .is_empty()); + assert_eq!( + hosted_mentions("go to https://app.coderhelm.com/x").len(), + 1 + ); + assert_eq!(hosted_mentions("mail support@coderhelm.com").len(), 1); + assert_eq!( + hosted_mentions("").len(), + 1 + ); + assert_eq!(hosted_mentions("API.CODERHELM.COM").len(), 1); + assert!(hosted_mentions("coderhelm.company").is_empty()); + } + #[test] fn host_for_display() { assert_eq!(host_of("https://app.example.com/x"), "app.example.com"); diff --git a/services/common/src/selfhost_links.rs b/services/common/src/selfhost_links.rs new file mode 100644 index 000000000..0094aabff --- /dev/null +++ b/services/common/src/selfhost_links.rs @@ -0,0 +1,140 @@ +//! A self-hosted install's links point at the install. Every link builder and +//! message in this crate that reaches a person (unsubscribe and approval +//! links, review cards, knowledge-source alerts, log fix cards, merge-gate +//! controls, the CI quarantine call) is rendered as an install at +//! `https://coderhelm.example.com`, and nothing it produces may name a +//! coderhelm.com host other than the public docs. Approval cards are checked +//! next to their fixture in `agent_policy::notify`. + +use crate::knowledge::sources::{alert, signin_error, Kind, SignIn, Source}; +use crate::notify::{ChannelKind, Message}; +use crate::public_urls::{ + app_url, hosted_mentions, override_for_this_thread, pretend_self_hosted, EXAMPLE_SELF_HOST, +}; + +fn rendered(m: &Message) -> Vec { + ChannelKind::ALL + .iter() + .map(|k| k.render(m).to_string()) + .chain(m.buttons.iter().map(|b| b.url.clone())) + .collect() +} + +#[test] +fn every_link_and_message_points_at_the_install() { + pretend_self_hosted(); + let app = app_url("prod"); + assert_eq!(app, EXAMPLE_SELF_HOST); + + let mut out: Vec<(&str, String)> = vec![ + ("unsubscribe link", crate::unsubscribe::base_url()), + ("plugin approval link", crate::plugins::signed::url("tok")), + ("CI quarantine call", crate::e2e::ci_setup::quarantine_url()), + ( + "merge gate control", + crate::merge_gate::control_url(app, "acme", "web", 7, crate::merge_gate::Control::Stop), + ), + ]; + + let artifact = crate::plugins::drafts::Artifact { + id: "art1".into(), + plugin_name: "marketing".into(), + kind: "social".into(), + title: "Launch".into(), + version: 3, + ..Default::default() + }; + let card = crate::plugins::chat::review_card( + &artifact, + "We shipped.", + crate::plugins::chat::dashboard("prod"), + ); + out.extend( + rendered(&card) + .into_iter() + .map(|s| ("plugin review card", s)), + ); + + let si = SignIn { + email: "ada@example.org".into(), + name: "Ada".into(), + ..Default::default() + }; + let source = Source { + id: "s1".into(), + kb_id: "kb1".into(), + kind: Some(Kind::Sanity), + name: "Help center".into(), + error: Some(signin_error(&si, Kind::Sanity, String::new(), false)), + signin: Some(si), + ..Default::default() + }; + let err = source.error.clone().unwrap(); + out.extend( + rendered(&alert::signin_message(app, &source, &err)) + .into_iter() + .map(|s| ("knowledge sign-in card", s)), + ); + let (subject, body) = alert::signin_email(app, &source, &err); + out.push(("knowledge sign-in email", format!("{subject}\n{body}"))); + + let fix = crate::alert_notify::fix_message( + "CPU high", + "acme/web", + 7, + "Fix the loop", + "https://github.com/acme/web/pull/7", + &format!("{app}/alerts/detail?id=a1"), + ); + out.extend(rendered(&fix).into_iter().map(|s| ("alert fix card", s))); + + let finding = crate::log_findings::Finding { + rec_id: "f1".into(), + ..Default::default() + }; + let url = format!("{app}/logs?finding=f1"); + let repo_check = + crate::log_findings::repo_check_message(&finding, None, "two candidates", &[], &url); + out.extend( + rendered(&repo_check) + .into_iter() + .map(|s| ("log repo card", s)), + ); + let ticket = crate::log_findings::TicketRecord::default(); + let log_fix = crate::log_findings::fix_message( + &ticket, + "acme/web", + 7, + "Fix the loop", + "https://github.com/acme/web/pull/7", + &url, + ); + out.extend(rendered(&log_fix).into_iter().map(|s| ("log fix card", s))); + + override_for_this_thread(None); + for (what, o) in &out { + assert_eq!(hosted_mentions(o), Vec::::new(), "{what}: {o}"); + } + for (what, o) in out.iter().take(4) { + assert!(o.starts_with(EXAMPLE_SELF_HOST), "{what}: {o}"); + } +} + +#[test] +fn an_install_without_its_address_never_falls_back_to_the_hosted_one() { + override_for_this_thread(Some(crate::public_urls::Override { + urls: None, + site: None, + self_hosted: true, + })); + let out = [ + crate::unsubscribe::base_url(), + crate::plugins::signed::url("tok"), + crate::e2e::ci_setup::quarantine_url(), + crate::agent_policy::dashboard_url().to_string(), + ]; + override_for_this_thread(None); + for o in &out { + assert_eq!(hosted_mentions(o), Vec::::new(), "{o}"); + } +} diff --git a/services/common/tests/no_hosted_urls.rs b/services/common/tests/no_hosted_urls.rs new file mode 100644 index 000000000..f2feafae8 --- /dev/null +++ b/services/common/tests/no_hosted_urls.rs @@ -0,0 +1,168 @@ +//! No hardcoded hosted addresses in the product. +//! +//! A self-hosted install links to itself: its dashboard, API, stream and +//! sign-in come from `public_urls.rs` (APP_URL, API_URL or the SSM parameter). +//! This scans the code that ships (services, lambdas, infra, installer) for +//! the hosted service's own hosts (`app.`, `api.`, `stream.`, `auth.` +//! coderhelm.com) and its marketing site, and fails on any outside the files +//! below, each kept for a stated reason. Comments, Rust test modules and test +//! files are not scanned. Public docs (docs.coderhelm.com) are always fine. + +use std::path::{Path, PathBuf}; + +/// Files that may name a hosted address, and why. +const ALLOWED: &[(&str, &str)] = &[ + ("services/common/src/public_urls.rs", "the one place the hosted defaults live, used only when the deployment is not self-hosted"), + ("services/common/src/hybrid/mod.rs", "hybrid: the hosted API an install talks to once an admin turns hybrid on"), + ("services/gateway/src/routes/hybrid.rs", "hybrid: the hosted side's fallback page for {name}.coderhelm.com"), + ("services/gateway/src/routes/hybrid_install.rs", "hybrid: tells an install it can't reach the hosted API"), + ("services/gateway/src/openapi.rs", "the committed API document names the hosted server; a self-hosted install serves its own (served_document)"), + ("services/common/src/mcp_remote/http.rs", "the User-Agent names the product; not a link anyone opens"), + ("infra/lib/config.ts", "hybrid: the hosted API's default URL"), + ("infra/lib/service-env.ts", "hybrid: the hosted API's default URL"), + ("installer/lib/hybrid.mjs", "hybrid: the hosted API's default URL"), + ("installer/lib/util.mjs", "telemetry endpoint, off unless the admin turns it on"), +]; + +/// Where shipped code lives (relative to the repository root). +const ROOTS: &[&str] = &[ + "services", + "lambda", + "infra/lib", + "infra/bin", + "installer/lib", + "installer/bin", + "selfhost", +]; + +const EXTS: &[&str] = &["rs", "ts", "mjs", "js", "py", "sh", "yaml", "yml", "html"]; + +fn repo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .canonicalize() + .unwrap() +} + +fn files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + let name = e.file_name().to_string_lossy().to_string(); + if p.is_dir() { + if matches!( + name.as_str(), + "target" | "node_modules" | "test" | "tests" | "__pycache__" | "cdk.out" | "golden" + ) { + continue; + } + files(&p, out); + } else if p + .extension() + .is_some_and(|x| EXTS.contains(&x.to_string_lossy().as_ref())) + && !name.contains(".test.") + && !name.starts_with("test_") + { + out.push(p); + } + } +} + +/// A hosted address in this line, if any. +fn hosted(line: &str) -> Option<&'static str> { + let l = line.to_ascii_lowercase(); + [ + "app.coderhelm.com", + "api.coderhelm.com", + "stream.coderhelm.com", + "auth.coderhelm.com", + "://coderhelm.com", + "://www.coderhelm.com", + ] + .into_iter() + .find(|h| { + l.match_indices(h).any(|(i, _)| { + // `x.app.coderhelm.com` is someone's own name, not the hosted app. + h.starts_with("://") + || i == 0 + || !l.as_bytes()[i - 1].is_ascii_alphanumeric() + && l.as_bytes()[i - 1] != b'.' + && l.as_bytes()[i - 1] != b'-' + }) + }) +} + +fn is_comment(t: &str) -> bool { + t.starts_with("//") + || t.starts_with('#') && !t.starts_with("#[") + || t.starts_with("* ") + || t == "*" + || t.starts_with("/*") +} + +#[test] +fn no_hardcoded_hosted_addresses_outside_the_allowed_files() { + let root = repo_root(); + let mut all = Vec::new(); + for r in ROOTS { + files(&root.join(r), &mut all); + } + assert!( + all.len() > 50, + "the scan found the code ({} files)", + all.len() + ); + let mut found = Vec::new(); + for p in &all { + let rel = p + .strip_prefix(&root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + if ALLOWED.iter().any(|(f, _)| *f == rel) { + continue; + } + let Ok(text) = std::fs::read_to_string(p) else { + continue; + }; + for (n, line) in text.lines().enumerate() { + if rel.ends_with(".rs") && line.starts_with("#[cfg(test)]") { + break; + } + let t = line.trim(); + if is_comment(t) { + continue; + } + if let Some(h) = hosted(line) { + found.push(format!("{rel}:{}: {h}: {}", n + 1, t)); + } + } + } + assert!( + found.is_empty(), + "Hardcoded hosted addresses. Build the install's links from common::public_urls (app_url, api_url), or add the file to ALLOWED with the reason it must name the hosted service:\n{}", + found.join("\n") + ); +} + +#[test] +fn the_scan_catches_what_it_should() { + assert_eq!( + hosted(r#"let u = "https://app.coderhelm.com/runs";"#), + Some("app.coderhelm.com") + ); + assert_eq!( + hosted("API_URL=https://api.coderhelm.com"), + Some("api.coderhelm.com") + ); + assert_eq!( + hosted("see https://coderhelm.com/privacy"), + Some("://coderhelm.com") + ); + assert_eq!(hosted("https://docs.coderhelm.com/self-host/"), None); + assert_eq!(hosted("https://acme.app.coderhelm.com"), None); + assert!(is_comment("// https://app.coderhelm.com")); + assert!(!is_comment("#[derive(Debug)]")); +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 1f611b427..d424cf042 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1182,6 +1182,8 @@ async fn main() -> Result<(), Error> { .route("/google/callback", get(routes::auth::google_callback)) .route("/github", get(routes::auth::github_login)) .route("/github/callback", get(routes::auth::github_callback)) + // This deployment's GitHub App on GitHub (install, or configure). + .route("/github/app", get(routes::github::app_install)) // Hybrid linking: GitHub sign-in that proves an installation is yours. .route( "/github/callback/hybrid", diff --git a/services/gateway/src/openapi.rs b/services/gateway/src/openapi.rs index b0c2d6792..6e3c831ac 100644 --- a/services/gateway/src/openapi.rs +++ b/services/gateway/src/openapi.rs @@ -427,10 +427,28 @@ pub async fn serve() -> impl axum::response::IntoResponse { (axum::http::header::CONTENT_TYPE, "application/json"), (axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"), ], - DOC.get_or_init(document_json).clone(), + served_document(DOC.get_or_init(document_json).clone()), ) } +/// The document as this deployment serves it: a self-hosted install names +/// its own API as the server, not the hosted one. +fn served_document(doc: String) -> String { + if !common::public_urls::self_hosted() { + return doc; + } + let Ok(mut v) = serde_json::from_str::(&doc) else { + return doc; + }; + v["servers"] = serde_json::json!([{ + "url": common::public_urls::api_url_from_env(), + "description": "This install" + }]); + serde_json::to_string_pretty(&v) + .map(|s| s + "\n") + .unwrap_or(doc) +} + /// The document as committed: pretty JSON with a final newline. pub fn document_json() -> String { let mut doc = serde_json::to_value(ApiDoc::openapi()).expect("the OpenAPI document serializes"); @@ -505,6 +523,26 @@ fn inline_schemas(node: &mut serde_json::Value) { #[cfg(test)] mod tests { + #[test] + fn a_self_hosted_install_serves_its_own_api_as_the_server() { + use common::public_urls::{from_single, override_for_this_thread, Override}; + override_for_this_thread(Some(Override { + urls: from_single("https://coderhelm.example.com"), + site: None, + self_hosted: true, + })); + let doc = super::served_document(super::document_json()); + override_for_this_thread(None); + let v: serde_json::Value = serde_json::from_str(&doc).unwrap(); + assert_eq!(v["servers"][0]["url"], "https://coderhelm.example.com"); + assert!(!doc.contains("api.coderhelm.com")); + // The hosted deployment serves the committed document unchanged. + assert_eq!( + super::served_document(super::document_json()), + super::document_json() + ); + } + use super::*; use std::collections::BTreeSet; diff --git a/services/gateway/src/routes/agent_policy.rs b/services/gateway/src/routes/agent_policy.rs index 5bcd9a71c..e5ac3f780 100644 --- a/services/gateway/src/routes/agent_policy.rs +++ b/services/gateway/src/routes/agent_policy.rs @@ -960,12 +960,9 @@ pub struct LinkForm { note: String, } +/// This deployment's dashboard (a self-hosted install's own address). fn dashboard_origin(stage: &str) -> &'static str { - if stage == "prod" { - "https://app.coderhelm.com" - } else { - "http://localhost:3000" - } + common::public_urls::app_url(stage) } fn esc(s: &str) -> String { @@ -1317,6 +1314,29 @@ mod tests { ) } + #[test] + fn a_self_hosted_install_opens_its_own_approval_page() { + common::public_urls::pretend_self_hosted(); + let (v, _) = link_view( + "s3cret", + "prod", + &signed(Channel::Slack, "", 2_000), + "approve", + 1_000, + ); + common::public_urls::override_for_this_thread(None); + match v { + LinkView::Open(to) => assert_eq!( + to, + format!( + "{}/settings/agents/?approval=ap_1&do=approve&via=slack", + common::public_urls::EXAMPLE_SELF_HOST + ) + ), + _ => panic!("expected a redirect"), + } + } + #[test] fn slack_and_teams_links_open_the_approval_page_and_never_answer() { for ch in [Channel::Slack, Channel::Teams] { diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 434d6d825..3a1141d47 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -528,7 +528,7 @@ pub async fn rename_team( /// so it never counts. pub(crate) fn is_platform_admin(claims: &Claims) -> bool { let admins = std::env::var("PLATFORM_ADMIN_EMAILS") - .unwrap_or_else(|_| "admin@coderhelm.com".to_string()); + .unwrap_or_else(|_| common::public_urls::default_platform_admins().to_string()); // A support-view session is the team's read-only view, never the admin's // own powers: the admin routes refuse it. claims.support_view.is_none() diff --git a/services/gateway/src/routes/email.rs b/services/gateway/src/routes/email.rs index 4c875d661..c7de22db5 100644 --- a/services/gateway/src/routes/email.rs +++ b/services/gateway/src/routes/email.rs @@ -329,6 +329,35 @@ mod tests { unsubscribe::sign(SECRET, "team-1", "USER#a", unsubscribe::WEEKLY_SUMMARY, exp) } + /// The unsubscribe pages of a self-hosted install link to the install + /// and name no CoderHelm site. + #[tokio::test] + async fn a_self_hosted_install_pages_link_to_itself() { + common::public_urls::pretend_self_hosted(); + let outcomes = [ + Outcome::Confirm { + team: "Acme".into(), + }, + Outcome::Unsubscribed, + Outcome::Test, + Outcome::Invalid, + Outcome::Failed, + ]; + let mut pages = Vec::new(); + for o in &outcomes { + pages.push(body(page(o)).await); + } + common::public_urls::override_for_this_thread(None); + for p in &pages { + assert_eq!( + common::public_urls::hosted_mentions(p), + Vec::::new(), + "{p}" + ); + } + assert!(pages[1].contains(common::public_urls::EXAMPLE_SELF_HOST)); + } + async fn body(resp: Response) -> String { let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20) .await diff --git a/services/gateway/src/routes/github.rs b/services/gateway/src/routes/github.rs index 5c4537de3..c71abbce2 100644 --- a/services/gateway/src/routes/github.rs +++ b/services/gateway/src/routes/github.rs @@ -238,6 +238,50 @@ fn attr_s(val: &str) -> aws_sdk_dynamodb::types::AttributeValue { aws_sdk_dynamodb::types::AttributeValue::S(val.to_string()) } +/// Query for [`app_install`]. +#[derive(Deserialize, Default)] +pub struct AppInstallQuery { + /// Passed on to GitHub, which hands it back on the setup redirect. + #[serde(default)] + pub state: Option, + /// Open this installation's settings instead of a new installation. + #[serde(default)] + pub installation_id: Option, +} + +/// Where this deployment's GitHub App is installed (or an installation of it +/// configured). The slug is this install's own app, never the hosted one. +pub fn app_install_url(slug: &str, q: &AppInstallQuery) -> String { + let slug = urlencoding::encode(slug); + match q.installation_id { + Some(id) => format!("https://github.com/apps/{slug}/installations/{id}"), + None => match q.state.as_deref().filter(|s| !s.is_empty()) { + Some(st) => format!( + "https://github.com/apps/{slug}/installations/new?state={}", + urlencoding::encode(st) + ), + None => format!("https://github.com/apps/{slug}/installations/new"), + }, + } +} + +/// GET /auth/github/app: sends the browser to this deployment's GitHub App +/// on GitHub (the dashboard links here, so a self-hosted install's buttons +/// open its own app). Before the app exists, back to the dashboard's GitHub +/// settings. +pub async fn app_install( + State(state): State>, + axum::extract::Query(q): axum::extract::Query, +) -> axum::response::Redirect { + match crate::auth::github_app::app_slug(&state).await { + Some(slug) => axum::response::Redirect::to(&app_install_url(&slug, &q)), + None => axum::response::Redirect::to(&format!( + "{}/settings/integrations/github/", + common::public_urls::app_url(&state.config.stage) + )), + } +} + #[cfg(test)] mod tests { use super::*; @@ -259,6 +303,26 @@ mod tests { ); } + #[test] + fn the_app_link_is_this_installs_own_app() { + let q = |state: Option<&str>, id: Option| AppInstallQuery { + state: state.map(str::to_string), + installation_id: id, + }; + assert_eq!( + app_install_url("acme-coderhelm", &q(None, None)), + "https://github.com/apps/acme-coderhelm/installations/new" + ); + assert_eq!( + app_install_url("acme-coderhelm", &q(Some("a b&c"), None)), + "https://github.com/apps/acme-coderhelm/installations/new?state=a%20b%26c" + ); + assert_eq!( + app_install_url("acme-coderhelm", &q(Some("x"), Some(42))), + "https://github.com/apps/acme-coderhelm/installations/42" + ); + } + #[test] fn sign_in_url_follows_the_stage() { assert_eq!( diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index e5585fd0e..1b41fbe5b 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -740,8 +740,23 @@ pub fn updates(status: Option<&Value>) -> Check { } } -/// The public address answers over HTTPS. -pub fn public_url(url: &str, status: Option) -> Check { +/// The public address answers over HTTPS. `problem` is set when a +/// self-hosted install doesn't know its own address +/// ([`common::public_urls::problem`]): its links would be relative, so this +/// fails rather than linking anywhere else. +pub fn public_url(url: &str, status: Option, problem: Option<&str>) -> Check { + if let Some(p) = problem { + return Check::not_ok( + Status::Fail, + "url", + I, + "Web address answers", + p.to_string(), + "Links in emails, Slack, Teams and GitHub point at this address.", + Fix::text("Deploy again from your machine: the installer sets the address.") + .command(format!("{CLI} deploy")), + ); + } match status { Some(200..=399) => Check::pass( "url", @@ -1598,6 +1613,9 @@ async fn url_status(state: &AppState) -> (String, Option) { let url = common::public_urls::app_url_from_env() .trim_end_matches('/') .to_string(); + if url.is_empty() { + return (url, None); + } let code = state .http .get(format!("{url}/")) @@ -1828,7 +1846,11 @@ pub async fn run_all(state: &AppState, team_id: &str) -> (Vec, Option Mail { } fn inbox() -> String { - std::env::var("SUPPORT_INBOX") - .ok() - .map(|v| v.trim().to_string()) - .filter(|v| !v.is_empty()) - .unwrap_or_else(|| DEFAULT_INBOX.to_string()) + common::public_urls::support_inbox() } /// Send through SES from the same address as the weekly summary. A failed @@ -3119,6 +3113,46 @@ mod tests { assert_eq!(v[0].author_name, "Coderhelm support"); } + /// A self-hosted install's support emails link to the install and go to + /// its own inbox, never to CoderHelm's site or support. + #[tokio::test] + async fn a_self_hosted_install_emails_link_to_itself() { + use common::public_urls::{hosted_mentions, pretend_self_hosted, EXAMPLE_SELF_HOST}; + pretend_self_hosted(); + let store = Mem::default(); + let alice = person("alpha", "alice"); + let items = Items::default(); + let (t, first) = create( + &store, + &items, + &roster(), + &alice, + &ask("Broken"), + "acme", + "", + ) + .await + .unwrap(); + let mut mails = vec![mail_new_ticket(&inbox(), &t, &first.body)]; + let (t, m) = admin_reply(&store, &admin(), &t.id, "Fixed it", None) + .await + .unwrap(); + mails.extend(mail_support_reply(&t, &m)); + let (t, m) = reply_as_customer(&store, &none(), &alice, &t.id, "Thanks", &[]) + .await + .unwrap(); + mails.push(mail_customer_reply(&inbox(), &t, &m)); + mails.extend(mail_status(&t, "resolved", "Coderhelm support")); + mails.push(mail_team_resolved(&inbox(), &t, "alice")); + common::public_urls::override_for_this_thread(None); + assert!(mails.len() >= 5); + for m in &mails { + let all = format!("{}\n{}\n{}\n{}", m.to, m.subject, m.text, m.html); + assert_eq!(hosted_mentions(&all), Vec::::new(), "{all}"); + } + assert!(mails[0].text.contains(EXAMPLE_SELF_HOST)); + } + #[tokio::test] async fn emails_go_both_ways_and_escape_what_people_typed() { let store = Mem::default(); diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 433b8f1b0..c56af21cd 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -748,6 +748,8 @@ pub mod review_sweep; pub mod review_verdict; pub mod rewards; mod security; +#[cfg(test)] +mod selfhost_links; pub mod skill_compat; pub mod skill_suggest; pub mod skills; @@ -5562,7 +5564,10 @@ async fn lookup_team_installation_id( .and_then(|n| n.parse::().ok()) .filter(|&id| id > 0) .ok_or_else(|| { - "GitHub App is not installed for this team. Please install it at https://github.com/apps/coderhelm/installations/new".to_string() + format!( + "GitHub App is not installed for this team. Install it from {}/settings/integrations/github/", + common::public_urls::app_url_from_env() + ) .into() }) } diff --git a/services/worker/src/passes/selfhost_links.rs b/services/worker/src/passes/selfhost_links.rs new file mode 100644 index 000000000..23f92e76b --- /dev/null +++ b/services/worker/src/passes/selfhost_links.rs @@ -0,0 +1,39 @@ +//! A self-hosted install's GitHub comments and PR text link to the install: +//! the progress comment on an issue, the "consulted agents" line in PR bodies +//! and reviews, and the merge-gate controls. Rendered as an install at +//! `https://coderhelm.example.com`; nothing may name a coderhelm.com host +//! other than the public docs. (The weekly summary is checked next to its +//! fixture in `weekly_summary`.) + +use common::public_urls::{ + hosted_mentions, override_for_this_thread, pretend_self_hosted, EXAMPLE_SELF_HOST, +}; + +#[test] +fn github_comments_link_to_the_install() { + pretend_self_hosted(); + let consulted = vec![super::skills::Consulted { + name: "Payments expert".into(), + repo: "acme/web".into(), + path: ".coderhelm/agents/payments.md".into(), + asked: 2, + answered: 1, + }]; + let out = vec![ + super::format_progress("triage", "01RUN"), + super::format_progress("implement", "01RUN"), + super::skills::consulted_markdown(&consulted, super::skills::app_url("prod")), + common::merge_gate::control_url( + super::skills::app_url("prod"), + "acme", + "web", + 7, + common::merge_gate::Control::Rearm, + ), + ]; + override_for_this_thread(None); + for o in &out { + assert_eq!(hosted_mentions(o), Vec::::new(), "{o}"); + assert!(o.contains(EXAMPLE_SELF_HOST), "{o}"); + } +} diff --git a/services/worker/src/passes/weekly_summary.rs b/services/worker/src/passes/weekly_summary.rs index 3075d5bb7..c702078b9 100644 --- a/services/worker/src/passes/weekly_summary.rs +++ b/services/worker/src/passes/weekly_summary.rs @@ -47,10 +47,7 @@ const SENT_MARKER_SECS: u64 = 14 * 86_400; /// Mail apps read this address for the `mailto:` unsubscribe; requests that /// land there are handled by hand. fn unsubscribe_mailto() -> String { - let inbox = std::env::var("SUPPORT_INBOX") - .ok() - .filter(|s| !s.trim().is_empty()) - .unwrap_or_else(|| "support@coderhelm.com".to_string()); + let inbox = common::public_urls::support_inbox(); format!("mailto:{inbox}?subject=Unsubscribe%20from%20weekly%20summaries") } @@ -2283,6 +2280,45 @@ mod tests { } } + /// A self-hosted install's weekly summary links to the install (runs, + /// settings, unsubscribe) and names no CoderHelm site or support inbox, + /// for every role. + #[test] + fn a_self_hosted_install_summary_links_to_itself() { + use common::public_urls::{hosted_mentions, pretend_self_hosted, EXAMPLE_SELF_HOST}; + pretend_self_hosted(); + let link = format!( + "{}?t={}", + common::unsubscribe::base_url(), + common::unsubscribe::sign( + "s", + "TEAM#1", + "u1", + common::unsubscribe::WEEKLY_SUMMARY, + 2_000_000_000 + ) + ); + let headers = unsubscribe_headers(&link); + let mut out: Vec = headers.iter().map(|(_, v)| v.clone()).collect(); + for access in [Access::Admin, Access::Member, Access::Viewer] { + let e = render(&sample(), access, &link); + out.push(e.subject); + out.push(e.html); + out.push(e.text); + } + common::public_urls::override_for_this_thread(None); + for o in &out { + assert_eq!(hosted_mentions(o), Vec::::new(), "{o}"); + } + // The HTML (after the two headers and the subject) links to the install. + assert!( + out[3].contains(&format!("href=\"{EXAMPLE_SELF_HOST}/")), + "{}", + out[3] + ); + assert!(link.starts_with(EXAMPLE_SELF_HOST)); + } + fn sample() -> Summary { let app = app(); let (start, end) = week();