Skip to content

Commit e9c3d95

Browse files
fix(auth): preserve explicitly granted pairing scopes (pingdotgg#9785)
Co-authored-by: Claude Fable 5 <[email protected]>
1 parent bfec238 commit e9c3d95

28 files changed

Lines changed: 812 additions & 91 deletions

‎apps/mobile/src/connection/platform.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
Wakeups,
1111
} from "@t3tools/client-runtime/connection";
1212
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
13-
import { AuthStandardClientScopes } from "@t3tools/contracts";
1413
import * as Context from "effect/Context";
1514
import * as Effect from "effect/Effect";
1615
import * as Layer from "effect/Layer";
@@ -216,7 +215,6 @@ const layerCapabilities = Layer.effectContext(
216215
ClientCapabilities.ClientPresentation,
217216
ClientCapabilities.ClientPresentation.of({
218217
metadata: authClientMetadata(Constants.expoConfig?.version),
219-
scopes: AuthStandardClientScopes,
220218
}),
221219
),
222220
Context.add(

‎apps/server/src/auth/EnvironmentAuth.test.ts‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
353353
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
354354
);
355355

356-
it.effect("does not exchange ordinary pairing grants for administrative access tokens", () =>
356+
it.effect("preserves pairing grants after rejecting scopes they do not grant", () =>
357357
Effect.gen(function* () {
358358
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
359359
const pairingCredential = yield* serverAuth.issuePairingCredential();
@@ -367,10 +367,40 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
367367
.pipe(Effect.flip);
368368

369369
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
370+
expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).toContain(
371+
pairingCredential.id,
372+
);
373+
expect(yield* serverAuth.listSessions()).toEqual([]);
374+
375+
const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
376+
pairingCredential.credential,
377+
["orchestration:read"],
378+
requestMetadata,
379+
);
380+
const session = yield* serverAuth.authenticateHttpRequest(
381+
makeBearerRequest(token.access_token),
382+
);
383+
384+
expect(token.scope).toBe("orchestration:read");
385+
expect(session.scopes).toEqual(["orchestration:read"]);
386+
expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).not.toContain(
387+
pairingCredential.id,
388+
);
389+
const reused = yield* serverAuth
390+
.exchangeBootstrapCredentialForAccessToken(
391+
pairingCredential.credential,
392+
["orchestration:read"],
393+
requestMetadata,
394+
)
395+
.pipe(Effect.flip);
396+
expect(reused._tag).toBe("ServerAuthInvalidCredentialError");
370397
}).pipe(Effect.provide(layerEnvironmentAuth())),
371398
);
372399

373-
it.effect("inherits a constrained pairing grant when token exchange omits scope", () =>
400+
it.effect.each([
401+
{ label: "omits scope", requestedScopes: undefined },
402+
{ label: "requests no scopes", requestedScopes: [] },
403+
])("inherits a constrained pairing grant when token exchange $label", ({ requestedScopes }) =>
374404
Effect.gen(function* () {
375405
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
376406
const pairingCredential = yield* serverAuth.issuePairingCredential({
@@ -379,14 +409,33 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
379409

380410
const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
381411
pairingCredential.credential,
382-
undefined,
412+
requestedScopes,
383413
requestMetadata,
384414
);
385415

386416
expect(token.scope).toBe("orchestration:read");
387417
}).pipe(Effect.provide(layerEnvironmentAuth())),
388418
);
389419

420+
it.effect("narrows seeded desktop grants to the requested scopes", () =>
421+
Effect.gen(function* () {
422+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
423+
const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
424+
"desktop-bootstrap-token",
425+
["orchestration:read"],
426+
requestMetadata,
427+
);
428+
const session = yield* serverAuth.authenticateHttpRequest(
429+
makeBearerRequest(token.access_token),
430+
);
431+
432+
expect(token.scope).toBe("orchestration:read");
433+
expect(session.scopes).toEqual(["orchestration:read"]);
434+
}).pipe(
435+
Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })),
436+
),
437+
);
438+
390439
it.effect("rotates desktop bearer sessions without accumulating authorized clients", () =>
391440
Effect.gen(function* () {
392441
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 60 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ export class EnvironmentAuth extends Context.Service<
466466
readonly createBrowserSession: (
467467
credential: string,
468468
requestMetadata: AuthClientMetadata,
469+
previousSessionToken?: string,
469470
) => Effect.Effect<
470471
{
471472
readonly response: AuthBrowserSessionResult;
@@ -786,12 +787,11 @@ export const make = Effect.gen(function* () {
786787
Effect.withSpan("EnvironmentAuth.getSessionState"),
787788
);
788789

789-
const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = (
790-
credential,
791-
requestMetadata,
792-
) => {
790+
const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn(
791+
"EnvironmentAuth.createBrowserSession",
792+
)(function* (credential, requestMetadata, previousSessionToken) {
793793
if (devAuth?.matches(credential)) {
794-
return sessions.verify(credential).pipe(
794+
return yield* sessions.verify(credential).pipe(
795795
mapSessionVerificationErrors,
796796
Effect.flatMap((session) =>
797797
DateTime.now.pipe(
@@ -814,38 +814,40 @@ export const make = Effect.gen(function* () {
814814
Effect.withSpan("EnvironmentAuth.createBrowserSession"),
815815
);
816816
}
817-
return bootstrapCredentials.consume(credential).pipe(
818-
Effect.mapError(toBootstrapExchangeError),
819-
Effect.flatMap((grant) =>
820-
sessions
821-
.issue({
822-
method: "browser-session-cookie",
823-
subject: grant.subject,
824-
scopes: grant.scopes,
825-
client: {
826-
...requestMetadata,
827-
...(grant.label ? { label: grant.label } : {}),
828-
},
829-
})
830-
.pipe(
831-
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
832-
),
833-
),
834-
Effect.map(
835-
(session) =>
836-
({
837-
response: {
838-
authenticated: true,
839-
scopes: session.scopes,
840-
sessionMethod: session.method,
841-
expiresAt: DateTime.toUtc(session.expiresAt),
842-
} satisfies AuthBrowserSessionResult,
843-
sessionToken: session.token,
844-
}) satisfies BootstrapExchangeResult,
845-
),
846-
Effect.withSpan("EnvironmentAuth.createBrowserSession"),
847-
);
848-
};
817+
const previousSession =
818+
previousSessionToken === undefined
819+
? undefined
820+
: yield* sessions.verify(previousSessionToken).pipe(
821+
Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.void),
822+
Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })),
823+
);
824+
const grant = yield* bootstrapCredentials
825+
.consume(credential)
826+
.pipe(Effect.mapError(toBootstrapExchangeError));
827+
const session = yield* sessions
828+
.issue({
829+
method: "browser-session-cookie",
830+
subject: grant.subject,
831+
scopes: grant.scopes,
832+
...(previousSession?.method === "browser-session-cookie"
833+
? { replaceSessionId: previousSession.sessionId }
834+
: {}),
835+
client: {
836+
...requestMetadata,
837+
...(grant.label ? { label: grant.label } : {}),
838+
},
839+
})
840+
.pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })));
841+
return {
842+
response: {
843+
authenticated: true,
844+
scopes: session.scopes,
845+
sessionMethod: session.method,
846+
expiresAt: DateTime.toUtc(session.expiresAt),
847+
} satisfies AuthBrowserSessionResult,
848+
sessionToken: session.token,
849+
} satisfies BootstrapExchangeResult;
850+
});
849851

850852
type ResolvedBootstrapGrant = Pick<
851853
PairingGrantStore.BootstrapGrant,
@@ -855,15 +857,24 @@ export const make = Effect.gen(function* () {
855857
};
856858
const resolveBootstrapGrant = (
857859
credential: string,
858-
input?: { readonly proofKeyThumbprint?: string },
860+
input?: {
861+
readonly proofKeyThumbprint?: string;
862+
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
863+
},
859864
): Effect.Effect<
860865
ResolvedBootstrapGrant,
861-
ServerAuthInvalidCredentialError | ServerAuthInternalError
866+
ServerAuthInvalidCredentialError | ServerAuthInternalError | ServerAuthScopeNotGrantedError
862867
> => {
863868
if (!devAuth?.matches(credential)) {
864869
return bootstrapCredentials
865870
.consume(credential, input)
866-
.pipe(Effect.mapError(toBootstrapExchangeError));
871+
.pipe(
872+
Effect.mapError((cause) =>
873+
cause._tag === "BootstrapCredentialScopeNotGrantedError"
874+
? new ServerAuthScopeNotGrantedError({})
875+
: toBootstrapExchangeError(cause),
876+
),
877+
);
867878
}
868879
return sessions.verify(credential).pipe(
869880
mapSessionVerificationErrors,
@@ -879,14 +890,15 @@ export const make = Effect.gen(function* () {
879890
};
880891

881892
const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
882-
(credential, requestedScopes, requestMetadata, input) =>
883-
resolveBootstrapGrant(credential, input).pipe(
893+
(credential, requestedScopesInput, requestMetadata, input) => {
894+
const requestedScopes = requestedScopesInput?.length ? requestedScopesInput : undefined;
895+
return resolveBootstrapGrant(credential, {
896+
...input,
897+
...(requestedScopes !== undefined ? { requestedScopes } : {}),
898+
}).pipe(
884899
Effect.flatMap((grant) =>
885900
Effect.gen(function* () {
886901
const grantedScopes = requestedScopes ?? grant.scopes;
887-
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
888-
return yield* new ServerAuthScopeNotGrantedError({});
889-
}
890902
return yield* sessions
891903
.issue({
892904
method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
@@ -934,6 +946,7 @@ export const make = Effect.gen(function* () {
934946
),
935947
Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
936948
);
949+
};
937950

938951
const issuePairingCredentialForSubject = (input: {
939952
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
@@ -1238,6 +1251,8 @@ export const make = Effect.gen(function* () {
12381251
Effect.catchTags({
12391252
ServerAuthInvalidCredentialError: () =>
12401253
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1254+
ServerAuthScopeNotGrantedError: () =>
1255+
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
12411256
}),
12421257
Effect.flatMap((grant) =>
12431258
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"

‎apps/server/src/auth/PairingGrantStore.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,11 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
104104
const token = yield* bootstrapCredentials.issueOneTimeToken();
105105
const results = yield* Effect.all(
106106
Array.from({ length: 8 }, () =>
107-
Effect.result(bootstrapCredentials.consume(token.credential)),
107+
Effect.result(
108+
bootstrapCredentials.consume(token.credential, {
109+
requestedScopes: ["orchestration:read"],
110+
}),
111+
),
108112
),
109113
{
110114
concurrency: "unbounded",
@@ -128,20 +132,30 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
128132
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
129133
const token = yield* bootstrapCredentials.issueOneTimeToken({
130134
proofKeyThumbprint: "client-proof-key-thumbprint",
135+
scopes: ["orchestration:read"],
131136
});
132137

133138
const missing = yield* Effect.flip(bootstrapCredentials.consume(token.credential));
134139
const wrong = yield* Effect.flip(
135140
bootstrapCredentials.consume(token.credential, {
136141
proofKeyThumbprint: "other-proof-key-thumbprint",
142+
requestedScopes: ["access:write"],
143+
}),
144+
);
145+
const forbiddenScope = yield* Effect.flip(
146+
bootstrapCredentials.consume(token.credential, {
147+
proofKeyThumbprint: "client-proof-key-thumbprint",
148+
requestedScopes: ["access:write"],
137149
}),
138150
);
139151
const consumed = yield* bootstrapCredentials.consume(token.credential, {
140152
proofKeyThumbprint: "client-proof-key-thumbprint",
153+
requestedScopes: ["orchestration:read"],
141154
});
142155

143156
expect(missing.message).toContain("proof key mismatch");
144157
expect(wrong.message).toContain("proof key mismatch");
158+
expect(forbiddenScope._tag).toBe("BootstrapCredentialScopeNotGrantedError");
145159
expect(consumed.proofKeyThumbprint).toBe("client-proof-key-thumbprint");
146160
}).pipe(Effect.provide(layerPairingGrantStore())),
147161
);

‎apps/server/src/auth/PairingGrantStore.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,15 @@ export class UnavailableBootstrapCredentialError extends Schema.TaggedError<Unav
6969
}
7070
}
7171

72+
export class BootstrapCredentialScopeNotGrantedError extends Schema.TaggedError<BootstrapCredentialScopeNotGrantedError>()(
73+
"BootstrapCredentialScopeNotGrantedError",
74+
{},
75+
) {
76+
override get message(): string {
77+
return "The requested authentication scope was not granted.";
78+
}
79+
}
80+
7281
export const BootstrapCredentialInvalidError = Schema.Union([
7382
UnknownBootstrapCredentialError,
7483
ExpiredBootstrapCredentialError,
@@ -174,6 +183,7 @@ export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialI
174183
export const BootstrapCredentialError = Schema.Union([
175184
BootstrapCredentialInvalidError,
176185
BootstrapCredentialInternalError,
186+
BootstrapCredentialScopeNotGrantedError,
177187
]);
178188
export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
179189

@@ -220,6 +230,7 @@ export class PairingGrantStore extends Context.Service<
220230
credential: string,
221231
input?: {
222232
readonly proofKeyThumbprint?: string;
233+
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
223234
},
224235
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
225236
}
@@ -232,7 +243,7 @@ interface StoredBootstrapGrant extends BootstrapGrant {
232243
type ConsumeResult =
233244
| {
234245
readonly _tag: "error";
235-
readonly reason: "not-found" | "expired";
246+
readonly reason: "not-found" | "expired" | "scope-not-granted";
236247
readonly error: BootstrapCredentialError;
237248
}
238249
| {
@@ -493,6 +504,17 @@ export const make = Effect.gen(function* () {
493504
];
494505
}
495506

507+
if (input?.requestedScopes?.some((scope) => !grant.scopes.includes(scope))) {
508+
return [
509+
{
510+
_tag: "error",
511+
reason: "scope-not-granted",
512+
error: new BootstrapCredentialScopeNotGrantedError({}),
513+
},
514+
current,
515+
];
516+
}
517+
496518
const remainingUses = grant.remainingUses;
497519
if (typeof remainingUses === "number") {
498520
if (remainingUses <= 1) {
@@ -531,10 +553,16 @@ export const make = Effect.gen(function* () {
531553
return yield* seededResult.error;
532554
}
533555

556+
// The scope check is part of the UPDATE's WHERE clause so a rejected
557+
// request cannot consume a one-time link. The re-check below only
558+
// explains why nothing matched.
534559
const consumed = yield* pairingLinks
535560
.consumeAvailable({
536561
credential,
537562
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
563+
...(input?.requestedScopes !== undefined
564+
? { requestedScopes: input.requestedScopes }
565+
: {}),
538566
consumedAt: now,
539567
now,
540568
})
@@ -580,6 +608,10 @@ export const make = Effect.gen(function* () {
580608
return yield* new BootstrapCredentialProofKeyMismatchError({});
581609
}
582610

611+
if (input?.requestedScopes?.some((scope) => !matching.value.scopes.includes(scope))) {
612+
return yield* new BootstrapCredentialScopeNotGrantedError({});
613+
}
614+
583615
return yield* new UnavailableBootstrapCredentialError({});
584616
},
585617
);

0 commit comments

Comments
 (0)