From b07cb08941e52323d75ceeef775ec8f7c2722945 Mon Sep 17 00:00:00 2001 From: SAPHID Date: Mon, 12 Oct 2026 00:00:48 +0000 Subject: [PATCH 1/3] fix(auth): preserve pairing codes after scope rejection Require every MCP approval scope before atomically consuming a pairing code. Keep OAuth scope intersection unchanged. Co-Authored-By: GPT-6.1 Sol --- apps/server/src/auth/EnvironmentAuth.test.ts | 69 +++++++++++++++++++ apps/server/src/auth/EnvironmentAuth.ts | 3 +- apps/server/src/auth/McpOAuth.test.ts | 14 +++- apps/server/src/auth/PairingGrantStore.ts | 15 ++-- .../src/persistence/AuthPairingLinks.ts | 17 ++++- 5 files changed, 109 insertions(+), 9 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index a85db0fd14923..74371c909b2d9 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -23,6 +23,12 @@ import * as SessionStore from "./SessionStore.ts"; /** Pinned so dev-mode cookie tests can assert the port-scoped name. */ const TEST_SERVER_PORT = 13_773; +const mcpFullAccessScopes = [ + "orchestration:read", + "orchestration:operate", + "settings:write", + "source-control:write", +] as const; const isPairingCredentialIssueError = Schema.is(PairingGrantStore.PairingCredentialIssueError); const isPersistenceSqlError = Schema.is(PersistenceErrors.PersistenceSqlError); @@ -429,6 +435,69 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => { }).pipe(Effect.provide(layerEnvironmentAuth())), ); + it.effect.each([ + { label: "read-only", scopes: ["orchestration:read"] as const }, + ...mcpFullAccessScopes.map((missingScope) => ({ + label: `missing ${missingScope}`, + scopes: mcpFullAccessScopes.filter((scope) => scope !== missingScope), + })), + ])("preserves a $label pairing code after rejecting full-access MCP approval", ({ scopes }) => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const pairing = yield* serverAuth.issuePairingCredential({ scopes }); + + const rejected = yield* Effect.flip( + serverAuth.consumeMcpApprovalCode(pairing.credential, "full-access"), + ); + expect(rejected).toMatchObject({ + _tag: "ServerAuthMcpApprovalCodeError", + reason: "insufficient_scope", + }); + + // Retry with an access level this code can approve. + if (scopes.includes("orchestration:read")) { + yield* serverAuth.consumeMcpApprovalCode(pairing.credential, "read-only"); + const reused = yield* Effect.flip( + serverAuth.consumeMcpApprovalCode(pairing.credential, "read-only"), + ); + expect(reused).toMatchObject({ + _tag: "ServerAuthMcpApprovalCodeError", + reason: "unknown_or_used", + }); + } else { + expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).toContain(pairing.id); + } + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + + it.effect("consumes a pairing code only once across concurrent full-access MCP approvals", () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const pairing = yield* serverAuth.issuePairingCredential({ + scopes: mcpFullAccessScopes, + }); + const results = yield* Effect.all( + Array.from({ length: 8 }, () => + Effect.result(serverAuth.consumeMcpApprovalCode(pairing.credential, "full-access")), + ), + { concurrency: "unbounded" }, + ); + + expect(results.filter((result) => result._tag === "Success")).toHaveLength(1); + const failures = results.filter((result) => result._tag === "Failure"); + expect(failures).toHaveLength(7); + for (const failure of failures) { + expect(failure.failure).toMatchObject({ + _tag: "ServerAuthMcpApprovalCodeError", + reason: "unknown_or_used", + }); + } + expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).not.toContain( + pairing.id, + ); + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + it.effect("narrows seeded desktop grants to the requested scopes", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index d66cdbb62c365..c47ef995beab1 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -873,6 +873,7 @@ export const make = Effect.gen(function* () { input?: { readonly proofKeyThumbprint?: string; readonly requestedScopes?: ReadonlyArray; + readonly requiredScopes?: ReadonlyArray; }, ): Effect.Effect< ResolvedBootstrapGrant, @@ -1267,7 +1268,7 @@ export const make = Effect.gen(function* () { access, ) => // No proof key: a code bound to a T3 Connect client's key fails without being spent. - resolveBootstrapGrant(code.trim()).pipe( + resolveBootstrapGrant(code.trim(), { requiredScopes: mcpClientScopes(access) }).pipe( Effect.catchTags({ ServerAuthInvalidCredentialError: () => Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })), diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index cb58294fb2bf8..b86107c1eca22 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -451,6 +451,13 @@ it.live( const readOnlyResponse = yield* approveWith(readOnly.credential); expect(readOnlyResponse.status).toBe(400); expect(readOnlyResponse.message).toContain("cannot grant this access"); + const readOnlyFull = yield* decide(handler, params, { + _tag: "pairing-code", + access: "full-access", + code: readOnly.credential, + }); + expect(readOnlyFull.status).toBe(400); + expect(readOnlyFull.message).toContain("cannot grant this access"); const operator = yield* auth.issuePairingCredential({ scopes: ["orchestration:read", "orchestration:operate"], }); @@ -460,13 +467,14 @@ it.live( code: operator.credential, }); expect(operatorFull.status).toBe(400); + expect(operatorFull.message).toContain("cannot grant this access"); + expect((yield* approveWith(operator.credential)).status).toBe(200); - // A read-only code can approve read-only access. - const readOnlyCode = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] }); + // Retry the rejected code with read-only access and finish the OAuth exchange. const readOnlyApproval = yield* decide(handler, params, { _tag: "pairing-code", access: "read-only", - code: readOnlyCode.credential, + code: readOnly.credential, }); expect(readOnlyApproval.status).toBe(200); const readOnlyToken = yield* handler( diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index d3f5bf7ef8e5e..8aede60a637d5 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -231,6 +231,8 @@ export class PairingGrantStore extends Context.Service< input?: { readonly proofKeyThumbprint?: string; readonly requestedScopes?: ReadonlyArray; + /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */ + readonly requiredScopes?: ReadonlyArray; }, ) => Effect.Effect; } @@ -505,8 +507,10 @@ export const make = Effect.gen(function* () { } if ( - input?.requestedScopes !== undefined && - !input.requestedScopes.some((scope) => grant.scopes.includes(scope)) + (input?.requestedScopes !== undefined && + !input.requestedScopes.some((scope) => grant.scopes.includes(scope))) || + (input?.requiredScopes !== undefined && + !input.requiredScopes.every((scope) => grant.scopes.includes(scope))) ) { return [ { @@ -566,6 +570,7 @@ export const make = Effect.gen(function* () { ...(input?.requestedScopes !== undefined ? { requestedScopes: input.requestedScopes } : {}), + ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}), consumedAt: now, now, }) @@ -612,8 +617,10 @@ export const make = Effect.gen(function* () { } if ( - input?.requestedScopes !== undefined && - !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope)) + (input?.requestedScopes !== undefined && + !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) || + (input?.requiredScopes !== undefined && + !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope))) ) { return yield* new BootstrapCredentialScopeNotGrantedError({}); } diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.ts index 623fc8159db92..fb853d71efcf1 100644 --- a/apps/server/src/persistence/AuthPairingLinks.ts +++ b/apps/server/src/persistence/AuthPairingLinks.ts @@ -47,6 +47,7 @@ export const ConsumeAuthPairingLinkInput = Schema.Struct({ credential: Schema.String, proofKeyThumbprint: Schema.NullOr(Schema.String), requestedScopes: Schema.optionalKey(AuthEnvironmentScopes), + requiredScopes: Schema.optionalKey(AuthEnvironmentScopes), consumedAt: Schema.DateTimeUtcFromString, now: Schema.DateTimeUtcFromString, }); @@ -160,7 +161,14 @@ export const make = Effect.gen(function* () { const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({ Request: ConsumeAuthPairingLinkInput, Result: AuthPairingLinkRawDbRow, - execute: ({ credential, proofKeyThumbprint, requestedScopes, consumedAt, now }) => + execute: ({ + credential, + proofKeyThumbprint, + requestedScopes, + requiredScopes, + consumedAt, + now, + }) => sql` UPDATE auth_pairing_links SET consumed_at = ${consumedAt} @@ -179,6 +187,13 @@ export const make = Effect.gen(function* () { SELECT value FROM json_each(auth_pairing_links.scopes) ) )) + AND NOT EXISTS ( + SELECT 1 + FROM json_each(${JSON.stringify(requiredScopes ?? [])}) AS required + WHERE required.value NOT IN ( + SELECT value FROM json_each(auth_pairing_links.scopes) + ) + ) RETURNING id AS "id", credential AS "credential", From b515cbd245c6b89b1624aaa25830dddb9cd045c5 Mon Sep 17 00:00:00 2001 From: SAPHID Date: Mon, 12 Oct 2026 00:23:54 +0000 Subject: [PATCH 2/3] fix(auth): say a rejected pairing code is still usable The insufficient-scope message still said the code was used up, which this fix makes untrue: the code is kept, so the user can retry with an access level it grants. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/EnvironmentAuth.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index c47ef995beab1..329cdf119d8e1 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -453,7 +453,7 @@ export class ServerAuthMcpApprovalCodeError extends Schema.TaggedError Date: Mon, 19 Oct 2026 06:03:05 +0000 Subject: [PATCH 3/3] fix(auth): preserve rejected pairing codes with focused retry coverage --- apps/server/src/auth/EnvironmentAuth.test.ts | 82 +++++--------------- apps/server/src/auth/EnvironmentAuth.ts | 10 ++- apps/server/src/auth/McpOAuth.test.ts | 9 --- apps/server/src/auth/PairingGrantStore.ts | 5 +- 4 files changed, 30 insertions(+), 76 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 9742f3752dd30..15ebb3f6d49ca 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -18,12 +18,6 @@ import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as SessionStore from "./SessionStore.ts"; const TEST_SERVER_PORT = 13_773; -const mcpFullAccessScopes = [ - "orchestration:read", - "orchestration:operate", - "settings:write", - "source-control:write", -] as const; const isPairingCredentialIssueError = Schema.is(PairingGrantStore.PairingCredentialIssueError); const isPersistenceSqlError = Schema.is(PersistenceErrors.PersistenceSqlError); @@ -430,67 +424,33 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => { }).pipe(Effect.provide(layerEnvironmentAuth())), ); - it.effect.each([ - { label: "read-only", scopes: ["orchestration:read"] as const }, - ...mcpFullAccessScopes.map((missingScope) => ({ - label: `missing ${missingScope}`, - scopes: mcpFullAccessScopes.filter((scope) => scope !== missingScope), - })), - ])("preserves a $label pairing code after rejecting full-access MCP approval", ({ scopes }) => - Effect.gen(function* () { - const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; - const pairing = yield* serverAuth.issuePairingCredential({ scopes }); - - const rejected = yield* Effect.flip( - serverAuth.consumeMcpApprovalCode(pairing.credential, "full-access"), - ); - expect(rejected).toMatchObject({ - _tag: "ServerAuthMcpApprovalCodeError", - reason: "insufficient_scope", - }); + it.effect( + "preserves a rejected MCP pairing code for exactly one concurrent lower-access retry", + () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const pairing = yield* serverAuth.issuePairingCredential({ + scopes: ["orchestration:read"], + }); - // Retry with an access level this code can approve. - if (scopes.includes("orchestration:read")) { - yield* serverAuth.consumeMcpApprovalCode(pairing.credential, "read-only"); - const reused = yield* Effect.flip( - serverAuth.consumeMcpApprovalCode(pairing.credential, "read-only"), + const rejected = yield* Effect.flip( + serverAuth.consumeMcpApprovalCode(pairing.credential, "full-access"), ); - expect(reused).toMatchObject({ + expect(rejected).toMatchObject({ _tag: "ServerAuthMcpApprovalCodeError", - reason: "unknown_or_used", + reason: "insufficient_scope", }); - } else { - expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).toContain(pairing.id); - } - }).pipe(Effect.provide(layerEnvironmentAuth())), - ); - it.effect("consumes a pairing code only once across concurrent full-access MCP approvals", () => - Effect.gen(function* () { - const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; - const pairing = yield* serverAuth.issuePairingCredential({ - scopes: mcpFullAccessScopes, - }); - const results = yield* Effect.all( - Array.from({ length: 8 }, () => - Effect.result(serverAuth.consumeMcpApprovalCode(pairing.credential, "full-access")), - ), - { concurrency: "unbounded" }, - ); + const retry = Effect.result( + serverAuth.consumeMcpApprovalCode(pairing.credential, "read-only"), + ); + const results = yield* Effect.all([retry, retry], { concurrency: "unbounded" }); - expect(results.filter((result) => result._tag === "Success")).toHaveLength(1); - const failures = results.filter((result) => result._tag === "Failure"); - expect(failures).toHaveLength(7); - for (const failure of failures) { - expect(failure.failure).toMatchObject({ - _tag: "ServerAuthMcpApprovalCodeError", - reason: "unknown_or_used", - }); - } - expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).not.toContain( - pairing.id, - ); - }).pipe(Effect.provide(layerEnvironmentAuth())), + expect(results.filter((result) => result._tag === "Success")).toHaveLength(1); + expect(results.filter((result) => result._tag === "Failure")).toMatchObject([ + { failure: { _tag: "ServerAuthMcpApprovalCodeError", reason: "unknown_or_used" } }, + ]); + }).pipe(Effect.provide(layerEnvironmentAuth())), ); it.effect("narrows seeded desktop grants to the requested scopes", () => diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index ac5758f7e86e1..0e33b5ea353c5 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -946,6 +946,12 @@ export const make = Effect.gen(function* () { } return sessions.verify(credential).pipe( mapSessionVerificationErrors, + Effect.filterOrFail( + (session) => + input?.requiredScopes === undefined || + input.requiredScopes.every((scope) => session.scopes.includes(scope)), + () => new ServerAuthScopeNotGrantedError({}), + ), Effect.map( (session) => ({ @@ -1328,9 +1334,7 @@ export const make = Effect.gen(function* () { Effect.flatMap((grant) => grant.method !== "one-time-token" && grant.method !== "reusable-dev-token" ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" })) - : mcpClientScopes(access).every((scope) => grant.scopes.includes(scope)) - ? Effect.void - : Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })), + : Effect.void, ), Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"), ); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index c852ee6ce3da3..5203f130b8fd1 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -439,13 +439,6 @@ it.live( const readOnlyResponse = yield* approveWith(readOnly.credential); expect(readOnlyResponse.status).toBe(400); expect(readOnlyResponse.message).toContain("cannot grant this access"); - const readOnlyFull = yield* decide(handler, params, { - _tag: "pairing-code", - access: "full-access", - code: readOnly.credential, - }); - expect(readOnlyFull.status).toBe(400); - expect(readOnlyFull.message).toContain("cannot grant this access"); const operator = yield* auth.issuePairingCredential({ scopes: ["orchestration:read", "orchestration:operate"], }); @@ -455,8 +448,6 @@ it.live( code: operator.credential, }); expect(operatorFull.status).toBe(400); - expect(operatorFull.message).toContain("cannot grant this access"); - expect((yield* approveWith(operator.credential)).status).toBe(200); const readOnlyApproval = yield* decide(handler, params, { _tag: "pairing-code", diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index 570b373e9553e..30f90ca19f231 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -542,9 +542,8 @@ export const make = Effect.gen(function* () { return yield* seededResult.error; } - // The scope check is part of the UPDATE's WHERE clause so a rejected - // request cannot consume a one-time link. The re-check below only - // explains why nothing matched. + // Scope validation belongs in the atomic UPDATE to preserve rejected links. + // The lookup below only explains why the UPDATE did not match. const consumed = yield* pairingLinks .consumeAvailable({ credential,