Context7 Platform -- Up-to-date docs for AI agents
CTX7-2592: Verify Entra token signatures before the audience lookup (#3360)
Enes Gules28825961808d
diff --git a/.changeset/entra-signature-first.md b/.changeset/entra-signature-first.mdnew file mode 100644index 00000000..b70a1793--- /dev/null+++ b/.changeset/entra-signature-first.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Verify Microsoft Entra token signatures before looking up the audience, and cap the Entra config cache.diff --git a/packages/mcp/src/lib/jwt.ts b/packages/mcp/src/lib/jwt.tsindex 3fd6290b..06ee8846 100644--- a/packages/mcp/src/lib/jwt.ts+++ b/packages/mcp/src/lib/jwt.ts@@ -14,23 +14,23 @@ const oauthJwks = jose.createRemoteJWKSet(new URL(OAUTH_JWKS_URL));const emaJwks = jose.createRemoteJWKSet(new URL(EMA_JWKS_URL));-const ENTRA_V2_ISSUER_RE = /^https:\/\/login\.microsoftonline\.com\/[0-9a-f-]{36}\/v2\.0$/;+const ENTRA_V2_ISSUER_RE = /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/;/** RFC 9068 media type of a JWT OAuth access token. */const OAUTH_ACCESS_TOKEN_TYP = "at+jwt";/** Allowed skew between Clerk's clock and ours when checking `exp`/`nbf`. */const OAUTH_CLOCK_TOLERANCE_SECONDS = 60;-const jwksByTenant = new Map<string, ReturnType<typeof jose.createRemoteJWKSet>>();-function entraJwks(tenantId: string) {- let jwks = jwksByTenant.get(tenantId);- if (!jwks) {- jwks = jose.createRemoteJWKSet(- new URL(`https://login.microsoftonline.com/${tenantId}/discovery/v2.0/keys`)- );- jwksByTenant.set(tenantId, jwks);- }- return jwks;+// Microsoft's tenant-independent key set. It holds the keys of every tenant-specific set+// plus the personal-account (MSA) keys, so each key's `issuer` limits which tokens it may sign.+// Apps with custom signing keys (claims mapping, `?appid=` key set) are not supported.+const entraJwks = jose.createRemoteJWKSet(+ new URL("https://login.microsoftonline.com/common/discovery/v2.0/keys")+);++function entraKeyMayIssue(kid: string | undefined, issuer: string, tenantId: string): boolean {+ const key = entraJwks.jwks()?.keys.find((k) => k.kid === kid) as { issuer?: unknown } | undefined;+ return typeof key?.issuer === "string" && key.issuer.replace("{tenantid}", tenantId) === issuer;}interface EntraConfig {@@ -40,12 +40,24 @@ interface EntraConfig {}const CONFIG_TTL_MS = 5 * 60 * 1000;+const CONFIG_CACHE_MAX = 1000;const configByAudience = new Map<string, { value: EntraConfig | null; expiresAt: number }>();+function cacheEntraConfig(audience: string, value: EntraConfig | null, now: number) {+ // Evicts the oldest insert (Map order), not the least recently used; enough for a size cap.+ if (configByAudience.size >= CONFIG_CACHE_MAX) {+ configByAudience.delete(configByAudience.keys().next().value!);+ }+ configByAudience.set(audience, { value, expiresAt: now + CONFIG_TTL_MS });+}+async function fetchEntraConfig(audience: string): Promise<EntraConfig | null> {const now = Date.now();const cached = configByAudience.get(audience);- if (cached && cached.expiresAt > now) return cached.value;+ if (cached) {+ if (cached.expiresAt > now) return cached.value;+ configByAudience.delete(audience);+ }try {const res = await fetch(@@ -53,13 +65,13 @@ async function fetchEntraConfig(audience: string): Promise<EntraConfig | null> {);if (res.ok) {const value = (await res.json()) as EntraConfig;- configByAudience.set(audience, { value, expiresAt: now + CONFIG_TTL_MS });+ cacheEntraConfig(audience, value, now);return value;}if (res.status === 404) {// Authoritative "not configured" response — safe to cache the miss so we// don't hammer the app on every token verification.- configByAudience.set(audience, { value: null, expiresAt: now + CONFIG_TTL_MS });+ cacheEntraConfig(audience, null, now);return null;}} catch {@@ -145,17 +157,28 @@ export async function validateJWT(token: string): Promise<JWTValidationResult> {const decoded = jose.decodeJwt(token);const iss = typeof decoded.iss === "string" ? decoded.iss : "";- if (ENTRA_V2_ISSUER_RE.test(iss)) {+ const entraTenantId = ENTRA_V2_ISSUER_RE.exec(iss)?.[1];+ if (entraTenantId) {const audience = typeof decoded.aud === "string" ? decoded.aud : "";if (!audience) return { valid: false, error: "Missing audience" };- const config = await fetchEntraConfig(audience);- if (!config) return { valid: false, error: "Unknown audience" };-- const { payload } = await jose.jwtVerify(token, entraJwks(config.tenantId), {- issuer: `https://login.microsoftonline.com/${config.tenantId}/v2.0`,+ // The claims are untrusted until Microsoft's signature is verified, so no backend lookup before it.+ const issuer = `https://login.microsoftonline.com/${entraTenantId}/v2.0`;+ const { payload, protectedHeader } = await jose.jwtVerify(token, entraJwks, {+ issuer,audience,+ algorithms: ["RS256"],});+ // Microsoft's multi-tenant rule: the signed tid must be the issuer's tenant, and the+ // key's {tenantid} template is filled from tid, not from the issuer we just matched.+ if (payload.tid !== entraTenantId) return { valid: false, error: "Invalid token claims" };+ if (!entraKeyMayIssue(protectedHeader.kid, issuer, payload.tid)) {+ return { valid: false, error: "Invalid signature" };+ }++ const config = await fetchEntraConfig(audience);+ if (!config) return { valid: false, error: "Unknown audience" };+ if (config.tenantId !== entraTenantId) return { valid: false, error: "Invalid token claims" };if (config.requiredScope) {const scopes = String(payload.scp ?? "").split(" ");diff --git a/packages/mcp/test/jwt.test.ts b/packages/mcp/test/jwt.test.tsindex d481dacc..6b8a0ec7 100644--- a/packages/mcp/test/jwt.test.ts+++ b/packages/mcp/test/jwt.test.ts@@ -1,12 +1,22 @@import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import * as jose from "jose";+const ENTRA_KEYS_URL = "https://login.microsoftonline.com/common/discovery/v2.0/keys";+// Stands in for Microsoft's common key set; filled with a local key pair per test.+const entraKeys = vi.hoisted(() => ({ set: { keys: [] as (jose.JWK & { issuer?: string })[] } }));+vi.mock("jose", async () => {const actual = await vi.importActual<typeof jose>("jose");return {...actual,- createRemoteJWKSet: vi.fn(- () => "fake-jwks" as unknown as ReturnType<typeof jose.createRemoteJWKSet>+ createRemoteJWKSet: vi.fn((url: URL) =>+ url.href === ENTRA_KEYS_URL+ ? Object.assign(+ (header: jose.JWSHeaderParameters, token: jose.FlattenedJWSInput) =>+ actual.createLocalJWKSet(entraKeys.set)(header, token),+ { jwks: () => entraKeys.set }+ )+ : ("fake-jwks" as unknown as ReturnType<typeof jose.createRemoteJWKSet>)),jwtVerify: vi.fn(),};@@ -88,53 +98,107 @@ describe("isJWT", () => {});describe("validateJWT - Entra path", () => {- test("validates token after fetching tenant config", async () => {- const fetchMock = vi.mocked(fetch);- fetchMock.mockResolvedValueOnce(- makeFetchResponse({- jsonData: { teamspaceId: "team-1", tenantId: TENANT_ID, requiredScope: "mcp.access" },- })+ const KID = "entra-test-key";+ let privateKey: CryptoKey;++ beforeEach(async () => {+ const actual = await vi.importActual<typeof jose>("jose");+ vi.mocked(jose.jwtVerify).mockImplementation(actual.jwtVerify);+ const pair = await jose.generateKeyPair("RS256");+ privateKey = pair.privateKey;+ const jwk = await jose.exportJWK(pair.publicKey);+ entraKeys.set = {+ keys: [{ ...jwk, kid: KID, issuer: "https://login.microsoftonline.com/{tenantid}/v2.0" }],+ };+ });++ function signEntraToken(aud: string, claims: jose.JWTPayload = {}, key = privateKey) {+ return new jose.SignJWT({ tid: TENANT_ID, ...claims })+ .setProtectedHeader({ alg: "RS256", kid: KID })+ .setIssuer(ENTRA_ISSUER)+ .setAudience(aud)+ .setExpirationTime("5m")+ .sign(key);+ }++ function mockConfig(config: { tenantId: string; requiredScope: string | null }) {+ vi.mocked(fetch).mockResolvedValue(+ makeFetchResponse({ jsonData: { teamspaceId: "team-1", ...config } }));- vi.mocked(jose.jwtVerify).mockResolvedValue({- payload: { oid: "user-oid", scp: "mcp.access" },- protectedHeader: { alg: "RS256" },- } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);+ }++ test("rejects forged tokens before any config lookup", async () => {+ const { privateKey: attackerKey } = await jose.generateKeyPair("RS256");+ const { validateJWT } = await loadModule();++ for (const token of [+ makeEntraToken({ iss: ENTRA_ISSUER, aud: AUDIENCE }),+ new jose.UnsecuredJWT({ iss: ENTRA_ISSUER, aud: AUDIENCE }).encode(),+ await signEntraToken(AUDIENCE, {}, attackerKey),+ ]) {+ expect((await validateJWT(token)).valid).toBe(false);+ }+ expect(fetch).not.toHaveBeenCalled();+ });++ test("rejects a key that Microsoft scopes to another issuer", async () => {+ entraKeys.set.keys[0].issuer =+ "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0";+ const { validateJWT } = await loadModule();++ const result = await validateJWT(await signEntraToken(AUDIENCE));++ expect(result).toEqual({ valid: false, error: "Invalid signature" });+ expect(fetch).not.toHaveBeenCalled();+ });++ test("accepts a signed token after fetching the audience config", async () => {+ mockConfig({ tenantId: TENANT_ID, requiredScope: "mcp.access" });+ const { validateJWT } = await loadModule();++ const result = await validateJWT(await signEntraToken(AUDIENCE, { scp: "mcp.access" }));++ expect(result).toEqual({ valid: true });+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(vi.mocked(fetch).mock.calls[0][0]).toContain(`/v2/entra/config/${AUDIENCE}`);+ });++ test("rejects a signed token whose tid is missing or differs from the issuer tenant", async () => {+ mockConfig({ tenantId: TENANT_ID, requiredScope: null });+ const { validateJWT } = await loadModule();++ for (const tid of [undefined, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"]) {+ const result = await validateJWT(await signEntraToken(AUDIENCE, { tid }));+ expect(result).toEqual({ valid: false, error: "Invalid token claims" });+ }+ expect(fetch).not.toHaveBeenCalled();+ });+ test("rejects a token whose issuer tenant differs from the configured tenant", async () => {+ mockConfig({ tenantId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", requiredScope: null });const { validateJWT } = await loadModule();- const result = await validateJWT(makeEntraToken({ iss: ENTRA_ISSUER, aud: AUDIENCE }));- expect(result.valid).toBe(true);- expect(fetchMock).toHaveBeenCalledTimes(1);- expect(fetchMock.mock.calls[0][0]).toContain(`/v2/entra/config/${AUDIENCE}`);+ const result = await validateJWT(await signEntraToken(AUDIENCE));++ expect(result).toEqual({ valid: false, error: "Invalid token claims" });});test("returns 'Unknown audience' when config endpoint returns 404", async () => {vi.mocked(fetch).mockResolvedValue(makeFetchResponse({ ok: false, status: 404 }));-const { validateJWT } = await loadModule();- const result = await validateJWT(makeEntraToken({ iss: ENTRA_ISSUER, aud: "unknown-aud" }));- expect(result.valid).toBe(false);- expect(result.error).toBe("Unknown audience");- expect(jose.jwtVerify).not.toHaveBeenCalled();+ const result = await validateJWT(await signEntraToken("unknown-aud"));++ expect(result).toEqual({ valid: false, error: "Unknown audience" });});test("returns 'Missing required scope' when scp claim lacks the configured scope", async () => {- vi.mocked(fetch).mockResolvedValue(- makeFetchResponse({- jsonData: { teamspaceId: "team-1", tenantId: TENANT_ID, requiredScope: "mcp.access" },- })- );- vi.mocked(jose.jwtVerify).mockResolvedValue({- payload: { scp: "other.scope" },- protectedHeader: { alg: "RS256" },- } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);-+ mockConfig({ tenantId: TENANT_ID, requiredScope: "mcp.access" });const { validateJWT } = await loadModule();- const result = await validateJWT(makeEntraToken({ iss: ENTRA_ISSUER, aud: AUDIENCE }));- expect(result.valid).toBe(false);- expect(result.error).toBe("Missing required scope");+ const result = await validateJWT(await signEntraToken(AUDIENCE, { scp: "other.scope" }));++ expect(result).toEqual({ valid: false, error: "Missing required scope" });});test("returns 'Missing audience' for Entra issuer with no aud claim", async () => {@@ -147,23 +211,26 @@ describe("validateJWT - Entra path", () => {});test("caches config across repeated audiences", async () => {- const fetchMock = vi.mocked(fetch);- fetchMock.mockResolvedValue(- makeFetchResponse({- jsonData: { teamspaceId: "team-1", tenantId: TENANT_ID, requiredScope: null },- })- );- vi.mocked(jose.jwtVerify).mockResolvedValue({- payload: { oid: "u" },- protectedHeader: { alg: "RS256" },- } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);-+ mockConfig({ tenantId: TENANT_ID, requiredScope: null });const { validateJWT } = await loadModule();- const token = makeEntraToken({ iss: ENTRA_ISSUER, aud: AUDIENCE });+ const token = await signEntraToken(AUDIENCE);await validateJWT(token);await validateJWT(token);- expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ test("caps the config cache and evicts the oldest audience", async () => {+ vi.mocked(fetch).mockResolvedValue(makeFetchResponse({ ok: false, status: 404 }));+ const { validateJWT } = await loadModule();++ for (let i = 0; i <= 1000; i++) await validateJWT(await signEntraToken(`aud-${i}`));+ expect(fetch).toHaveBeenCalledTimes(1001);++ await validateJWT(await signEntraToken("aud-1000"));+ expect(fetch).toHaveBeenCalledTimes(1001);+ await validateJWT(await signEntraToken("aud-0"));+ expect(fetch).toHaveBeenCalledTimes(1002);});test("does not cache transient 500 errors — next request retries", async () => {@@ -174,13 +241,8 @@ describe("validateJWT - Entra path", () => {jsonData: { teamspaceId: "team-1", tenantId: TENANT_ID, requiredScope: null },}));- vi.mocked(jose.jwtVerify).mockResolvedValue({- payload: { oid: "u" },- protectedHeader: { alg: "RS256" },- } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);-const { validateJWT } = await loadModule();- const token = makeEntraToken({ iss: ENTRA_ISSUER, aud: AUDIENCE });+ const token = await signEntraToken(AUDIENCE);const first = await validateJWT(token);expect(first.valid).toBe(false);