diff --git a/docs/self-host/check-your-install.md b/docs/self-host/check-your-install.md index fe79078c5..6f58a68c9 100644 --- a/docs/self-host/check-your-install.md +++ b/docs/self-host/check-your-install.md @@ -210,7 +210,7 @@ Install admins (`admins` in the config) who are team admins can call these while } ``` -`status` is `pass`, `warn`, `fail` or `skip` (an optional integration that isn't set up). `fix` has `text` and any of `command` (to copy), `url` (outside CoderHelm) and `href` (a dashboard page). `ready` is true when nothing fails. Keys: `url`, `domain`, `github_keys`, `github_app`, `github_permissions`, `github_installations`, `github_webhook`, `github_sign_in`, `email_sender`, `email_identity`, `email_sandbox`, `email_cognito`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`. A self-hosted install has no Google sign-in, so there is no `google_sign_in` check. On an install that uses CoderHelm's GitHub App (hybrid), `github_app` and `github_installations` say whether the app is linked instead, and never block an update. `github_sign_in` warns when the install's own GitHub App has no OAuth client id and secret stored (or only one of them): without both, the sign-in page doesn't offer Continue with GitHub. On an install that uses CoderHelm's GitHub App it is `skip`, since CoderHelm's app can't sign anyone in to the install; people sign in with email and password. It never blocks an update. +`status` is `pass`, `warn`, `fail` or `skip` (an optional integration that isn't set up). `fix` has `text` and any of `command` (to copy), `url` (outside CoderHelm) and `href` (a dashboard page). `ready` is true when nothing fails. Keys: `url`, `domain`, `github_keys`, `github_app`, `github_permissions`, `github_installations`, `github_webhook`, `github_sign_in`, `email_sender`, `email_identity`, `email_sandbox`, `email_cognito`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`. A self-hosted install has no Google sign-in, so there is no `google_sign_in` check. On an install that uses CoderHelm's GitHub App (hybrid), `github_app` and `github_installations` say whether the app is linked instead, and never block an update. `github_sign_in` passes when the install's own GitHub App has its OAuth client id and secret stored, or when the install has neither and is registered with CoderHelm (GitHub sign-in then goes through CoderHelm's app, [Sign in with GitHub through CoderHelm](./hybrid.md#sign-in-with-github-through-coderhelm)). It warns when only one of the two is stored, when the install's own app has neither, and when an install on CoderHelm's GitHub App isn't registered yet: the sign-in page doesn't offer Continue with GitHub until then. It never blocks an update. ### `GET /api/system/domain`, `PUT /api/system/domain`, `DELETE /api/system/domain` diff --git a/docs/self-host/hybrid.md b/docs/self-host/hybrid.md index 857cc90af..1a6e587ca 100644 --- a/docs/self-host/hybrid.md +++ b/docs/self-host/hybrid.md @@ -28,6 +28,7 @@ Your code, runs, plans, reviews, memory, knowledge and secrets stay in your AWS | Token broker | the short-lived installation token it mints for your install (scoped to the repositories you chose, never more than the app's permissions) | no tokens; a record of each mint for 14 days | | Jira app relay | each issue event, in transit, unchanged | as for GitHub. The Forge app's secret is checked by your install, so CoderHelm can't make an event up | | Jira site link | each event of the linked site (the Jira app's and a plain Jira webhook's), in transit, without the app's secret; your install's calls to the site's Jira app (comments, tickets, release notes), in transit, through CoderHelm's Jira proxy | as for GitHub; the link itself (which team's site, who linked it, when). The site's Jira app secret and links stay with CoderHelm | +| GitHub sign-in (when your install has no GitHub OAuth client of its own) | GitHub's one-time code on its way to your install, and the person's GitHub token twice: in the answer to your install's exchange, and when your install has it revoked moments later | no codes and no tokens: the code's hash for at most 5 minutes, and an audit line that a sign-in happened (no name, no account) | | Notion, Confluence, Google Drive | the sign-in, once | the provider sign-in, encrypted with a key only CoderHelm's services can use, so it can hand your install access tokens. Disconnecting revokes it. Notion's tokens don't expire by themselves: a copy your install holds stays valid until Notion's own integration page removes it | | Email through CoderHelm (opt-in, [Email](./email.md#send-through-coderhelm)) | each email's recipient address, template id and parameters (names, PR titles and run links in the weekly summary), in transit; CoderHelm writes the email from its own templates | delivery metadata only: template id, a shortened address and the status, for 3 days. Salted hashes of the addresses your install listed, and your install admins' addresses sealed with a key only CoderHelm's services can use, to tell them if email pauses | | Sharing with support (opt-in) | metadata of failed deliveries, and payload previews only if you also choose that | for 14 days, so support can see what failed | @@ -53,6 +54,7 @@ How the pieces are protected: - **Signed both ways, each call once.** Every call from your install is signed (`X-CoderHelm-Signature: v2=…`) over the time, a single-use request id (`X-CoderHelm-Request-Id`), the method, the path with its query, and the body. CoderHelm takes each request id once, so a copy of a call (from a log, a proxy or a HAR file) is refused even within the 5 minutes it would otherwise be fresh. Releases before `v2` sign with `v1=`, which covers neither an id nor the query: CoderHelm accepts those only until **2026-11-17 00:00 UTC**, never with a query, and takes each one once by its own signature, so it can't be replayed either. Update before then (Settings, System, Update now). 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, and an event without it is refused). 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. +- **Your install decides who signs in.** GitHub sign-in through CoderHelm's app is bound to the browser and the install that started it, and your install asks GitHub itself whose account it is. See [Sign in with GitHub through CoderHelm](#sign-in-with-github-through-coderhelm). - **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. - **Email only as itself.** See [Email threat model](#email-threat-model) below. @@ -104,7 +106,25 @@ A name can change five times a day. [Uninstalling](./uninstall.md#hybrid-install 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. +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. + +## Sign in with GitHub through CoderHelm + +An install on CoderHelm's GitHub App has no GitHub OAuth client of its own, and GitHub only sends people back to addresses registered on CoderHelm's app. So once your install is registered, **Continue with GitHub** on its sign-in page goes through CoderHelm, and your install still makes the decision: + +1. Your install makes a random state and a secret PKCE verifier, keeps them in a sealed cookie in the person's browser, and asks CoderHelm (signed with its registration secret) to start a sign-in that comes back to its own address. CoderHelm refuses any address that isn't your install's verified CloudFront address or CoderHelm address. +2. The person signs in on GitHub's own page, with CoderHelm's app. +3. GitHub sends the browser to CoderHelm with a one-time code, and CoderHelm sends it straight on to your install with that code. CoderHelm doesn't exchange it. +4. Your install checks the state against the cookie (so a sign-in started in another browser, or for another install, is refused), then asks CoderHelm (signed) to exchange the code with its verifier. GitHub checks the verifier too: without it the code is useless. Each code is taken once. +5. Your install asks GitHub, with the person's token, whose account it is, then applies its own rules: only members, invited people and allowed domains get in (no new sign-ups), and two-factor is asked for as on every sign-in. Then it has CoderHelm revoke the token at GitHub, so it lives for seconds. + +What CoderHelm sees and can do: + +- **Sees:** that someone on your install started a GitHub sign-in, the one-time code on its way through, and the person's GitHub token for the few seconds between the exchange and the revoke. It keeps neither, and it doesn't ask GitHub who the person is. It keeps the code's hash for at most 5 minutes and an audit line with no name. +- **Can't:** start a session on your install, pick who signs in, or get past your install's rules. Your install reads the GitHub account from GitHub, not from CoderHelm, and the second factor is your install's own. +- **Could, in principle:** use the token in those few seconds for what CoderHelm's GitHub App may do as that person, since it passes through CoderHelm's servers. If that matters to you, give the install its own GitHub App (Settings, System, Hybrid, **Use my own GitHub App (fully private)**); sign-in then never touches CoderHelm. + +Signing in through CoderHelm doesn't link GitHub organizations: that only happens through [CoderHelm's GitHub App](#coderhelms-github-app) linking. It works on your CloudFront address and your CoderHelm address; an install that answers on a domain of its own uses one of those for GitHub sign-in. The `github_sign_in` check in **Settings, Setup** says whether it's on. ## Jira through CoderHelm @@ -145,7 +165,7 @@ The Setup checks show the link as `hybrid_jira` (in Settings, Setup and the inst | Slack and Teams notifications | not needed | your install posts to the incoming webhook you paste | | Figma, Linear, Sentry, Sanity and other sign-in apps | not needed | your install registers itself with each provider | | Slack and Teams commands | no | there is no shared Slack or Teams app: each team uses its own app's signing secret, as today | -| Sign in with GitHub | no | it would hand your people's identities to CoderHelm; use email and password | +| Sign in with GitHub | yes | CoderHelm's app carries the trip to GitHub; your install checks the account with GitHub and applies its own rules ([Sign in with GitHub through CoderHelm](#sign-in-with-github-through-coderhelm)) | | Sign in with Google | no | a self-hosted install has no Google sign-in, through CoderHelm or its own ([Sign-in and people](./sign-in.md#no-google-sign-in)) | ## Turn hybrid off @@ -154,7 +174,7 @@ The Setup checks show the link as `hybrid_jira` (in Settings, Setup and the inst ## For CoderHelm's operators -The hosted side runs in the hosted deployment's API stack when `hybrid.zone` is set in its config (the parent zone is configurable, so moving customer addresses to a separate domain later is a config change). It needs `hybrid_master_key` (32 or more random characters) in the hosted secret, the callback URL `https://api.coderhelm.com/auth/github/callback/hybrid` on CoderHelm's GitHub App, and the GitHub App's setup page (the dashboard's Settings, GitHub) to forward `state=hyb_…` returns. A hosted team links its Jira site with `GET` and `POST /api/hybrid/jira-link/:state` (team admins, from the dashboard's Settings, Integrations, Jira, which opens with `?hybrid_link=hyj_…`); sees and removes the link with `GET` and `DELETE /api/hybrid/jira-link`; installs call `POST /hybrid/jira/link-start`, `DELETE /hybrid/jira/link` and `POST /hybrid/jira/config` (signed), and the Jira proxy at `POST /hybrid/jira/trigger///`. Platform admins see every install and the audit log (`jira_link_start`, `link_jira`, `unlink_jira`, `jira_link_refused`, `jira_link_declined`) at `GET /api/admin/hybrid`, and revoke one with `POST /api/admin/hybrid/:install_id/revoke`. +The hosted side runs in the hosted deployment's API stack when `hybrid.zone` is set in its config (the parent zone is configurable, so moving customer addresses to a separate domain later is a config change). It needs `hybrid_master_key` (32 or more random characters) in the hosted secret, the callback URL `https://api.coderhelm.com/auth/github/callback/hybrid` on CoderHelm's GitHub App, and the GitHub App's setup page (the dashboard's Settings, GitHub) to forward `state=hyb_…` returns. The same callback URL takes installs' GitHub sign-ins (`state=hsi_…`): installs call `POST /hybrid/github/sign-in/start` and `POST /hybrid/github/sign-in/exchange` (signed), and the audit log has `github_sign_in` and `github_sign_in_refused`; no other GitHub App setting is needed. A hosted team links its Jira site with `GET` and `POST /api/hybrid/jira-link/:state` (team admins, from the dashboard's Settings, Integrations, Jira, which opens with `?hybrid_link=hyj_…`); sees and removes the link with `GET` and `DELETE /api/hybrid/jira-link`; installs call `POST /hybrid/jira/link-start`, `DELETE /hybrid/jira/link` and `POST /hybrid/jira/config` (signed), and the Jira proxy at `POST /hybrid/jira/trigger///`. Platform admins see every install and the audit log (`jira_link_start`, `link_jira`, `unlink_jira`, `jira_link_refused`, `jira_link_declined`) at `GET /api/admin/hybrid`, and revoke one with `POST /api/admin/hybrid/:install_id/revoke`. **Approving an install for the mail relay.** An install with a GitHub link may use the relay already. To approve one without, set `relay_approved` to `true` on its `HYBRID#` / `INSTALL` record in the hosted settings table, after checking who runs it. diff --git a/docs/self-host/sign-in.md b/docs/self-host/sign-in.md index 2ed6c64a1..96646da30 100644 --- a/docs/self-host/sign-in.md +++ b/docs/self-host/sign-in.md @@ -97,11 +97,11 @@ An install that had Google sign-in on loses it at its next update, which removes ## GitHub accounts -People connect their GitHub account in their own settings, so pull requests and reviews are credited to them. Signing in with GitHub follows the same rules as everything else: it lands on the organization only for someone already in it, invited, or at an allowed domain (by the email on their GitHub account). It uses the GitHub App's own OAuth client, which the GitHub App step stores; nothing to set up. The sign-in page offers **Continue with GitHub** only while that client's id and secret are both stored (it asks the API, `GET /auth/methods`). An install on CoderHelm's GitHub App (hybrid) has no client of its own, so its sign-in page shows email and password only: signing in through CoderHelm would hand your people's identities to CoderHelm. The `github_sign_in` check in **Settings, Setup** says which applies. +People connect their GitHub account in their own settings, so pull requests and reviews are credited to them. Signing in with GitHub follows the same rules as everything else: it lands on the organization only for someone already in it, invited, or at an allowed domain (by the email on their GitHub account). It uses the GitHub App's own OAuth client, which the GitHub App step stores; nothing to set up. An install on CoderHelm's GitHub App (hybrid) has no client of its own: once it is registered with CoderHelm, GitHub sign-in goes through CoderHelm's app, and the install still checks the account with GitHub itself and applies these same rules and two-factor ([Sign in with GitHub through CoderHelm](./hybrid.md#sign-in-with-github-through-coderhelm)). The sign-in page offers **Continue with GitHub** only when one of the two works (it asks the API, `GET /auth/methods`). The `github_sign_in` check in **Settings, Setup** says which applies. ## Single sign-on (SAML, OIDC) -Not available yet: CoderHelm's sign-in page offers email and password, and GitHub when the install has its own GitHub App. The Cognito user pool is in your account, so an identity provider added there by hand is not shown on the sign-in page and isn't supported. +Not available yet: CoderHelm's sign-in page offers email and password, and GitHub. The Cognito user pool is in your account, so an identity provider added there by hand is not shown on the sign-in page and isn't supported. ## Install admins and team roles diff --git a/services/common/src/hybrid/github_sign_in.rs b/services/common/src/hybrid/github_sign_in.rs new file mode 100644 index 000000000..d7888a30f --- /dev/null +++ b/services/common/src/hybrid/github_sign_in.rs @@ -0,0 +1,424 @@ +//! GitHub sign-in on a hybrid install through CoderHelm's GitHub App. +//! +//! A hybrid install has no GitHub OAuth client of its own, and GitHub only +//! sends people back to the callback addresses registered on CoderHelm's +//! app. So the hosted side carries the GitHub trip, and the install makes +//! every decision: +//! +//! 1. The install makes a state, a PKCE verifier and its challenge, and asks +//! the hosted side (signed with its registration secret) to start a flow +//! for its own callback address. The hosted side refuses any address that +//! isn't one of the install's verified hosts. +//! 2. GitHub comes back to the hosted callback with a one-time code. The +//! hosted side sends the browser on to the install's callback with that +//! code, the install's state and the flow id. It never exchanges the code +//! on its own. +//! 3. The install checks the state and the flow against its sealed cookie, +//! then asks the hosted side (signed) to exchange the code with the PKCE +//! verifier only it holds. GitHub checks the verifier against the +//! challenge from step 1, so a code from another flow can't be used. +//! 4. The install reads the person's GitHub id and login from GitHub itself +//! with that token and applies its own sign-in rules (team, invites, +//! two-factor). Then it has the hosted side revoke the token at GitHub +//! (only CoderHelm's client can), so it lives for seconds. The hosted +//! side can't mint a session on the install and doesn't choose who signs in. +//! +//! Everything here is pure (no AWS, no HTTP) so each check has a test. + +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha256}; + +/// The install's callback for this flow (on its own API address). +pub const CALLBACK_PATH: &str = "/auth/github/hybrid-callback"; +/// The hosted callback GitHub returns to: the one already registered on +/// CoderHelm's GitHub App for hybrid linking. +pub const HOSTED_CALLBACK_PATH: &str = "/auth/github/callback/hybrid"; +/// The signed calls the install makes. +pub const START_PATH: &str = "/hybrid/github/sign-in/start"; +pub const EXCHANGE_PATH: &str = "/hybrid/github/sign-in/exchange"; +pub const REVOKE_PATH: &str = "/hybrid/github/sign-in/revoke"; +/// A flow id's prefix (`hsi_` and 40 random characters). +pub const FLOW_PREFIX: &str = "hsi"; +/// How long a started flow waits for GitHub, and a returned code for the +/// install's exchange. +pub const START_TTL_SECS: i64 = 600; +pub const RETURN_TTL_SECS: i64 = 300; +/// How long the install's sealed cookie is good for. +pub const COOKIE_TTL_SECS: i64 = 600; + +const ALNUM: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + +fn random(n: usize) -> String { + use rand::Rng; + let mut rng = rand::rng(); + (0..n) + .map(|_| ALNUM[rng.random_range(0..ALNUM.len())] as char) + .collect() +} + +fn alnum(s: &str) -> bool { + s.bytes().all(|b| b.is_ascii_alphanumeric()) +} + +/// A flow id the hosted side made ([`FLOW_PREFIX`]). +pub fn is_flow(s: &str) -> bool { + s.strip_prefix("hsi_") + .is_some_and(|t| t.len() == 40 && alnum(t)) +} + +/// The install's state: 43 random characters. +pub fn new_state() -> String { + random(43) +} + +/// An install state the hosted side accepts and carries back. +pub fn is_state(s: &str) -> bool { + (32..=128).contains(&s.len()) && alnum(s) +} + +/// A PKCE verifier (RFC 7636): 64 characters from the unreserved set. +pub fn new_verifier() -> String { + random(64) +} + +/// The S256 challenge for a verifier. +pub fn challenge(verifier: &str) -> String { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +/// An S256 challenge's shape: 43 base64url characters. +pub fn is_challenge(c: &str) -> bool { + c.len() == 43 + && c.bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// What the hosted side keeps of a returned code: its hash, never the code. +pub fn code_hash(code: &str) -> String { + hex::encode(Sha256::digest(code.as_bytes())) +} + +/// Constant-time string equality. +pub fn same(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// Whether `redirect_uri` is the install's sign-in callback on one of its +/// verified hosts: https, no port, no user, no query or fragment, exactly +/// [`CALLBACK_PATH`], host compared whole (never by prefix). +pub fn redirect_allowed(redirect_uri: &str, origins: &[String]) -> bool { + let Ok(u) = url::Url::parse(redirect_uri) else { + return false; + }; + if u.scheme() != "https" + || u.port().is_some() + || !u.username().is_empty() + || u.password().is_some() + || u.query().is_some() + || u.fragment().is_some() + || u.path() != CALLBACK_PATH + { + return false; + } + let origin = format!( + "https://{}", + u.host_str().unwrap_or("").to_ascii_lowercase() + ); + origins + .iter() + .any(|o| o.trim_end_matches('/').eq_ignore_ascii_case(&origin)) +} + +/// GitHub's authorize page for a flow: CoderHelm's client, the hosted +/// callback, the flow id as GitHub's state, and the install's challenge. +pub fn authorize_url(client_id: &str, hosted_api: &str, flow: &str, challenge: &str) -> String { + let redirect = format!("{}{HOSTED_CALLBACK_PATH}", hosted_api.trim_end_matches('/')); + format!( + "https://github.com/login/oauth/authorize?client_id={}&redirect_uri={}&state={}&code_challenge={}&code_challenge_method=S256&allow_signup=false", + urlencoding::encode(client_id), + urlencoding::encode(&redirect), + urlencoding::encode(flow), + urlencoding::encode(challenge), + ) +} + +/// The install's check of the authorize address the hosted side answered: +/// GitHub's page, for this flow, with this install's own challenge. Anything +/// else is refused before the browser goes anywhere. +pub fn authorize_url_ok(url: &str, flow: &str, challenge: &str) -> bool { + let Ok(u) = url::Url::parse(url) else { + return false; + }; + if u.scheme() != "https" + || u.host_str() != Some("github.com") + || u.port().is_some() + || u.path() != "/login/oauth/authorize" + { + return false; + } + let q = |k: &str| { + u.query_pairs() + .filter(|(n, _)| n == k) + .map(|(_, v)| v.into_owned()) + .collect::>() + }; + q("state") == [flow] + && q("code_challenge") == [challenge] + && q("code_challenge_method") == ["S256"] +} + +/// Where the hosted side sends the browser back to: the install's callback +/// with GitHub's code (or error), the install's state and the flow id. +pub fn return_url( + redirect: &str, + outcome: Result<&str, &str>, + install_state: &str, + flow: &str, +) -> String { + let first = match outcome { + Ok(code) => format!("code={}", urlencoding::encode(code)), + Err(e) => { + // GitHub's error names are short fixed tokens; keep only those. + let e: String = e + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(64) + .collect(); + format!( + "error={}", + if e.is_empty() { + "access_denied".into() + } else { + e + } + ) + } + }; + format!( + "{redirect}?{first}&state={}&flow={}", + urlencoding::encode(install_state), + urlencoding::encode(flow) + ) +} + +/// What the install keeps in its cookie between the start and the return. +#[derive(Clone, PartialEq, Eq)] +pub struct Pending { + pub state: String, + pub flow: String, + pub verifier: String, +} + +impl std::fmt::Debug for Pending { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Pending") + .field("flow", &self.flow) + .finish_non_exhaustive() + } +} + +fn mac(key: &str, body: &str) -> String { + let mut m = Hmac::::new_from_slice(key.as_bytes()).expect("any key length"); + m.update(b"coderhelm-hybrid-github-sign-in\n"); + m.update(body.as_bytes()); + hex::encode(m.finalize().into_bytes()) +} + +/// The cookie value: the pending flow and its expiry, with the install's own +/// MAC (a key only the install has), so the browser can't change any part. +pub fn seal(key: &str, p: &Pending, now: i64) -> String { + let body = format!( + "{}.{}.{}.{}", + p.state, + p.flow, + p.verifier, + now + COOKIE_TTL_SECS + ); + format!("{body}.{}", mac(key, &body)) +} + +/// Opens a cookie [`seal`] made: None when altered, malformed or expired. +pub fn open(key: &str, value: &str, now: i64) -> Option { + let (body, tag) = value.rsplit_once('.')?; + if !same(&mac(key, body), tag) { + return None; + } + let mut it = body.split('.'); + let (state, flow, verifier, exp) = (it.next()?, it.next()?, it.next()?, it.next()?); + if it.next().is_some() || exp.parse::().ok()? < now { + return None; + } + (is_state(state) && is_flow(flow) && verifier.len() == 64 && alnum(verifier)).then(|| Pending { + state: state.into(), + flow: flow.into(), + verifier: verifier.into(), + }) +} + +/// The return belongs to the flow this browser started: the same state and +/// the same flow id (no mix-up with another flow or install). +pub fn return_matches(p: &Pending, state: &str, flow: &str) -> bool { + same(&p.state, state) && same(&p.flow, flow) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn origins() -> Vec { + vec![ + "https://d1234.cloudfront.net".into(), + "https://acme.coderhelm.com".into(), + ] + } + + fn flow() -> String { + format!("hsi_{}", "a".repeat(40)) + } + + #[test] + fn the_redirect_is_only_the_install_callback_on_its_own_hosts() { + let o = origins(); + assert!(redirect_allowed( + "https://d1234.cloudfront.net/auth/github/hybrid-callback", + &o + )); + assert!(redirect_allowed( + "https://ACME.coderhelm.com/auth/github/hybrid-callback", + &o + )); + for bad in [ + "http://d1234.cloudfront.net/auth/github/hybrid-callback", + "https://d1234.cloudfront.net:8443/auth/github/hybrid-callback", + "https://d1234.cloudfront.net.evil.example/auth/github/hybrid-callback", + "https://evil.example/auth/github/hybrid-callback", + "https://user@d1234.cloudfront.net/auth/github/hybrid-callback", + "https://d1234.cloudfront.net/auth/github/hybrid-callback?x=1", + "https://d1234.cloudfront.net/auth/github/hybrid-callback#x", + "https://d1234.cloudfront.net/auth/github/callback", + "https://d1234.cloudfront.net/auth/github/hybrid-callback/", + "https://other.coderhelm.com/auth/github/hybrid-callback", + "not a url", + "", + ] { + assert!(!redirect_allowed(bad, &o), "{bad}"); + } + } + + #[test] + fn handles_and_secrets_have_their_shapes() { + assert!(is_flow(&flow())); + assert!(!is_flow("hyb_aaaa")); + assert!(!is_flow(&format!("hsi_{}", "a".repeat(39)))); + assert!(!is_flow(&format!("hsi_{}.", "a".repeat(39)))); + let s = new_state(); + assert!(is_state(&s) && s != new_state()); + assert!(!is_state("short") && !is_state(&format!("{}.", "a".repeat(40)))); + let v = new_verifier(); + let c = challenge(&v); + assert!(is_challenge(&c)); + assert!(crate::hybrid::broker::pkce_matches(&c, &v)); + assert!(!crate::hybrid::broker::pkce_matches(&c, &new_verifier())); + assert_eq!(code_hash("abc"), code_hash("abc")); + assert_ne!(code_hash("abc"), code_hash("abd")); + assert!(!code_hash("abc").contains("abc")); + } + + #[test] + fn the_authorize_url_carries_the_flow_and_the_install_challenge() { + let c = challenge(&new_verifier()); + let u = authorize_url("Iv1.coderhelm", "https://api.coderhelm.com/", &flow(), &c); + assert!(u.starts_with("https://github.com/login/oauth/authorize?client_id=Iv1.coderhelm&")); + assert!(u.contains(&format!( + "redirect_uri={}", + urlencoding::encode("https://api.coderhelm.com/auth/github/callback/hybrid") + ))); + assert!(authorize_url_ok(&u, &flow(), &c)); + // Another flow, another challenge, or somewhere other than GitHub. + assert!(!authorize_url_ok( + &u, + &format!("hsi_{}", "b".repeat(40)), + &c + )); + assert!(!authorize_url_ok(&u, &flow(), &challenge(&new_verifier()))); + let elsewhere = u.replace("https://github.com/", "https://github.com.evil.example/"); + assert!(!authorize_url_ok(&elsewhere, &flow(), &c)); + let plain = u.replace("code_challenge_method=S256", "code_challenge_method=plain"); + assert!(!authorize_url_ok(&plain, &flow(), &c)); + let twice = format!("{u}&state=hsi_{}", "b".repeat(40)); + assert!(!authorize_url_ok(&twice, &flow(), &c)); + } + + #[test] + fn the_return_url_carries_the_code_or_a_clean_error() { + let r = "https://acme.coderhelm.com/auth/github/hybrid-callback"; + let u = return_url(r, Ok("c0de"), "S1", &flow()); + assert_eq!(u, format!("{r}?code=c0de&state=S1&flow={}", flow())); + let u = return_url(r, Err("access_denied"), "S1", &flow()); + assert!(u.starts_with(&format!("{r}?error=access_denied&state=S1"))); + let u = return_url(r, Err("