Repository navigation
test: reproduce cross-host GitHub installation callbacks #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| # Reproduce an installation return across hosts | ||
|
|
||
| An application can start OAuth at `https://aictrl.dev` while its GitHub App's configured setup callback returns to `https://app.aictrl.dev/api/github-app/setup`. A host-only correlation cookie belongs to the initiating host. Validating it at the other host rejects the installation return because the browser doesn't send it there. | ||
|
|
||
| The emulator already redirects to the full configured `apps[].setup_url`, including its host. This proof exercises that behavior through the OAuth user picker and GitHub App installation form. Both application listeners stay on port 3005: | ||
|
|
||
| | Role | Local origin | | ||
| | --- | --- | | ||
| | Initiating application | `https://127.0.0.98:3005` | | ||
| | Configured setup callback | `https://127.0.0.99:3005` | | ||
| | GitHub emulator | `http://127.0.0.100:4200` | | ||
|
|
||
| These separate loopback IP hosts require no DNS or hosts-file changes. A second port on the same host wouldn't test host-only cookie isolation. | ||
|
|
||
| ## Run the browser proof | ||
|
|
||
| Use Node 24, pnpm 11, OpenSSL, and `certutil` from `libnss3-tools`. On Debian or Ubuntu, install the last prerequisite with `sudo apt install libnss3-tools`. If the binary is outside `PATH`, set `CERTUTIL_PATH` to its absolute path. | ||
|
|
||
| From the repository root: | ||
|
|
||
| ```bash | ||
| pnpm install --frozen-lockfile | ||
| pnpm build | ||
| pnpm exec playwright install --with-deps firefox | ||
| pnpm test:cross-host | ||
| ``` | ||
|
|
||
| The test generates a temporary CA and a server certificate for both loopback hosts. It imports that CA into a temporary Firefox profile, starts the HTTPS listeners, and keeps browser certificate verification enabled. It removes the profile and certificates and closes the listeners afterward. The user's browser profile and system trust store remain unchanged. | ||
|
|
||
| The browser runs two flows. Each starts OAuth on the initiating host, chooses **octocat**, chooses **Install on example-org**, selects **Only select repositories**, checks **Select repository: example-org/selected**, and submits **Install**. | ||
|
|
||
| 1. The first return stays on the configured callback host. The server receives no `__Host-emulator_oauth_correlation` cookie and reports `Missing host-only OAuth cookie`. | ||
| 2. The second return verifies the fixture's signed state, redirects to the initiating host's same callback path, then validates the correlation cookie there. The browser supplies the cookie, and the fixture exchanges an App JWT for an installation token. `/installation/repositories` returns only `example-org/selected`. | ||
|
|
||
| The assertions check the emulator's installation response redirects to the configured host, the cookie's `Secure`, `HttpOnly`, `SameSite=Lax`, and `Path=/` attributes, and its absence from the other host. They also check the opaque `state`, `installation_id`, `setup_action=install`, and existing query parameters. The bounce preserves the entire callback query, including repeated parameters and encoded values. Requests use browser-managed cookies throughout. | ||
|
|
||
| ## Run the demonstration interactively | ||
|
|
||
| Provide a PEM key and certificate whose subject alternative names include `127.0.0.98` and `127.0.0.99`, signed by a CA your browser trusts. The browser test's temporary trust applies only to its own Firefox profile. | ||
|
|
||
| ```bash | ||
| CROSS_HOST_TLS_KEY=/path/to/server.key \ | ||
| CROSS_HOST_TLS_CERT=/path/to/server.crt \ | ||
| pnpm demo:cross-host | ||
| ``` | ||
|
|
||
| Open `https://127.0.0.98:3005`. Choose **Reproduce missing callback cookie** or **Return to the initiating host**, then complete the user, account, and repository choices. The callback displays the result as JSON. `/observations` on either application origin exposes the callback host, synthetic fixture state, raw query, and whether the request carried the correlation cookie. | ||
|
|
||
| The demonstration creates an installation on the selected account. Restart it before installing the same App on that account again. Stop it with Ctrl+C. | ||
|
|
||
| ## Reuse the fixture in an application regression | ||
|
|
||
| [`examples/lib/local-https.mjs`](../examples/lib/local-https.mjs) exports: | ||
|
|
||
| - `createLocalTls(hostnames)` accepts IP addresses, creates temporary CA/server PEM files, and returns `{ ca, directory, tls, close }`. Its defaults are `127.0.0.98` and `127.0.0.99`. | ||
| - `launchTrustedFirefox(firefox, certificates, { headless })` imports the CA into an isolated profile and returns a Playwright browser context with HTTPS verification enabled. | ||
| - `startHttpsOrigins({ tls, handler, appPort, sourceHostname, callbackHostname })` binds two HTTPS listeners and returns `{ sourceOrigin, callbackOrigin, close }`. The handler receives Node request/response objects and both origins. The default application port is 3005. | ||
|
|
||
| [`startCrossHostDemo`](../examples/cross-host-demo.mjs) combines these origins with a seeded emulator. It returns `sourceOrigin`, `callbackOrigin`, `emulatorUrl`, `observations`, `reset()`, and `close()`. Its optional asynchronous `setupHandler` receives `{ request, response, url, sourceOrigin, callbackOrigin, observation }`. Return `true` after handling a setup callback, or return a false value to use the demonstration handler. `reset()` clears observations and resets emulator state between browser cases. | ||
|
|
||
| For an application's own handler, reuse the HTTPS and trusted-browser helpers, configure the emulator's `setup_url` to the callback origin, and route both HTTPS listeners to the application. Initiate OAuth through its normal route. Keep the negative assertion at the callback host and assert that the successful return reaches the initiating host with the original query and browser correlation cookie. The fixture's HMAC/state implementation illustrates the redirect order; the application must run its own state verification and correlation checks. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,250 @@ | ||
| import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; | ||
| import { readFile } from "node:fs/promises"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import { createGitHubEmulator } from "../packages/github-emulator/dist/index.js"; | ||
| import { renderCardPage } from "../packages/@emulators/core/dist/index.js"; | ||
| import { getAppPrivateKey, mintAppJwt } from "./lib/github-app.mjs"; | ||
| import { json, redirect } from "./lib/http.mjs"; | ||
| import { startHttpsOrigins } from "./lib/local-https.mjs"; | ||
|
|
||
| export const correlationCookie = "__Host-emulator_oauth_correlation"; | ||
| const clientId = "cross-host-client"; | ||
| const clientSecret = "cross-host-local-secret"; | ||
| const appId = 12345; | ||
| const hashNonce = (nonce) => createHash("sha256").update(nonce).digest("hex"); | ||
| const cookieFor = (request) => | ||
| request.headers.cookie | ||
| ?.split(/;\s*/) | ||
| .find((part) => part.startsWith(`${correlationCookie}=`)) | ||
| ?.slice(correlationCookie.length + 1); | ||
| const matchesCorrelation = (claims, request) => { | ||
| const nonce = cookieFor(request); | ||
| if (!nonce || typeof claims.nonceHash !== "string") return false; | ||
| const actual = Buffer.from(hashNonce(nonce)); | ||
| const expected = Buffer.from(claims.nonceHash); | ||
| return actual.length === expected.length && timingSafeEqual(actual, expected); | ||
| }; | ||
|
|
||
| export async function startCrossHostDemo({ | ||
| tls, | ||
| appPort = 3005, | ||
| sourceHostname = "127.0.0.98", | ||
| callbackHostname = "127.0.0.99", | ||
| emulatorHostname = "127.0.0.100", | ||
| emulatorPort = 4200, | ||
| setupHandler, | ||
| } = {}) { | ||
| let emulator; | ||
| const observations = []; | ||
| const stateKey = randomBytes(32); | ||
| const mac = (body) => createHmac("sha256", stateKey).update(body).digest("base64url"); | ||
| const verifyState = (state) => { | ||
|
byapparov marked this conversation as resolved.
Resolved
|
||
| const index = state.lastIndexOf("."); | ||
| if (index < 0) return undefined; | ||
| const body = state.slice(0, index); | ||
| const actual = Buffer.from(state.slice(index + 1)); | ||
| const expected = Buffer.from(mac(body)); | ||
| if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return undefined; | ||
| try { | ||
| return JSON.parse(body); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| }; | ||
| const origins = await startHttpsOrigins({ | ||
| tls, | ||
| appPort, | ||
| sourceHostname, | ||
| callbackHostname, | ||
| handler: async (request, response, { sourceOrigin, callbackOrigin }) => { | ||
| const origin = `https://${request.headers.host}`; | ||
| if (![sourceOrigin, callbackOrigin].includes(origin)) { | ||
| json(response, 400, { error: "Unexpected host" }); | ||
| return; | ||
| } | ||
| const url = new URL(request.url, origin); | ||
| if (request.method !== "GET") { | ||
| json(response, 405, { error: "Use GET" }); | ||
| return; | ||
| } | ||
| if (url.pathname === "/") { | ||
| response.writeHead(200, { "content-type": "text/html; charset=utf-8" }); | ||
| response.end( | ||
| renderCardPage( | ||
| "Cross-host GitHub installation", | ||
| "Observe a host-only OAuth cookie across the configured setup callback.", | ||
| '<p><a href="/login?mode=reject">Reproduce missing callback cookie</a></p><p><a href="/login?mode=bounce">Return to the initiating host</a></p>', | ||
| "GitHub", | ||
| ), | ||
| ); | ||
| return; | ||
| } | ||
| if (url.pathname === "/login" && origin === sourceOrigin) { | ||
| const nonce = randomBytes(24).toString("base64url"); | ||
| const body = JSON.stringify({ | ||
| origin, | ||
| nonceHash: hashNonce(nonce), | ||
| bounce: url.searchParams.get("mode") === "bounce", | ||
| note: "opaque + /?&=%#return", | ||
| }); | ||
| const state = `${body}.${mac(body)}`; | ||
| response.setHeader("set-cookie", `${correlationCookie}=${nonce}; HttpOnly; Secure; SameSite=Lax; Path=/`); | ||
| redirect( | ||
| response, | ||
| `${emulator.url}/login/oauth/authorize?${new URLSearchParams({ client_id: clientId, redirect_uri: `${sourceOrigin}/oauth/callback`, scope: "repo read:org", state })}`, | ||
| ); | ||
| return; | ||
| } | ||
| if (url.pathname === "/oauth/callback" && origin === sourceOrigin) { | ||
| const state = url.searchParams.get("state") ?? ""; | ||
| const claims = verifyState(state); | ||
| if (claims?.origin !== sourceOrigin || !matchesCorrelation(claims, request)) { | ||
| json(response, 400, { error: "Invalid OAuth correlation" }); | ||
| return; | ||
| } | ||
| const exchanged = await fetch(`${emulator.url}/login/oauth/access_token`, { | ||
| method: "POST", | ||
| headers: { "content-type": "application/json", accept: "application/json" }, | ||
| body: JSON.stringify({ | ||
| code: url.searchParams.get("code"), | ||
| client_id: clientId, | ||
| client_secret: clientSecret, | ||
| redirect_uri: `${sourceOrigin}/oauth/callback`, | ||
| }), | ||
| }); | ||
| const result = await exchanged.json(); | ||
| if (!exchanged.ok || !result.access_token) throw new Error("OAuth exchange failed"); | ||
| redirect(response, `${emulator.url}/apps/cross-host-proof/installations/new?${new URLSearchParams({ state })}`); | ||
| return; | ||
| } | ||
| if (url.pathname === "/api/github-app/setup") { | ||
| const state = url.searchParams.get("state") ?? ""; | ||
| const claims = verifyState(state); | ||
| const observation = { | ||
| origin, | ||
| path: url.pathname, | ||
| search: url.search, | ||
| state, | ||
| installationId: url.searchParams.get("installation_id"), | ||
| setupAction: url.searchParams.get("setup_action"), | ||
| hasCorrelationCookie: cookieFor(request) !== undefined, | ||
| }; | ||
| observations.push(observation); | ||
| if (setupHandler && (await setupHandler({ request, response, url, sourceOrigin, callbackOrigin, observation }))) | ||
| return; | ||
| if ( | ||
| claims?.origin !== sourceOrigin || | ||
| !/^\d+$/.test(observation.installationId ?? "") || | ||
| observation.setupAction !== "install" | ||
| ) { | ||
| json(response, 400, { error: "Invalid installation callback" }); | ||
| return; | ||
| } | ||
| if (origin !== claims.origin && claims.bounce) { | ||
| // Copy the original callback query before correlating the initiating host's cookie. | ||
| redirect(response, `${claims.origin}${url.pathname}${url.search}`); | ||
| return; | ||
| } | ||
| if (!matchesCorrelation(claims, request)) { | ||
| json(response, 400, { error: "Missing host-only OAuth cookie", observation }); | ||
| return; | ||
| } | ||
| const jwt = mintAppJwt(getAppPrivateKey(emulator), appId); | ||
| const minted = await fetch(`${emulator.url}/app/installations/${observation.installationId}/access_tokens`, { | ||
| method: "POST", | ||
| headers: { authorization: `Bearer ${jwt}` }, | ||
| }); | ||
| const credentials = await minted.json(); | ||
| if (!minted.ok || !credentials.token) throw new Error("Installation token exchange failed"); | ||
| const repositories = await fetch(`${emulator.url}/installation/repositories`, { | ||
| headers: { authorization: `Bearer ${credentials.token}` }, | ||
| }); | ||
| if (!repositories.ok) throw new Error("Installation repositories request failed"); | ||
| json(response, 200, { | ||
| complete: true, | ||
| observation, | ||
| repositories: (await repositories.json()).repositories.map((repo) => repo.full_name), | ||
| }); | ||
| return; | ||
| } | ||
| if (url.pathname === "/observations") { | ||
| json(response, 200, observations); | ||
| return; | ||
| } | ||
| json(response, 404, { error: "Not found" }); | ||
| }, | ||
| }); | ||
| try { | ||
| emulator = await createGitHubEmulator({ | ||
| port: emulatorPort, | ||
| hostname: emulatorHostname, | ||
| seed: { | ||
| users: [{ login: "octocat", name: "Local developer" }], | ||
| orgs: [{ login: "example-org", members: [{ login: "octocat", role: "admin" }] }], | ||
| repos: [ | ||
| { owner: "example-org", name: "selected", private: true }, | ||
| { owner: "example-org", name: "unselected", private: true }, | ||
| ], | ||
| oauth_apps: [ | ||
| { | ||
| client_id: clientId, | ||
| client_secret: clientSecret, | ||
| name: "Cross-host proof", | ||
| redirect_uris: [`${origins.sourceOrigin}/oauth/callback`], | ||
| }, | ||
| ], | ||
| apps: [ | ||
| { | ||
| app_id: appId, | ||
| slug: "cross-host-proof", | ||
| name: "Cross-host proof", | ||
| setup_url: `${origins.callbackOrigin}/api/github-app/setup?marker=keep%2Bencoded&extra=first&extra=second`, | ||
| permissions: { contents: "read" }, | ||
| events: [], | ||
| installations: [], | ||
| }, | ||
| ], | ||
| }, | ||
| }); | ||
| return { | ||
| ...origins, | ||
| emulatorUrl: emulator.url, | ||
| observations, | ||
| reset() { | ||
| observations.length = 0; | ||
| emulator.reset(); | ||
| }, | ||
| close: () => Promise.all([origins.close(), emulator.close()]), | ||
| }; | ||
| } catch (error) { | ||
| await origins.close(); | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { | ||
| try { | ||
| if (!process.env.CROSS_HOST_TLS_KEY || !process.env.CROSS_HOST_TLS_CERT) | ||
| throw new Error("Set CROSS_HOST_TLS_KEY and CROSS_HOST_TLS_CERT to trusted local PEM files"); | ||
| const demo = await startCrossHostDemo({ | ||
| tls: { | ||
| key: await readFile(process.env.CROSS_HOST_TLS_KEY), | ||
| cert: await readFile(process.env.CROSS_HOST_TLS_CERT), | ||
| }, | ||
| }); | ||
| console.log( | ||
| `Initiating application: ${demo.sourceOrigin}\nConfigured setup host: ${demo.callbackOrigin}\nGitHub emulator: ${demo.emulatorUrl}`, | ||
| ); | ||
| const stop = () => { | ||
| void demo.close().catch((error) => { | ||
| console.error(error.message); | ||
| process.exitCode = 1; | ||
| }); | ||
| }; | ||
| process.once("SIGINT", stop); | ||
| process.once("SIGTERM", stop); | ||
| } catch (error) { | ||
| console.error(error.message); | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.