diff --git a/README.md b/README.md index bc3942726..c4b608b1f 100644 --- a/README.md +++ b/README.md @@ -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`. @@ -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" \ @@ -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: diff --git a/apps/web/app/docs/github/page.mdx b/apps/web/app/docs/github/page.mdx index 141d27965..2be03050c 100644 --- a/apps/web/app/docs/github/page.mdx +++ b/apps/web/app/docs/github/page.mdx @@ -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. diff --git a/apps/web/app/docs/ledger/page.mdx b/apps/web/app/docs/ledger/page.mdx index 2fe74c193..a86c77221 100644 --- a/apps/web/app/docs/ledger/page.mdx +++ b/apps/web/app/docs/ledger/page.mdx @@ -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 diff --git a/apps/web/app/docs/page.mdx b/apps/web/app/docs/page.mdx index f2ce2aaa6..1e1a602c1 100644 --- a/apps/web/app/docs/page.mdx +++ b/apps/web/app/docs/page.mdx @@ -163,6 +163,12 @@ Every service exposes a public control plane under `/_emulate`. 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 diff --git a/packages/@emulators/cloudflare/src/__tests__/durable-credentials.test.ts b/packages/@emulators/cloudflare/src/__tests__/durable-credentials.test.ts index 2f2d90f46..51252f811 100644 --- a/packages/@emulators/cloudflare/src/__tests__/durable-credentials.test.ts +++ b/packages/@emulators/cloudflare/src/__tests__/durable-credentials.test.ts @@ -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"); + }); +}); diff --git a/packages/@emulators/core/src/__tests__/revoke-and-header-faults.test.ts b/packages/@emulators/core/src/__tests__/revoke-and-header-faults.test.ts new file mode 100644 index 000000000..277153875 --- /dev/null +++ b/packages/@emulators/core/src/__tests__/revoke-and-header-faults.test.ts @@ -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["app"], token: string) => + app.request("/me", { headers: { authorization: `Bearer ${token}` } }).then((r) => r.status); +const post = (app: ReturnType["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); + }); +}); diff --git a/packages/@emulators/core/src/control-plane.ts b/packages/@emulators/core/src/control-plane.ts index 55c05841a..6df79dd0c 100644 --- a/packages/@emulators/core/src/control-plane.ts +++ b/packages/@emulators/core/src/control-plane.ts @@ -49,6 +49,8 @@ export interface ControlPlaneOptions { reset?: () => void | Promise; seed?: (seed: unknown) => void | Promise; issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise; + /** A service's own revocation for tokens it keeps in its store (ServicePlugin.revokeToken). */ + revokeToken?: (token: string) => boolean; } export const INSTANCE_NOTES = @@ -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 { + let set = store.getData>(REVOKED_TOKENS_KEY); + if (!set) { + set = new Set(); + store.setData(REVOKED_TOKENS_KEY, set); + } + return set; +} + export function registerControlPlane(app: Hono, options: ControlPlaneOptions): void { const { instance, store, webhooks, ledger, faults } = options; const manifest = enrichManifest(options.manifest, { ledgerPersistent: options.ledgerPersistent }); @@ -202,6 +216,28 @@ export function registerControlPlane(app: Hono, 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 { diff --git a/packages/@emulators/core/src/faults.ts b/packages/@emulators/core/src/faults.ts index d88e19aec..f09cb6c9b 100644 --- a/packages/@emulators/core/src/faults.ts +++ b/packages/@emulators/core/src/faults.ts @@ -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; } export interface FaultResponse { @@ -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(); @@ -155,6 +161,7 @@ interface FaultRequest { operationId?: string; method: string; path: string; + header?: (name: string) => string | undefined; } function validateFaultInput(input: FaultArmInput): void { @@ -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."); } @@ -194,6 +212,9 @@ 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])) } + : {}), }; } @@ -201,6 +222,11 @@ 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; } diff --git a/packages/@emulators/core/src/middleware/auth.ts b/packages/@emulators/core/src/middleware/auth.ts index 0c4f0c8d4..eefbc65d5 100644 --- a/packages/@emulators/core/src/middleware/auth.ts +++ b/packages/@emulators/core/src/middleware/auth.ts @@ -113,7 +113,12 @@ export interface AuthFallback { scopes: string[]; } -export function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) { +export function authMiddleware( + tokens: TokenMap, + appKeyResolver?: AppKeyResolver, + fallbackUser?: AuthFallback, + isRevoked: (token: string) => boolean = () => false, +) { return async (c: Context, next: Next) => { const authHeader = c.req.header("Authorization"); if (authHeader) { @@ -141,8 +146,10 @@ export function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver // JWT verification failed } } else { - let user = tokens.get(token); - if (!user && fallbackUser && token.length > 0) { + // A revoked token is refused even where unknown tokens fall back to a default user. + const revoked = isRevoked(token); + let user = revoked ? undefined : tokens.get(token); + if (!user && !revoked && fallbackUser && token.length > 0) { debug("auth", "fallback user for unknown token", { login: fallbackUser.login, id: fallbackUser.id }); user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes, fallback: true }; } diff --git a/packages/@emulators/core/src/plugin.ts b/packages/@emulators/core/src/plugin.ts index 710f724c6..5277199ff 100644 --- a/packages/@emulators/core/src/plugin.ts +++ b/packages/@emulators/core/src/plugin.ts @@ -36,4 +36,10 @@ export interface ServicePlugin { ledger?: RequestLedger, ): void; seed?(store: Store, baseUrl: string): void; + /** + * Revoke a token this service keeps in its own store (not the shared token + * map), so later requests with it get the provider's own 401. True when the + * token was found. Used by POST /_emulate/tokens/revoke. + */ + revokeToken?(store: Store, token: string): boolean; } diff --git a/packages/@emulators/core/src/server.ts b/packages/@emulators/core/src/server.ts index 155982c6f..8a7301f1e 100644 --- a/packages/@emulators/core/src/server.ts +++ b/packages/@emulators/core/src/server.ts @@ -12,7 +12,7 @@ import { import type { ServicePlugin } from "./plugin.js"; import { registerFontRoutes } from "./fonts.js"; import { RequestLedger, createLedgerMiddleware } from "./ledger.js"; -import { registerControlPlane, type CredentialRequest, type IssuedCredential } from "./control-plane.js"; +import { registerControlPlane, revokedTokens, type CredentialRequest, type IssuedCredential } from "./control-plane.js"; import { createDefaultManifest, type ServiceManifest } from "./manifest.js"; import { FaultRegistry, createFaultMiddleware } from "./faults.js"; @@ -65,7 +65,10 @@ export function createServer(plugin: ServicePlugin, options: ServerOptions = {}) app.onError(createApiErrorHandler(docsUrl)); app.use("*", cors()); app.use("*", createErrorHandler(docsUrl)); - app.use("*", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser)); + app.use( + "*", + authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser, (token) => revokedTokens(store).has(token)), + ); if (options.enableControlPlane !== false) { const manifest = options.manifest ?? createDefaultManifest(plugin.name); @@ -88,6 +91,7 @@ export function createServer(plugin: ServicePlugin, options: ServerOptions = {}) reset: options.reset, seed: options.seed, issueCredential: options.issueCredential, + revokeToken: plugin.revokeToken ? (token) => plugin.revokeToken!(store, token) : undefined, }); } diff --git a/packages/@emulators/github/src/index.ts b/packages/@emulators/github/src/index.ts index 4cb762321..2dbfc688b 100644 --- a/packages/@emulators/github/src/index.ts +++ b/packages/@emulators/github/src/index.ts @@ -455,11 +455,32 @@ async function deliverToAppWebhookUrls( } } +/** Paths outside the REST API, which answer a bad token in their own way. */ +const NOT_REST_API = /^\/(_emulate|login|settings|\.well-known|mcp|oauth|authorize|register|token|__)/; + export const githubPlugin: ServicePlugin = { name: "github", register(app: Hono, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void { const gh = getGitHubStore(store); + // A token GitHub does not accept (unknown, expired or revoked) is refused on every + // API route with GitHub's 401, as api.github.com does, rather than treated as anonymous. + app.use("*", async (c, next) => { + const header = c.req.header("Authorization") ?? ""; + if ( + /^(bearer|token)\s+\S/i.test(header) && + !c.get("authUser") && + !c.get("authApp") && + !NOT_REST_API.test(new URL(c.req.url).pathname) + ) { + return c.json( + { message: "Bad credentials", documentation_url: "https://docs.github.com/rest", status: "401" }, + 401, + ); + } + return next(); + }); + const originalDispatch = webhooks.dispatch.bind(webhooks); webhooks.dispatch = async ( event: string, diff --git a/packages/@emulators/github/src/manifest.ts b/packages/@emulators/github/src/manifest.ts index 5b7f531cf..bbc179e56 100644 --- a/packages/@emulators/github/src/manifest.ts +++ b/packages/@emulators/github/src/manifest.ts @@ -37,6 +37,14 @@ export const manifest: ServiceManifest = { coverage: "hand-authored", operations: [ { operationId: "users/getAuthenticated", method: "GET", path: "/user", status: "hand-authored" }, + { + operationId: "apps/deleteToken", + method: "DELETE", + path: "/applications/:client_id/token", + status: "hand-authored", + summary: + "An OAuth app revokes one of its tokens (Basic client auth); the token then gets 401 Bad credentials.", + }, { operationId: "users/getByUsername", method: "GET", path: "/users/:username", status: "hand-authored" }, { operationId: "repos/get", method: "GET", path: "/repos/:owner/:repo", status: "hand-authored" }, { diff --git a/packages/@emulators/github/src/routes/oauth.ts b/packages/@emulators/github/src/routes/oauth.ts index c9a261ba4..9f9fa96ca 100644 --- a/packages/@emulators/github/src/routes/oauth.ts +++ b/packages/@emulators/github/src/routes/oauth.ts @@ -535,4 +535,36 @@ export function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): vo return c.redirect("/settings/applications", 302); }); + + // DELETE /applications/:client_id/token: an OAuth app revokes one of its tokens + // (Basic auth with the app's client id and secret, the token in the body). The + // token then answers 401; the app's other tokens keep working. + const DELETE_TOKEN_DOCS = "https://docs.github.com/rest/apps/oauth-applications#delete-an-app-token"; + app.delete("/applications/:client_id/token", async (c) => { + const clientId = c.req.param("client_id"); + const basic = /^Basic\s+(.+)$/i.exec(c.req.header("Authorization") ?? ""); + const [id, secret] = basic ? Buffer.from(basic[1]!, "base64").toString("utf8").split(":") : []; + const oauthApp = gh.oauthApps.findOneBy("client_id", clientId); + if (!oauthApp || id !== clientId || !secret || !constantTimeSecretEqual(secret, oauthApp.client_secret)) { + return c.json({ message: "Not Found", documentation_url: DELETE_TOKEN_DOCS }, 404); + } + const body = (await c.req.json().catch(() => ({}))) as { access_token?: unknown }; + const token = typeof body.access_token === "string" ? body.access_token : ""; + if (!token) { + return c.json( + { + message: 'Invalid request.\n\n"access_token" wasn\'t supplied.', + documentation_url: DELETE_TOKEN_DOCS, + status: "422", + }, + 422, + ); + } + if (!tokenMap?.has(token) || getTokenToClientId(store).get(token) !== clientId) { + return c.json({ message: "Not Found", documentation_url: DELETE_TOKEN_DOCS }, 404); + } + tokenMap.delete(token); + getTokenToClientId(store).delete(token); + return c.body(null, 204); + }); } diff --git a/packages/@emulators/mcp/src/oauth.ts b/packages/@emulators/mcp/src/oauth.ts index 909b14c1d..7cd6e52a0 100644 --- a/packages/@emulators/mcp/src/oauth.ts +++ b/packages/@emulators/mcp/src/oauth.ts @@ -65,13 +65,15 @@ function userButtonsHtml(store: Store, baseUrl: string, hidden: ConsentFields): .join("\n"); } -// Copy-pasteable instructions to seed a user into THIS instance (the only way to -// add an authorizable identity). The github seed shape lives under the `github` key. +// Copy-pasteable instructions to add a user to THIS instance (the only way to add an +// authorizable identity). /_emulate/seed adds to the instance and takes the service's +// own config, so the same body works on the MCP service and on GitHub's MCP surface; +// /__seed would replace the instance, and with it the client that is signing in. function seedHintHtml(baseUrl: string, login: string): string { const who = login || "octocat"; - const cmd = `curl -X POST ${baseUrl}/__seed \\ + const cmd = `curl -X POST ${baseUrl}/_emulate/seed \\ -H 'content-type: application/json' \\ - -d '{"github":{"users":[{"login":"${who}"}]}}'`; + -d '{"users":[{"login":"${who}"}]}'`; return `

Only seeded users can be authorized. Add one to this instance, then retry:

${escapeBasic(cmd)}
`; } @@ -257,7 +259,7 @@ export function registerOAuthRoutes(ctx: RouteContext): void { ) .join("\n"); - const footer = `

Don't see the user you want? Seed it: POST ${baseUrl}/__seed with {"github":{"users":[{"login":"…"}]}}.

`; + const footer = `

Don't see the user you want? Add it: POST ${baseUrl}/_emulate/seed with {"users":[{"login":"…"}]}.

`; const body = users.length === 0 ? `

No users seeded in this instance yet.

${seedHintHtml(baseUrl, "")}` diff --git a/packages/@emulators/miro/src/index.ts b/packages/@emulators/miro/src/index.ts index 579b5903b..3b1c96822 100644 --- a/packages/@emulators/miro/src/index.ts +++ b/packages/@emulators/miro/src/index.ts @@ -143,6 +143,13 @@ export function issueCredential(store: Store, baseUrl: string, request: Credenti export const miroPlugin: ServicePlugin = { name: "miro", + revokeToken(store: Store, token: string): boolean { + const ms = getMiroStore(store); + const t = ms.oauthTokens.findOneBy("access_token", token) ?? ms.oauthTokens.findOneBy("refresh_token", token); + if (!t || t.revoked) return false; + ms.oauthTokens.update(t.id, { revoked: true }); + return true; + }, register(app: Hono, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void { const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap }; registerOAuthRoutes(ctx); diff --git a/packages/@emulators/openai/src/__tests__/openai.test.ts b/packages/@emulators/openai/src/__tests__/openai.test.ts index 743ab8f81..d7e2c88e2 100644 --- a/packages/@emulators/openai/src/__tests__/openai.test.ts +++ b/packages/@emulators/openai/src/__tests__/openai.test.ts @@ -386,6 +386,29 @@ describe("keys, models, limits and the ledger", () => { expect(usage.calls[0]).toMatchObject({ key_name: "primary", request_bytes: entry.request.bodyBytes }); }); + it("answers a request of hundreds of thousands of messages on both endpoints, and records it", async () => { + const { raw, control } = await start({ answer_rules: [{ answer: "ok" }] }); + const many = Array.from({ length: 300_000 }, () => ({ role: "user", content: "hi" })); + const responses = await raw("/v1/responses", { + method: "POST", + body: JSON.stringify({ model: "gpt-5-mini", input: many }), + }); + expect(responses.status).toBe(200); + expect(((await responses.json()) as Json).usage.input_tokens).toBe(Math.ceil((300_000 * 2) / 4)); + const chat = await raw("/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "gpt-5-mini", messages: many }), + }); + expect(chat.status).toBe(200); + const usage = (await (await control("/usage")).json()) as Json; + expect(usage.calls).toHaveLength(2); + }); + + it("counts characters as code points, surrogate pairs once, as before", () => { + const text = "a\u00e9\u{1F600}b\uD800"; + expect(approxTokens(text.repeat(4))).toBe(Math.ceil([...text.repeat(4)].length / 4)); + }); + it("refuses a body over its stated limit with a 413 in OpenAI's error shape, through the official SDK", async () => { const { client, ledger } = await start(); const big = "a".repeat(MAX_REQUEST_BYTES + 1); diff --git a/packages/@emulators/openai/src/answers.ts b/packages/@emulators/openai/src/answers.ts index 930a16ea4..98210dd48 100644 --- a/packages/@emulators/openai/src/answers.ts +++ b/packages/@emulators/openai/src/answers.ts @@ -66,11 +66,21 @@ export function enqueueAnswers(store: Store, answers: unknown[]): number { return os.queue.all().length; } +/** True when the needle appears in the instructions or any message, as the joined input would show it. */ +function containsText(conv: Conversation, needle: string): boolean { + if (conv.instructions?.includes(needle)) return true; + if (conv.messages.some((x) => x.text.includes(needle))) return true; + // A needle that spans the line break between two texts. + if (!needle.includes("\n")) return false; + const texts = [conv.instructions ?? "", ...conv.messages.map((x) => x.text)]; + return texts.join("\n").includes(needle); +} + function matches(rule: OpenAIRule, model: string, conv: Conversation): boolean { const m = rule.match; - const all = [conv.instructions ?? "", ...conv.messages.map((x) => x.text)].join("\n"); if (m.model !== undefined && m.model !== model) return false; - if (m.contains !== undefined && !all.includes(m.contains)) return false; + // Each text on its own: joining them would hold a second copy of the whole input. + if (m.contains !== undefined && !containsText(conv, m.contains)) return false; if (m.last_user_equals !== undefined && lastUserText(conv) !== m.last_user_equals) return false; if (m.instructions_contains !== undefined && !(conv.instructions ?? "").includes(m.instructions_contains)) { return false; diff --git a/packages/@emulators/openai/src/common.ts b/packages/@emulators/openai/src/common.ts index 17d8a4188..6229beec7 100644 --- a/packages/@emulators/openai/src/common.ts +++ b/packages/@emulators/openai/src/common.ts @@ -177,7 +177,9 @@ async function readLimitedText(c: Context, limit: number): Promise {}); return null; } - parts.push(value); + pieces.push(decoder.decode(value, { stream: true })); } - return Buffer.concat(parts).toString("utf8"); + pieces.push(decoder.decode()); + return pieces.join(""); } /** Read and parse the JSON body, recording a large one in the ledger by size only. */ diff --git a/packages/@emulators/openai/src/index.ts b/packages/@emulators/openai/src/index.ts index efdd22892..d280ceafb 100644 --- a/packages/@emulators/openai/src/index.ts +++ b/packages/@emulators/openai/src/index.ts @@ -69,6 +69,13 @@ export const DEFAULT_API_KEY = "sk-proj-emulate-default-key"; export const openaiPlugin: ServicePlugin = { name: "openai", + revokeToken(store: Store, token: string): boolean { + const keys = getOpenAIStore(store).keys; + const key = keys.findOneBy("key", token); + if (!key) return false; + keys.delete(key.id); + return true; + }, register(app, store, webhooks, baseUrl, tokenMap): void { const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap }; // Refuse an oversized body before any route reads it. diff --git a/packages/@emulators/openai/src/text.ts b/packages/@emulators/openai/src/text.ts index ab6eb6068..01cb0caa3 100644 --- a/packages/@emulators/openai/src/text.ts +++ b/packages/@emulators/openai/src/text.ts @@ -7,11 +7,32 @@ import { randomBytes } from "crypto"; * OpenAI's tokenizer, and the manifest says so. */ export function approxTokens(...texts: Array): number { + return tokensOfTexts(texts); +} + +/** approxTokens over a list of any length (no argument spread, no per-character array). */ +export function tokensOfTexts(texts: Iterable): number { let chars = 0; - for (const t of texts) if (t) chars += [...t].length; + for (const t of texts) if (t) chars += codePoints(t); return Math.ceil(chars / 4); } +/** Characters as code points, counted without building an array of them. */ +function codePoints(text: string): number { + let pairs = 0; + for (let i = 0; i < text.length; i++) { + const c = text.charCodeAt(i); + if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length) { + const next = text.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + pairs++; + i++; + } + } + } + return text.length - pairs; +} + /** A text-only conversation, as the emulator sees a request's input. */ export interface Conversation { instructions: string | null; @@ -104,7 +125,7 @@ export function conversationFromChatMessages(messages: unknown): Conversation { } export function inputTokens(conv: Conversation): number { - return approxTokens(conv.instructions, ...conv.messages.map((m) => m.text)); + return tokensOfTexts([conv.instructions, ...conv.messages.map((m) => m.text)]); } export function lastUserText(conv: Conversation): string { diff --git a/packages/@emulators/planetscale/src/index.ts b/packages/@emulators/planetscale/src/index.ts index 5000d06d7..bce76fceb 100644 --- a/packages/@emulators/planetscale/src/index.ts +++ b/packages/@emulators/planetscale/src/index.ts @@ -158,6 +158,13 @@ export function issueCredential(store: Store, baseUrl: string, request: Credenti export const planetscalePlugin: ServicePlugin = { name: "planetscale", + revokeToken(store: Store, token: string): boolean { + const ps = getPlanetScaleStore(store); + const t = ps.oauthTokens.findOneBy("access_token", token) ?? ps.oauthTokens.findOneBy("refresh_token", token); + if (!t || t.revoked) return false; + ps.oauthTokens.update(t.id, { revoked: true }); + return true; + }, register(app: Hono, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void { const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap }; registerOAuthRoutes(ctx); diff --git a/packages/@emulators/workos/src/index.ts b/packages/@emulators/workos/src/index.ts index 2add46c02..ab7a8a6b6 100644 --- a/packages/@emulators/workos/src/index.ts +++ b/packages/@emulators/workos/src/index.ts @@ -60,6 +60,20 @@ export function seedFromConfig(store: Store, _baseUrl: string, config: WorkosSee export const workosPlugin: ServicePlugin = { name: "workos", + // API keys and refresh tokens. Access tokens are signed JWTs checked by signature + // alone, so one cannot be revoked here; revoking its refresh token ends the session. + revokeToken(store: Store, token: string): boolean { + const ws = getWorkosStore(store); + const key = ws.apiKeys.findOneBy("value", token); + if (key) { + ws.apiKeys.delete(key.id); + return true; + } + const session = ws.sessions.findOneBy("refresh_token", token); + if (!session || session.revoked) return false; + ws.sessions.update(session.id, { revoked: true }); + return true; + }, register(app: Hono, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void { const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap }; oauthRoutes(ctx); diff --git a/packages/@emulators/x/src/index.ts b/packages/@emulators/x/src/index.ts index 6069f8cdb..61e995452 100644 --- a/packages/@emulators/x/src/index.ts +++ b/packages/@emulators/x/src/index.ts @@ -187,6 +187,13 @@ export function seedFromConfig(store: Store, baseUrl: string, config: XSeedConfi export const xPlugin: ServicePlugin = { name: "x", + revokeToken(store: Store, token: string): boolean { + const xs = getXStore(store); + let found = false; + for (const t of xs.accessTokens.findBy("token", token)) found = xs.accessTokens.delete(t.id) || found; + for (const t of xs.refreshTokens.findBy("token", token)) found = xs.refreshTokens.delete(t.id) || found; + return found; + }, // X's own limiter (x-rate-limit-* headers, 429) replaces the shared GitHub-shaped one. rateLimit: "provider", register(app, store, webhooks, baseUrl, tokenMap): void { diff --git a/packages/@emulators/zapier/src/index.ts b/packages/@emulators/zapier/src/index.ts index a3bc325c7..336d0bef9 100644 --- a/packages/@emulators/zapier/src/index.ts +++ b/packages/@emulators/zapier/src/index.ts @@ -42,6 +42,13 @@ export function issueCredential(store: Store, _baseUrl: string, request: Credent export const zapierPlugin: ServicePlugin = { name: "zapier", + revokeToken(store: Store, token: string): boolean { + const zs = getZapierStore(store); + const t = zs.tokens.findOneBy("access_token", token) ?? zs.tokens.findOneBy("refresh_token", token); + if (!t || t.revoked) return false; + zs.tokens.update(t.id, { revoked: true }); + return true; + }, register(app, store, webhooks, baseUrl, tokenMap, ledger): void { const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap, ledger }; controlRoutes(ctx); diff --git a/skills/emulate/SKILL.md b/skills/emulate/SKILL.md index 003b593d0..d0086d8b1 100644 --- a/skills/emulate/SKILL.md +++ b/skills/emulate/SKILL.md @@ -62,6 +62,7 @@ Provider traffic and control-plane traffic are separate. Provider routes stay fa | `POST /_emulate/seed` | Add runtime seed data using the service seed schema | | `POST /_emulate/reset` | Reset state, webhooks, and request logs, then replay seed data | | `POST /_emulate/credentials` | Mint a credential for the service (the canonical, uniform way) | +| `POST /_emulate/tokens/revoke` | Revoke one token: later requests with it get the provider's own 401, other tokens keep working | There is also a global, host-level catalog: @@ -112,7 +113,7 @@ Send `X-Correlation-Id` on a request to trace it end to end, then read it back f ### Fault injection -Use `POST /_emulate/faults` to arm a one-shot or counted response for matching provider requests. The body is `{ "match": { "operationId": "...", "method": "GET", "pathPattern": "/v1/*" }, "response": { "status": 503, "body": { "error": "temporary" } }, "times": 1 }`. Match criteria are combined, and `pathPattern` is a glob where `*` matches any characters in the request path. Matched requests short-circuit, decrement `remaining`, and still appear in `GET /_emulate/ledger` with `faulted: true` and `faultId`. +Use `POST /_emulate/faults` to arm a one-shot or counted response for matching provider requests. The body is `{ "match": { "operationId": "...", "method": "GET", "pathPattern": "/v1/*" }, "response": { "status": 503, "body": { "error": "temporary" } }, "times": 1 }`. Match criteria are combined, and `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). Matched requests short-circuit, decrement `remaining`, and still appear in `GET /_emulate/ledger` with `faulted: true` and `faultId`. ## Host-Based Routing (Deployed Emulators) diff --git a/skills/github/SKILL.md b/skills/github/SKILL.md index b00412d77..05659e8ea 100644 --- a/skills/github/SKILL.md +++ b/skills/github/SKILL.md @@ -495,6 +495,13 @@ curl http://localhost:4001/settings/connections/applications/Iv1.abc123 -H "Auth # Revoke OAuth app curl -X POST http://localhost:4001/settings/connections/applications/Iv1.abc123/revoke \ -H "Authorization: Bearer $TOKEN" + +# Revoke one token, as the app (GitHub's own route): 204, then that token gets 401 Bad credentials +curl -X DELETE http://localhost:4001/applications/Iv1.abc123/token -u "Iv1.abc123:secret_abc123" \ + -H "Content-Type: application/json" -d "{\"access_token\":\"$TOKEN\"}" + +# Or through the control plane, without the app's secret +curl -X POST http://localhost:4001/_emulate/tokens/revoke -H "Content-Type: application/json" -d "{\"token\":\"$TOKEN\"}" ``` ### MCP surface