Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,10 @@ jobs:
- run: pnpm format:check
- run: pnpm test
- run: pnpm test:smoke
- name: Install browser prerequisites
run: |
sudo apt-get update
sudo apt-get install -y libnss3-tools
- run: pnpm exec playwright install --with-deps firefox
Comment thread
byapparov marked this conversation as resolved.
Resolved
- run: pnpm test:cross-host
- run: node scripts/package-smoke.mjs
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ Both servers use local synthetic credentials. The private App key stays in the d

If another local application already uses `127.0.0.1:3005`, choose another available loopback address while keeping the demo on port 3005: `DEMO_HOST=127.0.0.98 pnpm demo`.

Use the [cross-host installation proof](docs/cross-host-installation.md) to reproduce an HTTPS application starting OAuth on one host while the App's `setup_url` returns to another. `pnpm test:cross-host` drives the browser through account and repository selection, observes the missing host-only cookie, and verifies its return after a redirect to the initiating host.

## Run the emulator by itself

```bash
Expand Down
61 changes: 61 additions & 0 deletions docs/cross-host-installation.md
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.
2 changes: 2 additions & 0 deletions docs/github-app-installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ The standalone wrapper generates omitted App keys. Direct `seedFromConfig` calle

Installation forms expire after 10 minutes, are bound to their user, App, and account, and can be submitted once. Pending forms are limited to 32 per user across accounts and 1024 per emulator instance. Reaching either limit evicts the oldest applicable form. Reopen the installation page after expiry or eviction. The server rechecks membership and repository ownership at submission, rejects empty selected sets and cross-account IDs with `422`, and rejects a duplicate App/account installation with `409`. Form sessions and pending forms are in memory and reset with the emulator.

The configured `setup_url` can use a different host from the application that started OAuth. The emulator retains that host. Use the [cross-host installation proof](cross-host-installation.md) to observe a secure, host-only application cookie missing at the setup host and returning after a browser redirect to the initiating host.

## Discover memberships and installed repositories

`GET /user/memberships/orgs?state=active&per_page=100` requires a user token with `read:org`, `write:org`, or `admin:org`. Responses include `state: "active"`, `role: "admin" | "member"`, and organization metadata. The emulator has active memberships only; requesting `state=pending` returns an empty list. Installation tokens cannot call this endpoint. OAuth-authenticated `GET /user` and `PATCH /user` report the token's granted scopes in `X-OAuth-Scopes`.
Expand Down
250 changes: 250 additions & 0 deletions examples/cross-host-demo.mjs
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) => {
Comment thread
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;
}
}
Loading
Loading