Skip to content

Context7 Platform -- Up-to-date docs for AI agents

CTX7-3109: feat(mcp): add a foreign mode to the OAuth audience check (#3391)

Ramazan Onur Acar2d57b23bba76
diff --git a/.changeset/oauth-audience-foreign-mode.md b/.changeset/oauth-audience-foreign-mode.md
new file mode 100644
index 00000000..d68353f9
--- /dev/null
+++ b/.changeset/oauth-audience-foreign-mode.md
@@ -0,0 +1,5 @@
+---
+"@upstash/context7-mcp": minor
+---
+
+Add a `foreign` mode to the OAuth audience check on the hosted HTTP transport. `MCP_OAUTH_AUDIENCE_ENFORCEMENT=foreign` answers HTTP 401 (`WWW-Authenticate: Bearer error="invalid_token"`, "This token was issued for another server. If you connect through a gateway or proxy, use a Context7 API key instead.") to a Clerk OAuth JWT whose `aud` names another server, and still admits a token with no `aud`, which grants authorized before Clerk's "Include Audience" setting carry on every refresh. `observe` (the default) and `required` are unchanged. The query string of an audience on an allowed host is ignored, since Cursor writes the configured MCP URL (`https://mcp.context7.com/mcp?client=codex`) into `resource`; on any other host it is kept. The `audienceMismatch` log line now carries `outcome=accepted|rejected` and is written at most once per token per hour instead of every ten minutes.
diff --git a/.env.example b/.env.example
index 79ea2277..66567ddf 100644
--- a/.env.example
+++ b/.env.example
@@ -22,14 +22,18 @@ MCP_AUTH_ENFORCEMENT=
# Set off to forward opaque OAuth tokens (oat_…) without checking them against
# the Context7 API first.
MCP_OAUTH_TOKEN_VALIDATION=
-# Audience check for OAuth JWT access tokens from OAUTH_AUTH_SERVER_URL.
-# observe (default): a token whose aud is missing or not allowed is accepted
-# and logged as audienceMismatch (clientId, aud). required: it gets HTTP 401.
-# Flip back to observe to roll back.
+# Audience check for OAuth JWT access tokens from OAUTH_AUTH_SERVER_URL. Every
+# mismatch is logged as audienceMismatch (clientId, aud, enforcement, outcome).
+# observe (default): a token whose aud is missing or not allowed is accepted.
+# foreign: a token whose aud names another server gets HTTP 401; a missing aud
+# is still accepted (grants from before Clerk's "Include Audience" have none).
+# required: both get HTTP 401. Set the mode back one step to roll back.
MCP_OAUTH_AUDIENCE_ENFORCEMENT=
# Comma-separated allowed audiences, normalized (lowercase scheme and host, no
-# trailing slash) before comparison. Defaults to the RESOURCE_URL origin plus
-# its /mcp and /mcp/oauth paths, e.g.
+# trailing slash, no query string) before comparison. A token's aud on one of
+# these hosts loses its query string too (Cursor sends
+# https://mcp.context7.com/mcp?client=codex); on any other host it is kept.
+# Defaults to the RESOURCE_URL origin plus its /mcp and /mcp/oauth paths, e.g.
# https://mcp.context7.com,https://mcp.context7.com/mcp,https://mcp.context7.com/mcp/oauth
MCP_OAUTH_ALLOWED_AUDIENCES=
diff --git a/docs/resources/developer.mdx b/docs/resources/developer.mdx
index 6617afa5..d64e6dd9 100644
--- a/docs/resources/developer.mdx
+++ b/docs/resources/developer.mdx
@@ -31,14 +31,15 @@ node packages/mcp/dist/index.js
`context7-mcp` accepts the following CLI flags:
-| Flag | Description | Default |
-|------|-------------|---------|
+| Flag | Description | Default |
+| --------------------------- | ------------------------------------------------------------------------------------- | ------- |
| `--transport <stdio\|http>` | Transport to use. Use `http` for remote HTTP server or `stdio` for local integration. | `stdio` |
-| `--port <number>` | Port to listen on when using `http` transport. | `3000` |
-| `--api-key <key>` | API key for authentication (or set `CONTEXT7_API_KEY` env var). | - |
+| `--port <number>` | Port to listen on when using `http` transport. | `3000` |
+| `--api-key <key>` | API key for authentication (or set `CONTEXT7_API_KEY` env var). | - |
<Note>
- Get your API key by creating an account at [context7.com/dashboard](https://context7.com/dashboard).
+ Get your API key by creating an account at
+ [context7.com/dashboard](https://context7.com/dashboard).
</Note>
### Examples
@@ -53,7 +54,7 @@ HTTP transport requires a credential on every request by default. Clients send `
Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory, and a rejected token stays rejected for ten minutes). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.
-OAuth JWT access tokens from the authorization server (`OAUTH_AUTH_SERVER_URL`) are verified locally: signature against its JWKS, issuer, a `typ` of `at+jwt`, and expiry with a minute of clock tolerance. Clerk ID tokens and session JWTs share that issuer but are not access tokens, so they are always rejected. The token's `aud` must name this server (`RESOURCE_URL` origin, `/mcp`, or `/mcp/oauth`; override with a comma-separated `MCP_OAUTH_ALLOWED_AUDIENCES`). `MCP_OAUTH_AUDIENCE_ENFORCEMENT=observe` (default) admits a token with a missing or foreign audience and logs the OAuth client ID and audience, once per token every ten minutes; `required` answers HTTP 401.
+OAuth JWT access tokens from the authorization server (`OAUTH_AUTH_SERVER_URL`) are verified locally: signature against its JWKS, issuer, a `typ` of `at+jwt`, and expiry with a minute of clock tolerance. Clerk ID tokens and session JWTs share that issuer but are not access tokens, so they are always rejected. The token's `aud` must name this server (`RESOURCE_URL` origin, `/mcp`, or `/mcp/oauth`; override with a comma-separated `MCP_OAUTH_ALLOWED_AUDIENCES`). The query string of an audience on an allowed host is ignored. `MCP_OAUTH_AUDIENCE_ENFORCEMENT` sets what a mismatch does: `observe` (default) admits a token with a missing or foreign audience; `foreign` answers HTTP 401 to a token issued for another server and still admits one with no `aud`; `required` answers 401 to both. Every mismatch is logged with the OAuth client ID, the audience and the outcome, once per token per hour on each replica.
Stdio transport with API key:
@@ -105,7 +106,12 @@ When developing locally, use this configuration to run from source:
"mcpServers": {
"context7": {
"command": "npx",
- "args": ["tsx", "/path/to/folder/context7/packages/mcp/src/index.ts", "--api-key", "YOUR_API_KEY"]
+ "args": [
+ "tsx",
+ "/path/to/folder/context7/packages/mcp/src/index.ts",
+ "--api-key",
+ "YOUR_API_KEY"
+ ]
}
}
}
diff --git a/packages/mcp/README.md b/packages/mcp/README.md
index 75d583f0..7707e40e 100644
--- a/packages/mcp/README.md
+++ b/packages/mcp/README.md
@@ -1447,7 +1447,7 @@ HTTP transport requires a credential on every request by default. Clients send `
Opaque OAuth access tokens (`oat_…`) are checked against the Context7 API before each request is served (one check per token per minute on each replica; the cache is in memory, and a rejected token stays rejected for ten minutes). An expired or revoked token gets an HTTP 401 with a `WWW-Authenticate` challenge so MCP clients refresh it. Set `MCP_OAUTH_TOKEN_VALIDATION=off` to skip that check and forward the token unchecked.
-OAuth JWT access tokens from the authorization server (`OAUTH_AUTH_SERVER_URL`) are verified locally: signature against its JWKS, issuer, a `typ` of `at+jwt`, and expiry with a minute of clock tolerance. Clerk ID tokens and session JWTs share that issuer but are not access tokens, so they are always rejected. The token's `aud` must name this server (`RESOURCE_URL` origin, `/mcp`, or `/mcp/oauth`; override with a comma-separated `MCP_OAUTH_ALLOWED_AUDIENCES`). `MCP_OAUTH_AUDIENCE_ENFORCEMENT=observe` (default) admits a token with a missing or foreign audience and logs the OAuth client ID and audience, once per token every ten minutes; `required` answers HTTP 401.
+OAuth JWT access tokens from the authorization server (`OAUTH_AUTH_SERVER_URL`) are verified locally: signature against its JWKS, issuer, a `typ` of `at+jwt`, and expiry with a minute of clock tolerance. Clerk ID tokens and session JWTs share that issuer but are not access tokens, so they are always rejected. The token's `aud` must name this server (`RESOURCE_URL` origin, `/mcp`, or `/mcp/oauth`; override with a comma-separated `MCP_OAUTH_ALLOWED_AUDIENCES`). The query string of an audience on an allowed host is ignored. `MCP_OAUTH_AUDIENCE_ENFORCEMENT` sets what a mismatch does: `observe` (default) admits a token with a missing or foreign audience; `foreign` answers HTTP 401 to a token issued for another server and still admits one with no `aud`; `required` answers 401 to both. Every mismatch is logged with the OAuth client ID, the audience and the outcome, once per token per hour on each replica.
Another example with stdio transport:
diff --git a/packages/mcp/src/lib/jwt.ts b/packages/mcp/src/lib/jwt.ts
index 06ee8846..6b499c33 100644
--- a/packages/mcp/src/lib/jwt.ts
+++ b/packages/mcp/src/lib/jwt.ts
@@ -7,7 +7,7 @@ import {
OAUTH_JWKS_URL,
RESOURCE_URL,
} from "./constants.js";
-import { checkOAuthAudience } from "./oauth-audience.js";
+import { checkOAuthAudience, FOREIGN_OAUTH_AUDIENCE_MESSAGE } from "./oauth-audience.js";
import { isVercelMarketplaceIssuer, validateVercelMarketplaceJwt } from "./vercelMarketplaceJwt.js";
const oauthJwks = jose.createRemoteJWKSet(new URL(OAUTH_JWKS_URL));
@@ -126,8 +126,8 @@ export function isClerkOAuthJwt(token: string | undefined): token is string {
* resource server: an ID token is addressed to the OAuth client, and a session
* JWT carries the user's whole browser session, which the user never granted
* to an MCP client and which names no audience at all. Both are rejected with
- * 401 in every audience-enforcement mode; `observe` only relaxes the `aud`
- * comparison of a genuine access token.
+ * 401 in every audience-enforcement mode; `observe` and `foreign` only relax
+ * the `aud` comparison of a genuine access token.
*/
async function validateClerkOAuthJwt(token: string): Promise<JWTValidationResult> {
if (!isClerkOAuthJwt(token)) {
@@ -143,11 +143,17 @@ async function validateClerkOAuthJwt(token: string): Promise<JWTValidationResult
const audience = checkOAuthAudience(payload.aud);
if (audience.allowed) return { valid: true };
+ // The token is genuine; is it ours? A token issued for another resource
+ // (or for none) is a foreign MCP server's token until the audience check
+ // says otherwise. Whether that rejects it is the enforcement mode's call.
const clientId =
typeof payload.client_id === "string" && payload.client_id ? payload.client_id : "unknown";
- const warning = `audienceMismatch clientId=${clientId} aud=${audience.aud} enforcement=${audience.enforcement}`;
- if (audience.enforcement === "required") {
- return { valid: false, error: "Token audience not accepted", warning };
+ const warning = `audienceMismatch clientId=${clientId} aud=${audience.aud} enforcement=${audience.enforcement} outcome=${audience.outcome}`;
+ if (audience.outcome === "rejected") {
+ // A new token from the same client would be rejected the same way, so
+ // "re-authenticate" would only send it in a loop; the message names the
+ // way out instead.
+ return { valid: false, error: FOREIGN_OAUTH_AUDIENCE_MESSAGE, warning };
}
return { valid: true, warning };
}
diff --git a/packages/mcp/src/lib/mcp-http-auth.ts b/packages/mcp/src/lib/mcp-http-auth.ts
index 6809ac5b..28d5d0e5 100644
--- a/packages/mcp/src/lib/mcp-http-auth.ts
+++ b/packages/mcp/src/lib/mcp-http-auth.ts
@@ -20,8 +20,9 @@ export type McpAuthDecision = AuthenticationObservation &
// A JWT from a grant authorized before Clerk's "Include Audience" setting was
// on has no `aud` on every refresh, so its warning would repeat on every MCP
// request (millions of lines a day). One line per token per window is enough
-// to collect the (clientId, aud) pairs before enforcement.
-const JWT_WARNING_WINDOW_MS = 10 * 60_000;
+// to collect the (clientId, aud, outcome) triples; a Clerk access token lives
+// about an hour, so an hour's window is about one line per token per pod.
+export const JWT_WARNING_WINDOW_MS = 60 * 60_000;
const jwtWarningLog = createPerTokenLogWindow(JWT_WARNING_WINDOW_MS);
/** Test hook: forget which tokens have had their warning logged. */
@@ -77,7 +78,8 @@ export function effectiveMcpAuthMode(
*/
export async function evaluateMcpAuthentication(
token: string | undefined,
- mode: McpAuthMode
+ mode: McpAuthMode,
+ now = Date.now()
): Promise<McpAuthDecision> {
const method = classifyAuthMethod(token);
if (!token) {
@@ -131,7 +133,7 @@ export async function evaluateMcpAuthentication(
if (validation.warning) {
// Names the OAuth client and the audience, never the token. The verdict
// below is still applied on every request; only the line is deduplicated.
- const suppressed = jwtWarningLog.admit(token);
+ const suppressed = jwtWarningLog.admit(token, now);
if (suppressed !== undefined) {
console.error(`[Context7] ${validation.warning} suppressedSincePrevious=${suppressed}`);
}
diff --git a/packages/mcp/src/lib/oauth-audience.ts b/packages/mcp/src/lib/oauth-audience.ts
index 55775f8a..286713ee 100644
--- a/packages/mcp/src/lib/oauth-audience.ts
+++ b/packages/mcp/src/lib/oauth-audience.ts
@@ -16,7 +16,23 @@ import { RESOURCE_URL } from "./constants.js";
* which tokens are ours.
*/
-export type OAuthAudienceEnforcement = "observe" | "required";
+/**
+ * - `observe` (default): every mismatch is logged and accepted.
+ * - `foreign`: a present `aud` that is not allowed is rejected; a missing
+ * `aud` is logged and accepted. Grants authorized before Clerk's "Include
+ * Audience" setting was on carry no `aud`, and Clerk keeps it empty on
+ * refresh, so `missing` stays accepted until those grants are handled.
+ * - `required`: a foreign and a missing `aud` are both rejected.
+ */
+export type OAuthAudienceEnforcement = "observe" | "foreign" | "required";
+
+export type OAuthAudienceOutcome = "accepted" | "rejected";
+
+const ENFORCEMENT_MODES: readonly OAuthAudienceEnforcement[] = ["observe", "foreign", "required"];
+
+/** Shown to a client whose token was issued for another resource server. */
+export const FOREIGN_OAUTH_AUDIENCE_MESSAGE =
+ "This token was issued for another server. If you connect through a gateway or proxy, use a Context7 API key instead.";
/** The forms of the MCP resource identifier clients have been seen to request. */
export function defaultOAuthAllowedAudiences(resourceUrl = RESOURCE_URL): string[] {
@@ -24,19 +40,31 @@ export function defaultOAuthAllowedAudiences(resourceUrl = RESOURCE_URL): string
return [origin, `${origin}/mcp`, `${origin}/mcp/oauth`];
}
+export interface NormalizeAudienceOptions {
+ /**
+ * Hosts whose query string is not part of the audience. Cursor writes the
+ * MCP URL as it was configured into `resource`, so our own server's
+ * audience arrives as `https://mcp.context7.com/mcp?client=codex`. On any
+ * other host the query string stays, so a foreign audience is logged as
+ * the client sent it.
+ */
+ queryIgnoredHosts?: ReadonlySet<string>;
+}
+
/**
* Canonical form of an audience for comparison: lowercase scheme and host,
* default port dropped, fragment dropped, no trailing slash. The path keeps
* its case. A value that is not an http(s) URL is only trimmed, since it can
* never match an allowed audience and matters only in the log.
*/
-export function normalizeAudience(value: string): string {
+export function normalizeAudience(value: string, options: NormalizeAudienceOptions = {}): string {
const trimmed = value.trim();
let normalized = trimmed;
try {
const url = new URL(trimmed);
if (url.protocol === "http:" || url.protocol === "https:") {
- normalized = `${url.protocol}//${url.host}${url.pathname}${url.search}`;
+ const search = options.queryIgnoredHosts?.has(url.host) ? "" : url.search;
+ normalized = `${url.protocol}//${url.host}${url.pathname}${search}`;
}
} catch {
// Not a URL; compared and logged as written.
@@ -46,17 +74,20 @@ export function normalizeAudience(value: string): string {
/**
* `observe` (default) accepts a token whose `aud` is missing or not allowed
- * and only logs the mismatch; `required` answers 401. Unknown values throw so
- * a typo is caught at startup rather than silently staying in observe.
+ * and only logs the mismatch; `foreign` answers 401 to a token issued for
+ * another server and still accepts a missing `aud`; `required` answers 401
+ * to both. Unknown values throw so a typo is caught at startup rather than
+ * silently staying in observe.
*/
export function parseOAuthAudienceEnforcement(
raw = process.env.MCP_OAUTH_AUDIENCE_ENFORCEMENT
): OAuthAudienceEnforcement {
const value = raw?.trim().toLowerCase();
if (!value) return "observe";
- if (value === "observe" || value === "required") return value;
+ const mode = ENFORCEMENT_MODES.find((candidate) => candidate === value);
+ if (mode) return mode;
throw new Error(
- `MCP_OAUTH_AUDIENCE_ENFORCEMENT must be "observe" or "required"; received "${raw}"`
+ `MCP_OAUTH_AUDIENCE_ENFORCEMENT must be "observe", "foreign" or "required"; received "${raw}"`
);
}
@@ -64,13 +95,34 @@ export function getAllowedOAuthAudiences(
raw = process.env.MCP_OAUTH_ALLOWED_AUDIENCES
): Set<string> {
const configured = raw?.trim();
- const values = configured ? configured.split(",") : defaultOAuthAllowedAudiences();
- return new Set(
- values
- .map((value) => value.trim())
- .filter(Boolean)
- .map(normalizeAudience)
+ const values = (configured ? configured.split(",") : defaultOAuthAllowedAudiences())
+ .map((value) => value.trim())
+ .filter(Boolean);
+ // A token's audience on an allowed host loses its query string before the
+ // comparison, so a configured entry drops its own too; otherwise
+ // `https://x.example/mcp?a=1` in the list could never match.
+ const queryIgnoredHosts = getAllowedOAuthAudienceHosts(
+ new Set(values.map((value) => normalizeAudience(value)))
);
+ return new Set(values.map((value) => normalizeAudience(value, { queryIgnoredHosts })));
+}
+
+/** The hosts of the allowed http(s) audiences, as `URL.host` spells them. */
+export function getAllowedOAuthAudienceHosts(
+ allowed: ReadonlySet<string> = getAllowedOAuthAudiences()
+): Set<string> {
+ const hosts = new Set<string>();
+ for (const audience of allowed) {
+ try {
+ const url = new URL(audience);
+ if (url.protocol === "http:" || url.protocol === "https:") {
+ hosts.add(url.host);
+ }
+ } catch {
+ // Not a URL; it has no host.
+ }
+ }
+ return hosts;
}
export interface OAuthAudienceCheck {
@@ -79,29 +131,58 @@ export interface OAuthAudienceCheck {
/** The normalized audiences, comma-joined, or `missing`. Safe to log. */
aud: string;
enforcement: OAuthAudienceEnforcement;
+ /** What the enforcement mode makes of the verdict. */
+ outcome: OAuthAudienceOutcome;
+}
+
+function decideOutcome(
+ enforcement: OAuthAudienceEnforcement,
+ allowed: boolean,
+ missing: boolean
+): OAuthAudienceOutcome {
+ if (allowed) return "accepted";
+ switch (enforcement) {
+ case "observe":
+ return "accepted";
+ case "foreign":
+ return missing ? "accepted" : "rejected";
+ case "required":
+ return "rejected";
+ }
}
/**
* Checks a verified token's `aud` against the allowed audiences. A token with
* no `aud` fails the check like a foreign one: the client asked for no
- * resource, so nothing says the token was meant for this server.
+ * resource, so nothing says the token was meant for this server. Whether the
+ * failure rejects the token is the enforcement mode's decision (`outcome`).
*/
export function checkOAuthAudience(audiences: unknown): OAuthAudienceCheck {
const enforcement = parseOAuthAudienceEnforcement();
+ const allowedAudiences = getAllowedOAuthAudiences();
+ const queryIgnoredHosts = getAllowedOAuthAudienceHosts(allowedAudiences);
const list =
typeof audiences === "string"
? [audiences]
: Array.isArray(audiences)
? audiences.filter((value): value is string => typeof value === "string")
: [];
- const normalized = list.map(normalizeAudience).filter(Boolean);
+ const normalized = list
+ .map((audience) => normalizeAudience(audience, { queryIgnoredHosts }))
+ .filter(Boolean);
if (normalized.length === 0) {
- return { allowed: false, aud: "missing", enforcement };
+ return {
+ allowed: false,
+ aud: "missing",
+ enforcement,
+ outcome: decideOutcome(enforcement, false, true),
+ };
}
- const allowed = getAllowedOAuthAudiences();
+ const allowed = normalized.some((audience) => allowedAudiences.has(audience));
return {
- allowed: normalized.some((audience) => allowed.has(audience)),
+ allowed,
aud: normalized.join(","),
enforcement,
+ outcome: decideOutcome(enforcement, allowed, false),
};
}
diff --git a/packages/mcp/test/clerk-oauth-jwt.test.ts b/packages/mcp/test/clerk-oauth-jwt.test.ts
index 44f74025..57a9d374 100644
--- a/packages/mcp/test/clerk-oauth-jwt.test.ts
+++ b/packages/mcp/test/clerk-oauth-jwt.test.ts
@@ -34,9 +34,11 @@ import { isClerkOAuthJwt, validateJWT } from "../src/lib/jwt.js";
import {
classifyAuthMethod,
evaluateMcpAuthentication,
+ JWT_WARNING_WINDOW_MS,
resetJwtWarningLog,
setBearerChallenge,
} from "../src/lib/mcp-http-auth.js";
+import { FOREIGN_OAUTH_AUDIENCE_MESSAGE } from "../src/lib/oauth-audience.js";
import {
rememberInvalidOAuthToken,
resetOpaqueOAuthTokenValidation,
@@ -45,7 +47,10 @@ import { searchLibraries } from "../src/lib/api.js";
const ISSUER = "https://clerk.context7.com";
const AUDIENCE = "https://mcp.context7.com/mcp";
+const FOREIGN_AUDIENCE = "https://mcp.joom.it/context7";
const CLIENT_ID = "client_2abcDEF";
+const RESOURCE_METADATA =
+ 'resource_metadata="https://mcp.context7.com/.well-known/oauth-protected-resource/mcp"';
const KID = "ins_test_key";
let privateKey: jose.CryptoKey;
@@ -208,7 +213,7 @@ describe("an expired Clerk OAuth JWT", () => {
describe("Clerk ID tokens and session JWTs", () => {
test("are rejected with 401 whatever the audience enforcement", async () => {
- for (const enforcement of ["observe", "required"]) {
+ for (const enforcement of ["observe", "foreign", "required"]) {
vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", enforcement);
for (const token of [await idToken(), await sessionJwt()]) {
expect(classifyAuthMethod(token)).toBe("jwt");
@@ -231,92 +236,200 @@ describe("Clerk ID tokens and session JWTs", () => {
const relabelled = await sign({ aud: CLIENT_ID });
await expect(validateJWT(relabelled)).resolves.toMatchObject({
valid: false,
- error: "Token audience not accepted",
+ error: FOREIGN_OAUTH_AUDIENCE_MESSAGE,
});
});
});
describe("audience enforcement", () => {
- const foreign = () => sign({ aud: "https://other-mcp.example/mcp" });
+ const foreign = () => sign({ aud: FOREIGN_AUDIENCE });
+ const missing = () => sign({ aud: null });
+
+ const accepted = {
+ allowed: true,
+ method: "oauth",
+ event: "credential_validated",
+ outcome: "accepted",
+ };
+ const rejected = {
+ allowed: false,
+ method: "oauth",
+ error: FOREIGN_OAUTH_AUDIENCE_MESSAGE,
+ event: "credential_rejected",
+ outcome: "invalid",
+ };
+
+ test.each([
+ ["observe", accepted, accepted],
+ ["foreign", accepted, rejected],
+ ["required", rejected, rejected],
+ ] as const)(
+ "%s: allowed accepted, missing %o, foreign %o",
+ async (mode, onMissing, onForeign) => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", mode);
+
+ await expect(evaluateMcpAuthentication(await sign(), "required")).resolves.toEqual(accepted);
+ await expect(evaluateMcpAuthentication(await missing(), "required")).resolves.toEqual(
+ onMissing
+ );
+ await expect(evaluateMcpAuthentication(await foreign(), "required")).resolves.toEqual(
+ onForeign
+ );
- test("observe (default) admits a foreign audience and logs the client and audience", async () => {
+ const logged = loggedLines();
+ expect(logged).toContain(
+ `audienceMismatch clientId=${CLIENT_ID} aud=missing enforcement=${mode} outcome=${onMissing.outcome === "accepted" ? "accepted" : "rejected"}`
+ );
+ expect(logged).toContain(
+ `audienceMismatch clientId=${CLIENT_ID} aud=${FOREIGN_AUDIENCE} enforcement=${mode} outcome=${onForeign.outcome === "accepted" ? "accepted" : "rejected"}`
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ }
+ );
+
+ test("observe (default) admits a foreign audience and logs the client and audience, never the token", async () => {
const token = await foreign();
- await expect(evaluateMcpAuthentication(token, "required")).resolves.toMatchObject({
- allowed: true,
- method: "oauth",
- event: "credential_validated",
- outcome: "accepted",
- });
+ await expect(evaluateMcpAuthentication(token, "required")).resolves.toMatchObject(accepted);
const logged = loggedLines();
expect(logged).toContain(
- `audienceMismatch clientId=${CLIENT_ID} aud=https://other-mcp.example/mcp enforcement=observe`
+ `audienceMismatch clientId=${CLIENT_ID} aud=${FOREIGN_AUDIENCE} enforcement=observe outcome=accepted`
);
expect(logged).not.toContain(token);
expect(logged).not.toContain(token.split(".")[2]);
});
- test("logs the same mismatched token once, and each other token once", async () => {
- const missing = await sign({ aud: null });
- const other = await sign({ aud: null, claims: { client_id: CLIENT_ID, jti: "jti_other" } });
-
- for (let i = 0; i < 3; i += 1) {
- await expect(evaluateMcpAuthentication(missing, "required")).resolves.toMatchObject({
- allowed: true,
- outcome: "accepted",
- });
- }
- await expect(evaluateMcpAuthentication(other, "required")).resolves.toMatchObject({
- allowed: true,
- });
-
- const lines = vi.mocked(console.error).mock.calls.map((call) => String(call[0]));
- expect(lines).toEqual([
- `[Context7] audienceMismatch clientId=${CLIENT_ID} aud=missing enforcement=observe suppressedSincePrevious=0`,
- `[Context7] audienceMismatch clientId=${CLIENT_ID} aud=missing enforcement=observe suppressedSincePrevious=0`,
- ]);
- });
-
test("observe logs a missing audience as such", async () => {
const token = await sign({ aud: null, claims: {} });
await expect(validateJWT(token)).resolves.toEqual({
valid: true,
- warning: "audienceMismatch clientId=unknown aud=missing enforcement=observe",
+ warning: "audienceMismatch clientId=unknown aud=missing enforcement=observe outcome=accepted",
});
});
+ test("foreign answers a token issued for another server with the gateway message", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+
+ const decision = await evaluateMcpAuthentication(await foreign(), "observe");
+ expect(decision).toEqual(rejected);
+ expect(challenge(decision.allowed ? undefined : decision.error)).toBe(
+ `Bearer error="invalid_token", error_description="${FOREIGN_OAUTH_AUDIENCE_MESSAGE}", ${RESOURCE_METADATA}`
+ );
+ });
+
+ test("foreign keeps today's message for an expired token", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+
+ const decision = await evaluateMcpAuthentication(
+ await sign({ aud: FOREIGN_AUDIENCE, expiresIn: -600 }),
+ "observe"
+ );
+ expect(decision).toMatchObject({ allowed: false, error: "Token expired", outcome: "expired" });
+ expect(challenge(decision.allowed ? undefined : decision.error)).toBe(
+ `Bearer error="invalid_token", error_description="Token expired", ${RESOURCE_METADATA}`
+ );
+ expect(loggedLines()).toBe("");
+ });
+
+ test("foreign accepts our own audience with Cursor's query string, on either endpoint", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+
+ for (const aud of [
+ "https://mcp.context7.com/mcp?client=claude-code-plugin",
+ "https://mcp.context7.com/mcp?client=codex",
+ "https://mcp.context7.com/mcp/oauth?client=codex",
+ "https://MCP.context7.com/?client=codex",
+ ]) {
+ await expect(evaluateMcpAuthentication(await sign({ aud }), "required")).resolves.toEqual(
+ accepted
+ );
+ }
+ expect(loggedLines()).toBe("");
+ });
+
+ test("foreign still rejects a foreign host that carries a query string, logged as sent", async () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+
+ for (const aud of [
+ `${FOREIGN_AUDIENCE}?client=codex`,
+ "https://spivak-apim.azure-api.net/context7/mcp?client=claude-code-plugin",
+ ]) {
+ await expect(evaluateMcpAuthentication(await sign({ aud }), "observe")).resolves.toEqual(
+ rejected
+ );
+ expect(loggedLines()).toContain(`aud=${aud} enforcement=foreign outcome=rejected`);
+ }
+ });
+
test("required rejects a foreign or missing audience with 401 and still logs it", async () => {
vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "required");
- for (const token of [await foreign(), await sign({ aud: null })]) {
- await expect(evaluateMcpAuthentication(token, "observe")).resolves.toEqual({
- allowed: false,
- method: "oauth",
- error: "Token audience not accepted",
- event: "credential_rejected",
- outcome: "invalid",
- });
+ for (const token of [await foreign(), await missing()]) {
+ await expect(evaluateMcpAuthentication(token, "observe")).resolves.toEqual(rejected);
}
expect(loggedLines()).toContain(
- `audienceMismatch clientId=${CLIENT_ID} aud=https://other-mcp.example/mcp enforcement=required`
+ `audienceMismatch clientId=${CLIENT_ID} aud=${FOREIGN_AUDIENCE} enforcement=required outcome=rejected`
);
- expect(loggedLines()).toContain("aud=missing enforcement=required");
+ expect(loggedLines()).toContain("aud=missing enforcement=required outcome=rejected");
await expect(evaluateMcpAuthentication(await sign(), "required")).resolves.toMatchObject({
allowed: true,
});
});
+ test("logs the same mismatched token once an hour, and each other token once", async () => {
+ const first = await missing();
+ const other = await sign({ aud: null, claims: { client_id: CLIENT_ID, jti: "jti_other" } });
+ const start = Date.now();
+
+ for (let i = 0; i < 3; i += 1) {
+ await expect(evaluateMcpAuthentication(first, "required", start + i)).resolves.toMatchObject({
+ allowed: true,
+ outcome: "accepted",
+ });
+ }
+ await expect(evaluateMcpAuthentication(other, "required", start + 3)).resolves.toMatchObject({
+ allowed: true,
+ });
+ // Just inside the window: still suppressed. On the hour: logged again,
+ // carrying the lines suppressed since the previous one.
+ await evaluateMcpAuthentication(first, "required", start + JWT_WARNING_WINDOW_MS - 1);
+ await evaluateMcpAuthentication(first, "required", start + JWT_WARNING_WINDOW_MS);
+
+ const line = `[Context7] audienceMismatch clientId=${CLIENT_ID} aud=missing enforcement=observe outcome=accepted`;
+ const lines = vi.mocked(console.error).mock.calls.map((call) => String(call[0]));
+ expect(JWT_WARNING_WINDOW_MS).toBe(60 * 60_000);
+ expect(lines).toEqual([
+ `${line} suppressedSincePrevious=0`,
+ `${line} suppressedSincePrevious=0`,
+ `${line} suppressedSincePrevious=3`,
+ ]);
+ });
+
test("MCP_OAUTH_ALLOWED_AUDIENCES replaces the default list", async () => {
- vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "required");
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
vi.stubEnv("MCP_OAUTH_ALLOWED_AUDIENCES", "http://localhost:8787/mcp/");
await expect(validateJWT(await sign({ aud: "http://localhost:8787/mcp" }))).resolves.toEqual({
valid: true,
});
- await expect(validateJWT(await sign())).resolves.toMatchObject({ valid: false });
+ await expect(
+ validateJWT(await sign({ aud: "http://localhost:8787/mcp?client=codex" }))
+ ).resolves.toEqual({ valid: true });
+ // The default audience is now foreign, query string and all.
+ await expect(validateJWT(await sign())).resolves.toMatchObject({
+ valid: false,
+ error: FOREIGN_OAUTH_AUDIENCE_MESSAGE,
+ warning: `audienceMismatch clientId=${CLIENT_ID} aud=${AUDIENCE} enforcement=foreign outcome=rejected`,
+ });
+ await expect(
+ validateJWT(await sign({ aud: `${AUDIENCE}?client=codex` }))
+ ).resolves.toMatchObject({
+ valid: false,
+ warning: expect.stringContaining(`aud=${AUDIENCE}?client=codex`),
+ });
});
});
diff --git a/packages/mcp/test/mcp-http-auth.test.ts b/packages/mcp/test/mcp-http-auth.test.ts
index 8412ff55..1642a127 100644
--- a/packages/mcp/test/mcp-http-auth.test.ts
+++ b/packages/mcp/test/mcp-http-auth.test.ts
@@ -17,7 +17,7 @@ import {
resetOpaqueOAuthTokenValidation,
validateOpaqueOAuthToken,
} from "../src/lib/oauth-token-validation.js";
-import { resetJwtWarningLog } from "../src/lib/mcp-http-auth.js";
+import { JWT_WARNING_WINDOW_MS, resetJwtWarningLog } from "../src/lib/mcp-http-auth.js";
import {
classifyAuthMethod,
effectiveMcpAuthMode,
@@ -174,7 +174,8 @@ describe("MCP HTTP authentication policy", () => {
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
vi.mocked(validateJWT).mockResolvedValueOnce({
valid: true,
- warning: "audienceMismatch clientId=client_1 aud=https://other.example enforcement=observe",
+ warning:
+ "audienceMismatch clientId=client_1 aud=https://other.example enforcement=observe outcome=accepted",
});
await expect(evaluateMcpAuthentication("clerk.payload.signature", "required")).resolves.toEqual(
@@ -190,34 +191,46 @@ describe("MCP HTTP authentication policy", () => {
expect(logged).not.toContain("clerk.payload.signature");
});
- test("logs a repeated warning once per token and keeps rejecting in required mode", async () => {
+ test("logs a repeated warning once per token per hour and keeps rejecting in required mode", async () => {
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const warning = (aud: string) => ({
valid: false,
- error: "Token audience not accepted",
- warning: `audienceMismatch clientId=client_1 aud=${aud} enforcement=required`,
+ error: "This token was issued for another server.",
+ warning: `audienceMismatch clientId=client_1 aud=${aud} enforcement=required outcome=rejected`,
});
vi.mocked(validateJWT)
.mockResolvedValueOnce(warning("missing"))
.mockResolvedValueOnce(warning("missing"))
.mockResolvedValueOnce(warning("missing"))
- .mockResolvedValueOnce(warning("https://other.example"));
+ .mockResolvedValueOnce(warning("https://other.example"))
+ .mockResolvedValueOnce(warning("missing"));
+ const start = 1_000_000;
for (let i = 0; i < 3; i += 1) {
await expect(
- evaluateMcpAuthentication("clerk.first.signature", "observe")
- ).resolves.toMatchObject({ allowed: false, error: "Token audience not accepted" });
+ evaluateMcpAuthentication("clerk.first.signature", "observe", start + i)
+ ).resolves.toMatchObject({
+ allowed: false,
+ error: "This token was issued for another server.",
+ });
}
await expect(
- evaluateMcpAuthentication("clerk.second.signature", "observe")
+ evaluateMcpAuthentication("clerk.second.signature", "observe", start + 3)
+ ).resolves.toMatchObject({ allowed: false });
+ await expect(
+ evaluateMcpAuthentication("clerk.first.signature", "observe", start + JWT_WARNING_WINDOW_MS)
).resolves.toMatchObject({ allowed: false });
- expect(consoleError).toHaveBeenCalledTimes(2);
+ expect(JWT_WARNING_WINDOW_MS).toBe(60 * 60_000);
+ expect(consoleError).toHaveBeenCalledTimes(3);
expect(consoleError.mock.calls[0][0]).toBe(
- "[Context7] audienceMismatch clientId=client_1 aud=missing enforcement=required suppressedSincePrevious=0"
+ "[Context7] audienceMismatch clientId=client_1 aud=missing enforcement=required outcome=rejected suppressedSincePrevious=0"
);
expect(consoleError.mock.calls[1][0]).toBe(
- "[Context7] audienceMismatch clientId=client_1 aud=https://other.example enforcement=required suppressedSincePrevious=0"
+ "[Context7] audienceMismatch clientId=client_1 aud=https://other.example enforcement=required outcome=rejected suppressedSincePrevious=0"
+ );
+ expect(consoleError.mock.calls[2][0]).toBe(
+ "[Context7] audienceMismatch clientId=client_1 aud=missing enforcement=required outcome=rejected suppressedSincePrevious=2"
);
});
diff --git a/packages/mcp/test/oauth-audience.test.ts b/packages/mcp/test/oauth-audience.test.ts
index 3856f214..82820ead 100644
--- a/packages/mcp/test/oauth-audience.test.ts
+++ b/packages/mcp/test/oauth-audience.test.ts
@@ -2,6 +2,8 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import {
checkOAuthAudience,
defaultOAuthAllowedAudiences,
+ FOREIGN_OAUTH_AUDIENCE_MESSAGE,
+ getAllowedOAuthAudienceHosts,
getAllowedOAuthAudiences,
normalizeAudience,
parseOAuthAudienceEnforcement,
@@ -27,6 +29,24 @@ describe("normalizeAudience", () => {
expect(normalizeAudience(" client_abc ")).toBe("client_abc");
expect(normalizeAudience("urn:example:mcp/")).toBe("urn:example:mcp");
});
+
+ test("drops the query string only on the hosts it is told to", () => {
+ const queryIgnoredHosts = new Set(["mcp.context7.com"]);
+ expect(
+ normalizeAudience("https://mcp.context7.com/mcp?client=claude-code-plugin", {
+ queryIgnoredHosts,
+ })
+ ).toBe("https://mcp.context7.com/mcp");
+ expect(
+ normalizeAudience("https://mcp.context7.com/mcp/?client=codex", { queryIgnoredHosts })
+ ).toBe("https://mcp.context7.com/mcp");
+ expect(
+ normalizeAudience("https://mcp.joom.it/context7?client=codex", { queryIgnoredHosts })
+ ).toBe("https://mcp.joom.it/context7?client=codex");
+ expect(normalizeAudience("https://mcp.context7.com/mcp?client=codex")).toBe(
+ "https://mcp.context7.com/mcp?client=codex"
+ );
+ });
});
describe("allowed audiences", () => {
@@ -44,30 +64,63 @@ describe("allowed audiences", () => {
new Set(["https://a.example", "http://b.example/mcp"])
);
});
+
+ test("drops the query string of a configured entry, so it can still match a token", () => {
+ expect(getAllowedOAuthAudiences("https://a.example/mcp?a=1, urn:example:mcp?x")).toEqual(
+ new Set(["https://a.example/mcp", "urn:example:mcp?x"])
+ );
+ });
+
+ test("lists the hosts of the allowed http(s) audiences", () => {
+ expect(getAllowedOAuthAudienceHosts()).toEqual(new Set(["mcp.context7.com"]));
+ expect(
+ getAllowedOAuthAudienceHosts(
+ new Set(["http://localhost:8787/mcp", "https://a.example", "urn:example:mcp"])
+ )
+ ).toEqual(new Set(["localhost:8787", "a.example"]));
+ });
});
describe("parseOAuthAudienceEnforcement", () => {
- test("defaults to observe and accepts both modes", () => {
+ test("defaults to observe and accepts the three modes", () => {
expect(parseOAuthAudienceEnforcement(undefined)).toBe("observe");
expect(parseOAuthAudienceEnforcement("")).toBe("observe");
expect(parseOAuthAudienceEnforcement(" Observe ")).toBe("observe");
+ expect(parseOAuthAudienceEnforcement("Foreign")).toBe("foreign");
expect(parseOAuthAudienceEnforcement("REQUIRED")).toBe("required");
});
test("rejects unknown values", () => {
- expect(() => parseOAuthAudienceEnforcement("require")).toThrow(/observe.*required/);
+ expect(() => parseOAuthAudienceEnforcement("require")).toThrow(
+ /"observe", "foreign" or "required"/
+ );
+ expect(() => parseOAuthAudienceEnforcement("foreign-only")).toThrow(/received "foreign-only"/);
+ });
+});
+
+describe("FOREIGN_OAUTH_AUDIENCE_MESSAGE", () => {
+ test("is the agreed wording and safe inside a quoted WWW-Authenticate parameter", () => {
+ expect(FOREIGN_OAUTH_AUDIENCE_MESSAGE).toBe(
+ "This token was issued for another server. If you connect through a gateway or proxy, use a Context7 API key instead."
+ );
+ expect(FOREIGN_OAUTH_AUDIENCE_MESSAGE).not.toMatch(/["\\]/);
});
});
describe("checkOAuthAudience", () => {
+ const ALLOWED = "https://mcp.context7.com/mcp";
+ const FOREIGN = "https://mcp.joom.it/context7";
+
test("treats a missing or non-string audience as a mismatch", () => {
expect(checkOAuthAudience(undefined)).toEqual({
allowed: false,
aud: "missing",
enforcement: "observe",
+ outcome: "accepted",
});
expect(checkOAuthAudience([])).toMatchObject({ allowed: false, aud: "missing" });
expect(checkOAuthAudience(42)).toMatchObject({ allowed: false, aud: "missing" });
+ expect(checkOAuthAudience([42, null])).toMatchObject({ allowed: false, aud: "missing" });
});
test("accepts a string or array containing an allowed audience", () => {
@@ -76,6 +129,72 @@ describe("checkOAuthAudience", () => {
allowed: true,
aud: "http://localhost:8787,https://mcp.context7.com",
enforcement: "observe",
+ outcome: "accepted",
+ });
+ });
+
+ test.each([
+ ["observe", "accepted", "accepted", "accepted"],
+ ["foreign", "accepted", "accepted", "rejected"],
+ ["required", "accepted", "rejected", "rejected"],
+ ] as const)(
+ "%s: allowed → %s, missing → %s, foreign → %s",
+ (enforcement, onAllowed, onMissing, onForeign) => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", enforcement);
+
+ expect(checkOAuthAudience(ALLOWED)).toEqual({
+ allowed: true,
+ aud: ALLOWED,
+ enforcement,
+ outcome: onAllowed,
+ });
+ expect(checkOAuthAudience(undefined)).toEqual({
+ allowed: false,
+ aud: "missing",
+ enforcement,
+ outcome: onMissing,
+ });
+ expect(checkOAuthAudience(FOREIGN)).toEqual({
+ allowed: false,
+ aud: FOREIGN,
+ enforcement,
+ outcome: onForeign,
+ });
+ }
+ );
+
+ test("ignores the query string on an allowed host, as Cursor writes it", () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+
+ for (const aud of [
+ "https://mcp.context7.com/mcp?client=claude-code-plugin",
+ "https://mcp.context7.com/mcp?client=codex",
+ "https://mcp.context7.com/mcp/oauth?client=codex",
+ ]) {
+ expect(checkOAuthAudience(aud)).toMatchObject({
+ allowed: true,
+ aud: aud.replace(/\?.*$/, ""),
+ outcome: "accepted",
+ });
+ }
+ });
+
+ test("keeps the query string of a foreign host, so it stays foreign and is logged as sent", () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+
+ expect(checkOAuthAudience("https://mcp.joom.it/context7?client=codex")).toEqual({
+ allowed: false,
+ aud: "https://mcp.joom.it/context7?client=codex",
+ enforcement: "foreign",
+ outcome: "rejected",
+ });
+ // Same host, another path: the query string is dropped but the path still
+ // has to match.
+ expect(checkOAuthAudience("https://mcp.context7.com/other?client=codex")).toEqual({
+ allowed: false,
+ aud: "https://mcp.context7.com/other",
+ enforcement: "foreign",
+ outcome: "rejected",
});
});
@@ -87,11 +206,35 @@ describe("checkOAuthAudience", () => {
allowed: true,
aud: "http://localhost:8787",
enforcement: "required",
+ outcome: "accepted",
});
expect(checkOAuthAudience("https://mcp.context7.com/mcp")).toEqual({
allowed: false,
aud: "https://mcp.context7.com/mcp",
enforcement: "required",
+ outcome: "rejected",
+ });
+ });
+
+ test("the override list also decides which hosts drop their query string", () => {
+ vi.stubEnv("MCP_OAUTH_AUDIENCE_ENFORCEMENT", "foreign");
+ vi.stubEnv("MCP_OAUTH_ALLOWED_AUDIENCES", "http://localhost:8787/mcp?a=1");
+
+ expect(checkOAuthAudience("http://localhost:8787/mcp")).toMatchObject({
+ allowed: true,
+ aud: "http://localhost:8787/mcp",
+ outcome: "accepted",
+ });
+
+ expect(checkOAuthAudience("http://localhost:8787/mcp?client=codex")).toMatchObject({
+ allowed: true,
+ aud: "http://localhost:8787/mcp",
+ outcome: "accepted",
+ });
+ expect(checkOAuthAudience("https://mcp.context7.com/mcp?client=codex")).toMatchObject({
+ allowed: false,
+ aud: "https://mcp.context7.com/mcp?client=codex",
+ outcome: "rejected",
});
});
});