diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index bf9eccee8c51b..4bdbd8cec2bac 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -269,6 +269,12 @@ const PAIRING_TOKEN_PATTERN = new RegExp( "i", ); +/** Only credentials in the issued pairing-code formats are case-insensitive. */ +export const normalizePairingCredential = (credential: string) => + PAIRING_TOKEN_PATTERN.test(credential) + ? credential.toUpperCase() + : (parseMcpApprovalCode(credential)?.code ?? credential); + const make = Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; const config = yield* ServerConfig.ServerConfig; @@ -560,10 +566,7 @@ const make = Effect.gen(function* () { return yield* seededResult.error; } - // Only credentials in the issued pairing-code formats are case-insensitive. - const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential) - ? credential.toUpperCase() - : (parseMcpApprovalCode(credential)?.code ?? credential); + const pairingCredential = normalizePairingCredential(credential); // Check scopes in the UPDATE so rejected requests cannot spend one-time links. const consumed = yield* pairingLinks diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index 869c085cbad2b..f01db7e5f7039 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -17,6 +17,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as PeerLinks from "../peer/PeerLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -35,6 +36,7 @@ const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* ({ links: Context.get(context, PeerLinks.PeerLinks), + auth: Context.get(context, EnvironmentAuth.EnvironmentAuth), peer: Context.get(context, PeerMcpClient.PeerMcpClient), sql: Context.get(context, SqlClient.SqlClient), settings: Context.get(context, ServerSettings.ServerSettingsService), @@ -207,6 +209,30 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect( + "a pairing code this environment issued is refused by name and never sent to the peer", + () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveB(box); + const a = yield* makeA(laptop); + const own = yield* a.auth.issuePairingCredential(); + + for (const pairingCode of [own.credential, ` ${own.credential.toLowerCase()} `]) { + const refused = yield* a.links + .link({ url: b.url, pairingCode, access: "read-only" }) + .pipe(Effect.flip); + expect(refused.reason).toBe("pairing_rejected"); + expect(refused.message).toContain("Laptop"); + expect(refused.message).toContain("Box"); + } + expect((yield* Ref.get(b.paths)).filter((path) => path.startsWith("/oauth/mcp/"))).toEqual( + [], + ); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect( "each machine's Linked environments beta gates links, and a link waits while it is off", () => diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts index 9fa7b74d340c6..98be4ffb77c8c 100644 --- a/apps/server/src/peer/PeerLinks.testkit.ts +++ b/apps/server/src/peer/PeerLinks.testkit.ts @@ -70,6 +70,7 @@ export const servePeer = ( const descriptor = yield* Ref.make(initial); const bearers = yield* Ref.make>([]); const probes = yield* Ref.make(0); + const paths = yield* Ref.make>([]); const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, { getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)), getDescriptor: Ref.get(descriptor), @@ -89,6 +90,7 @@ export const servePeer = ( (httpEffect) => Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; + yield* Ref.update(paths, (seen) => [...seen, request.url]); if (request.url.startsWith("/.well-known/t3/environment")) { yield* Ref.update(probes, (count) => count + 1); } @@ -154,6 +156,8 @@ export const servePeer = ( bearers, /** How often its descriptor was asked for, as a probe of whether it answers. */ probes, + /** Every path it was asked for, in order. */ + paths, /** The sessions linking created there, which its Connections lists. */ linkedSessions: auth .listSessions() @@ -168,8 +172,9 @@ export const servePeer = ( export type ServedPeer = Effect.Success>; /** - * The environment that links: its own database and secret store, reaching - * peers over plain HTTP. Provide it to anything built on its links. + * The environment that links: its own database, secret store and pairing + * codes, reaching peers over plain HTTP. Provide it to anything built on its + * links. */ export const layerLinkingEnvironment = ( descriptor: ExecutionEnvironmentDescriptor, @@ -181,6 +186,11 @@ export const layerLinkingEnvironment = ( ) => PeerMcpClient.layer.pipe( Layer.provideMerge(PeerLinks.layer), + Layer.provideMerge( + EnvironmentAuth.layer.pipe( + Layer.provide(Layer.mergeAll(ManagedPolicy.layerTest(), ServerEnvironment.layerIdentity)), + ), + ), Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })), Layer.provideMerge(database), Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)), diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index f52faecfcc3e2..60c01e0983926 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -34,8 +34,10 @@ import * as HttpApi from "effect/http-api/HttpApi"; import * as HttpApiClient from "effect/http-api/HttpApiClient"; import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification"; +import { normalizePairingCredential } from "../auth/PairingGrantStore.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier) @@ -194,6 +196,7 @@ const make = Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; const environment = yield* ServerEnvironment.ServerEnvironment; const serverSettings = yield* ServerSettings.ServerSettingsService; + const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository; const enabled = serverSettings.getSettings.pipe( Effect.map((settings) => settings.linkedEnvironmentsEnabled), Effect.orElseSucceed(() => false), @@ -480,6 +483,19 @@ const make = Effect.gen(function* () { message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, }); } + // A code issued here, even a used or expired one, must not reach the peer. + const issuedHere = yield* pairingLinks + .getByCredential({ credential: normalizePairingCredential(input.pairingCode.trim()) }) + .pipe(Effect.catch(failStorage)); + if (Option.isSome(issuedHere)) { + return yield* new PeerLinkError({ + reason: "pairing_rejected", + message: + self.label === peer.label + ? `That pairing code was created on this environment, not on the ${peer.label} at ${primary}. Create the link there and paste its code here.` + : `That pairing code was created on ${self.label}, not on ${peer.label}. Create the link on ${peer.label} and paste its code here.`, + }); + } const issued = yield* signIn(primary, input, `T3 Code ยท ${self.label}`); const now = yield* DateTime.now; const linked: PeerLink = {