From 8e9022202487349c47a2031659cdc5ed329aab0d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 13:54:38 -0400 Subject: [PATCH] Hybrid: harden linking, sign-ins, the relay, names and same-site requests A security review of the hybrid self-host features, with a regression test for each fix: - Brokered sign-ins (Notion, Confluence, Google Drive) are finished in a holding partition and become the install's only when it redeems the code with its secret and PKCE verifier. Starting one is rate limited. - Linking CoderHelm's GitHub App needs a confirmation on a page that names the install's address and can't be framed; only installations of CoderHelm's own app count; a link reaches only the repositories the person who linked it can push to (sent to GitHub as the token's repository list); return addresses are compared host by host. - Requests to an install's address (relay forwards, ownership proofs) never follow redirects and read at most 16 KB of the answer. - The API refuses changes sent with cookies from another origin on the same site (customer {name}.coderhelm.com pages share a site with app and api). - Names that read as CoderHelm's own (coderhelm with digit look-alikes, or a part such as app, login, billing or support) are reserved. - The Route 53 permissions also deny anything under CoderHelm's own hosts, mail and certificate-authority records, and names three labels deep. - Relayed events also sign the source and event headers (v2); the intake refuses an event when it can't record its delivery id. - Revoking an install removes its GitHub links and keeps its CloudFront address from registering again. - docs/self-host/security.md gains the hybrid threat model. --- docs/api/openapi.json | 2 +- docs/self-host/hybrid.md | 18 +- docs/self-host/security.md | 56 ++ infra/lib/hybrid.ts | 28 + infra/test/hybrid.test.ts | 23 +- services/common/src/hybrid/broker.rs | 129 +++- services/common/src/hybrid/names.rs | 122 +++- services/common/src/hybrid/relay.rs | 127 +++- services/common/src/hybrid/sign.rs | 124 +++- services/common/src/mcp_remote/runtime.rs | 113 ++++ services/gateway/src/main.rs | 1 + services/gateway/src/middleware/cors.rs | 152 ++++- services/gateway/src/routes/hybrid.rs | 586 +++++++++++++++--- services/gateway/src/routes/hybrid_install.rs | 59 +- services/worker/src/passes/relay_retry.rs | 19 +- 15 files changed, 1431 insertions(+), 128 deletions(-) diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 77b030147..0e70e391e 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -4973,7 +4973,7 @@ }, "/webhooks/relay": { "post": { - "description": "On a hybrid self-hosted install, where CoderHelm's hosted relay forwards the events of CoderHelm's GitHub App (and Jira app) after checking the provider's own signature. Each request is signed with the install's relay key: `X-CoderHelm-Relay-Signature: t=,d=,v1=`, the HMAC-SHA256 of `..`. Requests older than 5 minutes are refused, and so is a delivery id the install has already taken (`409`). `X-CoderHelm-Relay-Source` is `github` or `jira`; for GitHub, `X-CoderHelm-Relay-Event` is GitHub's event type and the body is GitHub's payload, unchanged.", + "description": "On a hybrid self-hosted install, where CoderHelm's hosted relay forwards the events of CoderHelm's GitHub App (and Jira app) after checking the provider's own signature. Each request is signed with the install's relay key: `X-CoderHelm-Relay-Signature: t=,d=,v1=,v2=`, where `v1` is the HMAC-SHA256 of `..` and `v2` of `v2.....` (so the two headers below are signed too). Requests older than 5 minutes are refused, and so is a delivery id the install has already taken (`409`). `X-CoderHelm-Relay-Source` is `github` or `jira`; for GitHub, `X-CoderHelm-Relay-Event` is GitHub's event type and the body is GitHub's payload, unchanged.", "operationId": "receiveRelayedEvent", "parameters": [ { diff --git a/docs/self-host/hybrid.md b/docs/self-host/hybrid.md index 8d29dbf1e..062bcb603 100644 --- a/docs/self-host/hybrid.md +++ b/docs/self-host/hybrid.md @@ -33,15 +33,18 @@ How the pieces are protected: - **Registration.** Your install registers once and gets an id, a secret and a relay key. Both keys are derived from a key on CoderHelm's side, so CoderHelm stores no copy of them; your install keeps them in its own Secrets Manager secret. - **Proof of ownership.** Before a name or an app is linked, CoderHelm asks your install's CloudFront address to answer a challenge with its secret. Names only ever point at a verified install's own CloudFront distribution. -- **Signed both ways.** Every call from your install is signed (`X-CoderHelm-Signature`), and every relayed event is signed with your relay key (`X-CoderHelm-Relay-Signature: t=,d=,v1=`). Your install refuses anything older than 5 minutes and any delivery id it has already taken. -- **Linking proves both sides.** Linking CoderHelm's GitHub App needs your install (its setup key in the guide, or an install admin in Settings) and a GitHub sign-in that shows the installation is yours. A GitHub redirect alone can't link anything. -- **Scoped tokens.** The broker mints tokens only for installations linked to your install, narrowed to the repositories you chose. -- **Revocable.** CoderHelm can turn an install's access off (its name and records go, the relay and broker refuse it), and every action is in an audit log. -- **Same-site safety.** Every address under coderhelm.com is a different site to the browser: CoderHelm's own cookies are host-only (`__Host-`, no Domain attribute) and its CORS lists exact origins, so an install's pages can't read or change coderhelm.com sessions. +- **Signed both ways.** Every call from your install is signed (`X-CoderHelm-Signature`), and every relayed event is signed with your relay key (`X-CoderHelm-Relay-Signature: t=,d=,v1=,v2=`; `v2` also covers the source and event headers). Your install refuses anything older than 5 minutes and any delivery id it has already taken, and refuses an event it couldn't record as taken. +- **Linking proves both sides.** Linking CoderHelm's GitHub App needs your install (its setup key in the guide, or an install admin in Settings), a GitHub sign-in that shows the installation is yours, and a press of **Link** on a CoderHelm page that names your install's address. A GitHub redirect or a link someone sends you can't link anything by itself. +- **Scoped tokens.** The broker mints tokens only for installations linked to your install, narrowed to the repositories you chose and, within those, to the repositories the person who linked it can push to on GitHub. GitHub itself enforces both: they are part of the token request. +- **Sign-ins are yours only once your install takes them.** A Notion, Confluence or Google Drive sign-in is held apart until your install redeems it with its secret and its PKCE verifier, so nobody else can put their account in place of yours. +- **Revocable.** CoderHelm can turn an install's access off (its name and records go, its GitHub links are removed, the relay and broker refuse it, and the same CloudFront can't register again), and every action is in an audit log. +- **Same-site safety.** Addresses under coderhelm.com are the same site as app.coderhelm.com and api.coderhelm.com to a browser, so CoderHelm doesn't rely on that: its cookies are host-only (`__Host-`, no Domain attribute), its CORS lists exact origins, and the API refuses any change sent with cookies from another page on the same site. An install's pages can't read or change coderhelm.com sessions. + +The full threat model, with each attack and what stops it, is in [Security model](./security.md#hybrid-threat-model). ## A CoderHelm address -Pick a name in the guide or in **Settings, System, Domain**. The page checks it as you type: lowercase letters, digits and hyphens, 3 to 40 characters, not reserved (CoderHelm's own hosts such as `app`, `api`, `docs` and `auth`, and names such as `admin`, `support` or `status`), and not taken. +Pick a name in the guide or in **Settings, System, Domain**. The page checks it as you type: lowercase letters, digits and hyphens, 3 to 40 characters, not reserved (CoderHelm's own hosts such as `app`, `api`, `docs` and `auth`, and names such as `admin`, `support` or `status`), not reading as CoderHelm's own (no `coderhelm` in it, even spelled with digits, and no part such as `app`, `login`, `billing` or `support`, as in `app2` or `acme-login`), and not taken. Then everything happens by itself: @@ -58,7 +61,8 @@ A name can change five times a day. Uninstalling with `npx github:CoderHelm/code 1. In the guide (or **Settings, System, Hybrid**), choose **Use CoderHelm's GitHub App**. 2. Press **Install on GitHub**, pick the organization and repositories, and sign in to GitHub when it asks. That sign-in proves the installation is yours. -3. You come back linked. From then on GitHub sends events to CoderHelm, which forwards each one to `https:///webhooks/relay`, and your install asks the broker for tokens when it works on a repository. +3. CoderHelm shows which install the organization is about to be linked to. Check the address and press **Link**. +4. You come back linked. Tokens reach only the repositories you can push to on GitHub; someone with more access can link it again to widen that. From then on GitHub sends events to CoderHelm, which forwards each one to `https:///webhooks/relay`, and your install asks the broker for tokens when it works on a repository. A forward that fails is retried with growing waits for about 24 hours. Both sides show it on their **Deliveries** page with each attempt, the answer and the next retry. Choose your own GitHub App again any time; signing in with GitHub on your install needs your own app. diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 8adfde2f5..08e5c63d5 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -43,6 +43,62 @@ order: 11 Releases are built by GitHub Actions from a tag, with checksums and build provenance attestations (Sigstore, through GitHub). The installer checks both. You can also deploy from source (`--source`) after reviewing the code. +## Hybrid threat model + +This part covers a [hybrid](./hybrid.md) install: one that uses CoderHelm's address, GitHub App or integration apps. A fully private install talks to none of what follows. + +### What is worth protecting + +- **Your code and repositories.** CoderHelm's GitHub App can read and change code. Its installation tokens are the most valuable thing the hybrid side hands out. +- **Your install's identity**: its id, its registration secret and its relay key. Whoever holds them can act as your install toward CoderHelm. +- **Your provider sign-ins** (Notion, Confluence, Google Drive): what your agents read as knowledge. +- **Your events**: GitHub and Jira payloads, which can contain code, titles and comments. +- **Your address**, `yourname.coderhelm.com`, and CoderHelm's own hosts in the same zone (`app`, `api`, `auth`, `docs`). +- **Sessions on app.coderhelm.com and api.coderhelm.com** of people who also use the hosted service. + +### Who might attack + +1. Someone who runs their own hybrid install (and so controls its code, its CloudFront and its address). +2. Anyone on the internet, with no account. +3. Someone who controls one `{name}.coderhelm.com` address and the pages it serves. +4. Someone who can see one install's network traffic. + +### Attacks and what stops them + +| Attack | What stops it | +|---|---| +| Register an install, or act as another one | Anyone may register, but a registration does nothing until CoderHelm's challenge is answered from the install's own CloudFront address with that install's secret. Every later call is signed with the install's secret (HMAC-SHA256 over the time, method, path and body, compared in constant time, at most 5 minutes old). Ids have one fixed shape, so no id can be built to collide with another install's keys. | +| Work out an install's keys | Each install's secret and relay key are HMAC-SHA256 of CoderHelm's master key with a fixed label (`install:` or `relay:`) and the install id. The labels differ, so no install's secret can equal another install's relay key, and a key is useless without the master key. | +| Keep working after CoderHelm turns an install off | Every signed call, token request, sign-in and relayed event checks that the install is active. Revoking also removes its name and its GitHub links, and its CloudFront address can't register again. | +| Send a forged GitHub event | The hosted side checks GitHub's own signature (`X-Hub-Signature-256`) before it looks at anything else, and forwards only to the install that installation is linked to. | +| Send a forged or replayed relayed event to an install | The install checks the relay signature (time, delivery id, body, and from `v2` the source and event headers), refuses anything older than 5 minutes, and takes each delivery id once in its own database. If it can't record the delivery id, it refuses the event and the relay tries again. | +| Forge a Jira event through the relay | The install checks the Forge app's own secret, which CoderHelm forwards but doesn't decide. | +| Get events or tokens for someone else's GitHub organization | A link needs a GitHub sign-in that sees that installation of CoderHelm's app (another app's installation never counts), and a press of **Link** on a CoderHelm page that names the install's address and can't be shown inside another page. One installation links to one install, never to one a hosted team already uses. Tokens reach only the repositories the person who linked it can push to, so read access to one repository can't become write access to all. | +| Mint a wider token | The broker asks GitHub for the token with an explicit list of repositories and permissions, never more than the link allows and never more than the app's own permissions. GitHub refuses anything outside that list. Tokens last at most an hour. | +| Take over someone's Notion, Confluence or Google Drive sign-in | The sign-in is finished in a holding place of its own and becomes the install's only when the install redeems the one-time code with its secret and the PKCE verifier (S256), at the return address it registered. Starting sign-ins is limited per address. | +| Send people somewhere else after linking or signing in | Return addresses are compared host by host against the install's own CloudFront address and name (and the docs install guide); anything else goes to the install's settings page. Sign-in returns must be the install's own callback page, over HTTPS, with no port or user name. | +| Make CoderHelm's servers call something inside AWS | CoderHelm calls an install only at the CloudFront address it proved at registration, which never changes afterwards. Those calls never follow a redirect and read at most 16 KB of the answer. CloudFront's own names can't be pointed at other addresses. | +| Claim a reserved or misleading name | Names are lowercase letters, digits and single hyphens (so no punycode, other alphabets or trailing dots), 3 to 40 characters. CoderHelm's own hosts and a blocklist are refused, and so is any name that reads as CoderHelm's own: `coderhelm` anywhere, digits standing in for letters included, or a part such as `app`, `api`, `login`, `billing` or `support` (`app2`, `acme-login`). | +| Take over another install's name, or point a name elsewhere | A claim is a write that fails when the name exists. The address record must point at the install's own verified CloudFront, proved again just before it is written; the certificate record must have the exact shape ACM uses and point at `acm-validations.aws`. | +| Make CoderHelm write any other DNS record | The code writes only two CNAMEs per name (the name and `_.`) plus the setup page's alias while the name is new, and never overwrites a record it didn't write. Its AWS permissions are a second fence: CNAME, A and AAAA only, in that one zone, never the apex, the wildcard or a reserved name, never anything under CoderHelm's own hosts, never mail or certificate-authority records (`_domainkey`, `_dmarc`, `_mta-sts`, `_acme-challenge`) and never anything three labels deep. | +| Use a customer address against CoderHelm's own sites | Every address under coderhelm.com is the same site as app.coderhelm.com and api.coderhelm.com to a browser, so nothing relies on that. Cookies are `__Host-` (no Domain attribute), so a customer page can neither read nor set them. CORS answers only exact origins, never `*.coderhelm.com`. A change sent with cookies from any other page on the same site is refused. Sign-in messages between windows check the exact origin. | +| Show other content on the "no CoderHelm here yet" page | The wildcard site has one origin, CoderHelm's own fallback page, which shows one of two fixed pages and nothing from the request but whether the name is being set up. | +| Read through the public name check | It answers only whether a name is free (claimed names are public in DNS anyway), carries no cookies, and is limited to 30 checks a minute per address. The install guide's setup routes need the install's one-time setup key. | +| Read other teams' deliveries | Deliveries are read by team, by admins only. An install reads only its own relay and broker records, with its own signature. Stored headers have every secret-looking value removed, and the relay keeps no payload in its records. | +| Read traffic between an install and CoderHelm | Everything is HTTPS. The keys never travel after registration: requests carry only signatures, which are bound to the time, the path and the body. | + +### What CoderHelm can and cannot see + +CoderHelm **can** see: each relayed event's payload while it forwards it (and holds it for up to 24 hours only while retrying), the Forge app's secret as it passes, delivery metadata for 14 days, the installation tokens it mints as it hands them out, your provider sign-ins (sealed with a key only its services can use), your name, your CloudFront address and your two DNS records, and failed-delivery metadata you chose to share. + +CoderHelm **cannot** see: your code at rest, your runs, plans, reviews, memory, knowledge or secrets, your model calls, your AWS account, or your people's sign-ins. It can't sign in to your install. + +### Known limits + +- A link made before the **Link** confirmation and the push-permission limit existed keeps the repositories it had. Link it again to bring it under both. +- Someone who controls CoderHelm's hosted side could mint tokens for linked installations, read relayed events and act as the relay. Choose your own GitHub App and apps (fully private) if that is outside what you accept. +- Install requests carry no one-time number, so someone who could break HTTPS could repeat one within its 5 minutes. They would already see the same traffic, tokens included. + ## Reporting a problem Report security issues privately to the support address in the CoderHelm repository rather than in a public issue. diff --git a/infra/lib/hybrid.ts b/infra/lib/hybrid.ts index 9dc0c1249..6c1cd1237 100644 --- a/infra/lib/hybrid.ts +++ b/infra/lib/hybrid.ts @@ -147,6 +147,34 @@ export class Hybrid extends Construct { }, }), ); + // IAM's `*` crosses dots, so the allow above also matches deeper names. + // A separate deny (conditions inside one statement would AND together) + // fences what the code never writes: anything under a host CoderHelm serves + // (such as `_acme-challenge.app.`, which could get a certificate + // for the dashboard), mail and certificate-authority records anywhere in + // the zone, and names three or more labels deep. + fn_.addToRolePolicy( + new iam.PolicyStatement({ + sid: "HybridNeverDeeper", + effect: iam.Effect.DENY, + actions: ["route53:ChangeResourceRecordSets"], + resources: [zoneArn], + conditions: { + "ForAnyValue:StringLike": { + "route53:ChangeResourceRecordSetsNormalizedRecordNames": [ + `*.*.*.${h.zone}`, + "*_domainkey*", + "*_dmarc*", + "*_mta-sts*", + "*_smtp*", + "*_acme-challenge*", + "*_spf*", + ...reserved.zoneRecords.map((n) => `*.${n}.${h.zone}`), + ], + }, + }, + }), + ); fn_.addEnvironment("HYBRID_ZONE_ID", zone.hostedZoneId); fn_.addEnvironment("HYBRID_FALLBACK_DOMAIN", this.fallback.distributionDomainName); diff --git a/infra/test/hybrid.test.ts b/infra/test/hybrid.test.ts index f3c63f8a2..8879609a4 100644 --- a/infra/test/hybrid.test.ts +++ b/infra/test/hybrid.test.ts @@ -59,9 +59,10 @@ function str(v: unknown): string { test("the provisioning API may change only CNAMEs (and the setup alias) under the zone, in that zone only", () => { const api = hosted()["coderhelm-prod-api"]; const all = statements(api).filter((s) => [].concat(s.Action).some((a: string) => a.startsWith("route53:Change"))); - assert.equal(all.length, 2, "one allow and one deny"); + assert.equal(all.length, 3, "one allow and two denies"); const allow = all.find((s) => s.Effect === "Allow"); - const deny = all.find((s) => s.Effect === "Deny"); + const deny = all.find((s) => s.Effect === "Deny" && s.Condition["ForAnyValue:StringEquals"]); + const deep = all.find((s) => s.Effect === "Deny" && s.Condition["ForAnyValue:StringLike"]); assert.equal(allow.Action, "route53:ChangeResourceRecordSets"); assert.match(str(allow.Resource), /hostedzone\/ZTEST000001/); assert.ok(!str(allow.Resource).includes("hostedzone/*"), "never every zone"); @@ -71,10 +72,26 @@ test("the provisioning API may change only CNAMEs (and the setup alias) under th for (const n of ["coderhelm.com", "*.coderhelm.com", "api.coderhelm.com", "app.coderhelm.com", "auth.coderhelm.com", "docs.coderhelm.com", "stream.coderhelm.com", "www.coderhelm.com", "mail.coderhelm.com", "status.coderhelm.com", "admin.coderhelm.com", "careers.coderhelm.com"]) { assert.ok(denied.includes(n), `${n} is denied`); } + // IAM's `*` crosses dots, so the allow alone would let a change reach + // deeper names: under a reserved host (`x.api.coderhelm.com`, a + // `_acme-challenge.app.coderhelm.com` that could get a certificate for the + // dashboard), mail records (`_domainkey`, `_dmarc`), or three labels deep. + // A separate deny fences those (a second condition in the same statement + // would AND with the first and fence nothing). + assert.ok(deep, "a deny for deeper names"); + const like: string[] = deep.Condition["ForAnyValue:StringLike"]["route53:ChangeResourceRecordSetsNormalizedRecordNames"]; + const matches = (pattern: string, name: string) => + new RegExp("^" + pattern.split("*").map((p) => p.replace(/[.?+^$()[\]{}|\\]/g, "\\$&")).join(".*") + "$").test(name); + for (const n of ["x.api.coderhelm.com", "_acme-challenge.app.coderhelm.com", "_0123456789abcdef0123456789abcdef.app.coderhelm.com", "s1._domainkey.coderhelm.com", "_dmarc.coderhelm.com", "_dmarc.example.coderhelm.com", "a.b.example.coderhelm.com", "_acme-challenge.example.coderhelm.com", "_mta-sts.coderhelm.com"]) { + assert.ok(like.some((p) => matches(p, n)), `${n} is fenced`); + } + for (const n of ["example.coderhelm.com", "_0123456789abcdef0123456789abcdef.example.coderhelm.com"]) { + assert.ok(!like.some((p) => matches(p, n)), `${n} stays writable`); + } // No other statement anywhere grants record changes. for (const t of Object.values(hosted())) { for (const s of statements(t)) { - if (s === allow || s === deny) continue; + if (s === allow || s === deny || s === deep) continue; assert.ok(![].concat(s.Action).some((a: string) => a === "route53:ChangeResourceRecordSets" || a === "route53:*") || t !== api, "only the hybrid statements"); } } diff --git a/services/common/src/hybrid/broker.rs b/services/common/src/hybrid/broker.rs index b1634a753..efaa6a69e 100644 --- a/services/common/src/hybrid/broker.rs +++ b/services/common/src/hybrid/broker.rs @@ -31,9 +31,56 @@ pub struct GithubLink { /// The account (organization or user) the installation is on. pub account: String, /// The repositories the customer chose for this install. Empty: every - /// repository the installation itself grants on GitHub. + /// repository the link allows ([`GithubLink::ceiling`]). #[serde(default)] pub repositories: Vec, + /// The repositories the person who linked the installation may push to + /// on GitHub, read at link time ([`writable_repositories`]): no token is + /// ever wider. None only for links made before the ceiling existed + /// (whatever the installation grants). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ceiling: Option>, +} + +/// GitHub caps a token at this many named repositories, so a ceiling is +/// never longer. +pub const MAX_CEILING: usize = 500; + +/// The repositories in a page of GitHub's `GET /user/installations/{id}/repositories` +/// (asked with the person's own token) they may push to: their own +/// permissions, not the installation's. +pub fn writable_repositories(page: &serde_json::Value) -> Vec { + page["repositories"] + .as_array() + .map(|a| a.as_slice()) + .unwrap_or_default() + .iter() + .filter(|r| { + let p = &r["permissions"]; + p["push"].as_bool() == Some(true) || p["admin"].as_bool() == Some(true) + }) + .filter_map(|r| r["name"].as_str()) + .map(|n| n.to_ascii_lowercase()) + .collect() +} + +fn norm_repo(r: &str) -> String { + r.trim() + .rsplit('/') + .next() + .unwrap_or("") + .to_ascii_lowercase() +} + +/// Whether every repository in `asked` is inside the link's ceiling. +pub fn ceiling_allows(link: &GithubLink, asked: &[String]) -> bool { + match &link.ceiling { + None => true, + Some(c) => { + let c: Vec = c.iter().map(|r| norm_repo(r)).collect(); + asked.iter().all(|r| c.contains(&norm_repo(r))) + } + } } /// The permissions a brokered token may ever carry: what CoderHelm's app @@ -112,14 +159,27 @@ pub fn plan_token(links: &[GithubLink], ask: &TokenAsk) -> Result = link.repositories.iter().map(|r| norm(r)).collect(); + let allowed: Vec = match &link.ceiling { + None => chosen, + Some(c) => { + let c: Vec = c.iter().map(|r| norm(r)).take(MAX_CEILING).collect(); + if c.is_empty() { + return Err(BrokerRefusal::RepositoryNotAllowed); + } + if chosen.is_empty() { + c + } else { + // A chosen list never reaches past the ceiling. + let inside: Vec = chosen.into_iter().filter(|r| c.contains(r)).collect(); + if inside.is_empty() { + return Err(BrokerRefusal::RepositoryNotAllowed); + } + inside + } + } }; - let allowed: Vec = link.repositories.iter().map(|r| norm(r)).collect(); let mut repositories: Vec = Vec::new(); for r in &ask.repositories { let n = norm(r); @@ -232,15 +292,68 @@ mod tests { installation_id: 11, account: "example-org".into(), repositories: vec!["web".into(), "api".into()], + ceiling: None, }, GithubLink { installation_id: 22, account: "example-user".into(), repositories: vec![], + ceiling: None, }, ] } + /// A link holds what the person who linked it may push to on GitHub + /// (its ceiling): someone with read access to one repository can't link + /// the organization's installation and mint write tokens for every + /// repository in it. The ceiling goes to GitHub as the token's + /// `repositories`, so GitHub enforces it too. + #[test] + fn a_link_never_reaches_past_what_its_linker_can_push_to() { + let link = GithubLink { + installation_id: 44, + account: "example-org".into(), + repositories: vec![], + ceiling: Some(vec!["web".into(), "docs-site".into()]), + }; + let ask = |repos: &[&str]| TokenAsk { + installation_id: 44, + repositories: repos.iter().map(|r| r.to_string()).collect(), + ..Default::default() + }; + let all = plan_token(std::slice::from_ref(&link), &ask(&[])).unwrap(); + assert_eq!(all.repositories, vec!["web", "docs-site"]); + assert_eq!( + plan_token(std::slice::from_ref(&link), &ask(&["payments"])), + Err(BrokerRefusal::RepositoryNotAllowed) + ); + assert!(ceiling_allows(&link, &["web".into()])); + assert!(!ceiling_allows(&link, &["web".into(), "payments".into()])); + // A chosen list outside the ceiling (stored before) is cut back to it. + let mut wide = link.clone(); + wide.repositories = vec!["web".into(), "payments".into()]; + let t = plan_token(std::slice::from_ref(&wide), &ask(&[])).unwrap(); + assert_eq!(t.repositories, vec!["web"]); + // Nothing the linker can push to: nothing at all, never "everything". + let mut none = link.clone(); + none.ceiling = Some(vec![]); + assert_eq!( + plan_token(&[none], &ask(&[])), + Err(BrokerRefusal::RepositoryNotAllowed) + ); + } + + #[test] + fn writable_repositories_come_from_the_persons_own_permissions() { + let page = serde_json::json!({"repositories": [ + {"name": "web", "permissions": {"admin": false, "push": true, "pull": true}}, + {"name": "Docs", "permissions": {"admin": true, "push": true, "pull": true}}, + {"name": "readonly", "permissions": {"admin": false, "push": false, "pull": true}}, + {"name": "noperms"} + ]}); + assert_eq!(writable_repositories(&page), vec!["web", "docs"]); + } + #[test] fn only_linked_installations_get_tokens() { let ask = TokenAsk { diff --git a/services/common/src/hybrid/names.rs b/services/common/src/hybrid/names.rs index 85531be7e..a7a233f12 100644 --- a/services/common/src/hybrid/names.rs +++ b/services/common/src/hybrid/names.rs @@ -115,12 +115,88 @@ pub fn validate_name(raw: &str) -> Result { if name.contains("--") { return Err(NameProblem::DoubleHyphen); } - if reserved().iter().any(|r| r == &name) { + if reserved().iter().any(|r| r == &name) || looks_like_coderhelm(&name) { return Err(NameProblem::Reserved); } Ok(name) } +/// Words no part of a name may be: CoderHelm's own hosts and the pages +/// people sign in, pay or ask for help on. A name is a real coderhelm.com +/// address with a valid certificate, so "app-login" or "support-team" would +/// read as CoderHelm's own. +pub const LOOKALIKE_WORDS: &[&str] = &[ + "api", + "app", + "apps", + "auth", + "docs", + "stream", + "www", + "fallback", + "login", + "logon", + "signin", + "signup", + "sso", + "oauth", + "admin", + "support", + "helpdesk", + "help", + "billing", + "invoice", + "pay", + "payment", + "payments", + "account", + "accounts", + "secure", + "security", + "verify", + "verification", + "password", + "passwords", + "reset", + "official", + "staff", + "status", + "mail", + "email", + "webmail", + "dashboard", + "console", + "portal", + "trust", +]; + +/// Whether a (well-formed) name could pass for CoderHelm's own address: +/// "coderhelm" anywhere, digits standing in for letters included ("c0derhe1m"), +/// or a [`LOOKALIKE_WORDS`] word as one of its hyphen-separated parts, with +/// trailing digits ignored ("app2", "api-v2", "auth1"). +pub fn looks_like_coderhelm(name: &str) -> bool { + let letters: String = name + .chars() + .filter(|c| *c != '-') + .map(|c| match c { + '0' => 'o', + '1' => 'l', + '3' => 'e', + '4' => 'a', + '5' => 's', + '7' => 't', + c => c, + }) + .collect(); + if letters.contains("coderhelm") || letters.contains("coderheim") { + return true; + } + name.split('-').any(|part| { + let word = part.trim_end_matches(|c: char| c.is_ascii_digit()); + LOOKALIKE_WORDS.contains(&word) + }) +} + /// The full hostname for a valid name. pub fn hostname(name: &str) -> String { format!("{name}.{}", zone()) @@ -403,6 +479,50 @@ mod tests { assert_eq!(zone(), DEFAULT_ZONE); } + /// A name is a real coderhelm.com address with a valid certificate, so + /// it must never read as CoderHelm's own: no "coderhelm" (with digit + /// look-alikes), and no word of a CoderHelm host or a sign-in, billing + /// or support page as one of its parts. + #[test] + fn look_alike_names_are_refused() { + for n in [ + "coderhelm-support", + "my-coderhelm", + "c0derhelm", + "coderhe1m", + "c0derhe1m-app", + "coder-helm", + "app2", + "api-v2", + "app-login", + "login-app", + "secure-signin", + "acme-sso", + "support-team", + "billing-portal", + "auth1", + "www2", + "docs-site", + "verify-account", + "password-reset", + ] { + assert_eq!(validate_name(n), Err(NameProblem::Reserved), "{n}"); + } + for n in [ + "example", + "example-co", + "acme", + "my-team", + "apple", + "application-lab", + "mapbox", + "rapid7", + "team42", + ] { + assert!(validate_name(n).is_ok(), "{n}"); + } + } + #[test] fn every_problem_reads_plainly() { for p in [ diff --git a/services/common/src/hybrid/relay.rs b/services/common/src/hybrid/relay.rs index f3523ccf6..63dd6ffd6 100644 --- a/services/common/src/hybrid/relay.rs +++ b/services/common/src/hybrid/relay.rs @@ -40,19 +40,50 @@ pub struct Forward<'a> { pub body: &'a [u8], } +/// The HTTP client for every request the hosted side makes to an install's +/// address (relayed events and ownership proofs). It never follows a +/// redirect: the install's CloudFront is the only place these requests may +/// go, and a redirect from it (to the Lambda runtime API, a metadata address +/// or anything else inside AWS) is answered as the redirect status itself. +pub fn install_client() -> &'static reqwest::Client { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + C.get_or_init(|| { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .user_agent("coderhelm-relay") + .build() + .expect("a client with no redirects") + }) +} + +/// How much of an install's answer is ever read (the rest is dropped). +pub const MAX_ANSWER_BYTES: usize = 16 * 1024; + +/// Reads at most [`MAX_ANSWER_BYTES`] of an answer. +pub async fn read_capped(mut resp: reqwest::Response) -> Vec { + let mut out = Vec::new(); + while let Ok(Some(chunk)) = resp.chunk().await { + let room = MAX_ANSWER_BYTES - out.len(); + out.extend_from_slice(&chunk[..chunk.len().min(room)]); + if out.len() >= MAX_ANSWER_BYTES { + break; + } + } + out +} + /// Sends one forward and returns the attempt (with the HTTP status when the /// install answered). -pub async fn send(http: &reqwest::Client, f: &Forward<'_>) -> Attempt { +pub async fn send(f: &Forward<'_>) -> Attempt { let ts = chrono::Utc::now().timestamp(); let started = Instant::now(); - let r = http + let r = install_client() .post(target(f.origin)) .timeout(std::time::Duration::from_secs(8)) .header("content-type", "application/json") - .header("user-agent", "coderhelm-relay") .header( sign::RELAY_HEADER, - sign::sign_relay(f.relay_key, ts, f.delivery_id, f.body), + sign::sign_relay_routed(f.relay_key, ts, f.delivery_id, f.source, f.event, f.body), ) .header(sign::RELAY_SOURCE_HEADER, f.source) .header(sign::RELAY_EVENT_HEADER, f.event) @@ -66,13 +97,18 @@ pub async fn send(http: &reqwest::Client, f: &Forward<'_>) -> Attempt { let code = resp.status().as_u16(); let error = if resp.status().is_success() { String::new() + } else if resp.status().is_redirection() { + "answered with a redirect, which the relay never follows".into() } else { - let text = resp.text().await.unwrap_or_default(); + let text = String::from_utf8_lossy(&read_capped(resp).await).to_string(); let v: serde_json::Value = serde_json::from_str(&text).unwrap_or_default(); v["error"] .as_str() .map(str::to_string) - .unwrap_or_else(|| text.chars().take(200).collect()) + .unwrap_or(text) + .chars() + .take(200) + .collect() }; Attempt { at, @@ -225,3 +261,82 @@ mod tests { assert!(matches!(apply(&mut d, att(Some(429))), Next::RetryIn(_))); } } + +#[cfg(test)] +mod redirect_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// A one-route HTTP server that answers every request with `answer` and + /// counts how many connections it took. + async fn serve(answer: String) -> (String, Arc) { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = format!("http://{}", l.local_addr().unwrap()); + let hits = Arc::new(AtomicUsize::new(0)); + let h = hits.clone(); + tokio::spawn(async move { + while let Ok((mut s, _)) = l.accept().await { + h.fetch_add(1, Ordering::SeqCst); + let mut buf = vec![0u8; 8192]; + let _ = s.read(&mut buf).await; + let _ = s.write_all(answer.as_bytes()).await; + let _ = s.shutdown().await; + } + }); + (addr, hits) + } + + /// An install's CloudFront answers with a redirect to an internal + /// address: the relay must never follow it (no request to anything but + /// the install's own verified address). + #[tokio::test] + async fn the_relay_never_follows_a_redirect() { + let (internal, internal_hits) = serve( + "HTTP/1.1 500 Internal\r\ncontent-length: 21\r\nconnection: close\r\n\r\n{\"error\":\"internal\"}" + .to_string(), + ) + .await; + for code in [301, 302, 303, 307, 308] { + let (install, _) = serve(format!( + "HTTP/1.1 {code} Moved\r\nlocation: {internal}/2018-06-01/runtime/invocation/next\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" + )) + .await; + let a = send(&Forward { + origin: &install, + relay_key: "k", + source: "github", + event: "push", + delivery_id: "d1", + body: b"{}", + }) + .await; + assert_eq!(a.code, Some(code), "{code}"); + assert!(!a.error.contains("internal"), "{code}: {}", a.error); + } + assert_eq!(internal_hits.load(Ordering::SeqCst), 0); + } + + /// A huge error answer is cut, never read whole. + #[tokio::test] + async fn a_large_error_answer_is_cut() { + let big = "x".repeat(200_000); + let (install, _) = serve(format!( + "HTTP/1.1 400 Bad\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{big}", + big.len() + )) + .await; + let a = send(&Forward { + origin: &install, + relay_key: "k", + source: "github", + event: "push", + delivery_id: "d1", + body: b"{}", + }) + .await; + assert_eq!(a.code, Some(400)); + assert!(a.error.chars().count() <= 200); + } +} diff --git a/services/common/src/hybrid/sign.rs b/services/common/src/hybrid/sign.rs index 2b7d18403..259bfe6bc 100644 --- a/services/common/src/hybrid/sign.rs +++ b/services/common/src/hybrid/sign.rs @@ -10,7 +10,9 @@ //! `"{ts}.{METHOD}.{path}.{sha256(body) hex}"`. //! - **Relayed events** the hosted router forwards to an install: signed with //! the install's relay key. Header `X-CoderHelm-Relay-Signature: -//! t=,d=,v1=` over `"{ts}.{delivery id}.{body}"`. The +//! t=,d=,v1=,v2=`: `v1` over +//! `"{ts}.{delivery id}.{body}"`, `v2` over +//! `"v2.{ts}.{delivery id}.{source}.{event}.{body}"` ([`sign_relay_routed`]). The //! install refuses anything older than [`TOLERANCE_SECS`] and any delivery //! id it has seen (the caller claims the id; see [`replay_key`]). //! - **Ownership proofs**: the hosted side asks an install's CloudFront @@ -195,6 +197,43 @@ pub fn sign_relay(key: &str, ts: i64, delivery_id: &str, body: &[u8]) -> String format!("t={ts},d={delivery_id},v1={}", hex::encode(sig)) } +/// The relay header value with the route signed too: `v1` (the body and +/// delivery id, what older installs check) and `v2`, which also covers the +/// source and event headers the install routes on. +pub fn sign_relay_routed( + key: &str, + ts: i64, + delivery_id: &str, + source: &str, + event: &str, + body: &[u8], +) -> String { + format!( + "{},v2={}", + sign_relay(key, ts, delivery_id, body), + hex::encode(routed_mac(key, ts, delivery_id, source, event, body)) + ) +} + +fn routed_mac(key: &str, ts: i64, d: &str, source: &str, event: &str, body: &[u8]) -> Vec { + // Source and event are fixed words (no dots), so the parts can't run together. + mac( + key.as_bytes(), + &[ + b"v2.", + ts.to_string().as_bytes(), + b".", + d.as_bytes(), + b".", + source.as_bytes(), + b".", + event.as_bytes(), + b".", + body, + ], + ) +} + /// A verified relayed event's delivery id and timestamp. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RelayStamp { @@ -202,18 +241,22 @@ pub struct RelayStamp { pub ts: i64, } -/// Checks a relayed event's signature and age. Replays are the caller's -/// second step: claim [`replay_key`] once, refuse when it is already held. +/// Checks a relayed event's signature and age. With `v2` present, the +/// source and event headers must be the ones that were signed (a `v1` alone +/// is accepted from an older hosted side). Replays are the caller's second +/// step: claim [`replay_key`] once, refuse when it is already held. pub fn verify_relay( key: &str, header: Option<&str>, + source: &str, + event: &str, body: &[u8], now: i64, ) -> Result { let Some(h) = header else { return Err(SignatureProblem::Missing); }; - let (mut ts, mut d, mut v1) = (None, None, None); + let (mut ts, mut d, mut v1, mut v2) = (None, None, None, None); for part in h.split(',') { let (k, v) = part .trim() @@ -223,6 +266,7 @@ pub fn verify_relay( "t" => ts = v.parse::().ok(), "d" => d = Some(v.to_string()), "v1" => v1 = hex::decode(v).ok(), + "v2" => v2 = Some(hex::decode(v).map_err(|_| SignatureProblem::Malformed)?), _ => {} } } @@ -247,6 +291,11 @@ pub fn verify_relay( if !ct_eq(&got, &want) { return Err(SignatureProblem::Mismatch); } + if let Some(got2) = v2 { + if !ct_eq(&got2, &routed_mac(key, ts, &d, source, event, body)) { + return Err(SignatureProblem::Mismatch); + } + } Ok(RelayStamp { delivery_id: d, ts }) } @@ -414,7 +463,7 @@ mod tests { let k = relay_key(MASTER, "ins_a"); let body = br#"{"action":"opened"}"#; let h = sign_relay(&k, NOW, "72d3162e-cc78-11e3-81ab-4c9367dc0958", body); - let stamp = verify_relay(&k, Some(&h), body, NOW + 5).unwrap(); + let stamp = verify_relay(&k, Some(&h), "github", "push", body, NOW + 5).unwrap(); assert_eq!(stamp.delivery_id, "72d3162e-cc78-11e3-81ab-4c9367dc0958"); assert_eq!(stamp.ts, NOW); assert_eq!( @@ -429,42 +478,91 @@ mod tests { let body = b"{}"; let h = sign_relay(&k, NOW, "d1", body); assert_eq!( - verify_relay(&k, Some(&h), b"{ }", NOW), + verify_relay(&k, Some(&h), "github", "push", b"{ }", NOW), Err(SignatureProblem::Mismatch) ); assert_eq!( - verify_relay(&k, Some(&h), body, NOW + TOLERANCE_SECS + 1), + verify_relay( + &k, + Some(&h), + "github", + "push", + body, + NOW + TOLERANCE_SECS + 1 + ), Err(SignatureProblem::Stale) ); assert_eq!( - verify_relay(&relay_key(MASTER, "ins_b"), Some(&h), body, NOW), + verify_relay( + &relay_key(MASTER, "ins_b"), + Some(&h), + "github", + "push", + body, + NOW + ), Err(SignatureProblem::Mismatch) ); // The delivery id is signed: swapping it breaks the signature. let swapped = h.replace("d=d1", "d=d2"); assert_eq!( - verify_relay(&k, Some(&swapped), body, NOW), + verify_relay(&k, Some(&swapped), "github", "push", body, NOW), Err(SignatureProblem::Mismatch) ); assert_eq!( - verify_relay(&k, None, body, NOW), + verify_relay(&k, None, "github", "push", body, NOW), Err(SignatureProblem::Missing) ); assert_eq!( - verify_relay(&k, Some("t=1"), body, NOW), + verify_relay(&k, Some("t=1"), "github", "push", body, NOW), Err(SignatureProblem::Malformed) ); assert_eq!( - verify_relay(&k, Some("garbage"), body, NOW), + verify_relay(&k, Some("garbage"), "github", "push", body, NOW), Err(SignatureProblem::Malformed) ); let bad_id = sign_relay(&k, NOW, "d 1", body); assert_eq!( - verify_relay(&k, Some(&bad_id), body, NOW), + verify_relay(&k, Some(&bad_id), "github", "push", body, NOW), Err(SignatureProblem::Malformed) ); } + /// The source and event headers decide how the install handles a body, + /// so they are signed too (`v2`). A copy with them changed is refused; + /// an older hosted side that sends only `v1` still verifies. + #[test] + fn the_route_of_a_relayed_event_is_signed() { + let k = relay_key(MASTER, "ins_a"); + let body = br#"{"action":"opened"}"#; + let h = sign_relay_routed(&k, NOW, "d1", "github", "pull_request", body); + assert!(h.contains(",v1=") && h.contains(",v2=")); + assert_eq!( + verify_relay(&k, Some(&h), "github", "pull_request", body, NOW).map(|s| s.delivery_id), + Ok("d1".to_string()) + ); + for (src, ev) in [ + ("github", "issue_comment"), + ("jira", "pull_request"), + ("", ""), + ] { + assert_eq!( + verify_relay(&k, Some(&h), src, ev, body, NOW), + Err(SignatureProblem::Mismatch), + "{src} {ev}" + ); + } + // A v2 that doesn't match is never rescued by a good v1. + let forged = format!("{},v2={}", sign_relay(&k, NOW, "d1", body), "00".repeat(32)); + assert_eq!( + verify_relay(&k, Some(&forged), "github", "pull_request", body, NOW), + Err(SignatureProblem::Mismatch) + ); + // An older hosted side (v1 only) still verifies. + let old = sign_relay(&k, NOW, "d1", body); + assert!(verify_relay(&k, Some(&old), "github", "push", body, NOW).is_ok()); + } + #[test] fn the_replay_window_outlives_the_tolerance() { const { assert!(REPLAY_TTL_SECS > 2 * TOLERANCE_SECS) }; diff --git a/services/common/src/mcp_remote/runtime.rs b/services/common/src/mcp_remote/runtime.rs index 325ef0189..37876ef4b 100644 --- a/services/common/src/mcp_remote/runtime.rs +++ b/services/common/src/mcp_remote/runtime.rs @@ -937,6 +937,55 @@ impl Runtime { out } + /// Takes a finished sign-in from another partition into this one: the + /// tokens are opened under the other's keys, sealed again under this + /// one's, and the other partition's records are deleted. The hosted + /// broker finishes a hybrid install's provider sign-in in a holding + /// partition and calls this only when the install redeems the code (with + /// its secret and the PKCE verifier), so a sign-in someone else started + /// never replaces the install's own. + pub async fn adopt_sign_in( + &self, + from: &Runtime, + server_id: &str, + owner: &Owner, + ) -> Result<(), String> { + let t = from + .store + .get_token(&from.team, server_id, owner) + .await? + .ok_or("There is no finished sign-in to take.")?; + let set = from.open_tokens(server_id, owner, &t.sealed).await?; + let sealed = self.seal_tokens(server_id, owner, &set).await?; + let version = self + .store + .get_token(&self.team, server_id, owner) + .await? + .map(|x| x.version + 1) + .unwrap_or(1); + self.store + .put_token( + &self.team, + server_id, + &TokenRecord { + sealed, + version, + ..t + }, + None, + ) + .await?; + if *owner == Owner::Team { + self.store + .set_status(&self.team, server_id, Status::Connected, "") + .await?; + } + from.store + .delete_token(&from.team, server_id, owner) + .await?; + from.store.delete_server(&from.team, server_id).await + } + /// Removes a server: every connection is disconnected (and revoked) /// first, then the server goes. pub async fn remove(&self, s: &ServerRecord) -> Result<(), String> { @@ -1061,6 +1110,70 @@ mod tests { } } + /// A hybrid install's provider sign-in is finished in a holding + /// partition and only taken into the install's own once the install + /// redeems the code: the tokens move resealed under the install's keys, + /// and nothing is left behind. + #[tokio::test] + async fn a_sign_in_is_adopted_from_a_holding_partition() { + let store = Arc::new(MemStore::default()); + let http = Arc::new(Fake::default()); + let mk = |team: &str| Runtime { + store: store.clone(), + cipher: Arc::new(FakeKms), + http: http.clone(), + team: team.into(), + clock: Arc::new(|| 1_000_000), + }; + let main = mk("HYBRID#ins_a"); + let hold = mk("HYBRID#ins_a#SIGNIN#fl_1"); + let s = server(); + store.put_server(&main.team, &s).await.unwrap(); + store.put_server(&hold.team, &s).await.unwrap(); + super::testing::sign_in(&main, &s.id, &Owner::Team, "old", None, None, "a").await; + super::testing::sign_in(&hold, &s.id, &Owner::Team, "new", Some("r"), None, "b").await; + + main.adopt_sign_in(&hold, &s.id, &Owner::Team) + .await + .unwrap(); + + let t = store + .get_token(&main.team, &s.id, &Owner::Team) + .await + .unwrap() + .unwrap(); + let set = main + .open_tokens(&s.id, &Owner::Team, &t.sealed) + .await + .unwrap(); + assert_eq!(set.access_token, "new"); + assert_eq!(set.refresh_token.as_deref(), Some("r")); + assert_eq!(t.version, 2); + assert!(store + .get_token(&hold.team, &s.id, &Owner::Team) + .await + .unwrap() + .is_none()); + assert!(store.get_server(&hold.team, &s.id).await.unwrap().is_none()); + // Nothing held: refused, and the install's sign-in stays. + assert!(main + .adopt_sign_in(&hold, &s.id, &Owner::Team) + .await + .is_err()); + let t = store + .get_token(&main.team, &s.id, &Owner::Team) + .await + .unwrap() + .unwrap(); + assert_eq!( + main.open_tokens(&s.id, &Owner::Team, &t.sealed) + .await + .unwrap() + .access_token, + "new" + ); + } + fn server() -> ServerRecord { let mut s = ServerRecord::new("docs", "Docs", MCP); s.auth = AuthKind::OAuth; diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index b916bc3c9..8d999cfc3 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1144,6 +1144,7 @@ async fn main() -> Result<(), Error> { .route("/fallback", get(routes::hybrid::fallback)) .route("/github/link-start", post(routes::hybrid::link_start)) .route("/github/setup", get(routes::hybrid::github_setup)) + .route("/github/confirm", post(routes::hybrid::github_confirm)) .route( "/github/links/:installation_id", put(routes::hybrid::set_link_repos).delete(routes::hybrid::delete_link), diff --git a/services/gateway/src/middleware/cors.rs b/services/gateway/src/middleware/cors.rs index 98e745797..ccfd3b3b8 100644 --- a/services/gateway/src/middleware/cors.rs +++ b/services/gateway/src/middleware/cors.rs @@ -119,6 +119,17 @@ pub async fn apply(credentialed: &[String], req: Request, next: Next) -> Respons return res; } + if sibling_with_cookies(&req, origin.as_deref(), trusted.is_some(), hosts_names()) { + return ( + StatusCode::FORBIDDEN, + axum::Json(serde_json::json!({ + "code": "cross_origin_refused", + "error": "This change came from another page on the same domain, not from CoderHelm. Open CoderHelm itself and try again.", + })), + ) + .into_response(); + } + let mut res = next.run(req).await; let h = res.headers_mut(); if let Some(o) = &trusted { @@ -136,6 +147,58 @@ pub async fn apply(credentialed: &[String], req: Request, next: Next) -> Respons res } +/// A change (any method but GET, HEAD and OPTIONS) sent with cookies from +/// another origin on the same site that isn't the dashboard's. SameSite +/// cookies don't stop these: a customer's `{name}.coderhelm.com` is the same +/// site as the dashboard and the API, so its pages could post a form or a +/// no-cors fetch that carries the session. `Sec-Fetch-Site` says so on +/// current browsers; on older ones, on the deployment that hands out the +/// names (`hosts_names`), an origin under the hybrid zone does. Same-origin +/// pages, API clients (no Origin) and cookieless calls (the install guide) +/// are never affected. +fn sibling_with_cookies( + req: &Request, + origin: Option<&str>, + trusted: bool, + hosts_names: bool, +) -> bool { + if trusted + || matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS) + || !req.headers().contains_key(header::COOKIE) + { + return false; + } + match req + .headers() + .get("sec-fetch-site") + .and_then(|v| v.to_str().ok()) + { + Some(site) => site.eq_ignore_ascii_case("same-site"), + None => hosts_names && origin.is_some_and(under_hybrid_zone), + } +} + +/// Whether this deployment writes `{name}.` records (the hosted side +/// of hybrid; an install on such a name serves its dashboard and API from +/// that one origin, so it never needs the fallback above). +fn hosts_names() -> bool { + std::env::var("HYBRID_ZONE_ID").is_ok_and(|z| !z.trim().is_empty()) +} + +/// True for an origin whose host is the hybrid zone or under it. +fn under_hybrid_zone(origin: &str) -> bool { + let host = origin + .split("://") + .nth(1) + .unwrap_or("") + .split(['/', ':']) + .next() + .unwrap_or("") + .to_ascii_lowercase(); + let zone = common::hybrid::names::zone(); + host == zone || host.ends_with(&format!(".{zone}")) +} + fn trusted_headers(h: &mut HeaderMap, origin: &str) { if let Ok(v) = HeaderValue::from_str(origin) { h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, v); @@ -176,7 +239,7 @@ mod tests { .route("/openapi.json", get(|| async { "{}" })) .route("/api/setup/status", get(|| async { "{}" })) .route("/api/setup/hybrid/name", post(|| async { "{}" })) - .route("/api/teams", get(|| async { "[]" })) + .route("/api/teams", get(|| async { "[]" }).post(|| async { "{}" })) .layer(axum::middleware::from_fn(move |req, next| { let origins = origins.clone(); async move { apply(&origins, req, next).await } @@ -283,6 +346,93 @@ mod tests { } } + async fn post_with(origin: Option<&str>, fetch_site: Option<&str>, cookie: bool) -> StatusCode { + let mut b = Request::builder() + .method("POST") + .uri("/api/teams") + .header(header::CONTENT_TYPE, "text/plain"); + if let Some(o) = origin { + b = b.header(header::ORIGIN, o); + } + if let Some(s) = fetch_site { + b = b.header("sec-fetch-site", s); + } + if cookie { + b = b.header(header::COOKIE, "__Host-coderhelm_session=abc"); + } + app() + .oneshot(b.body(Body::from("{}")).unwrap()) + .await + .unwrap() + .status() + } + + /// A customer's `{name}.coderhelm.com` is the same site as the + /// dashboard and the API, so a SameSite=Strict session cookie goes along + /// with a form or a no-cors fetch from its pages. A change sent with + /// cookies from any same-site origin but the dashboard's own is refused. + #[tokio::test] + async fn a_customer_subdomain_cant_send_changes_with_the_session() { + const EVIL: &str = "https://example.coderhelm.com"; + assert_eq!( + post_with(Some(EVIL), Some("same-site"), true).await, + StatusCode::FORBIDDEN + ); + // The dashboard, same-origin pages, API clients and the guide still work. + assert_eq!( + post_with(Some(APP), Some("same-site"), true).await, + StatusCode::OK + ); + assert_eq!( + post_with(Some("https://api.coderhelm.com"), Some("same-origin"), true).await, + StatusCode::OK + ); + assert_eq!(post_with(None, None, true).await, StatusCode::OK); + assert_eq!( + post_with(Some(DOCS), Some("same-site"), false).await, + StatusCode::OK + ); + // Reads stay as they were (CORS already hides the answer). + let r = app() + .oneshot( + Request::builder() + .uri("/api/teams") + .header(header::ORIGIN, EVIL) + .header("sec-fetch-site", "same-site") + .header(header::COOKIE, "__Host-coderhelm_session=abc") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::OK); + assert_eq!(get_h(&r, header::ACCESS_CONTROL_ALLOW_ORIGIN), None); + } + + /// Browsers without Sec-Fetch-Site: on the hosted side, an origin under + /// the zone that isn't the dashboard's is refused; an install on its own + /// name (same origin, no Sec-Fetch-Site) is never refused. + #[test] + fn without_sec_fetch_site_the_hosted_side_goes_by_the_origin() { + let req = |o: &str| { + Request::builder() + .method("POST") + .uri("/api/teams") + .header(header::ORIGIN, o) + .header(header::COOKIE, "a=b") + .body(Body::empty()) + .unwrap() + }; + let evil = "https://example.coderhelm.com"; + assert!(sibling_with_cookies(&req(evil), Some(evil), false, true)); + assert!(!sibling_with_cookies(&req(evil), Some(evil), true, true)); + assert!(!sibling_with_cookies(&req(evil), Some(evil), false, false)); + let other = "https://example.org"; + assert!(!sibling_with_cookies(&req(other), Some(other), false, true)); + assert!(under_hybrid_zone("https://a.coderhelm.com:443")); + assert!(!under_hybrid_zone("https://coderhelm.com.example.org")); + } + #[test] fn public_paths_are_only_the_guides() { assert_eq!(public_methods("/hybrid/names/acme"), Some("GET")); diff --git a/services/gateway/src/routes/hybrid.rs b/services/gateway/src/routes/hybrid.rs index 14087fbce..de1bbbb6e 100644 --- a/services/gateway/src/routes/hybrid.rs +++ b/services/gateway/src/routes/hybrid.rs @@ -362,6 +362,15 @@ pub async fn register( "Send the install's CloudFront address, such as d1234abcd.cloudfront.net.", )); } + // A CloudFront address whose install CoderHelm turned off can't come + // back as a new registration: revoking would mean nothing otherwise. + if cloudfront_revoked(&state, &cloudfront).await { + return Err(fail( + StatusCode::FORBIDDEN, + broker::BrokerRefusal::Revoked.code(), + broker::BrokerRefusal::Revoked.message(), + )); + } let id = sign::new_install_id(); let install = Install { id: id.clone(), @@ -385,16 +394,38 @@ pub async fn register( }))) } +/// The record that keeps a revoked install's CloudFront address from registering again. +pub fn revoked_cloudfront_key(cloudfront: &str) -> String { + format!( + "HYBRIDREVOKED#{}", + cloudfront.trim().trim_end_matches('.').to_ascii_lowercase() + ) +} + +async fn cloudfront_revoked(state: &AppState, cloudfront: &str) -> bool { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(&revoked_cloudfront_key(cloudfront))) + .key("sk", s("REVOKED")) + .send() + .await + .map(|r| r.item().is_some()) + // Can't tell: refuse, the person tries again in a minute. + .unwrap_or(true) +} + /// Asks the install's CloudFront address to answer a challenge with its /// registration secret. True when it does. -async fn prove(state: &AppState, master: &str, install: &Install) -> bool { +async fn prove(master: &str, install: &Install) -> bool { let challenge = broker::new_handle("ch"); let url = format!( "{}/webhooks/relay/proof?challenge={challenge}", install.origin() ); - let Ok(r) = state - .http + // Never a redirect, never more than a small answer (relay::install_client). + let Ok(r) = relay::install_client() .get(&url) .timeout(std::time::Duration::from_secs(6)) .send() @@ -402,7 +433,10 @@ async fn prove(state: &AppState, master: &str, install: &Install) -> bool { else { return false; }; - let v: Value = r.json().await.unwrap_or_default(); + if !r.status().is_success() { + return false; + } + let v: Value = serde_json::from_slice(&relay::read_capped(r).await).unwrap_or_default(); v["install_id"].as_str() == Some(install.id.as_str()) && sign::check_proof( &sign::install_secret(master, &install.id), @@ -421,7 +455,7 @@ pub async fn verify( ) -> Reply { let mut install = signed(&state, &headers, &method, &uri, &body).await?; let master = master(&state).ok_or_else(not_here)?.to_string(); - if !prove(&state, &master, &install).await { + if !prove(&master, &install).await { return Err(fail( StatusCode::BAD_REQUEST, "proof_failed", @@ -847,7 +881,7 @@ pub async fn put_records( .map_err(|why| fail(StatusCode::BAD_REQUEST, "record_refused", why))?, ); } - if !prove(&state, &master, &install).await { + if !prove(&master, &install).await { return Err(fail(StatusCode::BAD_REQUEST, "proof_failed", "CoderHelm couldn't confirm your install at its CloudFront address just now. Try again in a minute.")); } let (old, pending) = stored_name(&state, &install.name).await; @@ -1133,19 +1167,10 @@ pub async fn link_start( "Verify the install first.", )); } - let ret = body_json(&body)["return_url"] - .as_str() - .unwrap_or("") - .to_string(); - let ret = if ret.starts_with(&install.origin()) - || ret.starts_with("https://docs.coderhelm.com/") - || (!install.name.is_empty() - && ret.starts_with(&format!("https://{}", names::hostname(&install.name)))) - { - ret - } else { - format!("{}/settings/system/#hybrid", install.origin()) - }; + let ret = return_url_for( + &install, + body_json(&body)["return_url"].as_str().unwrap_or(""), + ); let st = broker::new_handle("hyb"); put_state( &state, @@ -1169,6 +1194,34 @@ pub async fn link_start( }))) } +/// Where the person goes back to after linking: an address on one of the +/// install's own hosts (or the docs install guide), compared host by host, +/// never by text prefix (`https://d1.cloudfront.net.example.org` starts with +/// the install's origin too); anything else gets the install's settings page. +pub fn return_url_for(install: &Install, asked: &str) -> String { + let fallback = format!("{}/settings/system/#hybrid", install.origin()); + let Ok(u) = url::Url::parse(asked.trim()) else { + return fallback; + }; + if u.scheme() != "https" + || !u.username().is_empty() + || u.password().is_some() + || u.port().is_some() + { + return fallback; + } + let host = u.host_str().unwrap_or("").to_ascii_lowercase(); + let mut hosts = vec![install.cloudfront.clone(), "docs.coderhelm.com".to_string()]; + if !install.name.is_empty() { + hosts.push(names::hostname(&install.name)); + } + if hosts.contains(&host) { + u.to_string() + } else { + fallback + } +} + async fn put_state( state: &AppState, pk: &str, @@ -1301,15 +1354,109 @@ pub async fn github_signin_return( link_with_code(&state, &st, iid, &code).await } -/// Does this GitHub user see the installation (`GET /user/installations`)? -pub fn user_sees_installation(user_installations: &Value, installation_id: u64) -> Option { +/// Does this GitHub user see the installation of CoderHelm's own app +/// (`GET /user/installations`)? An installation of any other app never counts. +pub fn user_sees_installation( + user_installations: &Value, + installation_id: u64, + app_id: u64, +) -> Option { + if app_id == 0 { + return None; + } user_installations["installations"] .as_array()? .iter() - .find(|i| i["id"].as_u64() == Some(installation_id)) + .find(|i| i["id"].as_u64() == Some(installation_id) && i["app_id"].as_u64() == Some(app_id)) .map(|i| i["account"]["login"].as_str().unwrap_or("").to_string()) } +/// The repositories in the installation the person may push to (their own +/// permissions, asked with their token), at most [`broker::MAX_CEILING`]. +async fn writable_in_installation( + state: &AppState, + user_token: &str, + installation_id: u64, +) -> Result, ()> { + let mut out: Vec = Vec::new(); + for page in 1..=10 { + let v: Value = state + .http + .get(format!( + "https://api.github.com/user/installations/{installation_id}/repositories?per_page=100&page={page}" + )) + .header("Authorization", format!("Bearer {user_token}")) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "Coderhelm-bot") + .send() + .await + .map_err(|_| ())? + .json() + .await + .map_err(|_| ())?; + let n = v["repositories"].as_array().map_or(0, Vec::len); + for r in broker::writable_repositories(&v) { + if !out.contains(&r) && out.len() < broker::MAX_CEILING { + out.push(r); + } + } + if n < 100 || out.len() >= broker::MAX_CEILING { + break; + } + } + Ok(out) +} + +/// The page that asks the person to confirm the link: which GitHub account, +/// which install (by its own address), and how many repositories. Nothing +/// is linked until they press the button; it can't be framed. +pub fn confirm_page(account: &str, install_address: &str, repos: usize, token: &str) -> Response { + let esc = |t: &str| { + t.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") + }; + let (account, address, token) = (esc(account), esc(install_address), esc(token)); + let plural = if repos == 1 { + "repository" + } else { + "repositories" + }; + let html = format!( + r#"Link GitHub to a self-hosted CoderHelm

Link {account} to a self-hosted CoderHelm?

+

The CoderHelm install at {address} will get short-lived GitHub tokens that can read and change code in the {repos} {plural} you can push to in {account}, and it will receive that account's GitHub events.

+

Only continue if you started this from that install yourself. If someone sent you this link, choose Cancel.

+
"# + ); + let mut r = (StatusCode::OK, html).into_response(); + for (k, v) in [ + ("content-type", "text/html; charset=utf-8"), + ("cache-control", "no-store"), + ("x-frame-options", "DENY"), + ( + "content-security-policy", + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'", + ), + ("referrer-policy", "no-referrer"), + ("x-robots-tag", "noindex, nofollow"), + ] { + if let Ok(v) = axum::http::HeaderValue::from_str(v) { + r.headers_mut().insert(k, v); + } + } + r +} + async fn link_with_code(state: &AppState, st: &str, iid: u64, code: &str) -> Response { let Some(pending) = take_state(state, &format!("HYBRIDSTATE#{st}")).await else { return ( @@ -1353,7 +1500,8 @@ async fn link_with_code(state: &AppState, st: &str, iid: u64, code: &str) -> Res Ok(r) => r.json().await.unwrap_or_default(), Err(_) => return page_redirect(&ret, "github_unreachable"), }; - let Some(account) = user_sees_installation(&installs, iid) else { + let app_id: u64 = state.secrets.github_app_id.trim().parse().unwrap_or(0); + let Some(account) = user_sees_installation(&installs, iid, app_id) else { audit( state, &install_id, @@ -1363,10 +1511,64 @@ async fn link_with_code(state: &AppState, st: &str, iid: u64, code: &str) -> Res .await; return page_redirect(&ret, "not_yours"); }; + if let Some(r) = link_blocked(state, &install_id, iid).await { + return page_redirect(&ret, r); + } + // What the person may push to themselves: the link never reaches past it. + let Ok(ceiling) = writable_in_installation(state, user_token, iid).await else { + return page_redirect(&ret, "github_unreachable"); + }; + if ceiling.is_empty() { + audit( + state, + &install_id, + "link_refused", + json!({ "installation_id": iid, "why": "no repository the person can push to" }), + ) + .await; + return page_redirect(&ret, "no_write_access"); + } + let Ok(Some(install)) = load_install(state, &install_id).await else { + return page_redirect(&ret, "install_off"); + }; + let token = broker::new_handle("hl"); + let ceiling_json = serde_json::to_string(&ceiling).unwrap_or_default(); + let iid_s = iid.to_string(); + if put_state( + state, + &format!("HYBRIDCONFIRM#{token}"), + &[ + ("install_id", &install_id), + ("installation_id", &iid_s), + ("account", &account), + ("return_url", &ret), + ("ceiling", &ceiling_json), + ], + 600, + ) + .await + .is_err() + { + return page_redirect(&ret, "store_failed"); + } + let address = if install.name.is_empty() { + install.cloudfront.clone() + } else { + names::hostname(&install.name) + }; + confirm_page(&account, &address, ceiling.len(), &token) +} + +/// Why an installation can't be linked to this install right now, if it can't. +async fn link_blocked(state: &AppState, install_id: &str, iid: u64) -> Option<&'static str> { + match load_install(state, install_id).await { + Ok(Some(i)) if i.verified() => {} + _ => return Some("install_off"), + } // Already linked elsewhere: one install per installation. if let Some(other) = install_for_installation(state, iid).await { if other != install_id { - return page_redirect(&ret, "linked_elsewhere"); + return Some("linked_elsewhere"); } } // A hosted team already owns it: never take a hosted customer's installation. @@ -1374,12 +1576,61 @@ async fn link_with_code(state: &AppState, st: &str, iid: u64, code: &str) -> Res .await .is_some() { - return page_redirect(&ret, "used_by_hosted_team"); + return Some("used_by_hosted_team"); + } + None +} + +/// POST /hybrid/github/confirm `token=&choice=link|cancel` (form, from +/// [`confirm_page`]): the person's answer. Only `link` links. +pub async fn github_confirm(State(state): State>, body: Bytes) -> Response { + if master(&state).is_none() { + return StatusCode::NOT_FOUND.into_response(); + } + let f = form(&body); + let token = f.get("token").cloned().unwrap_or_default(); + if !token.starts_with("hl_") || token.len() > 60 { + return (StatusCode::BAD_REQUEST, "Unknown link.").into_response(); + } + let Some(p) = take_state(&state, &format!("HYBRIDCONFIRM#{token}")).await else { + return ( + StatusCode::BAD_REQUEST, + "That link expired or was already used. Start it again from your install.", + ) + .into_response(); + }; + let g = |k: &str| { + p.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let (install_id, ret, account) = (g("install_id"), g("return_url"), g("account")); + let Ok(iid) = g("installation_id").parse::() else { + return (StatusCode::BAD_REQUEST, "Unknown link.").into_response(); + }; + if f.get("choice").map(String::as_str) != Some("link") { + audit( + &state, + &install_id, + "link_declined", + json!({ "installation_id": iid }), + ) + .await; + return page_redirect(&ret, "declined"); + } + if let Some(r) = link_blocked(&state, &install_id, iid).await { + return page_redirect(&ret, r); + } + let ceiling: Vec = serde_json::from_str(&g("ceiling")).unwrap_or_default(); + if ceiling.is_empty() { + return page_redirect(&ret, "no_write_access"); } let link = broker::GithubLink { installation_id: iid, account: account.clone(), repositories: vec![], + ceiling: Some(ceiling.clone()), }; let ok = state .dynamo @@ -1399,6 +1650,9 @@ async fn link_with_code(state: &AppState, st: &str, iid: u64, code: &str) -> Res .item("pk", s(&format!("HYBRIDGH#{iid}"))) .item("sk", s("LINK")) .item("install_id", s(&install_id)) + // Never over another install's link made in the meantime. + .condition_expression("attribute_not_exists(pk) OR install_id = :i") + .expression_attribute_values(":i", s(&install_id)) .send() .await .is_ok(); @@ -1406,10 +1660,10 @@ async fn link_with_code(state: &AppState, st: &str, iid: u64, code: &str) -> Res return page_redirect(&ret, "store_failed"); } audit( - state, + &state, &install_id, "link_github", - json!({ "installation_id": iid, "account": account }), + json!({ "installation_id": iid, "account": account, "repositories": ceiling.len() }), ) .await; page_redirect(&ret, "linked") @@ -1438,7 +1692,7 @@ pub async fn set_link_repos( broker::BrokerRefusal::NotLinked.message(), ) })?; - link.repositories = body_json(&body)["repositories"] + let chosen: Vec = body_json(&body)["repositories"] .as_array() .map(|a| { a.iter() @@ -1449,6 +1703,14 @@ pub async fn set_link_repos( .collect() }) .unwrap_or_default(); + if !broker::ceiling_allows(link, &chosen) { + return Err(fail( + StatusCode::FORBIDDEN, + broker::BrokerRefusal::RepositoryNotAllowed.code(), + broker::BrokerRefusal::RepositoryNotAllowed.message(), + )); + } + link.repositories = chosen; state .dynamo .update_item() @@ -1631,17 +1893,14 @@ pub async fn relay_github( }; let key = sign::relay_key(master, &install_id); let origin = install.origin(); - let attempt = relay::send( - &state.http, - &relay::Forward { - origin: &origin, - relay_key: &key, - source: "github", - event: event_type, - delivery_id: &delivery_id, - body, - }, - ) + let attempt = relay::send(&relay::Forward { + origin: &origin, + relay_key: &key, + source: "github", + event: event_type, + delivery_id: &delivery_id, + body, + }) .await; if let relay::Next::RetryIn(secs) = relay::apply(&mut d, attempt) { { @@ -1713,17 +1972,14 @@ pub async fn relay_jira( let key = sign::relay_key(master, install_id); let origin = install.origin(); let id = d.id.clone(); - let attempt = relay::send( - &state.http, - &relay::Forward { - origin: &origin, - relay_key: &key, - source: "jira", - event: path_event, - delivery_id: &id, - body, - }, - ) + let attempt = relay::send(&relay::Forward { + origin: &origin, + relay_key: &key, + source: "jira", + event: path_event, + delivery_id: &id, + body, + }) .await; let next = relay::apply(&mut d, attempt); deliveries::record(&state.dynamo, &state.config.settings_table_name, &pk, &d).await; @@ -1814,17 +2070,14 @@ pub async fn redeliver( }; let key = sign::relay_key(&master, &install.id); let origin = install.origin(); - let a = relay::send( - &state.http, - &relay::Forward { - origin: &origin, - relay_key: &key, - source: "github", - event: &event, - delivery_id: &rid, - body: &bytes, - }, - ) + let a = relay::send(&relay::Forward { + origin: &origin, + relay_key: &key, + source: "github", + event: &event, + delivery_id: &rid, + body: &bytes, + }) .await; let next = relay::apply(&mut d, a); if matches!(next, relay::Next::Delivered | relay::Next::AlreadyDelivered) { @@ -1891,6 +2144,21 @@ fn hosted_team(install: &str) -> String { relay::install_pk(install) } +/// The holding partition one provider sign-in is finished in. It moves into +/// the install's own ([`hosted_team`]) only when the install redeems the +/// code with its secret and the PKCE verifier ([`oauth_token`]): the +/// authorize link is public, so whoever follows it could otherwise put their +/// own provider account (or nothing) in place of the install's. +pub fn signin_team(install: &str, flow: &str) -> String { + format!("{}#SIGNIN#{flow}", relay::install_pk(install)) +} + +/// A flow id: what [`signin_team`] is keyed by. +fn is_flow(flow: &str) -> bool { + flow.strip_prefix("fl_") + .is_some_and(|t| t.len() == 40 && t.chars().all(|c| c.is_ascii_alphanumeric())) +} + #[derive(Deserialize, Default)] pub struct AuthorizeQuery { client_id: Option, @@ -1907,11 +2175,20 @@ pub struct AuthorizeQuery { pub async fn oauth_authorize( State(state): State>, Path(kind): Path, + headers: HeaderMap, Query(q): Query, ) -> Response { if master(&state).is_none() { return StatusCode::NOT_FOUND.into_response(); } + // Public: each start writes a holding partition, so it is limited per address. + if crate::middleware::rate_limit::allow(&headers, "hybrid-authorize", 20, 600).is_err() { + return ( + StatusCode::TOO_MANY_REQUESTS, + "Too many sign-ins started from here. Try again in a few minutes.", + ) + .into_response(); + } let Some(k) = kind_of(&kind) else { return (StatusCode::NOT_FOUND, "Unknown provider.").into_response(); }; @@ -1938,8 +2215,10 @@ pub async fn oauth_authorize( ) .into_response(); } - // The provider sign-in itself: CoderHelm's app, stored under the install's partition. - let team = hosted_team(&install.id); + // The provider sign-in itself: CoderHelm's app, finished in a holding + // partition of its own; the install's partition is never touched here. + let flow = broker::new_handle("fl"); + let team = signin_team(&install.id, &flow); let rt = super::mcp_servers::runtime(&state, &team); let a = super::knowledge_sources::app(&state, k); let Some(p) = common::knowledge::sources::oauth::provider(k) else { @@ -1997,6 +2276,7 @@ pub async fn oauth_authorize( ("redirect_uri", redirect.as_str()), ("install_state", install_state.as_str()), ("code_challenge", challenge.as_str()), + ("flow", flow.as_str()), ]; if put_state(&state, &key, &fields, 900).await.is_err() { return StatusCode::SERVICE_UNAVAILABLE.into_response(); @@ -2031,13 +2311,18 @@ pub async fn oauth_callback(State(state): State>, body: Bytes) -> .cloned() .unwrap_or_default() }; - let (install_id, kind, redirect, install_state, challenge) = ( + let (install_id, kind, redirect, install_state, challenge, flow) = ( g("install_id"), g("kind"), g("redirect_uri"), g("install_state"), g("code_challenge"), + g("flow"), ); + // A flow started before holding partitions existed has none: start again. + if !is_flow(&flow) { + return Err(not_here()); + } let back = |q: &str| { format!( "{redirect}?{q}&state={}", @@ -2049,7 +2334,7 @@ pub async fn oauth_callback(State(state): State>, body: Bytes) -> json!({ "redirect": back(&format!("error={}", urlencoding::encode(err))) }), )); } - let team = hosted_team(&install_id); + let team = signin_team(&install_id, &flow); let rt = super::mcp_servers::runtime(&state, &team); let sub = format!("hybrid:{install_id}"); if let Err(e) = rt @@ -2075,6 +2360,7 @@ pub async fn oauth_callback(State(state): State>, body: Bytes) -> ("kind", &kind), ("code_challenge", &challenge), ("redirect_uri", &redirect), + ("flow", &flow), ], 300, ) @@ -2085,6 +2371,37 @@ pub async fn oauth_callback(State(state): State>, body: Bytes) -> )) } +/// Moves a finished provider sign-in from its holding partition into the +/// install's own, with CoderHelm's app as the connection there. +async fn adopt_provider_sign_in( + state: &AppState, + install_id: &str, + kind: &str, + flow: &str, +) -> Result<(), String> { + if !is_flow(flow) { + return Err("no holding partition".into()); + } + let k = kind_of(kind).ok_or("unknown provider")?; + let p = common::knowledge::sources::oauth::provider(k).ok_or("unknown provider")?; + let a = super::knowledge_sources::app(state, k); + if !a.is_set() { + return Err("CoderHelm's app for this provider isn't set up".into()); + } + let team = hosted_team(install_id); + let rt = super::mcp_servers::runtime(state, &team); + let hold = super::mcp_servers::runtime(state, &signin_team(install_id, flow)); + let id = common::knowledge::sources::oauth::connection_id(k); + let sealed = rt.seal_client_secret(&id, a.client_secret.trim()).await?; + let mut rec = + common::knowledge::sources::oauth::connection_record(k, &p, a.client_id.trim(), &sealed); + rec.added_by = format!("hybrid:{install_id}"); + rec.added_at = now(); + rt.store.put_server(&team, &rec).await?; + rt.adopt_sign_in(&hold, &id, &common::mcp_remote::store::Owner::Team) + .await +} + fn token_error(code: &str, desc: &str) -> (StatusCode, Json) { ( StatusCode::BAD_REQUEST, @@ -2150,6 +2467,17 @@ pub async fn oauth_token(State(state): State>, body: Bytes) -> Rep )); } let kind = cg("kind"); + // Only now, with the install's secret and verifier checked, does + // the sign-in become the install's. + adopt_provider_sign_in(&state, &install.id, &kind, &cg("flow")) + .await + .map_err(|e| { + warn!(install = %install.id, error = %e, "hybrid: sign-in not taken"); + token_error( + "invalid_grant", + "The sign-in couldn't be finished. Start it again.", + ) + })?; let handle = broker::new_handle("hr"); state .dynamo @@ -2346,8 +2674,31 @@ pub async fn admin_revoke( .await? .ok_or_else(|| fail(StatusCode::NOT_FOUND, "not_found", "No such install."))?; release_name(&state, &mut install).await?; + // Its GitHub installations stop relaying here and are free again. + for l in github_links(&state, &install.id).await { + unlink(&state, &install.id, l.installation_id).await; + } install.status = "revoked".into(); + install.integrations.clear(); save_install(&state, &install).await?; + // And the same CloudFront can't simply register again. + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(&revoked_cloudfront_key(&install.cloudfront))) + .item("sk", s("REVOKED")) + .item("install_id", s(&install.id)) + .item("at", s(&now())) + .send() + .await + .map_err(|_| { + fail( + StatusCode::SERVICE_UNAVAILABLE, + "store_unavailable", + "Try again in a minute.", + ) + })?; audit( &state, &id, @@ -2408,13 +2759,85 @@ mod tests { #[test] fn linking_needs_the_person_to_see_the_installation() { - let v = json!({"installations": [{"id": 5, "account": {"login": "example-org"}}, {"id": 6, "account": {"login": "other"}}]}); + let v = json!({"installations": [ + {"id": 5, "app_id": 9, "account": {"login": "example-org"}}, + {"id": 6, "app_id": 9, "account": {"login": "other"}}, + {"id": 8, "app_id": 1234, "account": {"login": "another-app"}} + ]}); assert_eq!( - user_sees_installation(&v, 5).as_deref(), + user_sees_installation(&v, 5, 9).as_deref(), Some("example-org") ); - assert_eq!(user_sees_installation(&v, 7), None); - assert_eq!(user_sees_installation(&json!({}), 5), None); + assert_eq!(user_sees_installation(&v, 7, 9), None); + assert_eq!(user_sees_installation(&json!({}), 5, 9), None); + // Another app's installation never counts, nor does an unknown app id. + assert_eq!(user_sees_installation(&v, 8, 9), None); + assert_eq!(user_sees_installation(&v, 5, 0), None); + } + + #[test] + fn the_return_address_is_one_of_the_installs_own_hosts() { + let i = Install { + id: "ins_abcdefghijklmnopqrstuvwx".into(), + status: "active".into(), + cloudfront: "d1abcdef234567.cloudfront.net".into(), + name: "example".into(), + ..Default::default() + }; + let home = "https://d1abcdef234567.cloudfront.net/settings/system/#hybrid"; + for ok in [ + "https://d1abcdef234567.cloudfront.net/settings/system/?x=1#hybrid", + "https://example.coderhelm.com/settings/system/", + "https://docs.coderhelm.com/self-host/install/", + ] { + assert_eq!( + return_url_for(&i, ok), + url::Url::parse(ok).unwrap().to_string(), + "{ok}" + ); + } + for bad in [ + "https://d1abcdef234567.cloudfront.net.example.org/x", + "https://d1abcdef234567.cloudfront.net@example.org/x", + "https://example.coderhelm.com.example.org/", + "https://docs.coderhelm.com.example.org/", + "http://d1abcdef234567.cloudfront.net/", + "https://d1abcdef234567.cloudfront.net:8443/", + "javascript:alert(1)", + "//example.org", + "", + ] { + assert_eq!(return_url_for(&i, bad), home, "{bad}"); + } + } + + #[test] + fn the_link_confirmation_names_the_install_and_cant_be_framed() { + let r = confirm_page("example-org", "example.coderhelm.com", 3, "hl_abc"); + assert_eq!(r.status(), StatusCode::OK); + let h = r.headers(); + assert_eq!(h.get("x-frame-options").unwrap(), "DENY"); + assert!(h + .get("content-security-policy") + .unwrap() + .to_str() + .unwrap() + .contains("frame-ancestors 'none'")); + assert_eq!(h.get("cache-control").unwrap(), "no-store"); + let r = confirm_page("x", "a\"b", 1, "hl_\">