diff --git a/.github/workflows/fork-principals.yml b/.github/workflows/fork-principals.yml new file mode 100644 index 0000000000000..1f1dd255d721f --- /dev/null +++ b/.github/workflows/fork-principals.yml @@ -0,0 +1,47 @@ +# Fork-only qualification for the multi-user principals branch. Upstream's +# ci.yml needs Blacksmith runners, which this fork does not have, so this one +# job runs typecheck and the full contracts and server suites on a hosted runner. +name: Fork principals + +on: + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: fork-principals-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +jobs: + server: + if: github.repository == 'caniko/t3code' + name: Typecheck and test (contracts, server) + runs-on: ubuntu-24.04 + timeout-minutes: 45 + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: "1" + steps: + - uses: actions/checkout@v6 + with: + sparse-checkout: | + /* + !/.repos/ + !/apps/mobile/modules/t3-terminal/Vendor/**/*.a + sparse-checkout-cone-mode: false + + - uses: ./.github/actions/setup-ci-deps + + - name: Install Chromium for server browser tests + run: node apps/web/node_modules/playwright/cli.js install --with-deps --only-shell chromium + + - name: Typecheck + run: vp run --filter @t3tools/contracts --filter t3 typecheck + + - name: Test contracts + run: vp run --filter @t3tools/contracts test + + - name: Test server + run: vp run --filter t3 test diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 20efa88f3b096..4aa889d4a966d 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -2,7 +2,11 @@ import * as NodeCrypto from "node:crypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { authScopeResponse, AuthStandardClientScopes } from "@t3tools/contracts"; +import { + authScopeResponse, + AuthPrincipalScopes, + AuthStandardClientScopes, +} from "@t3tools/contracts"; import { computeDpopAccessTokenHash, computeDpopJwkThumbprint, @@ -420,6 +424,40 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => { }).pipe(Effect.provide(layerEnvironmentAuth())), ); + it.effect( + "caps a principal's credentials at orchestration scopes and keeps them out of MCP", + () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const link = yield* serverAuth.createPairingLink({ principal: "alice" }); + expect(link).toMatchObject({ + subject: "principal:alice", + scopes: AuthPrincipalScopes, + }); + const session = yield* serverAuth.issueSession({ principal: "alice" }); + expect(session).toMatchObject({ subject: "principal:alice", scopes: AuthPrincipalScopes }); + + const tooWide = ["orchestration:read", "terminal:operate"] as const; + expect( + yield* serverAuth + .createPairingLink({ principal: "alice", scopes: tooWide }) + .pipe(Effect.flip), + ).toMatchObject({ _tag: "ServerAuthScopeNotGrantedError" }); + expect( + yield* serverAuth.issueSession({ principal: "alice", scopes: tooWide }).pipe(Effect.flip), + ).toMatchObject({ _tag: "ServerAuthScopeNotGrantedError" }); + expect( + yield* serverAuth + .issueSession({ subject: "principal:alice", scopes: tooWide }) + .pipe(Effect.flip), + ).toMatchObject({ _tag: "ServerAuthScopeNotGrantedError" }); + + expect( + yield* serverAuth.consumeMcpApprovalCode(link.credential, "read-only").pipe(Effect.flip), + ).toMatchObject({ _tag: "ServerAuthMcpApprovalCodeError", reason: "not_a_pairing_code" }); + }).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 ffc2a0a1ebd57..90edeafa32fe1 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -2,7 +2,11 @@ import { AuthAccessTokenType, AuthAccessWriteScope, AuthOrchestrationOperateScope, + AuthPrincipalScopes, AuthStandardClientScopes, + DEFAULT_PRINCIPAL_ID, + principalOfSubject, + principalSubject, type AuthAccessTokenResult, type AuthBrowserSessionResult, type AuthClientMetadata, @@ -482,9 +486,13 @@ export class EnvironmentAuth extends Context.Service< readonly label?: string; readonly scopes?: ReadonlyArray; readonly subject?: string; + readonly principal?: string; readonly proofKeyThumbprint?: string; readonly purpose?: "startup"; - }) => Effect.Effect; + }) => Effect.Effect< + IssuedPairingLink, + ServerAuthInternalError | ServerAuthScopeNotGrantedError + >; readonly issuePairingCredential: ( input?: AuthCreatePairingCredentialInput, ) => Effect.Effect; @@ -499,9 +507,13 @@ export class EnvironmentAuth extends Context.Service< readonly issueSession: (input?: { readonly ttl?: Duration.Duration; readonly subject?: string; + readonly principal?: string; readonly scopes?: ReadonlyArray; readonly label?: string; - }) => Effect.Effect; + }) => Effect.Effect< + IssuedBearerSession, + ServerAuthInternalError | ServerAuthScopeNotGrantedError + >; readonly listSessions: () => Effect.Effect< ReadonlyArray, ServerAuthInternalError @@ -1016,6 +1028,7 @@ export const make = Effect.gen(function* () { ...(input.label ? { label: input.label } : {}), ...(input.purpose ? { purpose: input.purpose } : {}), }).pipe( + Effect.catchTags({ ServerAuthScopeNotGrantedError: Effect.die }), Effect.map( (issued) => ({ @@ -1027,14 +1040,39 @@ export const make = Effect.gen(function* () { ), ); + const resolveIssuance = ( + input: + | { + readonly subject?: string; + readonly principal?: string; + readonly scopes?: ReadonlyArray; + } + | undefined, + fallbackSubject: string, + ): Effect.Effect< + { readonly subject: string; readonly scopes: ReadonlyArray }, + ServerAuthScopeNotGrantedError + > => { + const subject = + input?.principal === undefined || input.principal === DEFAULT_PRINCIPAL_ID + ? (input?.subject ?? fallbackSubject) + : principalSubject(input.principal); + const isPrincipal = principalOfSubject(subject) !== DEFAULT_PRINCIPAL_ID; + const scopes = input?.scopes ?? (isPrincipal ? AuthPrincipalScopes : AuthStandardClientScopes); + return isPrincipal && !scopes.every((scope) => AuthPrincipalScopes.some((own) => own === scope)) + ? Effect.fail(new ServerAuthScopeNotGrantedError({})) + : Effect.succeed({ subject, scopes }); + }; + const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn( "EnvironmentAuth.createPairingLink", )( function* (input) { + const { subject, scopes } = yield* resolveIssuance(input, "one-time-token"); const createdAt = yield* DateTime.now; const issued = yield* bootstrapCredentials.issueOneTimeToken({ - scopes: input?.scopes ?? AuthStandardClientScopes, - subject: input?.subject ?? "one-time-token", + scopes, + subject, ...(input?.ttl ? { ttl: input.ttl } : {}), ...(input?.label ? { label: input.label } : {}), ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}), @@ -1043,14 +1081,18 @@ export const make = Effect.gen(function* () { return { id: issued.id, credential: issued.credential, - scopes: input?.scopes ?? AuthStandardClientScopes, - subject: input?.subject ?? "one-time-token", + scopes, + subject, ...(issued.label ? { label: issued.label } : {}), createdAt: DateTime.toUtc(createdAt), expiresAt: DateTime.toUtc(issued.expiresAt), } satisfies IssuedPairingLink; }, - Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })), + Effect.mapError((cause) => + cause._tag === "ServerAuthScopeNotGrantedError" + ? cause + : new ServerAuthPairingLinkCreationError({ cause }), + ), ); const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) => @@ -1077,33 +1119,37 @@ export const make = Effect.gen(function* () { ); const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => - sessions - .issue({ - subject: input?.subject ?? DEFAULT_SESSION_SUBJECT, - method: "bearer-access-token", - scopes: input?.scopes ?? AuthStandardClientScopes, - client: { - ...(input?.label ? { label: input.label } : {}), - deviceType: "bot", - }, - ...(input?.ttl ? { ttl: input.ttl } : {}), - }) - .pipe( - Effect.map( - (issued) => - ({ - sessionId: issued.sessionId, - token: issued.token, - method: "bearer-access-token", - scopes: issued.scopes, - subject: input?.subject ?? DEFAULT_SESSION_SUBJECT, - client: issued.client, - expiresAt: DateTime.toUtc(issued.expiresAt), - }) satisfies IssuedBearerSession, - ), - Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })), - Effect.withSpan("EnvironmentAuth.issueSession"), - ); + resolveIssuance(input, DEFAULT_SESSION_SUBJECT).pipe( + Effect.flatMap(({ subject, scopes }) => + sessions + .issue({ + subject, + method: "bearer-access-token", + scopes, + client: { + ...(input?.label ? { label: input.label } : {}), + deviceType: "bot", + }, + ...(input?.ttl ? { ttl: input.ttl } : {}), + }) + .pipe( + Effect.map( + (issued) => + ({ + sessionId: issued.sessionId, + token: issued.token, + method: "bearer-access-token", + scopes: issued.scopes, + subject, + client: issued.client, + expiresAt: DateTime.toUtc(issued.expiresAt), + }) satisfies IssuedBearerSession, + ), + Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })), + ), + ), + Effect.withSpan("EnvironmentAuth.issueSession"), + ); const listSessions: EnvironmentAuth["Service"]["listSessions"] = () => sessions.listActive().pipe( @@ -1359,7 +1405,8 @@ export const make = Effect.gen(function* () { Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })), }), Effect.flatMap((grant) => - grant.method !== "one-time-token" && grant.method !== "reusable-dev-token" + (grant.method !== "one-time-token" && grant.method !== "reusable-dev-token") || + principalOfSubject(grant.subject) !== DEFAULT_PRINCIPAL_ID ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" })) : Effect.void, ), diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 8044740a7e2ee..73a5ec823b18e 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -5,6 +5,7 @@ import { AuthProvidersManageScope, AuthSettingsWriteScope, DEFAULT_SERVER_SETTINGS, + ORCHESTRATION_V2_WS_METHODS, ProviderDriverKind, ProviderInstanceId, SecretProviderId, @@ -401,3 +402,54 @@ it.effect("denies manual cleanup before the handler without settings permission" expect(handled).toBe(false); }).pipe(Effect.scoped), ); + +describe("principal RPC allowlist", () => { + const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const; + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + (tag): tag is Exclude => + !(tested as ReadonlyArray).includes(tag), + ), + ); + + it("keeps only allowlisted methods and gives owner-only methods no principal path", () => { + expect(RpcAuthorization.PRINCIPAL_RPC_METHODS.has(WS_METHODS.serverProbe)).toBe(true); + for (const method of [ + ORCHESTRATION_V2_WS_METHODS.launchThread, + ORCHESTRATION_V2_WS_METHODS.searchThread, + ORCHESTRATION_V2_WS_METHODS.searchThreadStream, + ]) { + expect(RpcAuthorization.PRINCIPAL_RPC_METHODS.has(method)).toBe(true); + } + for (const method of RpcAuthorization.PRINCIPAL_RPC_METHODS) { + expect(Object.hasOwn(RPC_REQUIRED_SCOPES, method)).toBe(true); + } + expect(RpcAuthorization.PRINCIPAL_RPC_METHODS.has(WS_METHODS.terminalOpen)).toBe(false); + }); + + it.effect("rejects other methods for a principal before scope checks or the handler", () => + Effect.gen(function* () { + const handled: Array = []; + const client = yield* RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.mergeAll( + group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})), + group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () => + Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)), + ), + RpcAuthorization.layer( + [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope], + undefined, + "alice", + ), + ), + ), + ); + expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({}); + expect( + yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip), + ).toMatchObject({ _tag: "EnvironmentAuthorizationError" }); + expect(handled).toEqual([]); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 6049121b41a5d..a5bc751596bdb 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -1,5 +1,6 @@ import { CLIENT_GUARDED_RPC_SCOPES, + DEFAULT_PRINCIPAL_ID, type DeviceListInput, clientRpcRequiredScopes, authScopeRequiredResponse, @@ -272,6 +273,24 @@ const requiredScopesForRpcCall = ( return [requiredScopeForRpcMethod(method)]; }; +/** Everything else stays denied to a non-default principal: those methods act as the server's OS user or across all workspaces. */ +export const PRINCIPAL_RPC_METHODS: ReadonlySet = new Set([ + ORCHESTRATION_V2_WS_METHODS.subscribeShell, + ORCHESTRATION_V2_WS_METHODS.subscribeThread, + ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + ORCHESTRATION_V2_WS_METHODS.launchThread, + ORCHESTRATION_V2_WS_METHODS.searchThread, + ORCHESTRATION_V2_WS_METHODS.searchThreadStream, + ORCHESTRATION_V2_WS_METHODS.getThreadProjection, + ORCHESTRATION_V2_WS_METHODS.getTurnItem, + ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads, + ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, + WS_METHODS.serverProbe, + WS_METHODS.serverGetConfig, + WS_METHODS.subscribeServerConfig, + WS_METHODS.subscribeServerLifecycle, +]); + /** * `onAuthorized` runs once after an authorized request succeeds; for a stream * RPC, that is when the stream completes. Every RPC passes through here, so it @@ -280,8 +299,17 @@ const requiredScopesForRpcCall = ( export const layer = ( scopes: ReadonlyArray, onAuthorized?: (method: string, payload: unknown) => Effect.Effect, + principal: string = DEFAULT_PRINCIPAL_ID, ) => Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => { + if (principal !== DEFAULT_PRINCIPAL_ID && !PRINCIPAL_RPC_METHODS.has(rpc._tag)) { + return Effect.fail( + new EnvironmentAuthorizationError({ + message: `RPC method ${rpc._tag} is not available to this principal.`, + ...authScopeRequiredResponse(requiredScopeForRpcMethod(rpc._tag)), + }), + ); + } const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload); const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope)); if (requiredScope !== undefined) return Effect.fail(rpcAuthorizationError(requiredScope)); diff --git a/apps/server/src/auth/http.test.ts b/apps/server/src/auth/http.test.ts index 325f0f991e9c2..216fa7aeb28fb 100644 --- a/apps/server/src/auth/http.test.ts +++ b/apps/server/src/auth/http.test.ts @@ -2,6 +2,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { AuthTokenExchangeGrantType, AuthEnvironmentBootstrapTokenType, + AuthSessionId, + EnvironmentAuthenticatedPrincipal, + type AuthEnvironmentScope, AuthAccessTokenType, EnvironmentHttpApi, } from "@t3tools/contracts"; @@ -155,3 +158,21 @@ it.effect("sets the selected browser session cookies through the HTTP route", () ); }).pipe(Effect.provide(NodeServices.layer)), ); + +it.effect("fails closed on ordinary scoped routes for a non-default principal", () => + Effect.gen(function* () { + const requireAs = (subject: string) => + AuthHttp.requireEnvironmentScope("orchestration:read").pipe( + Effect.provideService(EnvironmentAuthenticatedPrincipal, { + sessionId: AuthSessionId.make("test-session"), + subject, + method: "bearer-access-token", + scopes: new Set(["orchestration:read"]), + }), + ); + expect((yield* requireAs("principal:alice").pipe(Effect.flip))._tag).toBe( + "EnvironmentScopeRequiredError", + ); + expect((yield* requireAs("browser")).subject).toBe("browser"); + }), +); diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index e570be1b4793a..e76060bebb6a7 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -1,5 +1,7 @@ import { authScopeRequiredResponse, + DEFAULT_PRINCIPAL_ID, + principalOfSubject, AuthAccessWriteScope, AuthStandardClientScopes, AuthGrantScope, @@ -17,7 +19,7 @@ import { EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, } from "@t3tools/contracts"; -import type { AuthEnvironmentScope, DpopFailureReason } from "@t3tools/contracts"; +import type { AuthEnvironmentScope, DpopFailureReason, ThreadId } from "@t3tools/contracts"; import { parseOAuthScope } from "@t3tools/shared/oauthScope"; import { causeErrorTag } from "@t3tools/shared/observability"; import * as Clock from "effect/Clock"; @@ -31,6 +33,7 @@ import { HttpServerRequest, HttpServerResponse } from "effect/http"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import { threadVisibleTo } from "../orchestration-v2/ThreadOwnership.ts"; import * as SessionStore from "./SessionStore.ts"; import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts"; import { deriveAuthClientMetadata } from "./utils.ts"; @@ -177,7 +180,7 @@ export const authenticateMediaRequest = }), ), ); - if (!session.scopes.includes(requiredScope)) { + if (!session.scopes.includes(requiredScope) || !isDefaultPrincipal(session.subject)) { return yield* failEnvironmentScopeRequired(requiredScope); } return session; @@ -214,16 +217,47 @@ const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateT ), ); +/** Non-default principals reach only routes that filter by owner; every other route fails closed for them. */ +export const isDefaultPrincipal = (subject: string) => + principalOfSubject(subject) === DEFAULT_PRINCIPAL_ID; + +export const requireEnvironmentScopeForPrincipal = Effect.fn( + "environment.auth.requireScopeForPrincipal", +)(function* (scope: AuthEnvironmentScope) { + const session = yield* EnvironmentAuthenticatedPrincipal; + if (!session.scopes.has(scope)) { + return yield* failEnvironmentScopeRequired(scope); + } + return session; +}); + export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* ( scope: AuthEnvironmentScope, ) { - const session = yield* EnvironmentAuthenticatedPrincipal; - if (!session.scopes.has(scope)) { + const session = yield* requireEnvironmentScopeForPrincipal(scope); + if (!isDefaultPrincipal(session.subject)) { return yield* failEnvironmentScopeRequired(scope); } return session; }); +/** Not-found rather than forbidden, so another principal's thread is indistinguishable from a missing one. */ +export const requireThreadAccess = Effect.fn("environment.auth.requireThreadAccess")(function* ( + scope: AuthEnvironmentScope, + threadId: ThreadId, + readOwner: ( + threadId: ThreadId, + ) => Effect.Effect<{ readonly ownerPrincipal?: string | undefined } | null>, +) { + const session = yield* requireEnvironmentScopeForPrincipal(scope); + if (isDefaultPrincipal(session.subject)) return session; + const thread = yield* readOwner(threadId); + if (thread === null || !threadVisibleTo(principalOfSubject(session.subject), thread)) { + return yield* failEnvironmentNotFound("thread_not_found"); + } + return session; +}); + export const layerAuthenticatedAuth = Layer.effect( EnvironmentAuthenticatedAuth, Effect.gen(function* () { diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.ts index b75fba88bddc3..a7e34e4e19f73 100644 --- a/apps/server/src/cli/auth.ts +++ b/apps/server/src/cli/auth.ts @@ -1,4 +1,9 @@ -import { AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts"; +import { + type AuthGrantScope, + AuthSessionId, + AuthStandardClientScopes, + PrincipalId, +} from "@t3tools/contracts"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -68,6 +73,25 @@ const subjectFlag = Flag.String("subject").pipe( Flag.optional, ); +const principalFlag = Flag.String("principal").pipe( + Flag.withSchema(PrincipalId), + Flag.withDescription( + "Bind the credential to a principal that sees only its own threads; limited to orchestration scopes.", + ), + Flag.optional, +); + +// The flag substitutes the standard set when no scope is given; a principal then falls back to its own default. +const scopeInput = (flags: { + readonly scopes: ReadonlyArray; + readonly principal: Option.Option; +}) => + Option.isSome(flags.principal) && + flags.scopes.length === AuthStandardClientScopes.length && + AuthStandardClientScopes.every((scope) => flags.scopes.includes(scope)) + ? {} + : { scopes: flags.scopes }; + const baseUrlFlag = Flag.String("base-url").pipe( Flag.withSchema( Schema.URLFromString.pipe( @@ -92,6 +116,7 @@ const pairingCreateCommand = Command.make("create", { scopes: authScopesFlag(AuthStandardClientScopes), ttl: ttlFlag, label: labelFlag, + principal: principalFlag, baseUrl: baseUrlFlag, json: jsonFlag, }).pipe( @@ -102,8 +127,9 @@ const pairingCreateCommand = Command.make("create", { (environmentAuth) => Effect.gen(function* () { const issued = yield* environmentAuth.createPairingLink({ - scopes: flags.scopes, + ...scopeInput(flags), subject: "one-time-token", + ...(Option.isSome(flags.principal) ? { principal: flags.principal.value } : {}), ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}), }); @@ -172,6 +198,7 @@ const sessionIssueCommand = Command.make("issue", { ttl: ttlFlag, label: labelFlag, subject: subjectFlag, + principal: principalFlag, tokenOnly: tokenOnlyFlag, json: jsonFlag, }).pipe( @@ -182,10 +209,11 @@ const sessionIssueCommand = Command.make("issue", { (environmentAuth) => Effect.gen(function* () { const issued = yield* environmentAuth.issueSession({ - scopes: flags.scopes, + ...scopeInput(flags), ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}), ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}), + ...(Option.isSome(flags.principal) ? { principal: flags.principal.value } : {}), }); yield* Console.log( formatIssuedSession(issued, { diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts index 99530612463e1..ae318a2b86825 100644 --- a/apps/server/src/cloud/CloudLink.ts +++ b/apps/server/src/cloud/CloudLink.ts @@ -1577,13 +1577,15 @@ const make = Effect.gen(function* () { } const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets); - const issued = yield* environmentAuth.createPairingLink({ - scopes: AuthStandardClientScopes, - subject: "cloud-connect", - ttl: Duration.minutes(2), - label: "T3 Connect connect", - proofKeyThumbprint: proof.clientProofKeyThumbprint, - }); + const issued = yield* environmentAuth + .createPairingLink({ + scopes: AuthStandardClientScopes, + subject: "cloud-connect", + ttl: Duration.minutes(2), + label: "T3 Connect connect", + proofKeyThumbprint: proof.clientProofKeyThumbprint, + }) + .pipe(Effect.catchTags({ ServerAuthScopeNotGrantedError: Effect.die })); const responsePayload = { iss: `t3-env:${environmentId}`, aud: normalizeRelayIssuer(relayIssuer), diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index e792a233c6f06..350c4d07985c9 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -46,6 +46,7 @@ import { failEnvironmentScopeRequired, failEnvironmentAuthInvalid, failEnvironmentInternal, + isDefaultPrincipal, } from "./auth/http.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import { WEBHOOK_ROUTE_PREFIX } from "./scheduledTasks/ScheduledTaskService.ts"; @@ -306,7 +307,7 @@ const authenticateRawRouteWithScope = failEnvironmentInternal("internal_error", error), ), ); - if (!session.scopes.includes(scope)) { + if (!session.scopes.includes(scope) || !isDefaultPrincipal(session.subject)) { return yield* failEnvironmentScopeRequired(scope); } }); diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index b82d9bb5ae59c..7b3dc62b0d11c 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -28,9 +28,12 @@ import { assertFullAccess, assertLiveCaller, assertTargetWithinLimits, + assertThreadOwnedByCallerPrincipal, type Caller, + callerPrincipal, loadCaller, readCaller, + threadNotFound, unavailable, } from "./threadAccess.ts"; @@ -187,6 +190,9 @@ export const writesThreads = ( .getThreadShell(threadId) .pipe(Effect.mapError(unavailable)); if (target !== null && target.deletedAt === null) { + yield* assertThreadOwnedByCallerPrincipal(callerPrincipal(caller), target, () => + threadNotFound(caller.threads, threadId, "The thread was not found."), + ); yield* assertTargetWithinLimits(caller.limits, target); yield* assertSameLink(caller, target); } diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 47a6bda166ce1..f794aa4cd9146 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3253,16 +3253,25 @@ describe("OrchestratorMcpService thread list", () => { shell("thread:a-snoozed", "project:a", true), shell("thread:a-awake", "project:a", false), shell("thread:b-snoozed", "project:b", true), + { ...shell("thread:alice-snoozed", "project:a", true), ownerPrincipal: "alice" }, ]; const service = layerOrchestratorService.pipe( Layer.provide( Layer.mergeAll( NodeServices.layer, Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadShell: (threadId) => + Effect.succeed(shells.find((thread) => thread.id === threadId) ?? null), + getProjectThreadRecords: (input) => + Effect.succeed({ + thread: shells.find((thread) => thread.id === input.threadId), + } as never), listProjectThreads: (input) => Effect.succeed( shells.filter( - (thread) => input.projectId === undefined || thread.projectId === input.projectId, + (thread) => + (input.projectId === undefined || thread.projectId === input.projectId) && + (thread.ownerPrincipal ?? "owner") === input.ownerPrincipal, ), ), }), @@ -3295,6 +3304,17 @@ describe("OrchestratorMcpService thread list", () => { ["thread:b-snoozed", "project:b"], ], ); + assert.equal(listed.total, 2); + }).pipe(Effect.provide(service)), + ); + + it.effect("refuses to wait on another principal's thread as if it were missing", () => + Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + const error = yield* mcp + .waitForThread(client, { threadId: ThreadId.make("thread:alice-snoozed") }) + .pipe(Effect.flip); + assert.equal(error.code, "thread_not_found"); }).pipe(Effect.provide(service)), ); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index b124a03ea2c40..b820208229154 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,5 +1,6 @@ import { CommandId, + DEFAULT_PRINCIPAL_ID, type RunId, isProviderAvailable, MessageId, @@ -117,7 +118,11 @@ import { runtimeModeRank, taskPrompt, } from "./delegatedTaskModes.ts"; -import { isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; +import { + assertThreadOwnedByCallerPrincipal, + isLiveCallerShell, + threadNotFound, +} from "./threadAccess.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; @@ -1179,6 +1184,11 @@ const make = Effect.gen(function* () { caller.parent !== undefined && threadId === caller.parent.thread.id ? caller.parent : yield* loadTargetThread(threadId, includeHistory); + yield* assertThreadOwnedByCallerPrincipal( + caller.parent?.thread.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID, + target.thread, + () => threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`), + ); return { ...caller, target } as const; }); @@ -1244,6 +1254,12 @@ const make = Effect.gen(function* () { `Thread ${threadId} is no longer available.`, ); } + yield* assertThreadOwnedByCallerPrincipal( + parent?.thread.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID, + shell, + () => + threadNotFound(threadManagement, threadId, `Thread ${threadId} is no longer available.`), + ); const input = { projectId: shell.projectId, threadId }; // Transfers are needed only to acknowledge a caller's child-task result. const records = @@ -2803,6 +2819,9 @@ const make = Effect.gen(function* () { ...(parent.thread.linkOrigin === undefined ? {} : { linkOrigin: parent.thread.linkOrigin }), + ...(parent.thread.ownerPrincipal === undefined + ? {} + : { ownerPrincipal: parent.thread.ownerPrincipal }), }) .pipe( Effect.mapError((error) => @@ -2902,6 +2921,7 @@ const make = Effect.gen(function* () { .listProjectThreads({ projectId: projectId ?? undefined, includeSubagents: input.includeSubagents !== false, + ownerPrincipal: parent?.thread.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID, }) .pipe( Effect.mapError((error) => diff --git a/apps/server/src/mcp/threadAccess.test.ts b/apps/server/src/mcp/threadAccess.test.ts index aa107711f334e..477767dfd80ab 100644 --- a/apps/server/src/mcp/threadAccess.test.ts +++ b/apps/server/src/mcp/threadAccess.test.ts @@ -38,3 +38,45 @@ it.effect("points a bare uuid at the mcp: thread it belongs to", () => expect(error.message).toBe(`The thread was not found. Did you mean \`mcp:${bareId}\`?`); }), ); + +it.effect.each([ + { caller: undefined, owner: "alice", visible: false }, + { caller: "alice", owner: undefined, visible: false }, + { caller: "alice", owner: "alice", visible: true }, +])( + "hides a thread of another principal from $caller callers like a missing one", + ({ caller, owner, visible }) => + Effect.gen(function* () { + const target = ThreadId.make("thread:owned"); + const callerThread = ThreadId.make("thread:caller"); + const shells = new Map([ + [ + target, + { ...liveThreadShell(target), ...(owner === undefined ? {} : { ownerPrincipal: owner }) }, + ], + [ + callerThread, + { + ...liveThreadShell(callerThread), + ...(caller === undefined ? {} : { ownerPrincipal: caller }), + }, + ], + ]); + const result = yield* readThread(target).pipe( + Effect.result, + Effect.provideService(McpInvocationContext.McpInvocationContext, { + ...client, + thread: caller === undefined ? undefined : { threadId: callerThread }, + } as McpInvocationContext.McpInvocationScope), + Effect.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null), + getProjectThreadRecords: () => Effect.succeed({ thread: shells.get(target) } as never), + }), + ), + ); + expect(result._tag).toBe(visible ? "Success" : "Failure"); + if (!visible && result._tag === "Failure") + expect(result.failure.code).toBe("thread_not_found"); + }), +); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index ca8b373ba92ca..dbd089ec5ab58 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -1,6 +1,7 @@ import type { ProjectionRecordField } from "../orchestration-v2/ProjectionStore.ts"; import { CommandId, + DEFAULT_PRINCIPAL_ID, OrchestratorMcpFailure, type ProjectId, type ProviderInstanceId, @@ -15,6 +16,7 @@ import * as Effect from "effect/Effect"; import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts"; +import { threadVisibleTo } from "../orchestration-v2/ThreadOwnership.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; /** @@ -38,6 +40,17 @@ export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound") }); }); +/** An agent acts as its thread's owner; a client outside any thread acts as the default principal. */ +export const callerPrincipal = (caller: Pick) => + caller.caller?.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID; + +/** A thread of another principal fails as a missing one. */ +export const assertThreadOwnedByCallerPrincipal = ( + principal: string, + target: { readonly ownerPrincipal?: string | undefined }, + fail: () => Effect.Effect, +) => (threadVisibleTo(principal, target) ? Effect.void : fail()); + export const unavailable = () => new OrchestratorMcpFailure({ code: "orchestration_error", @@ -187,6 +200,9 @@ export const readThread = Effect.fn("mcp.readThread")(function* < if (shell === null || shell.deletedAt !== null) { return yield* threadNotFound(context.threads, targetId, "The thread was not found."); } + yield* assertThreadOwnedByCallerPrincipal(callerPrincipal(context), shell, () => + threadNotFound(context.threads, targetId, "The thread was not found."), + ); const projection = yield* context.threads .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, { turnItemTypes: ["user_input_request"], diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 7253bcedb0068..a9697476f555a 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -241,6 +241,9 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { createdBy: "agent", creationSource: "mcp", ...(linkOrigin === undefined ? {} : { linkOrigin }), + ...(caller?.ownerPrincipal === undefined + ? {} + : { ownerPrincipal: caller.ownerPrincipal }), // Kept only alongside linkOrigin: thread.create drops it otherwise. ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), }).pipe( diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index f968312437518..299acbf6c6ae6 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -1,5 +1,6 @@ import { type CommandId, + DEFAULT_PRINCIPAL_ID, type RuntimeRequestId, ThreadId, type OrchestrationV2ThreadProjection, @@ -129,7 +130,11 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { const scope = yield* McpInvocationContext.McpInvocationContext; const threadSearch = yield* ThreadSearch.ThreadSearch; const { matches } = yield* threadSearch - .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId }) + .searchThreads({ + ...input, + projectId: input.projectId ?? caller?.projectId, + ownerPrincipal: caller?.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID, + }) .pipe(Effect.mapError(unavailable)); return { matches: matches.map((match) => ({ diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 35e9a78c4cd55..50584e93b0722 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2695,6 +2695,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio activeProviderThreadId: null, pullRequests: [], ...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }), + ...(command.ownerPrincipal === undefined ? {} : { ownerPrincipal: command.ownerPrincipal }), // Only stamped work names a remote parent, so a client cannot claim one. ...(command.linkOrigin === undefined || command.delegatedFrom === undefined ? {} diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 9bd3566e559a8..fc5a5e09ade4a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1474,6 +1474,7 @@ it.effect("SQL list older settled threads below a cursor", () => readonly subagent?: boolean; readonly archived?: boolean; readonly snoozedUntilDay?: number; + readonly ownerPrincipal?: string; }) => store.apply({ id: EventId.make(`event:older:${input.name}`), @@ -1505,6 +1506,7 @@ it.effect("SQL list older settled threads below a cursor", () => settledOverride: input.settledDay === null ? null : "settled", settledAt: input.settledDay === null ? null : at(input.settledDay), snoozedUntil: input.snoozedUntilDay === undefined ? null : at(input.snoozedUntilDay), + ...(input.ownerPrincipal === undefined ? {} : { ownerPrincipal: input.ownerPrincipal }), lastVisitedAt: null, deletedAt: null, }, @@ -1552,6 +1554,20 @@ it.effect("SQL list older settled threads below a cursor", () => threadIds: [], counts: [{ projectId: ProjectId.make("project:b"), count: 1 }], }); + + yield* createThread({ name: "alices", settledDay: 9, ownerPrincipal: "alice" }); + const forOwner = yield* store.listOlderSettledThreads({ + before, + ownerPrincipal: "owner", + limit: 1, + }); + assert.deepEqual(forOwner.threadIds, [id("a")]); + const forAlice = yield* store.listOlderSettledThreads({ + before, + ownerPrincipal: "alice", + limit: 1, + }); + assert.deepEqual(forAlice.threadIds, [id("alices")]); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 95c0f7a4bae53..152ccc536b991 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,4 +1,4 @@ -import { pendingGuestMessageCount } from "@t3tools/contracts"; +import { DEFAULT_PRINCIPAL_ID, pendingGuestMessageCount } from "@t3tools/contracts"; import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts"; import { projectTurnItemForWire } from "./WireProjection.ts"; import * as Stream from "effect/Stream"; @@ -416,6 +416,8 @@ export interface ActiveShellIndexEntry extends Pick< export interface OlderSettledThreadsQuery { readonly before: OrchestrationV2OlderSettledCursor; readonly projectIds?: ReadonlyArray | undefined; + /** Only this principal's threads, applied before the limit so pages fill. */ + readonly ownerPrincipal?: string | undefined; readonly limit: number; } @@ -1517,6 +1519,9 @@ export function threadShellFromProjection( ...(projection.thread.linkOrigin === undefined ? {} : { linkOrigin: projection.thread.linkOrigin }), + ...(projection.thread.ownerPrincipal === undefined + ? {} + : { ownerPrincipal: projection.thread.ownerPrincipal }), ...(projection.thread.delegatedFrom === undefined ? {} : { delegatedFrom: projection.thread.delegatedFrom }), @@ -1798,6 +1803,9 @@ function shellFromState(input: { ...(input.state.thread.linkOrigin === undefined ? {} : { linkOrigin: input.state.thread.linkOrigin }), + ...(input.state.thread.ownerPrincipal === undefined + ? {} + : { ownerPrincipal: input.state.thread.ownerPrincipal }), ...(input.state.thread.delegatedFrom === undefined ? {} : { delegatedFrom: input.state.thread.delegatedFrom }), @@ -6878,7 +6886,7 @@ export const layer: Layer.Layer = const listOlderSettledThreads: ProjectionStoreV2Shape["listOlderSettledThreads"] = Effect.fn( "ProjectionStore.listOlderSettledThreads", - )(function* ({ before, projectIds, limit }) { + )(function* ({ before, projectIds, ownerPrincipal, limit }) { // ISO strings in one format, so string order is time order. const older = sql` SELECT t.thread_id, t.project_id, @@ -6891,6 +6899,11 @@ export const layer: Layer.Layer = AND json_extract(t.payload_json, '$.settledOverride') = 'settled' AND json_extract(t.payload_json, '$.settledAt') IS NOT NULL${ projectIds === undefined ? sql`` : sql` AND t.project_id IN ${sql.in(projectIds)}` + }${ + // ponytail: unindexed json_extract over payload_json; add an owner column when it matters + ownerPrincipal === undefined + ? sql`` + : sql` AND COALESCE(json_extract(t.payload_json, '$.ownerPrincipal'), ${DEFAULT_PRINCIPAL_ID}) = ${ownerPrincipal}` } `; const belowCursor = diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index 336f9b12f96bf..b83bf2a302599 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -16,6 +16,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import { scopeShellStreamItem } from "./ThreadOwnership.ts"; import { activeShellRowsForSubscriber, bufferShellLiveStream, @@ -349,6 +350,51 @@ describe("shellStreamItemsFromInitialSnapshot", () => { }); }); +describe("scopeShellStreamItem", () => { + const owned = shellFixture({ id: ThreadId.make("thread-alice"), ownerPrincipal: "alice" }); + const unowned = shellFixture({ id: ThreadId.make("thread-owner") }); + const snapshot = { + kind: "snapshot", + snapshot: { + ...emptyShellSnapshot, + threads: [owned, unowned], + archivedThreads: [owned, unowned], + }, + } as const; + + it("shows each principal only its own threads and the default principal only unowned ones", () => { + const idsFor = (principal: string) => { + const item = scopeShellStreamItem(principal, snapshot); + return item?.kind === "snapshot" + ? [item.snapshot.threads, item.snapshot.archivedThreads].map((threads) => + threads.map((thread) => thread.id), + ) + : []; + }; + expect(idsFor("alice")).toEqual([["thread-alice"], ["thread-alice"]]); + expect(idsFor("bob")).toEqual([[], []]); + expect(idsFor("owner")).toEqual([["thread-owner"], ["thread-owner"]]); + }); + + it("drops live updates for other principals' threads but keeps removals", () => { + const updated = { + kind: "thread.updated", + sequence: 1, + location: "active", + thread: owned, + } as const; + const removed = { + kind: "thread.removed", + sequence: 2, + location: "active", + threadId: owned.id, + } as const; + expect(scopeShellStreamItem("alice", updated)).toBe(updated); + expect(scopeShellStreamItem("owner", updated)).toBeNull(); + expect(scopeShellStreamItem("owner", removed)).toBe(removed); + }); +}); + describe("composeShellStreamWithEnrichment", () => { it.effect("preserves pending repository resolutions while an enrichment ACK is withheld", () => Effect.scoped( diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index b68eef4b2a40c..14564e7029aba 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -13,6 +13,7 @@ import { type OrchestrationV2LinkOrigin, type OrchestrationV2ProviderThreadNativeMetadata, type OrchestrationV2ThreadProjection, + type PrincipalId, type ProviderDriverKind, type ProviderInteractionMode, ProjectId, @@ -101,6 +102,7 @@ export interface ThreadLaunchInput { readonly creationSource: OrchestrationV2CreationSource; /** The linked environment this launch is for, if one asked for it. */ readonly linkOrigin?: OrchestrationV2LinkOrigin; + readonly ownerPrincipal?: PrincipalId; /** The parent there, when that environment's agent delegated this as a task. */ readonly delegatedFrom?: OrchestrationV2DelegatedFrom; } @@ -917,6 +919,9 @@ const make = Effect.gen(function* () { ? {} : { importedNativeThread: input.importedNativeThread }), ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }), + ...(input.ownerPrincipal === undefined + ? {} + : { ownerPrincipal: input.ownerPrincipal }), ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 9285f72d46f56..34d46ff01634a 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -56,6 +56,7 @@ it("stamps authoritative provenance on commands that create threads or messages" branch: null, worktreePath: null, // A client cannot claim a linked environment's origin, or a parent there. + ownerPrincipal: "forged", linkOrigin: { sessionId: "forged", label: "Somewhere else" }, delegatedFrom: { environmentId: EnvironmentId.make("environment:elsewhere"), @@ -74,6 +75,14 @@ it("stamps authoritative provenance on commands that create threads or messages" }); expect(stamped).not.toHaveProperty("linkOrigin"); expect(stamped).not.toHaveProperty("delegatedFrom"); + expect(stamped).not.toHaveProperty("ownerPrincipal"); + expect( + ThreadManagementService.withCreationProvenance( + command, + { createdBy: "user", creationSource: "web" }, + "alice", + ), + ).toMatchObject({ ownerPrincipal: "alice" }); }); const layerReceiptsTest = CommandReceiptStore.layer.pipe( diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index c1727567f9e3d..ad0c9034610fc 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1,3 +1,5 @@ +import { DEFAULT_PRINCIPAL_ID } from "@t3tools/contracts"; +import { threadVisibleTo } from "./ThreadOwnership.ts"; import type { OrchestrationV2SearchThreadInput, OrchestrationV2SearchThreadResult, @@ -77,12 +79,22 @@ export interface ThreadManagementProvenance { export function withCreationProvenance( command: OrchestrationV2Command, provenance: ThreadManagementProvenance, + principal: string = DEFAULT_PRINCIPAL_ID, ): OrchestrationV2Command { switch (command.type) { case "thread.create": { - // Only the server stamps a link's origin, so a client cannot set one. - const { linkOrigin: _linkOrigin, delegatedFrom: _delegatedFrom, ...rest } = command; - return { ...rest, ...provenance }; + // Only the server stamps a link's origin and a thread's owner, so a client cannot set either. + const { + linkOrigin: _linkOrigin, + delegatedFrom: _delegatedFrom, + ownerPrincipal: _ownerPrincipal, + ...rest + } = command; + return { + ...rest, + ...provenance, + ...(principal === DEFAULT_PRINCIPAL_ID ? {} : { ownerPrincipal: principal }), + }; } case "message.dispatch": case "thread.fork": @@ -423,6 +435,8 @@ export interface ThreadManagementServiceShape { readonly listProjectThreads: (input: { readonly projectId?: ProjectId | undefined; readonly includeSubagents: boolean; + /** Only this principal's threads, so callers paginate over what they may see. */ + readonly ownerPrincipal?: string | undefined; }) => Effect.Effect, ThreadManagementError>; readonly sendToThread: ( input: ThreadManagementSendInput, @@ -794,6 +808,10 @@ const make = Effect.gen(function* () { ), Effect.map((snapshot) => snapshot.threads + .filter( + (thread) => + input.ownerPrincipal === undefined || threadVisibleTo(input.ownerPrincipal, thread), + ) .filter((thread) => input.includeSubagents ? thread.lineage.sideChat !== true diff --git a/apps/server/src/orchestration-v2/ThreadOwnership.ts b/apps/server/src/orchestration-v2/ThreadOwnership.ts new file mode 100644 index 0000000000000..2402d0a8e53a0 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadOwnership.ts @@ -0,0 +1,57 @@ +import { + DEFAULT_PRINCIPAL_ID, + type OrchestrationV2Command, + type OrchestrationV2ShellStreamItem, + type OrchestrationV2ThreadShell, + type ThreadId, +} from "@t3tools/contracts"; + +export const threadVisibleTo = ( + principal: string, + thread: { readonly ownerPrincipal?: string | undefined }, +) => (thread.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID) === principal; + +const visibleThreads = (principal: string, threads: ReadonlyArray) => + threads.filter((thread) => threadVisibleTo(principal, thread)); + +/** Project and thread-removal items carry no thread content, so they pass through. */ +export const scopeShellStreamItem = ( + principal: string, + item: OrchestrationV2ShellStreamItem, +): OrchestrationV2ShellStreamItem | null => { + switch (item.kind) { + case "snapshot": + return { + ...item, + snapshot: { + ...item.snapshot, + threads: visibleThreads(principal, item.snapshot.threads), + archivedThreads: visibleThreads(principal, item.snapshot.archivedThreads), + }, + }; + case "thread.updated": + return threadVisibleTo(principal, item.thread) ? item : null; + default: + return item; + } +}; + +export const scopeThreadList = visibleThreads; + +/** Threads a command reads or changes that must already exist; null when a command that is not `thread.create` names none. */ +export const existingThreadIdsOfCommand = ( + command: OrchestrationV2Command, +): ReadonlyArray | null => { + if (command.type === "thread.create") return []; + if (command.type === "thread.fork") return [command.sourceThreadId]; + const named: ReadonlyArray = [ + "threadId" in command ? command.threadId : undefined, + "parentThreadId" in command ? command.parentThreadId : undefined, + "targetThreadId" in command ? command.targetThreadId : undefined, + "sourceThreadId" in command ? command.sourceThreadId : undefined, + "senderThreadId" in command ? command.senderThreadId : undefined, + "sourcePlanRef" in command ? command.sourcePlanRef?.threadId : undefined, + ]; + const ids = [...new Set(named.filter((id): id is ThreadId => typeof id === "string"))]; + return ids.length === 0 ? null : ids; +}; diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index b8d75340ec6bc..ee9f817c598a2 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -68,6 +68,7 @@ const thread = ( readonly subagentOf?: ThreadId; readonly sideChatOf?: ThreadId; readonly title?: string; + readonly ownerPrincipal?: string; readonly settledAt?: DateTime.Utc; readonly linkedPullRequest?: ThreadLinkedPullRequest; readonly branchPullRequest?: ThreadLinkedPullRequest; @@ -113,6 +114,7 @@ const thread = ( archivedAt: overrides.archivedAt ?? null, settledOverride: overrides.settledAt === undefined ? null : "settled", settledAt: overrides.settledAt ?? null, + ...(overrides.ownerPrincipal === undefined ? {} : { ownerPrincipal: overrides.ownerPrincipal }), lastVisitedAt: null, deletedAt: overrides.deletedAt ?? null, }, @@ -990,6 +992,32 @@ it.layer(layerTest)("ThreadSearch.searchThreads", (it) => { }), ); + it.effect("ranks only the asking principal's threads, title and message hits alike", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const search = yield* ThreadSearch.ThreadSearch; + const project = ProjectId.make("project:owned"); + yield* createProject(project); + const mine = ThreadId.make("thread:ibis-owner"); + const theirs = ThreadId.make("thread:ibis-alice"); + yield* Effect.forEach( + [ + thread(mine, project, { title: "Ibis" }), + thread(theirs, project, { title: "Ibis", ownerPrincipal: "alice" }), + message(theirs, "ibis-theirs", "user", "ibis note", { minute: 1 }), + ], + projections.apply, + { discard: true }, + ); + const idsFor = (ownerPrincipal: string) => + search + .searchThreads({ query: "ibis", limit: 1, ownerPrincipal }) + .pipe(Effect.map(({ matches }) => matches.map((match) => match.threadId))); + assert.deepEqual(yield* idsFor("owner"), [mine]); + assert.deepEqual(yield* idsFor("alice"), [theirs]); + }), + ); + it.effect("leaves titled threads out before the hit limit", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index 3c97122c1c63e..4e753bb7bc55d 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -35,6 +35,7 @@ import { import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests"; import { indexedMessageCondition, nonPlaceholderMessageCondition } from "./messageSearchIndex.ts"; import { loadOlderSettledThreadsPage } from "./ShellStream.ts"; +import { threadVisibleTo } from "./ThreadOwnership.ts"; // When the user last wrote in the thread aliased `threads`, as the clients // rank recency; agent notices in the user role do not count. @@ -258,7 +259,11 @@ export class ThreadSearch extends Context.Service< * palette ranks them, then message matches for the remaining threads. */ readonly searchThreads: ( - input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined }, + input: OrchestrationSearchThreadsInput & { + readonly projectId?: ProjectId | undefined; + /** Only this principal's threads, applied before ranking and the message limit. */ + readonly ownerPrincipal?: string | undefined; + }, ) => Effect.Effect<{ readonly matches: ReadonlyArray }, ThreadSearchError>; /** * The settled threads before `before` that clients omitting older settled threads should @@ -521,7 +526,15 @@ export const make = Effect.gen(function* () { const now = DateTime.toEpochMillis(yield* DateTime.now); // Agents call this rarely, and a project has hundreds of threads, not // millions, so ranking every active thread in memory stays cheap. - const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null })); + const allCandidates = yield* read(titleCandidates({ projectId: input.projectId ?? null })); + const owner = input.ownerPrincipal; + const candidates = + owner === undefined + ? allCandidates + : allCandidates.filter((row) => threadVisibleTo(owner, row.thread)); + const hidden = new Set( + allCandidates.filter((row) => !candidates.includes(row)).map((row) => row.thread.id), + ); const subjectById = new Map( candidates.map((row): [ThreadId, ThreadSearchSubject] => [ row.thread.id, @@ -558,7 +571,7 @@ export const make = Effect.gen(function* () { query: input.query, limit: 50, projectId: input.projectId ?? null, - excludedThreadIds: shown, + excludedThreadIds: new Set([...shown, ...hidden]), picks: false, }); const messageHits = matches diff --git a/apps/server/src/orchestration-v2/http.test.ts b/apps/server/src/orchestration-v2/http.test.ts index 570d34468d37a..170e728596216 100644 --- a/apps/server/src/orchestration-v2/http.test.ts +++ b/apps/server/src/orchestration-v2/http.test.ts @@ -97,7 +97,7 @@ const items = Schema.decodeUnknownSync(Schema.Array(OrchestrationV2TurnItem))( ); // Serves the orchestration HTTP routes over real stores; `allowed` gates the read scope. -const serveOrchestrationHttp = (allowed: () => boolean) => +const serveOrchestrationHttp = (allowed: () => boolean, subject = "test") => Effect.gen(function* () { const runtime = ProviderReplayHarness.layerWithRegistry( { name: "thread-transcript" }, @@ -141,7 +141,7 @@ const serveOrchestrationHttp = (allowed: () => boolean) => effect.pipe( Effect.provideService(EnvironmentAuthenticatedPrincipal, { sessionId: AuthSessionId.make("test-session"), - subject: "test", + subject, method: "bearer-access-token", scopes: new Set(allowed() ? ["orchestration:read"] : []), }), @@ -250,6 +250,40 @@ it.effect("exports full history with size, scope, and missing-thread checks", () }), ); +it.effect("shows a principal only its own threads over HTTP, as not-found otherwise", () => + Effect.gen(function* () { + const { eventSink, handler } = yield* serveOrchestrationHttp(() => true, "principal:alice"); + const get = (path: string) => + Effect.promise(() => + handler( + new Request(`http://localhost/api/orchestration/${path}`, { + headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT }, + }), + ), + ); + const owned = ThreadId.make("alice-thread"); + yield* eventSink.write({ + events: [ + { + id: EventId.make("create-alice-thread"), + type: "thread.created", + threadId: owned, + occurredAt: now, + payload: { ...thread, id: owned, ownerPrincipal: "alice" }, + }, + ], + }); + + expect((yield* get(`threads/${thread.id}/transcript`)).status).toBe(404); + expect((yield* get(`threads/${owned}/transcript`)).status).toBe(200); + const shellResponse = yield* get("shell"); + const shell = (yield* Effect.promise(() => shellResponse.json())) as { + threads: ReadonlyArray<{ id: string }>; + }; + expect(shell.threads.map(({ id }) => id)).toEqual([owned]); + }), +); + it.effect("leaves older settled threads out of the HTTP shell only when asked", () => Effect.gen(function* () { const { eventSink, handler } = yield* serveOrchestrationHttp(() => true); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index c2c67eb04d9dc..2639ddd83481d 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -2,6 +2,8 @@ import { AuthOrchestrationReadScope, EnvironmentHttpApi, type OrchestrationProjectShell, + principalOfSubject, + type ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; @@ -15,8 +17,10 @@ import { failEnvironmentInternal, failEnvironmentInvalidRequest, failEnvironmentNotFound, - requireEnvironmentScope, + requireEnvironmentScopeForPrincipal, + requireThreadAccess, } from "../auth/http.ts"; +import { scopeThreadList } from "./ThreadOwnership.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; @@ -58,6 +62,12 @@ export const layer = HttpApiBuilder.group( const projectStore = yield* ProjectStore.ProjectStoreV2; const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; + const readThread = (threadId: ThreadId) => + threadManagement.getThreadRecords(threadId, []).pipe( + Effect.map((records) => records.thread), + Effect.orElseSucceed(() => null), + ); + const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")( (projects: ReadonlyArray) => Effect.forEach( @@ -163,11 +173,17 @@ export const layer = HttpApiBuilder.group( "shellSnapshot", Effect.fn("environment.orchestration.shellSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); - yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const session = yield* requireEnvironmentScopeForPrincipal(AuthOrchestrationReadScope); + const principal = principalOfSubject(session.subject); return yield* loadShellSnapshot({ omitIdleSubagents: args.query.omitIdleSubagents === "1", omitOlderSettled: args.query.omitOlderSettled === "1", }).pipe( + Effect.map((snapshot) => ({ + ...snapshot, + threads: scopeThreadList(principal, snapshot.threads), + archivedThreads: scopeThreadList(principal, snapshot.archivedThreads), + })), traceLocalHandlerWork, Effect.catch((cause) => failEnvironmentInternal("orchestration_snapshot_failed", cause), @@ -179,7 +195,7 @@ export const layer = HttpApiBuilder.group( "threadSnapshot", Effect.fn("environment.orchestration.threadSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); - yield* requireEnvironmentScope(AuthOrchestrationReadScope); + yield* requireThreadAccess(AuthOrchestrationReadScope, args.params.threadId, readThread); const snapshot = yield* loadThreadSnapshot( args.params.threadId, "orchestration_thread_snapshot_failed", @@ -194,7 +210,7 @@ export const layer = HttpApiBuilder.group( "threadTranscript", Effect.fn("environment.orchestration.threadTranscript")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); - yield* requireEnvironmentScope(AuthOrchestrationReadScope); + yield* requireThreadAccess(AuthOrchestrationReadScope, args.params.threadId, readThread); return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe( Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), traceLocalHandlerWork, @@ -219,7 +235,7 @@ export const layer = HttpApiBuilder.group( "threadBoundedSnapshot", Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); - yield* requireEnvironmentScope(AuthOrchestrationReadScope); + yield* requireThreadAccess(AuthOrchestrationReadScope, args.params.threadId, readThread); const snapshot = yield* loadThreadSnapshotWindow( args.params.threadId, undefined, @@ -245,7 +261,7 @@ export const layer = HttpApiBuilder.group( "threadHistoryPage", Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); - yield* requireEnvironmentScope(AuthOrchestrationReadScope); + yield* requireThreadAccess(AuthOrchestrationReadScope, args.params.threadId, readThread); const decoded = yield* Effect.try(() => decodeThreadHistoryCursor(args.query.cursor), ).pipe(Effect.result); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8373bbfae0c55..8b94fc7b013c1 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -19,10 +19,18 @@ import * as Schema from "effect/Schema"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { rpcInitialItems } from "./rpcInitialItems.ts"; +import { + existingThreadIdsOfCommand, + scopeShellStreamItem, + scopeThreadList, + threadVisibleTo, +} from "./orchestration-v2/ThreadOwnership.ts"; import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { AcpRegistryOperationError, CommandId, + DEFAULT_PRINCIPAL_ID, + principalOfSubject, authScopeResponse, AuthAccessStreamError, type AuthAccessStreamEvent, @@ -1256,6 +1264,7 @@ export const layerWsRpc = ( Layer.effectContext( Effect.gen(function* () { const currentSessionId = currentSession.sessionId; + const principal = principalOfSubject(currentSession.subject); const sql = yield* SqlClient.SqlClient; const threadManagement = yield* ThreadManagementService.ThreadManagementService; const intakeContext = yield* Effect.context< @@ -1890,6 +1899,28 @@ export const layerWsRpc = ( return yield* mutateProjectWithClone(projectService, projectCloneTracker, mutation); }); + const threadVisible = Effect.fn("ws.threadVisibleToSession")(function* (threadId: ThreadId) { + const found = yield* threadManagement.getThreadRecords(threadId, []).pipe(Effect.option); + return Option.isSome(found) && threadVisibleTo(principal, found.value.thread); + }); + const threadNotFound = (threadId: ThreadId) => + new OrchestrationV2GetThreadProjectionError({ + threadId, + message: `Thread ${threadId} was not found`, + cause: "thread-not-visible", + }); + const whenThreadsVisible = Effect.fn("ws.whenThreadsVisible")(function* ( + threadIds: ReadonlyArray | null, + notFound: () => E2, + effect: Effect.Effect, + ) { + // The default principal administers the environment, so its point reads skip the lookup. + if (principal === DEFAULT_PRINCIPAL_ID) return yield* effect; + if (threadIds === null) return yield* Effect.fail(notFound()); + const visible = yield* Effect.forEach(threadIds, threadVisible); + return visible.every(Boolean) ? yield* effect : yield* Effect.fail(notFound()); + }); + const handlers = ServerWsRpcGroup.of({ [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => Effect.annotateCurrentSpan({ @@ -1910,35 +1941,49 @@ export const layerWsRpc = ( : {}), }).pipe( Effect.andThen( - startup - .enqueueCommand( - (command.type === "prepared-run.retry" - ? threadLaunch.retryPreparation(command) - : ThreadMessageIntake.dispatchCommand( - ThreadManagementService.withCreationProvenance(command, { - createdBy: "user", - creationSource: - "creationSource" in command ? command.creationSource : "web", - }), - ) - ).pipe(Effect.provide(intakeContext)), - ) - .pipe( - Effect.tap((result) => - result.replayed ? Effect.void : recordClientCommandAnalytics(command), - ), - Effect.map((result) => ({ sequence: result.sequence })), - Effect.mapError((cause) => { - const detail = userFacingDispatchErrorMessage(cause); - return new OrchestrationV2DispatchCommandError({ - commandId: command.commandId, - commandType: command.type, - message: detail ?? "Failed to dispatch orchestration V2 command", - ...(detail === undefined ? {} : { detail }), - cause, - }); + whenThreadsVisible( + existingThreadIdsOfCommand(command), + () => + new OrchestrationV2DispatchCommandError({ + commandId: command.commandId, + commandType: command.type, + message: "Thread not found", + cause: "thread-not-visible", }), - ), + startup + .enqueueCommand( + (command.type === "prepared-run.retry" + ? threadLaunch.retryPreparation(command) + : ThreadMessageIntake.dispatchCommand( + ThreadManagementService.withCreationProvenance( + command, + { + createdBy: "user", + creationSource: + "creationSource" in command ? command.creationSource : "web", + }, + principal, + ), + ) + ).pipe(Effect.provide(intakeContext)), + ) + .pipe( + Effect.tap((result) => + result.replayed ? Effect.void : recordClientCommandAnalytics(command), + ), + Effect.map((result) => ({ sequence: result.sequence })), + Effect.mapError((cause) => { + const detail = userFacingDispatchErrorMessage(cause); + return new OrchestrationV2DispatchCommandError({ + commandId: command.commandId, + commandType: command.type, + message: detail ?? "Failed to dispatch orchestration V2 command", + ...(detail === undefined ? {} : { detail }), + cause, + }); + }), + ), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input), @@ -1947,14 +1992,18 @@ export const layerWsRpc = ( [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => readWorkflowScript({ scriptPath: input.scriptPath }), [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) => - threadManagement.getTurnItem(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: "Failed to load turn item", - cause, - }), + whenThreadsVisible( + [input.threadId], + () => threadNotFound(input.threadId), + threadManagement.getTurnItem(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: "Failed to load turn item", + cause, + }), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: (input) => @@ -1978,13 +2027,27 @@ export const layerWsRpc = ( ), ), [ORCHESTRATION_V2_WS_METHODS.searchThread]: (input) => - threadManagement - .searchThread(input) - .pipe(Effect.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))), + whenThreadsVisible( + [input.threadId], + () => new OrchestrationV2SearchThreadError({ cause: "thread-not-visible" }), + threadManagement + .searchThread(input) + .pipe(Effect.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))), + ), [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: (input) => - threadManagement - .searchThreadStream(input) - .pipe(Stream.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))), + Stream.unwrap( + whenThreadsVisible( + [input.threadId], + () => new OrchestrationV2SearchThreadError({ cause: "thread-not-visible" }), + Effect.succeed( + threadManagement + .searchThreadStream(input) + .pipe( + Stream.mapError((cause) => new OrchestrationV2SearchThreadError({ cause })), + ), + ), + ), + ), [ORCHESTRATION_V2_WS_METHODS.searchThreads]: (input) => ThreadSearch.searchThreadsWithOlderSettledRows({ request: input, @@ -2004,13 +2067,21 @@ export const layerWsRpc = ( ), ), [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => - getOrchestrationV2ArchivedShellSnapshot, + getOrchestrationV2ArchivedShellSnapshot.pipe( + Effect.map((snapshot) => ({ + ...snapshot, + threads: scopeThreadList(principal, snapshot.threads), + })), + ), [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) => readOmittableShellRows({ familyOf: input.threadId }, "Failed to load the thread family"), [ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads]: (input) => loadOlderSettledThreadsPage({ sql, - listThreads: threadManagement.listOlderSettledThreads(input), + listThreads: threadManagement.listOlderSettledThreads({ + ...input, + ownerPrincipal: principal, + }), readThreads: (threadIds) => threadManagement.readShellSnapshot({ location: "active", threadIds }), latestSequence: applicationEvents.latestApplicationSequence, @@ -2031,28 +2102,32 @@ export const layerWsRpc = ( [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen( - // Bound compatibility snapshots so pre-pagination clients cannot materialize unlimited transcripts. - threadManagement - .getThreadSnapshotWindow(input.threadId, { - rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, - }) - .pipe( - Effect.map( - (snapshot) => - buildBoundedThreadProjection({ - projection: projectThreadProjectionForWire(snapshot.projection), - snapshotSequence: snapshot.snapshotSequence, - }).projection, - ), - Effect.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: `Failed to load orchestration V2 thread ${input.threadId}`, - cause, - }), + whenThreadsVisible( + [input.threadId], + () => threadNotFound(input.threadId), + // Bound compatibility snapshots so pre-pagination clients cannot materialize unlimited transcripts. + threadManagement + .getThreadSnapshotWindow(input.threadId, { + rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, + }) + .pipe( + Effect.map( + (snapshot) => + buildBoundedThreadProjection({ + projection: projectThreadProjectionForWire(snapshot.projection), + snapshotSequence: snapshot.snapshotSequence, + }).projection, + ), + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed to load orchestration V2 thread ${input.threadId}`, + cause, + }), + ), ), - ), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.launchThread]: (input) => @@ -2061,103 +2136,127 @@ export const layerWsRpc = ( "orchestration_v2.project_id": input.projectId, }).pipe( Effect.andThen( - startup - .enqueueCommand( - ThreadMessageIntake.launchThread({ + whenThreadsVisible( + input.reuseExistingThread === true && input.threadId !== undefined + ? [input.threadId] + : [], + () => + new OrchestrationV2ThreadLaunchError({ commandId: input.commandId, - ...(input.threadId === undefined ? {} : { threadId: input.threadId }), - ...(input.reuseExistingThread === undefined - ? {} - : { reuseExistingThread: input.reuseExistingThread }), projectId: input.projectId, - title: input.title, - ...(input.generateTitle === undefined - ? {} - : { generateTitle: input.generateTitle }), - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - workspaceStrategy: input.workspaceStrategy, - ...(input.initialMessage === undefined - ? {} - : { - initialMessage: { - ...(input.initialMessage.messageId === undefined - ? {} - : { messageId: input.initialMessage.messageId }), - text: input.initialMessage.text, - attachments: input.initialMessage.attachments, - ...(input.initialMessage.context === undefined - ? {} - : { context: input.initialMessage.context }), - }, - }), - createdBy: "user", - creationSource: input.creationSource ?? "web", - }).pipe(Effect.provide(intakeContext)), - ) - .pipe( - // A resumed launch is a retry of one already counted. - Effect.tap((result) => - result.resumed - ? Effect.void - : analytics - .record("client.thread.started", { - ...originProps, - workspaceStrategy: input.workspaceStrategy.type, - }) - .pipe( - Effect.andThen( - input.initialMessage === undefined - ? Effect.void - : analytics.record("client.turn.requested", originProps), + message: "Thread not found", + cause: "thread-not-visible", + }), + startup + .enqueueCommand( + ThreadMessageIntake.launchThread({ + commandId: input.commandId, + ...(principal === DEFAULT_PRINCIPAL_ID ? {} : { ownerPrincipal: principal }), + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input.reuseExistingThread === undefined + ? {} + : { reuseExistingThread: input.reuseExistingThread }), + projectId: input.projectId, + title: input.title, + ...(input.generateTitle === undefined + ? {} + : { generateTitle: input.generateTitle }), + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + workspaceStrategy: input.workspaceStrategy, + ...(input.initialMessage === undefined + ? {} + : { + initialMessage: { + ...(input.initialMessage.messageId === undefined + ? {} + : { messageId: input.initialMessage.messageId }), + text: input.initialMessage.text, + attachments: input.initialMessage.attachments, + ...(input.initialMessage.context === undefined + ? {} + : { context: input.initialMessage.context }), + }, + }), + createdBy: "user", + creationSource: input.creationSource ?? "web", + }).pipe(Effect.provide(intakeContext)), + ) + .pipe( + // A resumed launch is a retry of one already counted. + Effect.tap((result) => + result.resumed + ? Effect.void + : analytics + .record("client.thread.started", { + ...originProps, + workspaceStrategy: input.workspaceStrategy.type, + }) + .pipe( + Effect.andThen( + input.initialMessage === undefined + ? Effect.void + : analytics.record("client.turn.requested", originProps), + ), + Effect.ignore, ), - Effect.ignore, - ), + ), + Effect.map((result) => ({ + ...result, + projection: projectThreadProjectionForWire(result.projection), + })), + Effect.catchTags({ + AttachmentClaimError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: cause.message, + cause, + }), + ThreadLaunchError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: "Failed to launch thread", + cause, + }), + ServerRuntimeStartupError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: "Failed to launch thread", + cause, + }), + ThreadManagementProviderInstanceDisabledError: (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: cause.message, + cause, + }), + }), ), - Effect.map((result) => ({ - ...result, - projection: projectThreadProjectionForWire(result.projection), - })), - Effect.catchTags({ - AttachmentClaimError: (cause) => - new OrchestrationV2ThreadLaunchError({ - commandId: input.commandId, - projectId: input.projectId, - message: cause.message, - cause, - }), - ThreadLaunchError: (cause) => - new OrchestrationV2ThreadLaunchError({ - commandId: input.commandId, - projectId: input.projectId, - message: "Failed to launch thread", - cause, - }), - ServerRuntimeStartupError: (cause) => - new OrchestrationV2ThreadLaunchError({ - commandId: input.commandId, - projectId: input.projectId, - message: "Failed to launch thread", - cause, - }), - ThreadManagementProviderInstanceDisabledError: (cause) => - new OrchestrationV2ThreadLaunchError({ - commandId: input.commandId, - projectId: input.projectId, - message: cause.message, - cause, - }), - }), - ), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) => - Stream.unwrap(subscribeOrchestrationV2Shell(input)), + Stream.unwrap(subscribeOrchestrationV2Shell(input)).pipe( + Stream.flatMap((item) => { + const scoped = scopeShellStreamItem(principal, item); + return scoped === null ? Stream.empty : Stream.succeed(scoped); + }), + ), [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) => Stream.unwrap( Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( - Effect.andThen(subscribeOrchestrationV2Thread(input)), + Effect.andThen( + whenThreadsVisible( + [input.threadId], + () => threadNotFound(input.threadId), + subscribeOrchestrationV2Thread(input), + ), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: (input) => @@ -3345,21 +3444,25 @@ export const layer = Layer.unwrap( Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)), Effect.provide( Layer.merge( - RpcAuthorization.layer(session.scopes, (method, payload) => { - // Anonymous product signal: the feature and its enum variant, - // credited to the connecting client's surface only. - const usage = featureUsage(method, payload); - return usage === undefined - ? Effect.void - : analytics - .record("feature.used", { - ...usage, - ...(clientAnalyticsProps.surface === undefined - ? {} - : { surface: clientAnalyticsProps.surface }), - }) - .pipe(Effect.ignore); - }), + RpcAuthorization.layer( + session.scopes, + (method, payload) => { + // Anonymous product signal: the feature and its enum variant, + // credited to the connecting client's surface only. + const usage = featureUsage(method, payload); + return usage === undefined + ? Effect.void + : analytics + .record("feature.used", { + ...usage, + ...(clientAnalyticsProps.surface === undefined + ? {} + : { surface: clientAnalyticsProps.surface }), + }) + .pipe(Effect.ignore); + }, + principalOfSubject(session.subject), + ), rpcInstrumentationLayer, ), ), diff --git a/docs/internals/multi-user.md b/docs/internals/multi-user.md new file mode 100644 index 0000000000000..95bb988b03758 --- /dev/null +++ b/docs/internals/multi-user.md @@ -0,0 +1,278 @@ +# Multi-user environments (fork design) + +Status: fork-only design for caniko/t3code. Upstream has not approved this +direction; the related Ideas discussions are #12283 (multi-user self-hosting +with isolated execution), #27974 (each person signs in as themselves), #27708 +(share threads with a team) and #24944 (collaboration in the app). + +## Goal + +Several people use one T3 Code server on one machine. Each person has their own +workspace: their projects and threads, their provider logins, their Git and SSH +credentials. The machine runs one server on one port and is paired once per +device, so nobody needs a URL or port of their own. Later, people can share a +thread or project with a group and work on it together. + +The first deployment is a household: `can` and `dejana` each have an OS account +on every PC (atlas, murph, nomad, starlord). Today each PC runs one `t3 serve` +per person on separate ports. This design replaces that pair with one server per +PC. There is no central hub server: a public ingress only proxies to these +per-PC servers. + +Phases: + +- **C1a, principals and workspaces.** Identity, ownership and filtering. A + prototype is on `feat/multi-user-principals`. +- **C1b, per-principal execution.** Providers, terminals and Git run as the + principal's own OS user. +- **C2, groups and collaboration.** Outline only. +- **Later, separately:** launching a thread on a linked environment from the UI. + It is not part of C1. + +## Principals + +A principal is a person known to the environment. Its id is a short slug +(`[a-z0-9][a-z0-9-]{0,31}`). + +**Binding.** Pairing grants and sessions already carry a `subject`, and a +session inherits its grant's subject when it is exchanged. A principal is +encoded in that same field as `principal:`, so issuance, replacement, +revocation and listing need no new storage. `principalOfSubject` maps every +other subject (`browser`, `one-time-token`, `desktop-bootstrap`, `mcp-client`, +…) to the default principal `owner`. A malformed `principal:` value maps to +itself, never to `owner`, so a bad id cannot widen access. + +**Issuance.** `t3 auth pairing create --principal dejana` and +`t3 auth session issue --principal dejana` mint credentials for a principal. +Only a session that holds `access:write` can create them, as today. + +**Default principal.** `owner` administers the environment: settings, provider +instances, links, access management, maintenance. Every existing install has +exactly one principal, `owner`, so nothing changes for a single user. + +**MCP approval codes.** A principal's pairing code is refused as an MCP approval +code. MCP client sessions use the fixed `mcp-client` subject, so accepting the +code would mint a session that acts as `owner`. + +## Workspaces (C1a) + +**Ownership is stamped, never claimed.** `thread.create` gets `ownerPrincipal` +from the calling session in the same place the server strips a client-supplied +`linkOrigin` (`withCreationProvenance`). For `owner` the field is omitted, so +existing threads and new single-user threads stay byte-identical. Like +`linkOrigin`, the field lives in the thread payload, needs no migration, and +passes to subagents, forks and delegated children. + +**One visibility rule.** A thread is visible to principal P when +`(thread.ownerPrincipal ?? "owner") === P` +([ThreadOwnership.ts](../../apps/server/src/orchestration-v2/ThreadOwnership.ts)). +Every read and write that names a thread goes through that helper: + +- the shell snapshot and live shell items (other principals' `thread.updated` + items are dropped); +- thread subscriptions, projections, turn items, and the archived and + older-settled pages; +- the HTTP thread snapshot, transcript and history routes; +- `dispatchCommand` for every thread the command names. + +A thread another principal cannot see fails as not found, so its existence is +not revealed. `owner` skips the per-thread lookup on point reads: it already +holds environment-wide authority, so a check there would add latency without +creating a boundary. Its shell is still filtered, so its sidebar shows only its +own workspace. + +**Fail-closed surface.** A non-`owner` session may call only an explicit +allowlist of WebSocket RPCs (`PRINCIPAL_RPC_METHODS` in +[RpcAuthorization.ts](../../apps/server/src/auth/RpcAuthorization.ts)). Every +other RPC and every scoped HTTP route is refused for it unless the route has its +own principal-aware check. New RPCs therefore start out unavailable to +principals instead of starting out leaky. + +**Scope ceiling.** Until C1b, a principal holds at most `orchestration:read` and +`orchestration:operate`. Terminal, filesystem, settings, provider, access and +maintenance scopes act as the server's OS user or across the whole environment, +so they would cross workspaces. Issuance rejects them for a principal. + +**Projects.** Projects need the same treatment: a nullable `owner_principal` +column on `projection_projects` (migration `077`), stamping on `project.create`, +shell filtering, and ownership checks on `projects.mutate`. Two people may +register the same repository; each gets their own project record, so the +repository identity groups them and nothing more. + +## Per-principal execution (C1b) + +Agents run arbitrary commands. Whatever OS user runs a principal's provider +process can read everything that user can read. Workspace filtering alone keeps +honest clients apart, but it does not keep one principal's agents out of the +other principal's provider tokens, SSH keys or checkouts. Two ways to place +execution: + +**A. One OS user, a HOME per principal.** The server spawns each principal's +providers, terminals and Git with `HOME`, `XDG_*`, `CODEX_HOME`, +`CLAUDE_CONFIG_DIR`, `GIT_CONFIG_GLOBAL` and `SSH_AUTH_SOCK` pointing into +`/principals//`. + +- Small change: environment variables at the spawn sites. Nothing privileged. +- Logins and caches stay apart in practice. +- Not a boundary. Any agent with a shell, which includes every approval-required + or full-access agent, can read the other principal's HOME, because both run as + the same user. Repositories must also live somewhere both can write. +- Fits people who already share a machine account and trust each other, which is + the #27974 trust model. + +**B. A separate OS user per principal (recommended).** The server runs as an +unprivileged service user. Each principal maps to an OS account, for example +`dejana → dejana`. Everything the server starts on a principal's behalf runs as +that account, through a per-principal runner: + +- The runner is `t3 runner`: the same binary, started as the principal's own + user. On Linux that is a system unit `t3-runner@.service` with + `User=` and a socket in `/run/t3/runner/.sock`, mode 0660 and + group `t3`, so only the server can reach it. It spawns processes, holds their + stdio and PTYs, and forwards signals and resizes. +- On the server side, a principal's work gets a per-principal + `ChildProcessSpawner` layer that sends spawns to its runner. Most process + creation already goes through that service, so this is one seam. The + exceptions are the PTY adapter (`terminal/NodePtyAdapter.ts`) and the Claude + SDK spawn in `ClaudeAdapterV2.ts`, which need their own runner path. +- Provider CLIs, Git, worktrees, checkpoints and project setup scripts then run + as the principal. Logins, SSH agents and Git credentials stay in that user's + HOME, and the kernel keeps principals apart even from a full-access agent. +- The server still reads workspace files in-process for previews, diffs and + assets. Either give it group read access to the principal's project roots, + which is simple and treats the server as a trusted control plane, or send + those reads through the runner too. Start with group read. +- With a runner in place, the C1a scope ceiling can relax: a principal's + terminal and provider-login RPCs become safe once they run in that principal's + runner. +- Costs: a spawn protocol (stdio streaming, PTY, signals, exit status), one + extra hop per process, per-OS packaging (systemd on Linux; launchd and Windows + services are open questions), and installation needs root once to create the + units. + +Why B over the alternatives: + +- **CAP_SETUID in the server** would drop privileges per spawn. Node supports + `uid`/`gid` in `child_process`, but Effect's `ChildProcess` options do not. + More importantly, a compromised server could become any user, root included. + The runner design keeps the server unprivileged and limits it to the runners + that exist. +- **A front router to one stock server per person** (today's layout behind one + URL) isolates execution without touching the spawn paths. But the router would + have to impersonate one environment while relaying several, each with its own + environment id, event sequence and pairing state. That costs more and breaks + the identity rules in [remote.md](./remote.md). + +A single-user install keeps today's behavior. With no principal map configured, +`owner` runs in-process as the server user and no runner exists. + +## Settings and providers + +Server settings and provider instances stay environment-wide and owned by +`owner`. Each principal's provider availability comes from what its runner +reports: the CLIs that are installed and logged in for that OS user. Model +defaults and keybindings become per-principal preferences. +`subscribeServerConfig` would then return the caller's view. Until that exists, +principals see the environment's provider list. That leaks configuration, not +content. + +## Peer links + +Linked environments stay environment-to-environment. A link that one principal +creates belongs to that principal: the link record gains `ownerPrincipal`, and +`PeerForwarding.resolve` refuses callers whose thread has a different owner. +Each principal's agents therefore reach only that principal's links. On the +receiving side, a link pairs with a principal's code and gets that principal's +session, so its work lands in the right workspace. That requires `mcp-client` +sessions to carry a principal, a deliberate change to the MCP approval refusal +above. Launching a thread on a linked environment from the UI, without an agent +in between, is a separate later item. + +## MCP and agents + +Agent tools resolve the calling thread (`McpInvocationContext`). The caller's +principal is that thread's `ownerPrincipal`; an outside MCP client acts as +`owner`. Unlike client point reads, `owner` gets no exemption here, because its +agents must not read a principal's threads either. Direct thread reads and +writes, and thread listings, go through the same visibility helper in +[threadAccess.ts](../../apps/server/src/mcp/threadAccess.ts), and listings filter +before they paginate. Thread mentions in a message's context and +`delegate_task` targets in another project still need the same check. + +## Migration + +- **Existing state.** Rows without an owner belong to `owner`. No data + migration. +- **Merging a second person's server** (today's per-user ports). A one-time + `t3 principal import --from --as dejana` copies their projects + and threads into this database with `ownerPrincipal` set, then their old + server retires. Until it exists, a principal starts with an empty workspace + and old threads stay readable on the old server. +- **Clients.** Each device pairs once per principal with a principal pairing + link. A browser profile holds one principal per environment; switching + principals means another profile or device for now. + +## Threat model + +Trusted: + +- `owner`; +- the server process; +- in model A, every principal. + +Defended against, under model B: + +- a principal, or that principal's agents, reading or changing another + principal's threads, projects, provider logins or files; +- a principal escalating to environment administration. + +Not defended against: + +- `owner`, who can mint any principal's credential; +- root on the machine; +- denial of service between principals on shared CPU and memory; +- side channels such as timing and shell counts. Older-settled counts are still + per project. + +Known gaps in the prototype: + +- **Thread mentions** in message context are not checked yet (see above). +- **Project records** are not principal-filtered until migration 077 lands. + Their names and paths are visible to every principal. +- **Provider-native subagent threads** created from adapter paths that do not + inherit from the parent thread get no owner. They default to `owner` and are + hidden from the principal who started the parent. +- **Removal events** pass through: `thread.removed` reveals a thread id, and + nothing else, to every principal. + +Prerequisite for C2: + +- **#26490** (guest share stream ships raw owner thread events past the filtered + guest view) must be fixed before anything builds on guest shares. The same + rule applies here: a group viewer must get a projection built from an + allowlist of event types, never raw thread events. + +## C2: groups and collaboration (outline) + +- **Groups.** A group is a named set of principals that `owner` manages. Each + group membership is a role: `viewer` reads, and `participant` can send + messages, answer approvals and steer turns. +- **Sharing.** A thread or project can be shared with a group. A project share + covers threads created in it after the share, not older private ones. The + share lives in the thread or project projection, like a guest share today. + Replacing, closing or archiving a share revokes it at once. The visibility + helper becomes "owner, or a member of a group the thread is shared with". +- **Execution stays with the owner.** Turns in a shared thread run in the + thread owner's runner, with the owner's provider login. A participant's + message is attributed to them (#27974: record the sender on each message), + and the agent sees who is speaking. Participants never get a session as the + owner, and never reach the owner's terminal or files except through the + thread's normal UI. +- **Fences.** Work a participant starts in a shared thread carries a + `collabOrigin` modelled on `linkOrigin`, so `assertSameLink`-style rules keep + it from changing the owner's other threads, projects or settings. +- **Guests stay separate.** Guest links remain the anonymous, single-thread, + read-and-propose path. Groups are the authenticated path for known + principals. Both must use the allowlisted projection required by #26490. +- **Presence and chat** (#24944) are UI on top of shares and stay out of the + first C2 step. diff --git a/docs/proposals/multi-user-ideas-draft.md b/docs/proposals/multi-user-ideas-draft.md new file mode 100644 index 0000000000000..e810a87cd8872 --- /dev/null +++ b/docs/proposals/multi-user-ideas-draft.md @@ -0,0 +1,59 @@ + + +Adding a concrete case and a shape that might work for it. + +Two of us share each PC at home. Today every machine runs two `t3 serve` +processes, one per OS account, on different ports. That works, but every device +has to pair with two servers per PC, and the ports leak into everything. What we +actually want is one server per machine, where each of us signs in as ourselves +and sees only our own projects and threads. Our provider logins, SSH keys and Git +credentials should stay in our own accounts. + +I tried a small version of this in a fork to see how far the existing pieces go. +They go quite far: + +- **Identity.** Pairing grants and sessions already carry a `subject`, and a + session inherits it from its grant. Encoding a person as `principal:` in + that field (`t3 auth pairing create --principal dejana`) needs no new storage. + Every existing subject maps to a default `owner`, so single-user installs don't + change. +- **Ownership.** `thread.create` gets an `ownerPrincipal` stamped server-side, in + the same spot that already strips a client-supplied `linkOrigin`, and children + inherit it the same way. Shell, thread, history and dispatch paths all check it + through one helper. A thread you can't see is "not found". +- **Fail closed.** A principal's session can only call an allowlisted set of RPCs + and is capped at `orchestration:read`/`operate`. Terminal, filesystem, settings + and provider scopes would act as the server's OS user, so those stay with the + owner for now. + +That gives separate workspaces, but not isolation. Agents run shell commands, so +whichever OS user runs them can read everything that user can. Real isolation +needs each person's providers, terminals and Git to run as their own OS user. The +cleanest way I found is a small per-user runner: the same binary, started as that +user and reachable only by the server over a Unix socket. A principal's work then +gets a `ChildProcessSpawner` that goes through it. Most process creation already +uses that service. The PTY adapter and the Claude SDK spawn are the exceptions. + +Sharing (#27708) fits on top as a later step: share a thread or project with a +group of people as viewer or participant. Turns keep running as the thread owner, +and each message records who sent it, which is what #27974 asks for. I'd want +#26490 fixed first, since anything built on guest-style sharing needs an +allowlisted event projection rather than raw thread events. + +Questions for you: + +1. Is "principal" bound to the existing pairing `subject` a direction you'd + accept, or would you rather tie identity to T3 Connect accounts as #27974 + suggests? +2. Would you take identity plus workspace filtering on its own, with execution + isolation as a separate step? Or is it only worth doing with the runner? +3. If this is something you'd consider, which piece should come first as its own + PR? + +The design notes and prototype are in +https://github.com/caniko/t3code/tree/feat/multi-user-principals +(`docs/internals/multi-user.md`). I'm not opening a PR without your go-ahead. diff --git a/packages/contracts/src/auth.test.ts b/packages/contracts/src/auth.test.ts index d18a827c14228..2143cc895a609 100644 --- a/packages/contracts/src/auth.test.ts +++ b/packages/contracts/src/auth.test.ts @@ -9,6 +9,8 @@ import { AuthStandardClientScopes, authScopeResponse, AuthSessionState, + principalOfSubject, + principalSubject, sessionGrantsScope, } from "./auth.ts"; @@ -130,3 +132,15 @@ describe("authorization grants", () => { expect(sessionGrantsScope(session, scope)).toBe(expected); }); }); + +it.each([ + { subject: "principal:alice", expected: "alice" }, + { subject: principalSubject("bob-2"), expected: "bob-2" }, + { subject: "principal:", expected: "" }, + { subject: "browser", expected: "owner" }, + { subject: "one-time-token", expected: "owner" }, + { subject: "mcp-client", expected: "owner" }, + { subject: "xprincipal:alice", expected: "owner" }, +])("principalOfSubject maps $subject to $expected", ({ subject, expected }) => { + expect(principalOfSubject(subject)).toBe(expected); +}); diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 4037e6cc128bf..b1dcec024d592 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -145,6 +145,27 @@ export function sessionHasLegacyPermissions(session: SessionGrantInput): boolean ); } +export const DEFAULT_PRINCIPAL_ID = "owner"; + +export const PrincipalId = Schema.String.check(Schema.isPattern(/^[a-z0-9][a-z0-9-]{0,31}$/)); +export type PrincipalId = typeof PrincipalId.Type; + +const PRINCIPAL_SUBJECT_PREFIX = "principal:"; + +export const principalSubject = (id: string) => `${PRINCIPAL_SUBJECT_PREFIX}${id}`; + +/** Subjects without the prefix predate principals and act as the default one; a malformed id never widens to it. */ +export const principalOfSubject = (subject: string): string => + subject.startsWith(PRINCIPAL_SUBJECT_PREFIX) + ? subject.slice(PRINCIPAL_SUBJECT_PREFIX.length) + : DEFAULT_PRINCIPAL_ID; + +/** The most a non-default principal may hold: terminal, filesystem, settings, provider and access scopes act as the server's OS user or across the whole environment. */ +export const AuthPrincipalScopes = [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, +] as const; + // Shell and full-access agent scopes already confer access and relay authority. export const AuthStandardClientScopes = [ AuthOrchestrationReadScope, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 1c80128f8bbc5..7569d6b04bd65 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -41,7 +41,7 @@ import { TrimmedNonEmptyString, TurnItemId, } from "./baseSchemas.ts"; -import { AuthMcpClientAccess } from "./auth.ts"; +import { AuthMcpClientAccess, PrincipalId } from "./auth.ts"; import { ChatAttachment } from "./chatAttachment.ts"; import { ThreadGuestShare } from "./guestShare.ts"; import { @@ -455,6 +455,8 @@ export const OrchestrationV2AppThread = Schema.Struct({ activeProviderThreadId: Schema.NullOr(ProviderThreadId), historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), + /** Server-stamped at creation; absent means the default principal. */ + ownerPrincipal: Schema.optional(PrincipalId), delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), lineage: OrchestrationV2AppThreadLineage, forkedFrom: Schema.NullOr( @@ -2074,6 +2076,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ activeProviderThreadId: Schema.NullOr(ProviderThreadId), historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), + /** Server-stamped at creation; absent means the default principal. */ + ownerPrincipal: Schema.optional(PrincipalId), delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), latestRunId: Schema.NullOr(RunId), latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -2900,6 +2904,8 @@ export const OrchestrationV2Command = Schema.Union([ worktreePath: Schema.NullOr(TrimmedNonEmptyString), /** Only the server sets this; a client's thread.create never carries one. */ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), + /** Only the server sets this; a client's thread.create never carries one. */ + ownerPrincipal: Schema.optional(PrincipalId), /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), importedNativeThread: Schema.optional(