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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ Every running service also exposes a public control plane under `/_emulate`:
| `POST /_emulate/reset` | Reset state, webhooks, and request logs, then replay seed data |
| `POST /_emulate/seed` | Add runtime seed data using the service seed schema |
| `POST /_emulate/credentials` | Create bearer tokens, API keys, OAuth clients, or client-credentials apps where supported |
| `POST /_emulate/tokens/revoke` | Revoke one token: later requests with it get the provider's own 401, other tokens keep working |
| `POST /_emulate/instances` | Return URLs for a lazily created hosted instance with a server-generated, unguessable name |

Stripe exposes the same hand-authored OpenAPI subset at `GET /openapi.json` and `GET /openapi.yaml`.
Expand All @@ -75,7 +76,7 @@ The request ledger is a core feature, not a debug afterthought. Each entry recor

### Fault injection

Tests and development harnesses can arm one-shot faults with `POST /_emulate/faults`. A fault matches all provided criteria: `operationId` when the emulator can resolve one from its service manifest, `method`, and `pathPattern`. `pathPattern` uses a simple glob where `*` matches any characters in the request path. Matching requests short-circuit with the configured response, decrement `remaining`, and are removed at zero. Faulted requests are still written to `/_emulate/ledger` with `faulted: true` and `faultId`. On the hosted Cloudflare surface armed faults, their remaining counts and the next fault id are persisted with the instance, so a fault keeps its count when Cloudflare replaces the instance between arming it and the requests it targets.
Tests and development harnesses can arm one-shot faults with `POST /_emulate/faults`. A fault matches all provided criteria: `operationId` when the emulator can resolve one from its service manifest, `method`, and `pathPattern`. `pathPattern` uses a simple glob where `*` matches any characters in the request path. Matching requests short-circuit with the configured response, decrement `remaining`, and are removed at zero. A fault can also match request headers by exact value: `"headers": { "authorization": "Bearer tok_1" }` faults only that caller (header names are case-insensitive). Faulted requests are still written to `/_emulate/ledger` with `faulted: true` and `faultId`. On the hosted Cloudflare surface armed faults, their remaining counts and the next fault id are persisted with the instance, so a fault keeps its count when Cloudflare replaces the instance between arming it and the requests it targets.

```bash
curl -s -X POST "$EMULATOR_URL/_emulate/faults" \
Expand Down Expand Up @@ -553,6 +554,8 @@ github:

If no `oauth_apps` are configured, the emulator accepts any `client_id` (backward-compatible). With apps configured, strict validation is enforced.

An app revokes one of its tokens with `DELETE /applications/:client_id/token` (Basic auth with the client id and secret, `{ "access_token": "..." }` in the body), as on GitHub: `204`, then that token gets `401 Bad credentials` while the app's other tokens keep working. `POST /_emulate/tokens/revoke` does the same without the app's secret. `POST /_emulate/tokens/revoke` with `{ "token": "..." }` revokes one token, as when a user revokes an app's access: later requests with it get the provider's own 401 (GitHub's `Bad credentials`, OpenAI's `invalid_api_key`, and so on), on hosted instances across unloads too, while every other token keeps working. It covers tokens in the shared token map (GitHub, Google, Apple, Microsoft, Slack, Vercel, Okta, Clerk, PostHog, MCP, and `/_emulate/credentials` tokens) and the tokens X, Zapier, PlanetScale and Miro keep, OpenAI API keys, and WorkOS API keys and refresh tokens. WorkOS access tokens are signed JWTs checked by signature alone and cannot be revoked one by one; revoking the session's refresh token ends the session.

### GitHub Apps

Full GitHub App support with JWT authentication and installation access tokens:
Expand Down
7 changes: 7 additions & 0 deletions apps/web/app/docs/github/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,10 @@ Every endpoint below is fully stateful. Creates, updates, and deletes persist in
- `GET /emojis` - emoji URLs
- `GET /zen` - random zen phrase
- `GET /versions` - API versions

## Revoking a token

- `DELETE /applications/:client_id/token` - an OAuth app revokes one of its tokens (Basic auth with the client id and secret, `{ "access_token": "..." }` in the body); `204`, then that token gets `401 Bad credentials` while the app's other tokens keep working
- `POST /_emulate/tokens/revoke` with `{ "token": "..." }` - the same through the control plane, for any token the instance issued

A request whose token GitHub would not accept (unknown or revoked) gets `401 {"message":"Bad credentials"}` on every REST route, as on GitHub.
2 changes: 1 addition & 1 deletion apps/web/app/docs/ledger/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ Set `X-Correlation-Id` (or `X-Request-Id`) on a request and the emulator stores

## Faulted requests

`POST /_emulate/faults` arms a one-shot or counted response for matching provider requests. Match criteria are combined: `operationId` when the emulator can resolve one from the service manifest, `method`, and `pathPattern`. `pathPattern` is a glob where `*` matches any characters in the request path. A matched request short-circuits with the configured response, decrements the fault's remaining count, and is recorded here with `faulted: true` and `faultId`.
`POST /_emulate/faults` arms a one-shot or counted response for matching provider requests. Match criteria are combined: `operationId` when the emulator can resolve one from the service manifest, `method`, and `pathPattern`. `pathPattern` is a glob where `*` matches any characters in the request path. A fault can also match request headers by exact value: `"headers": { "authorization": "Bearer tok_1" }` faults only that caller (header names are case-insensitive). A matched request short-circuits with the configured response, decrements the fault's remaining count, and is recorded here with `faulted: true` and `faultId`.

## Persistence

Expand Down
6 changes: 6 additions & 0 deletions apps/web/app/docs/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ Every service exposes a public control plane under `/_emulate`.
</td>
<td>Create bearer tokens, API keys, OAuth clients, or client-credentials apps where supported</td>
</tr>
<tr>
<td>
<code>POST /_emulate/tokens/revoke</code>
</td>
<td>Revoke one token: later requests with it get the provider's own 401, other tokens keep working</td>
</tr>
<tr>
<td>
<code>POST /_emulate/instances</code>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,81 @@ describe("what a hosted instance issues outlives the object", () => {
expect(raw.get("minted-complete")).toBe(true);
});
});

describe("revoking one token on a hosted instance", () => {
it("GitHub: the revoked token gets GitHub's 401 across eviction; the other keeps working", async () => {
const h = hosted();
const base = "https://emulators.dev/github/revoke-one";
await h.json(`${base}/__seed`, githubSeed);
const first = await githubToken(h, base);
const second = await githubToken(h, base);
const user = (token: string) => h.call(`${base}/user`, { headers: { authorization: `Bearer ${token}` } });
expect((await h.json(`${base}/_emulate/tokens/revoke`, { token: first })).status).toBe(200);
h.evict();
const refused = await user(first);
expect(refused.status).toBe(401);
expect(((await refused.json()) as Json).message).toBe("Bad credentials");
expect((await user(second)).status).toBe(200);
});

it("GitHub: an OAuth app revokes its own token with DELETE /applications/:client_id/token", async () => {
const h = hosted();
const base = "https://emulators.dev/github/app-revoke";
await h.json(`${base}/__seed`, githubSeed);
const token = await githubToken(h, base);
const other = await githubToken(h, base);
const del = (auth: string, body: unknown) =>
h.call(`${base}/applications/cid/token`, {
method: "DELETE",
headers: { authorization: auth, "content-type": "application/json" },
body: JSON.stringify(body),
});
const basic = (secret: string) => "Basic " + Buffer.from(`cid:${secret}`).toString("base64");
expect((await del(basic("wrong"), { access_token: token })).status).toBe(404);
expect((await del(basic("csec"), {})).status).toBe(422);
expect((await del(basic("csec"), { access_token: token })).status).toBe(204);
expect((await del(basic("csec"), { access_token: token })).status).toBe(404);
h.evict();
const user = (t: string) =>
h.call(`${base}/user`, { headers: { authorization: `Bearer ${t}` } }).then((r) => r.status);
expect([await user(token), await user(other)]).toEqual([401, 200]);
});

it("X and OpenAI: a token kept in the service's own store is revoked the same way", async () => {
const h = hosted();
const x = "https://emulators.dev/x/revoke-x";
await h.json(`${x}/__seed`, {
x: {
users: [{ username: "ada", user_id: "1700000000000000001" }],
oauth_clients: [{ client_id: "app", client_secret: "sec", client_type: "confidential", redirect_uris: [R] }],
},
});
const app = (await (
await h.form(
`${x}/2/oauth2/token`,
{ grant_type: "client_credentials" },
{
authorization: "Basic " + Buffer.from("app:sec").toString("base64"),
},
)
).json()) as Json;
const me = () =>
h.call(`${x}/2/users/by/username/ada`, { headers: { authorization: `Bearer ${app.access_token}` } });
expect((await me()).status).toBe(200);
expect((await h.json(`${x}/_emulate/tokens/revoke`, { token: app.access_token })).status).toBe(200);
h.evict();
expect((await me()).status).toBe(401);

const o = "https://emulators.dev/openai/revoke-key";
const key = ((await (await h.json(`${o}/_emulate/credentials`, { type: "api-key" })).json()) as Json).credential
.token;
const ask = () =>
h.json(`${o}/v1/responses`, { model: "gpt-5-mini", input: "ping" }, { authorization: `Bearer ${key}` });
expect((await ask()).status).toBe(200);
expect((await h.json(`${o}/_emulate/tokens/revoke`, { token: key })).status).toBe(200);
h.evict();
const refused = await ask();
expect(refused.status).toBe(401);
expect(((await refused.json()) as Json).error.code).toBe("invalid_api_key");
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import { createServer } from "../server.js";
import type { ServicePlugin } from "../plugin.js";

const plugin: ServicePlugin = {
name: "demo",
register(app) {
app.get("/me", (c) => {
const user = c.get("authUser");
return user ? c.json({ login: user.login }) : c.json({ message: "Requires authentication" }, 401);
});
},
};

const tokens = {
tok_ada: { login: "ada", id: 1, scopes: [] },
tok_bob: { login: "bob", id: 2, scopes: [] },
};
const me = (app: ReturnType<typeof createServer>["app"], token: string) =>
app.request("/me", { headers: { authorization: `Bearer ${token}` } }).then((r) => r.status);
const post = (app: ReturnType<typeof createServer>["app"], path: string, body: unknown) =>
app.request(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });

describe("faults matched by a header", () => {
it("faults only the caller whose Authorization matches, and every other caller passes", async () => {
const { app } = createServer(plugin, { baseUrl: "http://localhost", tokens });
const armed = await post(app, "/_emulate/faults", {
match: { method: "GET", pathPattern: "/me", headers: { Authorization: "Bearer tok_ada" } },
response: { status: 401, body: { message: "Bad credentials" } },
times: 3,
});
expect(armed.status).toBe(200);
expect(((await armed.json()) as { fault: { match: unknown } }).fault.match).toEqual({
method: "GET",
pathPattern: "/me",
headers: { authorization: "Bearer tok_ada" },
});
expect([await me(app, "tok_bob"), await me(app, "tok_ada"), await me(app, "tok_bob")]).toEqual([200, 401, 200]);
// The fault's remaining count is spent only by the matching caller.
const faults = (await (await app.request("/_emulate/faults")).json()) as { faults: Array<{ remaining: number }> };
expect(faults.faults[0]!.remaining).toBe(2);
});

it("refuses a malformed headers match", async () => {
const { app } = createServer(plugin, { baseUrl: "http://localhost", tokens });
for (const headers of [{}, { authorization: 5 }, ["authorization"]]) {
const res = await post(app, "/_emulate/faults", {
match: { pathPattern: "/me", headers },
response: { status: 500 },
});
expect(res.status, JSON.stringify(headers)).toBe(400);
}
});
});

describe("revoking one token", () => {
it("turns that token away and leaves the others working", async () => {
const { app } = createServer(plugin, { baseUrl: "http://localhost", tokens });
expect(await me(app, "tok_ada")).toBe(200);
const revoked = await post(app, "/_emulate/tokens/revoke", { token: "tok_ada" });
expect(revoked.status).toBe(200);
expect([await me(app, "tok_ada"), await me(app, "tok_bob")]).toEqual([401, 200]);
expect((await post(app, "/_emulate/tokens/revoke", { token: "tok_ada" })).status).toBe(404);
expect((await post(app, "/_emulate/tokens/revoke", {})).status).toBe(400);
});

it("keeps a revoked token out where unknown tokens fall back to a default user", async () => {
const { app } = createServer(plugin, {
baseUrl: "http://localhost",
tokens,
fallbackUser: { login: "admin", id: 9, scopes: [] },
});
expect(await me(app, "anything")).toBe(200);
await post(app, "/_emulate/tokens/revoke", { token: "tok_ada" });
expect([await me(app, "tok_ada"), await me(app, "anything")]).toEqual([401, 200]);
});

it("asks the service to revoke a token it keeps in its own store", async () => {
const own = new Set(["svc_tok"]);
const service: ServicePlugin = {
...plugin,
revokeToken: (_store, token) => own.delete(token),
};
const { app } = createServer(service, { baseUrl: "http://localhost" });
expect((await post(app, "/_emulate/tokens/revoke", { token: "svc_tok" })).status).toBe(200);
expect(own.has("svc_tok")).toBe(false);
});
});
36 changes: 36 additions & 0 deletions packages/@emulators/core/src/control-plane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export interface ControlPlaneOptions {
reset?: () => void | Promise<void>;
seed?: (seed: unknown) => void | Promise<void>;
issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;
/** A service's own revocation for tokens it keeps in its store (ServicePlugin.revokeToken). */
revokeToken?: (token: string) => boolean;
}

export const INSTANCE_NOTES =
Expand Down Expand Up @@ -119,6 +121,18 @@ function connectionVars(
};
}

const REVOKED_TOKENS_KEY = "core.revoked_tokens";

/** Tokens revoked through the control plane, kept in the store so a host that saves it keeps them. */
export function revokedTokens(store: Store): Set<string> {
let set = store.getData<Set<string>>(REVOKED_TOKENS_KEY);
if (!set) {
set = new Set();
store.setData(REVOKED_TOKENS_KEY, set);
}
return set;
}

export function registerControlPlane(app: Hono<AppEnv>, options: ControlPlaneOptions): void {
const { instance, store, webhooks, ledger, faults } = options;
const manifest = enrichManifest(options.manifest, { ledgerPersistent: options.ledgerPersistent });
Expand Down Expand Up @@ -202,6 +216,28 @@ export function registerControlPlane(app: Hono<AppEnv>, options: ControlPlaneOpt
}
return c.json({ ok: true });
});
/**
* POST /_emulate/tokens/revoke: revoke one token, as when a user revokes an app's
* access or a provider expires it. Later requests with that token get the
* provider's own 401; every other token keeps working. Body: { "token": "..." }.
*/
app.post("/_emulate/tokens/revoke", async (c) => {
const body = (await c.req.json().catch(() => ({}))) as { token?: unknown };
const token = typeof body.token === "string" ? body.token.trim() : "";
if (!token)
return c.json({ error: "invalid_request", message: 'Give the token to revoke: { "token": "..." }.' }, 400);
const fromMap = options.tokenMap?.delete(token) ?? false;
const fromService = options.revokeToken?.(token) ?? false;
if (fromMap || fromService) revokedTokens(store).add(token);
if (!fromMap && !fromService) {
return c.json(
{ error: "not_found", message: "This instance did not issue that token, or it is already revoked." },
404,
);
}
return c.json({ revoked: true });
});

app.post("/_emulate/credentials", async (c) => {
const body = (await c.req.json().catch(() => ({}))) as CredentialRequest;
try {
Expand Down
26 changes: 26 additions & 0 deletions packages/@emulators/core/src/faults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export interface FaultMatch {
operationId?: string;
method?: string;
pathPattern?: string;
/**
* Request headers the fault applies to, by name (case-insensitive) and exact
* value: `{ "authorization": "Bearer tok_1" }` faults only that caller's requests.
*/
headers?: Record<string, string>;
}

export interface FaultResponse {
Expand Down Expand Up @@ -129,6 +134,7 @@ export function createFaultMiddleware(
operationId: operation?.operationId,
method: c.req.method,
path: url.pathname,
header: (name) => c.req.header(name),
});
if (!fault) {
await next();
Expand All @@ -155,6 +161,7 @@ interface FaultRequest {
operationId?: string;
method: string;
path: string;
header?: (name: string) => string | undefined;
}

function validateFaultInput(input: FaultArmInput): void {
Expand All @@ -164,6 +171,17 @@ function validateFaultInput(input: FaultArmInput): void {
if (!input.match.operationId && !input.match.method && !input.match.pathPattern) {
throw new Error("Fault match must include operationId, method, or pathPattern.");
}
if (input.match.headers !== undefined) {
const h = input.match.headers;
if (!h || typeof h !== "object" || Array.isArray(h) || Object.keys(h).length === 0) {
throw new Error("Fault match.headers must be an object of header names to values.");
}
for (const [key, value] of Object.entries(h)) {
if (typeof key !== "string" || typeof value !== "string") {
throw new Error("Fault match.headers must contain string names and values.");
}
}
}
if (!Number.isInteger(input.response.status) || input.response.status < 100 || input.response.status > 599) {
throw new Error("Fault response.status must be an HTTP status code.");
}
Expand Down Expand Up @@ -194,13 +212,21 @@ function normalizeMatch(match: FaultMatch): FaultMatch {
...(match.operationId ? { operationId: match.operationId } : {}),
...(match.method ? { method: match.method.toUpperCase() } : {}),
...(match.pathPattern ? { pathPattern: match.pathPattern } : {}),
...(match.headers
? { headers: Object.fromEntries(Object.entries(match.headers).map(([k, v]) => [k.toLowerCase(), v])) }
: {}),
};
}

function matchesFault(fault: ArmedFault, request: FaultRequest): boolean {
if (fault.match.operationId && fault.match.operationId !== request.operationId) return false;
if (fault.match.method && fault.match.method.toUpperCase() !== request.method.toUpperCase()) return false;
if (fault.match.pathPattern && !globToRegExp(fault.match.pathPattern).test(request.path)) return false;
if (fault.match.headers) {
for (const [name, value] of Object.entries(fault.match.headers)) {
if (request.header?.(name) !== value) return false;
}
}
return true;
}

Expand Down
Loading
Loading