Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 47 additions & 10 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
AuthAccessTokenType,
AuthAccessWriteScope,
AuthMcpClientAccess,
AuthOrchestrationOperateScope,
AuthStandardClientScopes,
type AuthAccessTokenResult,
Expand All @@ -9,7 +10,6 @@ import {
type AuthClientSession,
type AuthCreatePairingCredentialInput,
type AuthEnvironmentScope,
type AuthMcpClientAccess,
type AuthPairingLink,
type AuthPairingCredentialResult,
type AuthSessionId,
Expand Down Expand Up @@ -48,6 +48,7 @@ import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ManagedLimits from "../policy/managedLimits.ts";
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts";
import { requestUrl } from "../requestUrl.ts";

const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
Expand Down Expand Up @@ -488,6 +489,7 @@ export class EnvironmentAuth extends Context.Service<
readonly subject?: string;
readonly proofKeyThumbprint?: string;
readonly purpose?: "startup";
readonly mcpApproval?: AuthMcpClientAccess;
}) => Effect.Effect<
IssuedPairingLink,
ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
Expand Down Expand Up @@ -559,11 +561,17 @@ export class EnvironmentAuth extends Context.Service<
},
ServerAuthInternalError
>;
/** Spends a code covering all granted scopes. Rejects desktop grants and leaves refused proof-bound codes unspent. */
/**
* Spends a code covering all granted scopes and returns the level it approves. A level-bound
* code must name `access`. Rejects desktop grants and leaves refused codes unspent.
*/
readonly consumeMcpApprovalCode: (
code: string,
access: AuthMcpClientAccess,
) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
) => Effect.Effect<
AuthMcpClientAccess,
ServerAuthMcpApprovalCodeError | ServerAuthInternalError
>;
readonly authenticateBrowserSession: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
Expand Down Expand Up @@ -918,6 +926,8 @@ export const make = Effect.gen(function* () {
readonly proofKeyThumbprint?: string;
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
/** Only an agent sign-in opts in to spending a code issued for it. */
readonly mcpApproval?: AuthMcpClientAccess;
},
): Effect.Effect<
ResolvedBootstrapGrant,
Expand Down Expand Up @@ -1032,6 +1042,7 @@ export const make = Effect.gen(function* () {
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
...(input?.purpose ? { purpose: input.purpose } : {}),
...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}),
});
return {
id: issued.id,
Expand Down Expand Up @@ -1066,7 +1077,11 @@ export const make = Effect.gen(function* () {
INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
];
return pairingLinks
.filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
.filter(
(pairingLink) =>
!excludedSubjects.includes(pairingLink.subject) &&
!pairingLink.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX),
)
.map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
Expand Down Expand Up @@ -1132,11 +1147,17 @@ export const make = Effect.gen(function* () {

const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
createPairingLink({
scopes: input?.scopes ?? AuthStandardClientScopes,
scopes: input?.access
? mcpClientScopes(input.access)
: (input?.scopes ?? AuthStandardClientScopes),
subject: "one-time-token",
...(input?.label ? { label: input.label } : {}),
...(input?.access ? { mcpApproval: input.access } : {}),
}).pipe(
Effect.map(toPairingCredential),
Effect.map((issued) => ({
...toPairingCredential(issued),
...(input?.access ? { access: input.access } : {}),
})),
Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
);

Expand Down Expand Up @@ -1361,7 +1382,10 @@ export const make = Effect.gen(function* () {
code,
access,
) =>
resolveBootstrapGrant(code.trim(), { requiredScopes: mcpClientScopes(access) }).pipe(
resolveBootstrapGrant(code.trim(), {
requiredScopes: mcpClientScopes(access),
mcpApproval: access,
}).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
Expand All @@ -1371,7 +1395,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" }))
: Effect.void,
: Effect.succeed(mcpApprovalLevel(grant.subject) ?? access),
),
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
);
Expand Down Expand Up @@ -1410,6 +1434,16 @@ export const make = Effect.gen(function* () {
});
});

const isMcpClientAccess = Schema.is(AuthMcpClientAccess);

/** The level an approval code's subject names, or undefined for any other code. */
const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)
? subject.slice(MCP_APPROVAL_SUBJECT_PREFIX.length)
: undefined;
return isMcpClientAccess(level) ? level : undefined;
};

/** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const;

Expand Down Expand Up @@ -1440,8 +1474,11 @@ const revokePairedClientsThePolicyDisallows = Effect.fn(
session.client.ipAddress !== undefined &&
!isLocalLoopbackHost(session.client.ipAddress)),
);
const links = (yield* stores.pairingLinks.listActive()).filter((link) =>
disallowed.has(link.subject),
const links = (yield* stores.pairingLinks.listActive()).filter(
(link) =>
disallowed.has(link.subject) ||
// Approval codes let an agent elsewhere sign in, as plain codes do.
(!remoteAllowed && link.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)),
);
yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), {
discard: true,
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/auth/EnvironmentAuthAdmin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
const startupPhone = yield* startup("192.168.1.20");
const startupBrowser = yield* startup("127.0.0.1");
yield* environmentAuth.createPairingLink({ subject: "one-time-token" });
yield* environmentAuth.issuePairingCredential({ access: "auto" });

yield* EnvironmentAuth.make.pipe(
Effect.provide(
Expand Down Expand Up @@ -135,6 +136,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
subject: "one-time-token",
label: "CI phone",
});
// An app approval code is never listed.
yield* environmentAuth.issuePairingCredential({ access: "auto" });
const listedBeforeRevoke = yield* environmentAuth.listPairingLinks();
const revoked = yield* environmentAuth.revokePairingLink(created.id);
const listedAfterRevoke = yield* environmentAuth.listPairingLinks();
Expand Down
87 changes: 86 additions & 1 deletion apps/server/src/auth/McpOAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
AuthStandardClientScopes,
type AuthCreatePairingCredentialInput,
EnvironmentHttpApi,
MCP_PEER_LINK_SOFTWARE_ID,
mcpClientScopes,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
Expand Down Expand Up @@ -53,7 +54,7 @@ const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Servic
Layer.provide(
McpOAuthHttp.layer.pipe(
Layer.provide(McpOAuth.layer),
Layer.provide(ServerSettings.layerTest()),
Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
),
),
Layer.provide(AuthHttp.layerAuthenticatedAuth),
Expand Down Expand Up @@ -509,6 +510,90 @@ it.live("a code minted with an access level's scopes approves that access", () =
),
);

it.live("an app approval code approves only an app sign-in, at its own level", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const params = authorizeParams(clientId);
const issued = yield* auth.issuePairingCredential({ access: "approval-required" });
expect(issued.access).toBe("approval-required");
const code = issued.credential;
expect(code).toMatch(/^SUPERVISED-[2-9A-HJ-NP-Z]{12}$/);

// Signing in a browser, a token exchange and linking all refuse it and leave it unspent.
const browser = yield* handler(
at("/api/auth/browser-session", {
method: "POST",
headers: { "content-type": "application/json" },
body: encodeJson({ credential: code }),
}),
);
expect(browser.status).toBe(401);
const exchanged = yield* auth
.exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "bot" })
.pipe(Effect.flip);
expect(exchanged._tag).toBe("ServerAuthInvalidCredentialError");
const peer = yield* handler(
at("/oauth/mcp/register", {
method: "POST",
headers: { "content-type": "application/json" },
body: encodeJson({
client_name: "Studio",
software_id: MCP_PEER_LINK_SOFTWARE_ID,
redirect_uris: [REDIRECT],
}),
}),
).pipe(Effect.flatMap(json<{ client_id: string }>));
const linked = yield* decide(handler, authorizeParams(peer.client_id), {
_tag: "pairing-code",
access: "approval-required",
code,
});
expect(linked.status).toBe(400);

// Supervised and Auto share scopes, so only the code's own level may spend it.
const otherLevel = yield* decide(handler, params, {
_tag: "pairing-code",
access: "auto",
code,
});
expect(otherLevel.status).toBe(400);

const approved = yield* decide(handler, params, {
_tag: "pairing-code",
access: "approval-required",
code: code.toLowerCase(),
});
expect(approved.status).toBe(200);
const token = yield* handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code: new URL(approved.redirectTo!).searchParams.get("code")!,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: verifier,
}),
),
).pipe(Effect.flatMap(json<{ access_token: string }>));
const signedIn = yield* auth.authenticateMcpClient(
HttpServerRequest.fromWeb(
at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
),
);
expect(signedIn.access).toBe("approval-required");
expect(
(yield* decide(handler, params, {
_tag: "pairing-code",
access: "approval-required",
code,
})).status,
).toBe(400);
}),
),
);

it.live("one-click approves only access the browser session holds the scopes for", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
Expand Down
14 changes: 11 additions & 3 deletions apps/server/src/auth/McpOAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
AuthOrchestrationReadScope,
MCP_PEER_LINK_SOFTWARE_ID,
mcpClientScopes,
parseMcpApprovalCode,
type RuntimeMode,
} from "@t3tools/contracts";
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
Expand Down Expand Up @@ -447,8 +448,15 @@ const make = Effect.gen(function* () {

const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {
const { decision } = input;
let access = decision.access;
if (decision._tag === "pairing-code") {
yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
// An approval code is for one app's sign-in, never for linking another environment.
if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) {
return yield* new McpOAuthPageError({
description: "Linking needs a plain pairing code, not an app approval code.",
});
}
access = yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
Effect.logError("MCP approval code check failed.", { cause }).pipe(
Effect.andThen(
Expand All @@ -473,10 +481,10 @@ const make = Effect.gen(function* () {
});
}
}
const code = yield* mintCode(input.authorization, decision.access);
const code = yield* mintCode(input.authorization, access);
yield* Effect.logInfo("Approved an MCP client sign-in.", {
client: input.authorization.client.name,
access: decision.access,
access,
method: decision._tag,
});
return redirectWith(input.authorization.redirectUri, {
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/auth/PairingGrantStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
Stream.runForEach((change) => Queue.offer(changes, change)),
Effect.forkScoped({ startImmediately: true }),
);
// An app approval code sends no update, issued or spent; the next belongs to a plain code.
const approval = yield* grants.issueOneTimeToken({ mcpApproval: "auto" });
yield* grants.consume(approval.credential, { mcpApproval: "auto" });
for (const input of [{}, { label: "Synthetic phone" }]) {
const issued = yield* grants.issueOneTimeToken(input);
const change = yield* Queue.take(changes);
Expand Down
Loading
Loading