diff --git a/.github/workflows/fork-principals.yml b/.github/workflows/fork-principals.yml new file mode 100644 index 000000000000..1f1dd255d721 --- /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/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 68a622c541fe..70f004d1957d 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -47,6 +47,7 @@ import * as EventSink from "../src/orchestration-v2/EventSink.ts"; import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts"; import * as ThreadManagementService from "../src/orchestration-v2/ThreadManagementService.ts"; import * as ProjectStore from "../src/orchestration-v2/ProjectStore.ts"; +import * as SessionAccess from "../src/orchestration-v2/SessionAccess.ts"; import * as ProjectService from "../src/project/ProjectService.ts"; import * as ProjectEnrichmentService from "../src/project/ProjectEnrichmentService.ts"; import * as OrchestrationHttp from "../src/orchestration-v2/http.ts"; @@ -148,6 +149,7 @@ const layerServices = layerManagement.pipe( }), ), Layer.provideMerge(ProjectStore.layer), + Layer.provideMerge(SessionAccess.layer), Layer.provideMerge(Layer.mock(ProjectService.ProjectService)({})), Layer.provideMerge(layerEnrichment), Layer.provideMerge(layerPersistence), diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index eca30a871a10..3bbbb37bb40d 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, @@ -428,6 +432,40 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => { }).pipe(Effect.provide(layerEnvironmentAuth())), ); + it.effect( + "caps a principal's credentials below server administration 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", "access:write"] 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 813d23bc33dc..4124b3657627 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, @@ -469,6 +473,17 @@ export class EnvironmentAuth extends Context.Service< }, ServerAuthInvalidCredentialError | ServerAuthInternalError >; + readonly issuePrincipalBrowserSession: ( + principal: string, + requestMetadata: AuthClientMetadata, + ) => Effect.Effect< + { + readonly sessionToken: string; + readonly cookieName: string; + readonly expiresAt: DateTime.Utc; + }, + ServerAuthInternalError + >; readonly exchangeBootstrapCredentialForAccessToken: ( credential: string, requestedScopes: ReadonlyArray | undefined, @@ -485,11 +500,14 @@ 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< IssuedPairingLink, - ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError + | ServerAuthInternalError + | ManagedLimits.ManagedPolicyRefusedError + | ServerAuthScopeNotGrantedError >; readonly issuePairingCredential: ( input?: AuthCreatePairingCredentialInput, @@ -508,9 +526,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 @@ -905,6 +927,25 @@ export const make = Effect.gen(function* () { } satisfies BootstrapExchangeResult; }); + const issuePrincipalBrowserSession: EnvironmentAuth["Service"]["issuePrincipalBrowserSession"] = + Effect.fn("EnvironmentAuth.issuePrincipalBrowserSession")( + function* (principal, client) { + const { subject, scopes } = yield* resolveIssuance({ principal }, DEFAULT_SESSION_SUBJECT); + const session = yield* sessions.issue({ + method: "browser-session-cookie", + subject, + scopes, + client, + }); + return { + sessionToken: session.token, + cookieName: sessions.cookieName, + expiresAt: DateTime.toUtc(session.expiresAt), + }; + }, + Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })), + ); + type ResolvedBootstrapGrant = Pick< PairingGrantStore.BootstrapGrant, "scopes" | "subject" | "label" @@ -1014,6 +1055,30 @@ 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 toPairingCredential = (issued: IssuedPairingLink): AuthPairingCredentialResult => ({ id: issued.id, credential: issued.credential, @@ -1023,10 +1088,11 @@ export const make = Effect.gen(function* () { const issuePairingLink = Effect.fn("EnvironmentAuth.issuePairingLink")( function* (input: Parameters[0]) { + 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 } : {}), @@ -1035,14 +1101,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 createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn( @@ -1082,33 +1152,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( @@ -1135,6 +1209,8 @@ export const make = Effect.gen(function* () { subject: "one-time-token", ...(input?.label ? { label: input.label } : {}), }).pipe( + // A non-principal subject cannot be refused principal scopes. + Effect.catchTags({ ServerAuthScopeNotGrantedError: Effect.die }), Effect.map(toPairingCredential), Effect.withSpan("EnvironmentAuth.issuePairingCredential"), ); @@ -1146,7 +1222,10 @@ export const make = Effect.gen(function* () { scopes: AuthStandardClientScopes, subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT, purpose: "startup", - }).pipe(Effect.map(toPairingCredential)); + }).pipe( + Effect.catchTags({ ServerAuthScopeNotGrantedError: Effect.die }), + Effect.map(toPairingCredential), + ); if (!devAuth) { return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential")); } @@ -1368,7 +1447,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, ), @@ -1386,6 +1466,7 @@ export const make = Effect.gen(function* () { }), getSessionState, createBrowserSession, + issuePrincipalBrowserSession, exchangeBootstrapCredentialForAccessToken, createPairingLink, issuePairingCredential, diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.ts index 1a5ad39c3585..3a5c8a9ddd97 100644 --- a/apps/server/src/auth/EnvironmentAuthPolicy.ts +++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts @@ -44,6 +44,7 @@ export const make = Effect.gen(function* () { bootstrapMethods, sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"], serverUpdateScope: AuthEnvironmentMaintainScope, + ...(config.oidc ? { oidcSignIn: true as const } : {}), sessionCookieName: resolveSessionCookieName({ mode: config.mode, port: config.port, diff --git a/apps/server/src/auth/OidcLogin.ts b/apps/server/src/auth/OidcLogin.ts new file mode 100644 index 000000000000..5c11008f3a4c --- /dev/null +++ b/apps/server/src/auth/OidcLogin.ts @@ -0,0 +1,219 @@ +// @effect-diagnostics nodeBuiltinImport:off - PKCE and state need Node hashing and randomness. +// @effect-diagnostics globalFetch:off - jose fetches the JWKS with the same injectable fetch, not an HttpClient. +import * as NodeCrypto from "node:crypto"; +import { DEFAULT_PRINCIPAL_ID, PrincipalId } from "@t3tools/contracts"; +import { createRemoteJWKSet, customFetch, jwtVerify } from "jose"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import * as ServerConfig from "../config.ts"; + +export type OidcClient = "web" | "desktop"; + +const LOGIN_TTL_MS = 10 * 60 * 1000; +const REQUEST_TIMEOUT_MS = 10_000; +const MAX_PENDING_LOGINS = 1_000; + +export class OidcLoginError extends Schema.TaggedError()("OidcLoginError", { + reason: Schema.Literals([ + "disabled", + "origin", + "state", + "provider", + "token", + "group", + "principal", + ]), +}) { + override get message(): string { + return `OIDC sign-in refused: ${this.reason}.`; + } +} + +const Discovery = Schema.Struct({ + issuer: Schema.String, + authorization_endpoint: Schema.String, + token_endpoint: Schema.String, + jwks_uri: Schema.String, +}); +const TokenResponse = Schema.Struct({ id_token: Schema.String }); +const decodeDiscovery = Schema.decodeUnknownEffect(Discovery); +const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse); +const isPrincipalId = Schema.is(PrincipalId); + +interface PendingLogin { + readonly nonce: string; + readonly verifier: string; + readonly client: OidcClient; + readonly origin: string; + readonly expiresAt: number; +} + +export class OidcLogin extends Context.Service< + OidcLogin, + { + readonly start: (input: { + readonly client: OidcClient; + readonly origin: string; + }) => Effect.Effect; + readonly complete: (input: { + readonly state: string; + readonly code: string; + }) => Effect.Effect< + { readonly principal: string; readonly client: OidcClient; readonly origin: string }, + OidcLoginError + >; + } +>()("t3/auth/OidcLogin") {} + +const random = () => NodeCrypto.randomBytes(32).toString("base64url"); +const sha256 = (value: string) => NodeCrypto.createHash("sha256").update(value).digest("base64url"); + +const callbackUrl = (origin: string) => `${origin}/auth/oidc/callback`; + +/** Kanidm emits `name@domain`; a bare name matches too. */ +const inGroup = (groups: unknown, allowed: string) => + Array.isArray(groups) && + groups.some( + (group) => group === allowed || (typeof group === "string" && group.startsWith(`${allowed}@`)), + ); + +export const makeWith = Effect.fn("OidcLogin.make")(function* (fetchImpl: typeof fetch) { + const { oidc } = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + // ponytail: pending logins live in this process; a restart drops them and the user signs in again. + const pending = new Map(); + let discovered: + | { readonly meta: typeof Discovery.Type; readonly jwks: ReturnType } + | undefined; + + const request = (url: string, init?: RequestInit) => + Effect.tryPromise(async () => { + const response = await fetchImpl(url, { + ...init, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return (await response.json()) as unknown; + }).pipe( + Effect.tapError((cause) => Effect.logWarning("OIDC provider request failed", { cause })), + Effect.mapError(() => new OidcLoginError({ reason: "provider" })), + ); + + const discover = Effect.fn("OidcLogin.discover")(function* (issuer: string) { + if (discovered) return discovered; + const meta = yield* request(`${issuer}/.well-known/openid-configuration`).pipe( + Effect.flatMap(decodeDiscovery), + Effect.mapError(() => new OidcLoginError({ reason: "provider" })), + ); + if (meta.issuer !== issuer) return yield* new OidcLoginError({ reason: "provider" }); + discovered = { + meta, + jwks: createRemoteJWKSet(new URL(meta.jwks_uri), { [customFetch]: fetchImpl }), + }; + return discovered; + }); + + const start: OidcLogin["Service"]["start"] = Effect.fn("OidcLogin.start")(function* (input) { + if (!oidc) return yield* new OidcLoginError({ reason: "disabled" }); + if (!oidc.publicOrigins.includes(input.origin)) { + return yield* new OidcLoginError({ reason: "origin" }); + } + const { meta } = yield* discover(oidc.issuer); + const now = yield* Clock.currentTimeMillis; + for (const [key, login] of pending) if (login.expiresAt <= now) pending.delete(key); + if (pending.size >= MAX_PENDING_LOGINS) return yield* new OidcLoginError({ reason: "state" }); + const state = random(); + const verifier = random(); + const nonce = random(); + pending.set(state, { + nonce, + verifier, + client: input.client, + origin: input.origin, + expiresAt: now + LOGIN_TTL_MS, + }); + const url = new URL(meta.authorization_endpoint); + url.search = new URLSearchParams({ + response_type: "code", + client_id: oidc.clientId, + redirect_uri: callbackUrl(input.origin), + scope: "openid profile groups", + state, + nonce, + code_challenge: sha256(verifier), + code_challenge_method: "S256", + }).toString(); + return url.toString(); + }); + + const complete: OidcLogin["Service"]["complete"] = Effect.fn("OidcLogin.complete")( + function* (input) { + if (!oidc) return yield* new OidcLoginError({ reason: "disabled" }); + const login = pending.get(input.state); + pending.delete(input.state); + const now = yield* Clock.currentTimeMillis; + if (!login || login.expiresAt <= now) return yield* new OidcLoginError({ reason: "state" }); + const { meta, jwks } = yield* discover(oidc.issuer); + const secret = yield* fileSystem.readFileString(oidc.clientSecretFile).pipe( + Effect.map((value) => value.trim()), + Effect.mapError(() => new OidcLoginError({ reason: "provider" })), + ); + const basic = Buffer.from( + `${encodeURIComponent(oidc.clientId)}:${encodeURIComponent(secret)}`, + ).toString("base64"); + const { id_token } = yield* request(meta.token_endpoint, { + method: "POST", + headers: { + authorization: `Basic ${basic}`, + "content-type": "application/x-www-form-urlencoded", + accept: "application/json", + }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: input.code, + redirect_uri: callbackUrl(login.origin), + code_verifier: login.verifier, + }), + }).pipe( + Effect.flatMap(decodeTokenResponse), + Effect.mapError(() => new OidcLoginError({ reason: "provider" })), + ); + const payload = yield* Effect.tryPromise(() => + jwtVerify(id_token, jwks, { + issuer: oidc.issuer, + audience: oidc.clientId, + algorithms: ["ES256", "RS256"], + requiredClaims: ["exp"], + }), + ).pipe( + Effect.map((verified) => verified.payload), + Effect.mapError(() => new OidcLoginError({ reason: "token" })), + ); + if (payload.nonce !== login.nonce) return yield* new OidcLoginError({ reason: "token" }); + if (!inGroup(payload.groups, oidc.allowedGroup)) { + return yield* new OidcLoginError({ reason: "group" }); + } + const principal = payload[oidc.principalClaim]; + if ( + typeof principal !== "string" || + !isPrincipalId(principal) || + principal === DEFAULT_PRINCIPAL_ID + ) { + return yield* new OidcLoginError({ reason: "principal" }); + } + return { principal, client: login.client, origin: login.origin }; + }, + ); + + return OidcLogin.of({ start, complete }); +}); + +export const layer = Layer.effect( + OidcLogin, + makeWith((input, init) => globalThis.fetch(input, init)), +); diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 8044740a7e2e..49e17231c58a 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,49 @@ it.effect("denies manual cleanup before the handler without settings permission" expect(handled).toBe(false); }).pipe(Effect.scoped), ); + +describe("principal RPC deny-list", () => { + const tested = [WS_METHODS.serverProbe, WS_METHODS.agentSessionsScan] as const; + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + (tag): tag is Exclude => + !(tested as ReadonlyArray).includes(tag), + ), + ); + + it("names only declared methods and leaves everyday ones reachable", () => { + for (const method of RpcAuthorization.PRINCIPAL_DENIED_RPC_METHODS) { + expect(Object.hasOwn(RPC_REQUIRED_SCOPES, method)).toBe(true); + } + for (const method of [ + WS_METHODS.terminalOpen, + WS_METHODS.projectsMutate, + WS_METHODS.providerAuthStart, + ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + ]) { + expect(RpcAuthorization.PRINCIPAL_DENIED_RPC_METHODS.has(method)).toBe(false); + } + }); + + it.effect("refuses a denied method despite its scope, and runs the rest", () => + 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.agentSessionsScan, () => + Effect.sync(() => handled.push("storage")).pipe(Effect.andThen(Effect.never)), + ), + RpcAuthorization.layer([AuthOrchestrationReadScope], undefined, "alice"), + ), + ), + ); + expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({}); + expect(yield* client[WS_METHODS.agentSessionsScan]({}).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 f040dbc45940..8f692534d140 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, @@ -273,6 +274,22 @@ const requiredScopesForRpcCall = ( return [requiredScopeForRpcMethod(method)]; }; +/** + * Server-wide or server-account methods that stay refused to a principal even though its scopes + * pass them. Add any new such method here. + */ +export const PRINCIPAL_DENIED_RPC_METHODS: ReadonlySet = new Set([ + WS_METHODS.serverGetStorageCleanupReport, + WS_METHODS.serverGetDatabaseStorage, + WS_METHODS.scheduledTasksListWebhookDeliveries, + WS_METHODS.scheduledTasksGetWebhookDelivery, + WS_METHODS.agentSessionsScan, + WS_METHODS.agentSessionsImport, + WS_METHODS.serverListAcpRegistrySessions, + WS_METHODS.serverImportAcpRegistrySession, + WS_METHODS.serverDeleteAcpRegistrySession, +]); + /** * `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 @@ -281,8 +298,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_DENIED_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 4047974500c4..b36421586640 100644 --- a/apps/server/src/auth/http.test.ts +++ b/apps/server/src/auth/http.test.ts @@ -2,6 +2,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { AuthTokenExchangeGrantType, AuthEnvironmentBootstrapTokenType, + AuthSessionId, + ThreadId, + EnvironmentAuthenticatedPrincipal, + type AuthEnvironmentScope, AuthAccessTokenType, EnvironmentHttpApi, } from "@t3tools/contracts"; @@ -157,3 +161,26 @@ it.effect("sets the selected browser session cookies through the HTTP route", () ); }).pipe(Effect.provide(NodeServices.layer)), ); + +it.effect( + "lets a principal reach only its own threads over HTTP, and the default principal all", + () => + Effect.gen(function* () { + const accessAs = (subject: string, ownerPrincipal: string | undefined) => + AuthHttp.requireThreadAccess("orchestration:read", ThreadId.make("thread-1"), () => + Effect.succeed({ id: "thread-1", ownerPrincipal }), + () => Effect.succeed(new Map()), + ).pipe( + Effect.provideService(EnvironmentAuthenticatedPrincipal, { + sessionId: AuthSessionId.make("test-session"), + subject, + method: "bearer-access-token", + scopes: new Set(["orchestration:read"]), + }), + Effect.result, + ); + expect((yield* accessAs("principal:alice", "alice"))._tag).toBe("Success"); + expect((yield* accessAs("principal:bob", "alice"))._tag).toBe("Failure"); + expect((yield* accessAs("browser", "alice"))._tag).toBe("Success"); + }), +); diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 2358e73d6d86..c7fdcf0f50bc 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, @@ -18,7 +20,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"; @@ -32,6 +34,11 @@ import { HttpServerRequest, HttpServerResponse } from "effect/http"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import { + canAccessThread, + type ThreadAction, + type ThreadGrants, +} from "../orchestration-v2/ThreadOwnership.ts"; import * as SessionStore from "./SessionStore.ts"; import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts"; import { deriveAuthClientMetadata } from "./utils.ts"; @@ -225,6 +232,28 @@ export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope" 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 id: string; + readonly ownerPrincipal?: string | undefined; + } | null>, + grantsFor: (principal: string) => Effect.Effect, + action: ThreadAction = "read", +) { + const session = yield* requireEnvironmentScope(scope); + const principal = principalOfSubject(session.subject); + // The default principal reaches every thread; skip the owner read on its hot path. + if (principal === DEFAULT_PRINCIPAL_ID) return session; + const thread = yield* readOwner(threadId); + if (thread === null || !canAccessThread(principal, thread, action, yield* grantsFor(principal))) { + return yield* failEnvironmentNotFound("thread_not_found"); + } + return session; +}); + export const layerAuthenticatedAuth = Layer.effect( EnvironmentAuthenticatedAuth, Effect.gen(function* () { diff --git a/apps/server/src/auth/oidcHttp.test.ts b/apps/server/src/auth/oidcHttp.test.ts new file mode 100644 index 000000000000..5f1acc520669 --- /dev/null +++ b/apps/server/src/auth/oidcHttp.test.ts @@ -0,0 +1,282 @@ +// @effect-diagnostics nodeBuiltinImport:off - the fake issuer verifies PKCE with Node hashing. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Etag from "effect/http/Etag"; +import * as HttpPlatform from "effect/http/HttpPlatform"; +import * as HttpRouter from "effect/http/HttpRouter"; +import { HttpServerRequest, HttpServerResponse } from "effect/http"; +import { getPairingTokenFromUrl, readPairingAppLink } from "@t3tools/shared/remote"; +import { exportJWK, generateKeyPair, SignJWT } from "jose"; + +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as OidcHttp from "./oidcHttp.ts"; +import * as OidcLogin from "./OidcLogin.ts"; +import * as ServerSecretStore from "./ServerSecretStore.ts"; + +const ISSUER = "https://idm.test/oauth2/openid/t3code"; +const ORIGIN = "http://127.0.0.1"; +const CLIENT_ID = "t3code"; +const CLIENT_SECRET = "s3cret value"; + +const secretDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-oidc-test-")); +const secretFile = NodePath.join(secretDir, "client-secret"); +NodeFS.writeFileSync(secretFile, `${CLIENT_SECRET}\n`); + +const { publicKey, privateKey } = await generateKeyPair("ES256"); +const jwk = { ...(await exportJWK(publicKey)), kid: "k1", alg: "ES256", use: "sig" }; + +interface Claims { + groups: unknown; + preferred_username: unknown; + nonce?: string; + expiresAt: number; +} +const goodClaims = (): Claims => ({ + groups: ["t3code_users@idm.test", "other@idm.test"], + preferred_username: "dejana", + expiresAt: 4_102_444_800, +}); + +const makeFakeIssuer = () => { + const issuer = { + claims: goodClaims(), + codes: new Map(), + }; + const json = (body: unknown) => + new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } }); + const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : input.toString()); + if (url.pathname.endsWith("/.well-known/openid-configuration")) { + return json({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/authorize`, + token_endpoint: `${ISSUER}/token`, + jwks_uri: `${ISSUER}/jwks`, + }); + } + if (url.pathname.endsWith("/jwks")) return json({ keys: [jwk] }); + if (url.pathname.endsWith("/token")) { + const headers = new Headers(init?.headers); + const expected = Buffer.from(`${CLIENT_ID}:${encodeURIComponent(CLIENT_SECRET)}`).toString( + "base64", + ); + if (headers.get("authorization") !== `Basic ${expected}`) + return new Response("", { status: 401 }); + const form = new URLSearchParams(String(init?.body)); + const pending = issuer.codes.get(form.get("code") ?? ""); + const verifier = form.get("code_verifier") ?? ""; + const challenge = NodeCrypto.createHash("sha256").update(verifier).digest("base64url"); + if (!pending || pending.challenge !== challenge) return new Response("", { status: 400 }); + const { expiresAt, nonce, ...rest } = issuer.claims; + const idToken = await new SignJWT({ ...rest, nonce: nonce ?? pending.nonce }) + .setProtectedHeader({ alg: "ES256", kid: "k1" }) + .setIssuer(ISSUER) + .setAudience(CLIENT_ID) + .setSubject("uuid-1") + .setIssuedAt(1) + .setExpirationTime(expiresAt) + .sign(privateKey); + return json({ id_token: idToken }); + } + return new Response("", { status: 404 }); + }) as typeof fetch; + return { issuer, fetchImpl }; +}; + +const layerConfig = Layer.effect( + ServerConfig.ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + return { + ...config, + mode: "web", + oidc: { + issuer: ISSUER, + clientId: CLIENT_ID, + clientSecretFile: secretFile, + allowedGroup: "t3code_users", + principalClaim: "preferred_username", + publicOrigins: [ORIGIN], + }, + } satisfies ServerConfig.ServerConfig["Service"]; + }), +).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-oidc-http-test-" }))); + +const layerEnvironmentAuth = EnvironmentAuth.layer.pipe( + Layer.provide(ManagedPolicy.layerTest()), + Layer.provide(SqlitePersistence.layerMemory), + Layer.provide(ServerSecretStore.layer), + Layer.provide(ServerEnvironment.layerIdentity), + Layer.provide(layerConfig), +); + +const probeRoute = HttpRouter.add( + "GET", + "/probe", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const session = yield* auth.authenticateHttpRequest(request); + return yield* HttpServerResponse.json({ subject: session.subject, method: session.method }); + }), +); + +const makeRoutes = (fetchImpl: typeof fetch) => + Layer.mergeAll(OidcHttp.layer, probeRoute).pipe( + Layer.provideMerge(Layer.effect(OidcLogin.OidcLogin, OidcLogin.makeWith(fetchImpl))), + Layer.provideMerge(layerEnvironmentAuth), + Layer.provide(layerConfig), + Layer.provideMerge( + HttpPlatform.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Etag.layerWeak), + ), + ), + Layer.provide(NodeServices.layer), + ); + +const withServer = ( + use: ( + fake: ReturnType["issuer"], + get: (path: string, headers?: Record) => Promise, + ) => Promise, +) => + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const unusedSecretStore = ServerSecretStore.ServerSecretStore.of({ + get: () => Effect.succeedNone, + set: () => Effect.void, + create: () => Effect.void, + getOrCreateRandom: () => Effect.die("Not used by these routes."), + remove: () => Effect.void, + }); + const requestContext = Context.make(Crypto.Crypto, crypto).pipe( + Context.add(ServerSecretStore.ServerSecretStore, unusedSecretStore), + ); + const { issuer, fetchImpl } = makeFakeIssuer(); + return yield* Effect.acquireUseRelease( + Effect.sync(() => HttpRouter.toWebHandler(makeRoutes(fetchImpl), { disableLogger: true })), + (server) => + Effect.tryPromise(() => + use(issuer, (path, headers) => + server.handler( + new Request(path.startsWith("http") ? path : `${ORIGIN}${path}`, { + headers: { + host: new URL(path.startsWith("http") ? path : ORIGIN).host, + ...headers, + }, + redirect: "manual", + }), + requestContext, + ), + ), + ), + (server) => Effect.promise(() => server.dispose()), + ); + }).pipe(Effect.provide(NodeServices.layer)); + +/** Starts a login and returns the callback path the provider would send the browser to. */ +const beginLogin = async ( + fake: ReturnType["issuer"], + get: (path: string) => Promise, + client: "web" | "desktop" = "web", +) => { + const started = await get(`/auth/oidc/start?client=${client}`); + expect(started.status).toBe(302); + const location = new URL(started.headers.get("location") ?? ""); + expect(location.origin + location.pathname).toBe(`${ISSUER}/authorize`); + expect(location.searchParams.get("code_challenge_method")).toBe("S256"); + expect(location.searchParams.get("redirect_uri")).toBe(`${ORIGIN}/auth/oidc/callback`); + const state = location.searchParams.get("state") ?? ""; + fake.codes.set("code-1", { + nonce: location.searchParams.get("nonce") ?? "", + challenge: location.searchParams.get("code_challenge") ?? "", + }); + return `/auth/oidc/callback?state=${state}&code=code-1`; +}; + +it.effect("signs a group member in with a principal browser session", () => + withServer(async (fake, get) => { + const callback = await beginLogin(fake, get); + const response = await get(callback); + expect(response.status).toBe(302); + expect(response.headers.get("location")).toBe("/"); + const cookie = response.headers.getSetCookie().find((entry) => entry.startsWith("t3_session_")); + expect(cookie).toContain("HttpOnly"); + const probe = await get("/probe", { cookie: cookie?.split(";", 1)[0] ?? "" }); + expect(await probe.json()).toEqual({ + subject: "principal:dejana", + method: "browser-session-cookie", + }); + }), +); + +it.effect("hands the desktop a principal pairing link through the app deep link", () => + withServer(async (fake, get) => { + const response = await get(await beginLogin(fake, get, "desktop")); + expect(response.status).toBe(302); + const location = response.headers.get("location") ?? ""; + expect(location.startsWith("t3code://pair?")).toBe(true); + const pairingUrl = new URL(readPairingAppLink(location) ?? ""); + expect(pairingUrl.origin + pairingUrl.pathname).toBe(`${ORIGIN}/pair`); + expect(getPairingTokenFromUrl(pairingUrl)).toBeTruthy(); + }), +); + +it.effect("refuses a user outside the allowed group", () => + withServer(async (fake, get) => { + fake.claims.groups = ["t3code_users_extra@idm.test", "other"]; + const response = await get(await beginLogin(fake, get)); + expect(response.status).toBe(403); + expect(response.headers.getSetCookie()).toEqual([]); + }), +); + +it.effect("refuses an ID token whose nonce does not match", () => + withServer(async (fake, get) => { + fake.claims.nonce = "someone-elses-nonce"; + const response = await get(await beginLogin(fake, get)); + expect(response.status).toBe(403); + expect(response.headers.getSetCookie()).toEqual([]); + }), +); + +it.effect("refuses an expired ID token", () => + withServer(async (fake, get) => { + fake.claims.expiresAt = 2; + const response = await get(await beginLogin(fake, get)); + expect(response.status).toBe(403); + expect(response.headers.getSetCookie()).toEqual([]); + }), +); + +it.effect("refuses a principal claim that is not a valid principal id", () => + withServer(async (fake, get) => { + fake.claims.preferred_username = "owner"; + const response = await get(await beginLogin(fake, get)); + expect(response.status).toBe(403); + }), +); + +it.effect("refuses a reused or unknown state, and a start from an unlisted origin", () => + withServer(async (fake, get) => { + const callback = await beginLogin(fake, get); + expect((await get(callback)).status).toBe(302); + expect((await get(callback)).status).toBe(400); + expect((await get("/auth/oidc/callback?state=nope&code=code-1")).status).toBe(400); + const foreign = await get("http://evil.example/auth/oidc/start"); + expect(foreign.status).toBe(400); + }), +); diff --git a/apps/server/src/auth/oidcHttp.ts b/apps/server/src/auth/oidcHttp.ts new file mode 100644 index 000000000000..cc8a64bcda07 --- /dev/null +++ b/apps/server/src/auth/oidcHttp.ts @@ -0,0 +1,101 @@ +import { buildPairingAppLink, setPairingTokenOnUrl } from "@t3tools/shared/remote"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; + +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import { OidcLogin, OidcLoginError, type OidcClient } from "./OidcLogin.ts"; +import { deriveAuthClientMetadata } from "./utils.ts"; + +const NO_STORE = { "cache-control": "no-store", pragma: "no-cache" }; +const PAIRING_TTL = Duration.minutes(2); + +const STATUS: Record = { + disabled: 404, + origin: 400, + state: 400, + provider: 502, + token: 403, + group: 403, + principal: 403, +}; + +const failure = (status: number, text: string) => + HttpServerResponse.text(text, { status, headers: NO_STORE }); + +const refuse = (error: OidcLoginError) => + failure(STATUS[error.reason], "Sign-in was refused. Close this tab and try again."); + +const requestOrigin = Effect.map(HttpServerRequest.HttpServerRequest, (request) => { + const url = HttpServerRequest.toURL(request); + return url._tag === "Some" ? url.value.origin : ""; +}); + +const startRoute = HttpRouter.add( + "GET", + "/auth/oidc/start", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const query = new URLSearchParams(request.url.split("?", 2)[1] ?? ""); + const client: OidcClient = query.get("client") === "desktop" ? "desktop" : "web"; + const oidc = yield* OidcLogin; + const origin = yield* requestOrigin; + return yield* oidc.start({ client, origin }).pipe( + Effect.map((location) => + HttpServerResponse.redirect(location, { status: 302, headers: NO_STORE }), + ), + Effect.catchTags({ OidcLoginError: (error) => Effect.succeed(refuse(error)) }), + ); + }).pipe(Effect.withSpan("auth.oidc.start")), +); + +const callbackRoute = HttpRouter.add( + "GET", + "/auth/oidc/callback", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const query = new URLSearchParams(request.url.split("?", 2)[1] ?? ""); + const state = query.get("state"); + const code = query.get("code"); + if (query.has("error") || !state || !code) { + return failure(403, "Sign-in was refused. Close this tab and try again."); + } + const oidc = yield* OidcLogin; + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const login = yield* oidc.complete({ state, code }); + const metadata = deriveAuthClientMetadata({ request }); + if (login.client === "desktop") { + const link = yield* auth.createPairingLink({ + principal: login.principal, + ttl: PAIRING_TTL, + label: `${login.principal} (desktop)`, + }); + const pairingUrl = setPairingTokenOnUrl(new URL("/pair", login.origin), link.credential); + return HttpServerResponse.redirect(buildPairingAppLink(pairingUrl.toString()), { + status: 302, + headers: NO_STORE, + }); + } + const session = yield* auth.issuePrincipalBrowserSession(login.principal, metadata); + return yield* HttpServerResponse.redirect("/", { status: 302, headers: NO_STORE }).pipe( + HttpServerResponse.setCookie(session.cookieName, session.sessionToken, { + expires: DateTime.toDate(session.expiresAt), + httpOnly: true, + path: "/", + sameSite: "lax", + }), + ); + }).pipe( + Effect.catchTags({ OidcLoginError: (error) => Effect.succeed(refuse(error)) }), + Effect.catch((error) => + Effect.logError("OIDC sign-in failed after verification", { cause: error }).pipe( + Effect.as(failure(500, "Sign-in failed. Close this tab and try again.")), + ), + ), + Effect.withSpan("auth.oidc.callback"), + ), +); + +export const layer = Layer.mergeAll(startRoute, callbackRoute); diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 32f00bde6399..349a21a40522 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -12,6 +12,7 @@ import packageJson from "../package.json" with { type: "json" }; import { acpMcpBridgeCommand, acpMcpCallCommand } from "./cli/acpMcpBridge.ts"; import { authCommand } from "./cli/auth.ts"; import { environmentCommand } from "./cli/environment.ts"; +import { groupCommand, shareCommand, unshareCommand } from "./cli/sessionAccess.ts"; import { appCommand } from "./cli/app.ts"; import { browserCommand } from "./cli/browser.ts"; import { pairCommand } from "./cli/pair.ts"; @@ -80,6 +81,9 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => pairCommand, authCommand, environmentCommand, + groupCommand, + shareCommand, + unshareCommand, browserCommand, projectCommand, threadCommand, diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.ts index b75fba88bddc..a7e34e4e19f7 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/cli/config.ts b/apps/server/src/cli/config.ts index f86fde0f5975..380a1c4d10b6 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -147,6 +147,33 @@ const EnvServerConfig = Config.all({ .filter((entry) => entry.length > 0), ), ), + oidcIssuer: Config.String("T3CODE_OIDC_ISSUER").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + oidcClientId: Config.String("T3CODE_OIDC_CLIENT_ID").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + oidcClientSecretFile: Config.String("T3CODE_OIDC_CLIENT_SECRET_FILE").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + oidcAllowedGroup: Config.String("T3CODE_OIDC_ALLOWED_GROUP").pipe( + Config.withDefault("t3code_users"), + ), + oidcPrincipalClaim: Config.String("T3CODE_OIDC_PRINCIPAL_CLAIM").pipe( + Config.withDefault("preferred_username"), + ), + oidcPublicOrigins: Config.String("T3CODE_OIDC_PUBLIC_ORIGINS").pipe( + Config.withDefault(""), + Config.map((value) => + value + .split(",") + .map((entry) => entry.trim().replace(/\/+$/, "")) + .filter((entry) => entry.length > 0), + ), + ), noBrowser: Config.Boolean("T3CODE_NO_BROWSER").pipe( Config.option, Config.map(Option.getOrUndefined), @@ -194,6 +221,32 @@ const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe( Config.map(Option.getOrUndefined), ); +const resolveOidcConfig = Effect.fn("cli.resolveOidcConfig")(function* (env: { + readonly oidcIssuer: string | undefined; + readonly oidcClientId: string | undefined; + readonly oidcClientSecretFile: string | undefined; + readonly oidcAllowedGroup: string; + readonly oidcPrincipalClaim: string; + readonly oidcPublicOrigins: ReadonlyArray; +}) { + const issuer = env.oidcIssuer?.trim().replace(/\/+$/, ""); + if (!issuer) return undefined; + if (!env.oidcClientId || !env.oidcClientSecretFile || env.oidcPublicOrigins.length === 0) { + return yield* new CliError.UserError({ + cause: + "T3CODE_OIDC_ISSUER also needs T3CODE_OIDC_CLIENT_ID, T3CODE_OIDC_CLIENT_SECRET_FILE and T3CODE_OIDC_PUBLIC_ORIGINS.", + }); + } + return { + issuer, + clientId: env.oidcClientId, + clientSecretFile: env.oidcClientSecretFile, + allowedGroup: env.oidcAllowedGroup, + principalClaim: env.oidcPrincipalClaim, + publicOrigins: env.oidcPublicOrigins, + } satisfies ServerConfig.OidcConfig; +}); + export interface CliServerFlags { readonly mode: Option.Option; readonly port: Option.Option; @@ -473,6 +526,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct }, ); + const oidc = yield* resolveOidcConfig(env); const config: ServerConfig.ServerConfig["Service"] = { logLevel, traceMinLevel: env.traceMinLevel, @@ -505,6 +559,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct devUrl, ...(devAuthToken === undefined ? {} : { devAuthToken }), devAllowedOrigins: env.devAllowedOrigins, + ...(oidc === undefined ? {} : { oidc }), noBrowser, startupPresentation, desktopBootstrapToken, diff --git a/apps/server/src/cli/sessionAccess.ts b/apps/server/src/cli/sessionAccess.ts new file mode 100644 index 000000000000..b3de7f066f5b --- /dev/null +++ b/apps/server/src/cli/sessionAccess.ts @@ -0,0 +1,239 @@ +import { + DEFAULT_PRINCIPAL_ID, + PrincipalId, + SessionGroupId, + SessionRole, + SessionAccessSnapshot, + ThreadId, +} from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as Layer from "effect/Layer"; +import * as References from "effect/References"; +import * as Schema from "effect/Schema"; +import * as Argument from "effect/cli/Argument"; +import * as Command from "effect/cli/Command"; +import * as Flag from "effect/cli/Flag"; +import * as GlobalFlag from "effect/cli/GlobalFlag"; + +import * as ServerConfig from "../config.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as SessionAccess from "../orchestration-v2/SessionAccess.ts"; +import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; + +const asFlag = Flag.String("as").pipe( + Flag.withDescription( + "Act as this principal. Defaults to the environment owner, who may manage everything.", + ), + Flag.withDefault(DEFAULT_PRINCIPAL_ID), + Flag.withSchema(PrincipalId), +); + +const roleFlag = Flag.Literals("role", SessionRole.literals).pipe( + Flag.withDescription("viewer reads; participant also sends messages and steers turns."), + Flag.withDefault("viewer" as const), +); + +const jsonFlag = Flag.Boolean("json").pipe( + Flag.withDescription("Emit JSON instead of human-readable output."), + Flag.withDefault(false), +); + +const groupArg = Argument.String("group").pipe( + Argument.withDescription("The group id, from `t3 group list`."), + Argument.withSchema(SessionGroupId), +); +const threadArg = Argument.String("thread").pipe(Argument.withSchema(ThreadId)); +const principalArg = Argument.String("principal").pipe(Argument.withSchema(PrincipalId)); + +/** Groups and shares live in this environment's database, so these work whether or not its server runs. */ +const runWithSessionAccess = Effect.fn("sessionAccess.run")(function* ( + flags: CliAuthLocationFlags, + run: (access: SessionAccess.SessionAccess["Service"]) => Effect.Effect, + options?: { readonly quietLogs?: boolean }, +) { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel, options); + return yield* SessionAccess.SessionAccess.pipe( + Effect.flatMap(run), + Effect.provide( + SessionAccess.layer.pipe( + Layer.provide(SqlitePersistence.layerConfig), + Layer.provide(ServerConfig.layer(config)), + Layer.provide( + Layer.succeed(References.MinimumLogLevel, options?.quietLogs ? "Error" : config.logLevel), + ), + ), + ), + ); +}); + +const encodeSnapshot = Schema.encodeEffect(Schema.fromJsonString(SessionAccessSnapshot)); + +const formatGroups = (snapshot: SessionAccessSnapshot) => + snapshot.groups.length === 0 + ? "No groups.\n" + : `${snapshot.groups + .map( + (group) => + `${group.name} (${group.id}) owned by ${group.ownerPrincipal}, you: ${group.callerRole}\n members: ${group.members.map((member) => `${member.principal}:${member.role}`).join(", ") || "none"}\n threads: ${group.threadIds.join(", ") || "none"}`, + ) + .join("\n\n")}\n`; + +const groupCreate = Command.make("create", { + ...authLocationFlags, + as: asFlag, + name: Argument.String("name"), +}).pipe( + Command.withDescription("Create a session group you own."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const groupId = SessionGroupId.make( + Hex.encode(yield* crypto.randomBytes(8).pipe(Effect.orDie)), + ); + yield* access.mutate(flags.as, { type: "group.create", groupId, name: flags.name }); + yield* Console.log(`${groupId}\n`); + }), + ), + ), +); + +const groupList = Command.make("list", { ...authLocationFlags, as: asFlag, json: jsonFlag }).pipe( + Command.withDescription("List the groups you own or belong to."), + Command.withHandler((flags) => + runWithSessionAccess( + flags, + (access) => + Effect.gen(function* () { + const snapshot = yield* access.snapshot(flags.as); + yield* Console.log( + flags.json ? `${yield* encodeSnapshot(snapshot)}\n` : formatGroups(snapshot), + ); + }), + { quietLogs: flags.json }, + ), + ), +); + +const groupDelete = Command.make("delete", { + ...authLocationFlags, + as: asFlag, + group: groupArg, +}).pipe( + Command.withDescription("Delete a group. Its threads stay, and its members lose access to them."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + access.mutate(flags.as, { type: "group.delete", groupId: flags.group }), + ), + ), +); + +const groupAddThread = Command.make("add-thread", { + ...authLocationFlags, + as: asFlag, + group: groupArg, + thread: threadArg, +}).pipe( + Command.withDescription("Put one of your threads in a group. A thread belongs to one group."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + access.mutate(flags.as, { + type: "group.thread.add", + groupId: flags.group, + threadId: flags.thread, + }), + ), + ), +); + +const groupInvite = Command.make("invite", { + ...authLocationFlags, + as: asFlag, + group: groupArg, + principal: principalArg, + role: roleFlag, +}).pipe( + Command.withDescription("Invite a principal to a group, or change their role."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + access.mutate(flags.as, { + type: "group.member.invite", + groupId: flags.group, + principal: flags.principal, + role: flags.role, + }), + ), + ), +); + +const groupRemove = Command.make("remove", { + ...authLocationFlags, + as: asFlag, + group: groupArg, + principal: principalArg, +}).pipe( + Command.withDescription("Remove a member from a group."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + access.mutate(flags.as, { + type: "group.member.remove", + groupId: flags.group, + principal: flags.principal, + }), + ), + ), +); + +export const groupCommand = Command.make("group").pipe( + Command.withDescription("Manage session groups: threads shared with a set of principals."), + Command.withSubcommands([ + groupCreate, + groupList, + groupDelete, + groupAddThread, + groupInvite, + groupRemove, + ]), +); + +export const shareCommand = Command.make("share", { + ...authLocationFlags, + as: asFlag, + thread: threadArg, + principal: principalArg, + role: roleFlag, +}).pipe( + Command.withDescription("Share one of your threads with a principal."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + access.mutate(flags.as, { + type: "thread.share", + threadId: flags.thread, + principal: flags.principal, + role: flags.role, + }), + ), + ), +); + +export const unshareCommand = Command.make("unshare", { + ...authLocationFlags, + as: asFlag, + thread: threadArg, + principal: principalArg, +}).pipe( + Command.withDescription("Stop sharing one of your threads with a principal."), + Command.withHandler((flags) => + runWithSessionAccess(flags, (access) => + access.mutate(flags.as, { + type: "thread.unshare", + threadId: flags.thread, + principal: flags.principal, + }), + ), + ), +); diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts index 6909d66fe287..6a2ca422ef7b 100644 --- a/apps/server/src/cloud/CloudLink.ts +++ b/apps/server/src/cloud/CloudLink.ts @@ -1584,13 +1584,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/config.ts b/apps/server/src/config.ts index 468cc89ad01e..b41fbae2a3b0 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -59,6 +59,16 @@ export interface DeriveServerPathsOptions { readonly baseDirIsExplicit?: boolean; } +export interface OidcConfig { + readonly issuer: string; + readonly clientId: string; + readonly clientSecretFile: string; + readonly allowedGroup: string; + readonly principalClaim: string; + /** Origins that may host `/auth/oidc/callback`; the redirect URI is `/auth/oidc/callback`. */ + readonly publicOrigins: ReadonlyArray; +} + export class ServerConfig extends Context.Service< ServerConfig, ServerDerivedPaths & { @@ -92,6 +102,7 @@ export class ServerConfig extends Context.Service< readonly devUrl: URL | undefined; readonly devAuthToken?: Redacted.Redacted | undefined; readonly devAllowedOrigins: ReadonlyArray; + readonly oidc?: OidcConfig | undefined; readonly noBrowser: boolean; readonly startupPresentation: StartupPresentation; readonly desktopBootstrapToken: string | undefined; diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index b82d9bb5ae59..46316b9c4f41 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,12 @@ 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."), + "write", + ); 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 47a6bda166ce..c2fd79d76d5b 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,7 @@ describe("OrchestratorMcpService thread list", () => { ["thread:b-snoozed", "project:b"], ], ); + assert.equal(listed.total, 2); }).pipe(Effect.provide(service)), ); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 910a1531aedb..c560c12dc1e8 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"; @@ -1191,6 +1196,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; }); @@ -1255,6 +1265,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 = @@ -2814,6 +2830,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) => @@ -2913,6 +2932,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 aa107711f334..89826b044e73 100644 --- a/apps/server/src/mcp/threadAccess.test.ts +++ b/apps/server/src/mcp/threadAccess.test.ts @@ -38,3 +38,46 @@ 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: true }, + { caller: "bob", 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 d3fa0feda0d6..404259efb132 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 { canAccessThread, type ThreadAction } from "../orchestration-v2/ThreadOwnership.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; /** @@ -38,6 +40,18 @@ 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, + action: ThreadAction = "read", +) => (canAccessThread(principal, target, action) ? Effect.void : fail()); + export const unavailable = () => new OrchestratorMcpFailure({ code: "orchestration_error", @@ -188,6 +202,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 59399c7febde..de783c0be00e 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -245,6 +245,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 f96831243751..299acbf6c6ae 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/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 7bb8bf8a34c1..b8906497d6af 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -63,6 +63,9 @@ const RPC_AGGREGATES = { [WS_METHODS.peerLinksLink]: "peerLinks", [WS_METHODS.peerLinksUnlink]: "peerLinks", [WS_METHODS.peerLinksAnswerRequest]: "peerLinks", + [WS_METHODS.sessionAccessList]: "orchestration", + [WS_METHODS.sessionAccessThreadShares]: "orchestration", + [WS_METHODS.sessionAccessMutate]: "orchestration", [WS_METHODS.serverUpdateSettings]: "server", [WS_METHODS.serverSearchAcpRegistry]: "server", [WS_METHODS.serverPrepareAcpRegistryAgent]: "server", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 75df815127f3..374e1f276519 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2048,6 +2048,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(queuedMessage.senderThreadId === undefined ? {} : { senderThreadId: queuedMessage.senderThreadId }), + ...(queuedMessage.senderPrincipal === undefined ? {} : { senderPrincipal: queuedMessage.senderPrincipal }), ...(queuedMessage.idleCompaction === undefined ? {} : { idleCompaction: queuedMessage.idleCompaction }), @@ -2749,6 +2750,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 ? {} @@ -4667,6 +4669,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly creationSource: OrchestrationV2ConversationMessage["creationSource"]; readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"]; readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"]; + readonly senderPrincipal?: OrchestrationV2ConversationMessage["senderPrincipal"]; readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"]; readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"]; readonly forceRestart: boolean; @@ -4826,6 +4829,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: input.scheduledTaskId }), ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }), + ...(input.senderPrincipal === undefined ? {} : { senderPrincipal: input.senderPrincipal }), ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }), id: input.messageId, threadId: input.command.threadId, @@ -4846,6 +4850,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: input.scheduledTaskId }), ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }), + ...(input.senderPrincipal === undefined ? {} : { senderPrincipal: input.senderPrincipal }), ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }), id: idAllocator.derive.userTurnItem({ messageId: input.messageId }), threadId: input.command.threadId, @@ -5823,6 +5828,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), + ...(command.senderPrincipal === undefined ? {} : { senderPrincipal: command.senderPrincipal }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), forceRestart: dispatchMode.type === "restart_active", }); @@ -6058,6 +6064,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), + ...(command.senderPrincipal === undefined ? {} : { senderPrincipal: command.senderPrincipal }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: command.messageId, threadId: command.threadId, @@ -6405,6 +6412,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), + ...(command.senderPrincipal === undefined ? {} : { senderPrincipal: command.senderPrincipal }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: command.messageId, threadId: command.threadId, @@ -6427,6 +6435,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), + ...(command.senderPrincipal === undefined ? {} : { senderPrincipal: command.senderPrincipal }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), threadId: command.threadId, @@ -7157,6 +7166,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), + ...(command.senderPrincipal === undefined ? {} : { senderPrincipal: command.senderPrincipal }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: command.messageId, threadId: command.threadId, @@ -7179,6 +7189,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { scheduledTaskId: command.scheduledTaskId }), ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), + ...(command.senderPrincipal === undefined ? {} : { senderPrincipal: command.senderPrincipal }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), threadId: command.threadId, @@ -9562,6 +9573,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(queuedMessage.senderThreadId === undefined ? {} : { senderThreadId: queuedMessage.senderThreadId }), + ...(queuedMessage.senderPrincipal === undefined ? {} : { senderPrincipal: queuedMessage.senderPrincipal }), ...(queuedMessage.idleCompaction === undefined ? {} : { idleCompaction: queuedMessage.idleCompaction }), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index aadd9ecc8be0..b042de05643e 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 451a917770ec..dc19cf4cc58c 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; } @@ -1536,6 +1538,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 }), @@ -1817,6 +1822,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 }), @@ -6926,7 +6934,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, @@ -6939,6 +6947,16 @@ 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} + OR t.thread_id IN (SELECT thread_id FROM session_shares WHERE principal = ${ownerPrincipal}) + OR t.thread_id IN ( + SELECT gt.thread_id FROM session_group_threads gt + JOIN session_group_members m ON m.group_id = gt.group_id + WHERE m.principal = ${ownerPrincipal}))` } `; const belowCursor = diff --git a/apps/server/src/orchestration-v2/SessionAccess.test.ts b/apps/server/src/orchestration-v2/SessionAccess.test.ts new file mode 100644 index 000000000000..e5e0f921ecf2 --- /dev/null +++ b/apps/server/src/orchestration-v2/SessionAccess.test.ts @@ -0,0 +1,145 @@ +import { assert, it } from "@effect/vitest"; +import { ThreadId, type SessionAccessMutation } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as SessionAccess from "./SessionAccess.ts"; + +const layerTest = SessionAccess.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)); + +const groupId = (id: string) => id as never; +const thread = (id: string) => ThreadId.make(id); + +const insertThread = (id: string, owner: string | null) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const payload = JSON.stringify(owner === null ? {} : { ownerPrincipal: owner }); + yield* sql` + INSERT INTO orchestration_v2_projection_threads + (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + created_at, updated_at, payload_json) + VALUES (${id}, 'p', 't', 'codex', 'full-access', 'default', 'x', 'x', ${payload}) + `; + }); + +const reasonOf = (effect: Effect.Effect) => + effect.pipe( + Effect.flip, + Effect.map((error) => error.reason), + ); + +const create = (id: string): SessionAccessMutation => ({ + type: "group.create", + groupId: groupId(id), + name: id as never, +}); + +it.layer(layerTest)("SessionAccess", (it) => { + it.effect("only the thread owner shares a thread, and a grant opens it for the grantee", () => + Effect.gen(function* () { + const access = yield* SessionAccess.SessionAccess; + yield* insertThread("t-share", "alice"); + const share = (principal: string): SessionAccessMutation => ({ + type: "thread.share", + threadId: thread("t-share"), + principal: "carol", + role: "participant", + }); + assert.strictEqual(yield* reasonOf(access.mutate("bob", share("bob"))), "not_found"); + yield* access.mutate("alice", share("alice")); + assert.strictEqual((yield* access.grantsFor("carol")).get("t-share"), "participant"); + // A grantee sees the thread but still cannot share it on. + assert.strictEqual(yield* reasonOf(access.mutate("carol", share("carol"))), "forbidden"); + assert.strictEqual( + yield* reasonOf( + access.mutate("alice", { + ...share("alice"), + principal: "alice", + } as SessionAccessMutation), + ), + "invalid", + ); + yield* access.mutate("alice", { + type: "thread.unshare", + threadId: thread("t-share"), + principal: "carol", + }); + assert.isFalse((yield* access.grantsFor("carol")).has("t-share")); + }), + ); + + it.effect("group membership grants its threads; only the group owner manages it", () => + Effect.gen(function* () { + const access = yield* SessionAccess.SessionAccess; + yield* insertThread("t-group", "alice"); + yield* insertThread("t-bobs", "bob"); + yield* access.mutate("alice", create("g1")); + yield* access.mutate("alice", { + type: "group.thread.add", + groupId: groupId("g1"), + threadId: thread("t-group"), + }); + yield* access.mutate("alice", { + type: "group.member.invite", + groupId: groupId("g1"), + principal: "bob", + role: "viewer", + }); + assert.strictEqual((yield* access.grantsFor("bob")).get("t-group"), "viewer"); + // The cached grants refresh after a role change. + yield* access.mutate("alice", { + type: "group.member.invite", + groupId: groupId("g1"), + principal: "bob", + role: "participant", + }); + assert.strictEqual((yield* access.grantsFor("bob")).get("t-group"), "participant"); + + const invite: SessionAccessMutation = { + type: "group.member.invite", + groupId: groupId("g1"), + principal: "dave", + role: "viewer", + }; + assert.strictEqual(yield* reasonOf(access.mutate("bob", invite)), "forbidden"); + assert.strictEqual(yield* reasonOf(access.mutate("eve", invite)), "not_found"); + // A group holds only its owner's threads, and a thread joins one group. + assert.strictEqual( + yield* reasonOf( + access.mutate("alice", { + type: "group.thread.add", + groupId: groupId("g1"), + threadId: thread("t-bobs"), + }), + ), + "forbidden", + ); + yield* access.mutate("alice", create("g2")); + assert.strictEqual( + yield* reasonOf( + access.mutate("alice", { + type: "group.thread.add", + groupId: groupId("g2"), + threadId: thread("t-group"), + }), + ), + "conflict", + ); + + const snapshot = yield* access.snapshot("bob"); + assert.deepStrictEqual( + snapshot.groups.map((group) => ({ + id: group.id, + role: group.callerRole, + threads: group.threadIds, + })), + [{ id: groupId("g1"), role: "participant", threads: [thread("t-group")] }], + ); + + yield* access.mutate("alice", { type: "group.delete", groupId: groupId("g1") }); + assert.isFalse((yield* access.grantsFor("bob")).has("t-group")); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/SessionAccess.ts b/apps/server/src/orchestration-v2/SessionAccess.ts new file mode 100644 index 000000000000..eae5e6300192 --- /dev/null +++ b/apps/server/src/orchestration-v2/SessionAccess.ts @@ -0,0 +1,282 @@ +import { + DEFAULT_PRINCIPAL_ID, + type SessionAccessMutation, + SessionAccessError, + type SessionAccessSnapshot, + type SessionGroup, + type SessionGroupId, + type SessionRole, + type SessionThreadShare, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import type { ThreadGrants } from "./ThreadOwnership.ts"; + +export class SessionAccess extends Context.Service< + SessionAccess, + { + /** The threads of other principals this principal may open, with the role it holds on each. */ + readonly grantsFor: (principal: string) => Effect.Effect; + readonly snapshot: ( + principal: string, + ) => Effect.Effect; + /** Owner-only: who a thread is shared with directly. */ + readonly threadShares: ( + principal: string, + threadId: ThreadId, + ) => Effect.Effect, SessionAccessError>; + readonly mutate: ( + principal: string, + mutation: SessionAccessMutation, + ) => Effect.Effect; + } +>()("t3/orchestration-v2/SessionAccess") {} + +const fail = (reason: SessionAccessError["reason"], message: string) => + new SessionAccessError({ reason, message }); + +const strongest = (a: SessionRole | undefined, b: SessionRole): SessionRole => + a === "participant" || b === "participant" ? "participant" : "viewer"; + +export const layer = Layer.effect( + SessionAccess, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const storage = Effect.mapError((cause: unknown) => + fail("storage", cause instanceof Error ? cause.message : "Session access storage failed."), + ); + + const grantsFor: SessionAccess["Service"]["grantsFor"] = Effect.fn("SessionAccess.grantsFor")( + function* (principal) { + // ponytail: one indexed read per call, so the CLI writing the database directly is seen at once; cache by `PRAGMA data_version` if shell streams get hot. + const rows = yield* sql<{ readonly thread_id: string; readonly role: SessionRole }>` + SELECT thread_id, role FROM session_shares WHERE principal = ${principal} + UNION ALL + SELECT gt.thread_id, m.role + FROM session_group_members m + JOIN session_group_threads gt ON gt.group_id = m.group_id + WHERE m.principal = ${principal} + `.pipe(Effect.orDie); + const grants = new Map(); + for (const row of rows) + grants.set(row.thread_id, strongest(grants.get(row.thread_id), row.role)); + return grants; + }, + ); + + const threadOwner = Effect.fn("SessionAccess.threadOwner")(function* (threadId: ThreadId) { + const rows = yield* sql<{ readonly owner: string | null }>` + SELECT json_extract(payload_json, '$.ownerPrincipal') AS owner + FROM orchestration_v2_projection_threads + WHERE thread_id = ${threadId} AND deleted_at IS NULL + `; + return rows[0] === undefined ? null : (rows[0].owner ?? DEFAULT_PRINCIPAL_ID); + }); + + /** Owner or the default principal; anyone else who cannot see the thread learns nothing of it. */ + const requireThreadOwner = Effect.fn("SessionAccess.requireThreadOwner")(function* ( + principal: string, + threadId: ThreadId, + ) { + const owner = yield* threadOwner(threadId); + if (owner === null) return yield* fail("not_found", "Thread not found"); + if (principal === DEFAULT_PRINCIPAL_ID || principal === owner) return owner; + const grants = yield* grantsFor(principal); + return yield* grants.has(threadId) + ? fail("forbidden", "Only the thread owner can change who it is shared with") + : fail("not_found", "Thread not found"); + }); + + const requireGroupOwner = Effect.fn("SessionAccess.requireGroupOwner")(function* ( + principal: string, + groupId: SessionGroupId, + ) { + const rows = yield* sql<{ readonly owner_principal: string }>` + SELECT owner_principal FROM session_groups WHERE id = ${groupId} + `; + const owner = rows[0]?.owner_principal; + if (owner === undefined) return yield* fail("not_found", "Group not found"); + if (principal === DEFAULT_PRINCIPAL_ID || principal === owner) return owner; + const member = yield* sql` + SELECT 1 FROM session_group_members WHERE group_id = ${groupId} AND principal = ${principal} + `; + return yield* member.length > 0 + ? fail("forbidden", "Only the group owner can change the group") + : fail("not_found", "Group not found"); + }); + + const apply = Effect.fn("SessionAccess.apply")(function* ( + principal: string, + mutation: SessionAccessMutation, + ) { + switch (mutation.type) { + case "group.create": { + const createdAt = DateTime.formatIso(yield* DateTime.now); + const exists = yield* sql`SELECT 1 FROM session_groups WHERE id = ${mutation.groupId}`; + if (exists.length > 0) return yield* fail("conflict", "Group already exists"); + yield* sql` + INSERT INTO session_groups (id, name, owner_principal, created_at) + VALUES (${mutation.groupId}, ${mutation.name}, ${principal}, ${createdAt}) + `; + return; + } + case "group.rename": + yield* requireGroupOwner(principal, mutation.groupId); + yield* sql`UPDATE session_groups SET name = ${mutation.name} WHERE id = ${mutation.groupId}`; + return; + case "group.delete": + yield* requireGroupOwner(principal, mutation.groupId); + yield* sql`DELETE FROM session_groups WHERE id = ${mutation.groupId}`; + return; + case "group.thread.add": { + const groupOwner = yield* requireGroupOwner(principal, mutation.groupId); + const threadOwnerPrincipal = yield* threadOwner(mutation.threadId); + if (threadOwnerPrincipal === null) return yield* fail("not_found", "Thread not found"); + if (threadOwnerPrincipal !== groupOwner) { + return yield* fail("forbidden", "A group holds only its owner's threads"); + } + const current = yield* sql<{ readonly group_id: string }>` + SELECT group_id FROM session_group_threads WHERE thread_id = ${mutation.threadId} + `; + if (current[0] !== undefined && current[0].group_id !== mutation.groupId) { + return yield* fail("conflict", "The thread already belongs to another group"); + } + yield* sql` + INSERT OR IGNORE INTO session_group_threads (group_id, thread_id) + VALUES (${mutation.groupId}, ${mutation.threadId}) + `; + return; + } + case "group.thread.remove": + yield* requireGroupOwner(principal, mutation.groupId); + yield* sql` + DELETE FROM session_group_threads + WHERE group_id = ${mutation.groupId} AND thread_id = ${mutation.threadId} + `; + return; + case "group.member.invite": { + const groupOwner = yield* requireGroupOwner(principal, mutation.groupId); + if (mutation.principal === groupOwner) { + return yield* fail("invalid", "The group owner is already a member"); + } + yield* sql` + INSERT INTO session_group_members (group_id, principal, role) + VALUES (${mutation.groupId}, ${mutation.principal}, ${mutation.role}) + ON CONFLICT (group_id, principal) DO UPDATE SET role = excluded.role + `; + return; + } + case "group.member.remove": + yield* requireGroupOwner(principal, mutation.groupId); + yield* sql` + DELETE FROM session_group_members + WHERE group_id = ${mutation.groupId} AND principal = ${mutation.principal} + `; + return; + case "thread.share": { + const owner = yield* requireThreadOwner(principal, mutation.threadId); + if (mutation.principal === owner) { + return yield* fail("invalid", "The owner already has the thread"); + } + yield* sql` + INSERT INTO session_shares (thread_id, principal, role) + VALUES (${mutation.threadId}, ${mutation.principal}, ${mutation.role}) + ON CONFLICT (thread_id, principal) DO UPDATE SET role = excluded.role + `; + return; + } + case "thread.unshare": + yield* requireThreadOwner(principal, mutation.threadId); + yield* sql` + DELETE FROM session_shares + WHERE thread_id = ${mutation.threadId} AND principal = ${mutation.principal} + `; + return; + } + }); + + return SessionAccess.of({ + grantsFor, + mutate: Effect.fn("SessionAccess.mutate")(function* (principal, mutation) { + yield* sql + .withTransaction(apply(principal, mutation)) + .pipe( + Effect.mapError((cause) => + Schema.is(SessionAccessError)(cause) ? cause : fail("storage", String(cause)), + ), + ); + }), + threadShares: Effect.fn("SessionAccess.threadShares")(function* (principal, threadId) { + yield* requireThreadOwner(principal, threadId).pipe(storage); + return yield* sql` + SELECT principal, role FROM session_shares WHERE thread_id = ${threadId} ORDER BY principal + `.pipe(storage); + }), + snapshot: Effect.fn("SessionAccess.snapshot")(function* (principal) { + const groupRows = yield* sql<{ + readonly id: SessionGroupId; + readonly name: string; + readonly owner_principal: string; + readonly created_at: string; + }>` + SELECT id, name, owner_principal, created_at FROM session_groups + WHERE owner_principal = ${principal} + OR id IN (SELECT group_id FROM session_group_members WHERE principal = ${principal}) + ORDER BY created_at, id + `.pipe(storage); + const ids = groupRows.map((group) => group.id); + const members = + ids.length === 0 + ? [] + : yield* sql<{ + readonly group_id: string; + readonly principal: string; + readonly role: SessionRole; + }>` + SELECT group_id, principal, role FROM session_group_members + WHERE group_id IN ${sql.in(ids)} ORDER BY principal + `.pipe(storage); + const threads = + ids.length === 0 + ? [] + : yield* sql<{ readonly group_id: string; readonly thread_id: ThreadId }>` + SELECT group_id, thread_id FROM session_group_threads + WHERE group_id IN ${sql.in(ids)} ORDER BY thread_id + `.pipe(storage); + const shared = yield* sql<{ readonly thread_id: ThreadId; readonly role: SessionRole }>` + SELECT thread_id, role FROM session_shares WHERE principal = ${principal} ORDER BY thread_id + `.pipe(storage); + const groups = groupRows.map((group): SessionGroup => { + const mine = members.filter((member) => member.group_id === group.id); + return { + id: group.id, + name: group.name, + ownerPrincipal: group.owner_principal, + createdAt: DateTime.makeUnsafe(group.created_at), + members: mine.map(({ principal: memberPrincipal, role }) => ({ + principal: memberPrincipal, + role, + })), + threadIds: threads + .filter((row) => row.group_id === group.id) + .map((row) => row.thread_id), + callerRole: + group.owner_principal === principal + ? "owner" + : (mine.find((member) => member.principal === principal)?.role ?? "viewer"), + }; + }); + return { + groups, + sharedThreads: shared.map((row) => ({ threadId: row.thread_id, role: row.role })), + }; + }), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index 336f9b12f96b..ca28d790d39c 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 { canAccessThread, scopeShellStreamItem } from "./ThreadOwnership.ts"; import { activeShellRowsForSubscriber, bufferShellLiveStream, @@ -349,6 +350,93 @@ 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.each([ + { principal: "alice", ownerPrincipal: "alice", read: true, write: true }, + { principal: "bob", ownerPrincipal: "alice", read: false, write: false }, + { principal: "owner", ownerPrincipal: "alice", read: true, write: true }, + { principal: "alice", ownerPrincipal: undefined, read: false, write: false }, + { principal: "owner", ownerPrincipal: undefined, read: true, write: true }, + ])( + "$principal on a thread owned by $ownerPrincipal: read $read, write $write", + ({ principal, ownerPrincipal, read, write }) => { + const thread = { ownerPrincipal }; + expect(canAccessThread(principal, thread, "read")).toBe(read); + expect(canAccessThread(principal, thread, "write")).toBe(write); + }, + ); + + it.each([ + { role: "viewer", read: true, write: false }, + { role: "participant", read: true, write: true }, + { role: undefined, read: false, write: false }, + ] as const)( + "a grant of $role on alice's thread: read $read, write $write", + ({ role, read, write }) => { + const grants = new Map(role === undefined ? [] : [["thread-alice", role] as const]); + const thread = { id: "thread-alice", ownerPrincipal: "alice" }; + expect(canAccessThread("bob", thread, "read", grants)).toBe(read); + expect(canAccessThread("bob", thread, "write", grants)).toBe(write); + // A grant on another thread opens nothing here. + expect(canAccessThread("bob", { ...thread, id: "thread-other" }, "read", grants)).toBe(false); + }, + ); + + it("shows a granted thread in the grantee's snapshot", () => { + const item = scopeShellStreamItem("bob", snapshot, new Map([["thread-alice", "viewer"]])); + expect(item?.kind === "snapshot" && item.snapshot.threads.map((t) => t.id)).toEqual([ + "thread-alice", + ]); + }); + + it("shows each principal its own threads and the default principal all of them", () => { + 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-alice", "thread-owner"], + ["thread-alice", "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("bob", updated)).toBeNull(); + expect(scopeShellStreamItem("owner", updated)).toBe(updated); + expect(scopeShellStreamItem("bob", 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 4ab38c4b305e..3b570a3a6c53 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; } @@ -920,6 +922,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 9285f72d46f5..a6edf9bb6faa 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,34 @@ 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" }); +}); + +it("stamps a message's sender from the session and discards a client-supplied one", () => { + const message = { + type: "message.dispatch", + commandId: "c", + threadId: "t", + messageId: "m", + text: "hi", + attachments: [], + senderPrincipal: "mallory", + dispatchMode: { type: "start_immediately" }, + } as unknown as Parameters[0]; + const provenance = { createdBy: "user", creationSource: "web" } as const; + expect(ThreadManagementService.withCreationProvenance(message, provenance, "bob")).toMatchObject({ + senderPrincipal: "bob", + }); + expect(ThreadManagementService.withCreationProvenance(message, provenance)).not.toHaveProperty( + "senderPrincipal", + ); }); const layerReceiptsTest = CommandReceiptStore.layer.pipe( diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index c1727567f9e3..e99912438821 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 { canAccessThread } from "./ThreadOwnership.ts"; import type { OrchestrationV2SearchThreadInput, OrchestrationV2SearchThreadResult, @@ -77,14 +79,32 @@ 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": { + // The sender is the session's principal, never a client claim; the turn still runs as the thread owner. + const { senderPrincipal: _senderPrincipal, ...rest } = command; + return { + ...rest, + ...provenance, + ...(principal === DEFAULT_PRINCIPAL_ID ? {} : { senderPrincipal: principal }), + }; } - case "message.dispatch": case "thread.fork": case "thread.merge_back": case "delegated_task.request": @@ -423,6 +443,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 +816,11 @@ const make = Effect.gen(function* () { ), Effect.map((snapshot) => snapshot.threads + .filter( + (thread) => + input.ownerPrincipal === undefined || + canAccessThread(input.ownerPrincipal, thread, "read"), + ) .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 000000000000..5e575980003f --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadOwnership.ts @@ -0,0 +1,86 @@ +import { + DEFAULT_PRINCIPAL_ID, + type OrchestrationV2Command, + type OrchestrationV2ShellStreamItem, + type OrchestrationV2ThreadShell, + type SessionRole, + type ThreadId, +} from "@t3tools/contracts"; + +export type ThreadAction = "read" | "write"; + +/** What a principal holds on other principals' threads, from direct shares and group membership. */ +export type ThreadGrants = ReadonlyMap; + +/** + * The one rule for who may touch a thread: its owner, the default principal that administers the + * environment, or a principal granted the thread (read: viewer or participant; write: participant). + * `threadOwnerScope` and the grant subqueries in `ProjectionStore` are its SQL counterpart. + */ +export const canAccessThread = ( + principal: string, + thread: { readonly id?: string | undefined; readonly ownerPrincipal?: string | undefined }, + action: ThreadAction, + grants?: ThreadGrants, +) => { + if ( + principal === DEFAULT_PRINCIPAL_ID || + (thread.ownerPrincipal ?? DEFAULT_PRINCIPAL_ID) === principal + ) + return true; + const role = thread.id === undefined ? undefined : grants?.get(thread.id); + return role === "participant" || (role === "viewer" && action === "read"); +}; + +/** The owner a SQL query filters on to match `canAccessThread`; undefined means no filter. */ +export const threadOwnerScope = (principal: string) => + principal === DEFAULT_PRINCIPAL_ID ? undefined : principal; + +const visibleThreads = ( + principal: string, + threads: ReadonlyArray, + grants?: ThreadGrants, +) => threads.filter((thread) => canAccessThread(principal, thread, "read", grants)); + +/** Project and thread-removal items carry no thread content, so they pass through. */ +export const scopeShellStreamItem = ( + principal: string, + item: OrchestrationV2ShellStreamItem, + grants?: ThreadGrants, +): OrchestrationV2ShellStreamItem | null => { + switch (item.kind) { + case "snapshot": + return { + ...item, + snapshot: { + ...item.snapshot, + threads: visibleThreads(principal, item.snapshot.threads, grants), + archivedThreads: visibleThreads(principal, item.snapshot.archivedThreads, grants), + }, + }; + case "thread.updated": + return canAccessThread(principal, item.thread, "read", grants) ? 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 b8d75340ec6b..ee9f817c598a 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 3c97122c1c63..0e086dd69feb 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 { canAccessThread } 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) => canAccessThread(owner, row.thread, "read")); + 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/boundedSnapshotTransport.test.ts b/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts index 220e707b6c73..607c213223bb 100644 --- a/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts +++ b/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts @@ -49,6 +49,7 @@ import { subscribeOrchestrationV2Thread } from "../ws.ts"; import * as OrchestrationHttp from "./http.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProjectStore from "./ProjectStore.ts"; +import * as SessionAccess from "./SessionAccess.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; const decodeBounded = Schema.decodeUnknownSync( @@ -399,6 +400,7 @@ const TestLayer = Layer.mergeAll( Layer.effectDiscard(seed), Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}), Layer.mock(ProjectStore.ProjectStoreV2)({}), + Layer.mock(SessionAccess.SessionAccess)({ grantsFor: () => Effect.succeed(new Map()) }), Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({}), ).pipe(Layer.provideMerge(store)); diff --git a/apps/server/src/orchestration-v2/http.test.ts b/apps/server/src/orchestration-v2/http.test.ts index 570d34468d37..52b3dc169d37 100644 --- a/apps/server/src/orchestration-v2/http.test.ts +++ b/apps/server/src/orchestration-v2/http.test.ts @@ -36,6 +36,7 @@ import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts import * as OrchestrationHttp from "./http.ts"; import { EventSinkV2 } from "./EventSink.ts"; import * as ProjectStore from "./ProjectStore.ts"; +import * as SessionAccess from "./SessionAccess.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; @@ -97,7 +98,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 +142,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"] : []), }), @@ -151,6 +152,7 @@ const serveOrchestrationHttp = (allowed: () => boolean) => ), Layer.provide(Layer.succeedContext(services)), Layer.provide(Layer.mock(ProjectEnrichmentService)({})), + Layer.provide(Layer.mock(SessionAccess.SessionAccess)({ grantsFor: () => Effect.succeed(new Map()) })), Layer.provide(HttpPlatform.layer), Layer.provide(Etag.layerWeak), Layer.provide(NodeServices.layer), @@ -250,6 +252,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 c2c67eb04d9d..3b2aa92bce05 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"; @@ -16,7 +18,10 @@ import { failEnvironmentInvalidRequest, failEnvironmentNotFound, requireEnvironmentScope, + requireThreadAccess, } from "../auth/http.ts"; +import * as SessionAccess from "./SessionAccess.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"; @@ -57,6 +62,13 @@ export const layer = HttpApiBuilder.group( const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; const projectStore = yield* ProjectStore.ProjectStoreV2; const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; + const sessionAccess = yield* SessionAccess.SessionAccess; + + 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) => @@ -163,11 +175,21 @@ export const layer = HttpApiBuilder.group( "shellSnapshot", Effect.fn("environment.orchestration.shellSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); - yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const session = yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const principal = principalOfSubject(session.subject); return yield* loadShellSnapshot({ omitIdleSubagents: args.query.omitIdleSubagents === "1", omitOlderSettled: args.query.omitOlderSettled === "1", }).pipe( + Effect.flatMap((snapshot) => + sessionAccess.grantsFor(principal).pipe( + Effect.map((grants) => ({ + ...snapshot, + threads: scopeThreadList(principal, snapshot.threads, grants), + archivedThreads: scopeThreadList(principal, snapshot.archivedThreads, grants), + })), + ), + ), traceLocalHandlerWork, Effect.catch((cause) => failEnvironmentInternal("orchestration_snapshot_failed", cause), @@ -179,7 +201,12 @@ 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, + sessionAccess.grantsFor, + ); const snapshot = yield* loadThreadSnapshot( args.params.threadId, "orchestration_thread_snapshot_failed", @@ -194,7 +221,12 @@ 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, + sessionAccess.grantsFor, + ); return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe( Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), traceLocalHandlerWork, @@ -219,7 +251,12 @@ 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, + sessionAccess.grantsFor, + ); const snapshot = yield* loadThreadSnapshotWindow( args.params.threadId, undefined, @@ -245,7 +282,12 @@ 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, + sessionAccess.grantsFor, + ); const decoded = yield* Effect.try(() => decodeThreadHistoryCursor(args.query.cursor), ).pipe(Effect.result); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index feab4ef823f0..cfdde99ec736 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -80,6 +80,7 @@ import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSea import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts"; import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts"; import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts"; +import Migration0078 from "./Migrations/078_SessionAccess.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -160,6 +161,7 @@ const migrationEntries = [ [75, "SubagentDeliveryState", Migration0075], [76, "ProjectionProjectsPinArchive", Migration0076], [77, "RepairBooleanSettledOverride", Migration0077], + [78, "SessionAccess", Migration0078], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/078_SessionAccess.ts b/apps/server/src/persistence/Migrations/078_SessionAccess.ts new file mode 100644 index 000000000000..963955e635e9 --- /dev/null +++ b/apps/server/src/persistence/Migrations/078_SessionAccess.ts @@ -0,0 +1,42 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// Who besides a thread's owner may see or steer it. Plain tables rather than thread events: +// groups span threads, and access must never be replayed or rewound with a thread's history. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE IF NOT EXISTS session_groups ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + owner_principal TEXT NOT NULL, + created_at TEXT NOT NULL + ) + `; + yield* sql` + CREATE TABLE IF NOT EXISTS session_group_members ( + group_id TEXT NOT NULL REFERENCES session_groups(id) ON DELETE CASCADE, + principal TEXT NOT NULL, + role TEXT NOT NULL CHECK (role IN ('viewer', 'participant')), + PRIMARY KEY (group_id, principal) + ) + `; + yield* sql`CREATE INDEX IF NOT EXISTS idx_session_group_members_principal ON session_group_members(principal)`; + // A thread belongs to at most one group. + yield* sql` + CREATE TABLE IF NOT EXISTS session_group_threads ( + group_id TEXT NOT NULL REFERENCES session_groups(id) ON DELETE CASCADE, + thread_id TEXT NOT NULL PRIMARY KEY + ) + `; + yield* sql`CREATE INDEX IF NOT EXISTS idx_session_group_threads_group ON session_group_threads(group_id)`; + yield* sql` + CREATE TABLE IF NOT EXISTS session_shares ( + thread_id TEXT NOT NULL, + principal TEXT NOT NULL, + role TEXT NOT NULL CHECK (role IN ('viewer', 'participant')), + PRIMARY KEY (thread_id, principal) + ) + `; + yield* sql`CREATE INDEX IF NOT EXISTS idx_session_shares_principal ON session_shares(principal)`; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 4083978758ce..b469ca613f1f 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -57,6 +57,7 @@ describe("V2 preview upgrade", () => { [75, "SubagentDeliveryState"], [76, "ProjectionProjectsPinArchive"], [77, "RepairBooleanSettledOverride"], + [78, "SessionAccess"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -157,6 +158,7 @@ describe("V2 preview upgrade", () => { [75, "SubagentDeliveryState"], [76, "ProjectionProjectsPinArchive"], [77, "RepairBooleanSettledOverride"], + [78, "SessionAccess"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 67418010e38e..05b9f22a4a41 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -134,6 +134,8 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as AuthHttp from "./auth/http.ts"; +import * as OidcHttp from "./auth/oidcHttp.ts"; +import * as OidcLogin from "./auth/OidcLogin.ts"; import * as ReplayMarkers from "./auth/replayMarkers.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as CodexManagedTokenBroker from "./provider/CodexManagedTokenBroker.ts"; @@ -193,6 +195,7 @@ import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; +import * as SessionAccess from "./orchestration-v2/SessionAccess.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts"; import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts"; @@ -667,7 +670,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ).pipe( Layer.provideMerge(layerOrchestrationApplication), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), - Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)), + Layer.provideMerge(Layer.mergeAll(ProjectStore.layer, ThreadSearch.layer, SessionAccess.layer)), Layer.provideMerge(SecretResolver.layer), Layer.provideMerge(layerServerSettings), Layer.provideMerge(layerSourceControlProviderRegistry), @@ -746,6 +749,7 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( Layer.provideMerge(RemoteOpenTargets.layer), Layer.provideMerge(DirectEndpoints.layer), Layer.provideMerge(ServerLifecycleEvents.layer), + Layer.provideMerge(OidcLogin.layer), Layer.provide(NetService.layer), ); @@ -774,6 +778,7 @@ const layerMakeRoutes = Layer.mergeAll( ServerHttp.layerAssetRoute, ServerHttp.layerAttachmentUploadRoute, GuestHttp.layer, + OidcHttp.layer, DeviceHubProxy.layer, ServerBrowserStream.routeLayer, ServerHttp.layerStaticAndDevRoute, diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 40eebbf4825e..c24c3dcaf2d4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -97,6 +97,7 @@ import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; +import * as SessionAccess from "./orchestration-v2/SessionAccess.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; @@ -595,6 +596,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), Layer.mock(ThreadManagement.ThreadManagementService)({}), Layer.mock(ThreadSearch.ThreadSearch)({}), + Layer.mock(SessionAccess.SessionAccess)({ grantsFor: () => Effect.succeed(new Map()) }), Layer.mock(UsageService.UsageService)({}), Layer.mock(VcsProvisioningService.VcsProvisioningService)({}), Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e880551e65cc..1432ddcc2a0c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -20,10 +20,22 @@ 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, + canAccessThread, + threadOwnerScope, + type ThreadAction, +} from "./orchestration-v2/ThreadOwnership.ts"; import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { AcpRegistryOperationError, CommandId, + DEFAULT_PRINCIPAL_ID, + authScopeRequiredResponse, + AuthOrchestrationReadScope, + principalOfSubject, authScopeResponse, AuthAccessStreamError, type AuthAccessStreamEvent, @@ -61,6 +73,7 @@ import { OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, type OrchestrationProjectShell, + type OrchestrationV2ThreadShell, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadStreamItem, type ApplicationStoredEvent, @@ -167,6 +180,7 @@ import { import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; +import * as SessionAccess from "./orchestration-v2/SessionAccess.ts"; import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; @@ -1270,6 +1284,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< @@ -1287,6 +1302,7 @@ export const layerWsRpc = ( const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion; const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; const threadSearch = yield* ThreadSearch.ThreadSearch; + const sessionAccess = yield* SessionAccess.SessionAccess; const providerSessionsV2 = yield* ProviderSessionManager.ProviderSessionManagerV2; const mcpAppRequests = yield* McpAppRequests.McpAppRequests; @@ -1903,7 +1919,8 @@ export const layerWsRpc = ( (cause) => new OrchestrationV2GetShellSnapshotError({ message, cause }), ), ); - return { snapshotSequence, threads: threads.threads }; + const grants = yield* sessionAccess.grantsFor(principal); + return { snapshotSequence, threads: scopeThreadList(principal, threads.threads, grants) }; }, ); @@ -1911,6 +1928,62 @@ export const layerWsRpc = ( return yield* mutateProjectWithClone(projectService, projectCloneTracker, mutation); }); + const threadAllowed = Effect.fn("ws.threadAccessForSession")(function* ( + threadId: ThreadId, + action: ThreadAction, + ) { + const found = yield* threadManagement.getThreadRecords(threadId, []).pipe(Effect.option); + if (Option.isNone(found)) return false; + return canAccessThread( + principal, + found.value.thread, + action, + yield* sessionAccess.grantsFor(principal), + ); + }); + const threadVisible = (threadId: ThreadId) => threadAllowed(threadId, "read"); + const scopeSearchResult = Effect.fn("ws.scopeSearchResult")(function* < + R extends { + readonly matches: ReadonlyArray<{ readonly threadId: ThreadId }>; + readonly threads?: ReadonlyArray | undefined; + }, + >(result: R) { + if (threadOwnerScope(principal) === undefined) return result; + const grants = yield* sessionAccess.grantsFor(principal); + const visible = yield* Effect.forEach(result.matches, (match) => + threadVisible(match.threadId), + ); + return { + ...result, + matches: result.matches.filter((_, index) => visible[index]), + ...(result.threads === undefined + ? {} + : { threads: scopeThreadList(principal, result.threads, grants) }), + }; + }); + const threadAccessDenied = () => + new EnvironmentAuthorizationError({ + message: "Thread not found", + ...authScopeRequiredResponse(AuthOrchestrationReadScope), + }); + 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, + action: ThreadAction = "read", + ) { + if (threadOwnerScope(principal) === undefined) return yield* effect; + if (threadIds === null) return yield* Effect.fail(notFound()); + const visible = yield* Effect.forEach(threadIds, (id) => threadAllowed(id, action)); + return visible.every(Boolean) ? yield* effect : yield* Effect.fail(notFound()); + }); + const handlers = ServerWsRpcGroup.of({ [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => Effect.annotateCurrentSpan({ @@ -1931,83 +2004,143 @@ 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, + }); + }), + ), + "write", + ), ), ), - [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input), + [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + threadManagement.stopWorkflow(input), + "write", + ), [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: (input) => - threadManagement.forceStopThread(input), + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + threadManagement.forceStopThread(input), + "write", + ), [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => - readWorkflowScript({ scriptPath: input.scriptPath }), + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + readWorkflowScript({ scriptPath: input.scriptPath }), + ), [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: (input) => - nativeChildWork.getNativeChildWork(input), + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + nativeChildWork.getNativeChildWork(input), + ), [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) => - checkpointDiffQuery.getTurnDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetTurnDiffError({ - message: "Failed to load turn diff", - cause, - }), + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: (input) => - checkpointDiffQuery.getFullThreadDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetFullThreadDiffError({ - message: "Failed to load full thread diff", - cause, - }), + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), ), ), [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, @@ -2025,15 +2158,28 @@ export const layerWsRpc = ( cause, }), ), + Effect.flatMap(scopeSearchResult), ), [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => - getOrchestrationV2ArchivedShellSnapshot, + getOrchestrationV2ArchivedShellSnapshot.pipe( + Effect.flatMap((snapshot) => + sessionAccess.grantsFor(principal).pipe( + Effect.map((grants) => ({ + ...snapshot, + threads: scopeThreadList(principal, snapshot.threads, grants), + })), + ), + ), + ), [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: threadOwnerScope(principal), + }), readThreads: (threadIds) => threadManagement.readShellSnapshot({ location: "active", threadIds }), latestSequence: applicationEvents.latestApplicationSequence, @@ -2054,28 +2200,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) => @@ -2084,109 +2234,143 @@ 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) => + Stream.fromEffect(sessionAccess.grantsFor(principal)).pipe( + Stream.flatMap((grants) => { + const scoped = scopeShellStreamItem(principal, item, grants); + 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) => Stream.unwrap( Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( - Effect.as(commandOutputHub.subscribe(input)), + Effect.andThen( + whenThreadsVisible( + [input.threadId], + threadAccessDenied, + Effect.succeed(commandOutputHub.subscribe(input)), + ), + ), ), ), [WS_METHODS.scheduledTasksSubscribe]: (_input) => @@ -2552,6 +2736,12 @@ export const layerWsRpc = ( [WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow, [WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports, [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status, + [WS_METHODS.sessionAccessList]: (_input) => sessionAccess.snapshot(principal), + [WS_METHODS.sessionAccessThreadShares]: (input) => + sessionAccess + .threadShares(principal, input.threadId) + .pipe(Effect.map((shares) => ({ shares }))), + [WS_METHODS.sessionAccessMutate]: (input) => sessionAccess.mutate(principal, input), [WS_METHODS.peerLinksList]: (_input) => peerLinks.list.pipe(Effect.map((links) => ({ links }))), [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), @@ -3343,6 +3533,7 @@ export const layer = Layer.unwrap( const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const peerLinks = yield* PeerLinks.PeerLinks; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; + const sessionAccess = yield* SessionAccess.SessionAccess; const sql = yield* SqlClient.SqlClient; return HttpRouter.add( "GET", @@ -3383,21 +3574,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, ), ), @@ -3424,6 +3619,7 @@ export const layer = Layer.unwrap( reviewGuides, ), ), + Layer.provide(Layer.succeed(SessionAccess.SessionAccess, sessionAccess)), Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)), Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)), Layer.provide( diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index ad7a96c5eb46..c822fc04a5c6 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -27,6 +27,18 @@ model. DPoP binds a token to a client's proof key; an invalid proof must fail rather than fall back to bearer authentication. The OAuth token-exchange vocabulary gives these grants a familiar meaning. +### Native OIDC sign-in + +A server started with `T3CODE_OIDC_ISSUER` (plus `_CLIENT_ID`, `_CLIENT_SECRET_FILE`, +`_PUBLIC_ORIGINS`, and optionally `_ALLOWED_GROUP` and `_PRINCIPAL_CLAIM`) is a confidential OIDC +client ([OidcLogin](../../apps/server/src/auth/OidcLogin.ts)). `/auth/oidc/start` and +`/auth/oidc/callback` use authorization code with PKCE, `state` and `nonce`; pending logins live in +process memory for ten minutes and are single use. The redirect URI is the request's origin plus +`/auth/oidc/callback`, so every origin a client reaches the server by must be in +`T3CODE_OIDC_PUBLIC_ORIGINS` and registered with the provider. A verified member of the allowed +group becomes `principal:`: the web flow sets a browser-session cookie, the desktop flow +redirects to `t3code://pair` with a two-minute principal pairing link. + ### Guest links are not sessions A [guest link](../user/guest-links.md) gives one browser read access to one diff --git a/docs/internals/multi-user.md b/docs/internals/multi-user.md new file mode 100644 index 000000000000..361786489b37 --- /dev/null +++ b/docs/internals/multi-user.md @@ -0,0 +1,292 @@ +# 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. [`canAccessThread`](../../apps/server/src/orchestration-v2/ThreadOwnership.ts) +is the one rule, asked with `read` or `write` (dispatch, launch into an +existing thread, stop, and MCP writes need `write`). Today it admits the owner +and the default `owner` principal, which administers the environment and sees +every thread. Sharing extends it with `grants` (see below) and the +`listOlderSettledThreads` subqueries, its SQL counterpart, and nothing else. + +**Groups and shares.** Migration `078` adds `session_groups`, +`session_group_members`, `session_group_threads` (a thread is in at most one +group, owned by the group's owner) and `session_shares`, plain tables managed by +`SessionAccess` rather than thread events, because they span threads and must not +follow a thread's history. `grantsFor(principal)` returns the role (`viewer` or +`participant`) the principal holds on other principals' threads, read once per +request. `viewer` reads; `participant` also writes. Only a group's owner manages +it and only a thread's owner shares it. A participant's message carries +`senderPrincipal`, stamped from the session; the turn still runs for the thread's +owner. RPCs: `sessionAccess.list|threadShares|mutate`. CLI: `t3 group ...`, +`t3 share`, `t3 unshare`. MCP calls still see only the owner's own threads. + +**Server administration.** A principal's scopes (`AuthPrincipalScopes`) cover +working in the app: threads, projects, terminals, files, source control, +previews and provider management. They omit settings, environment maintenance, +diagnostics, relay and access scopes, so server-wide administration is refused by +the scope check on RPC and HTTP alike. `PRINCIPAL_DENIED_RPC_METHODS` in +[RpcAuthorization.ts](../../apps/server/src/auth/RpcAuthorization.ts) lists the +few methods under scopes a principal holds that still read server-wide state or +the server account's own agent sessions. A new server-wide method under such a +scope must be added there. Terminals, files, previews and provider credentials +are not owner-filtered and run as the server's OS user until per-principal +execution lands. + +**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 000000000000..e810a87cd887 --- /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 d18a827c1422..2143cc895a60 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 555fa7e90b26..731198ba7f87 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -146,6 +146,37 @@ 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; + +/** + * What a signed-in person holds: everything for working in the app except server administration + * (server settings, updates, diagnostics, T3 Connect, and access management). + */ +export const AuthPrincipalScopes = [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + AuthProvidersManageScope, + AuthPreviewOperateScope, + AuthTerminalReadScope, + AuthTerminalOperateScope, + AuthSourceControlWriteScope, + AuthFilesystemReadScope, + AuthFilesystemWriteScope, +] as const; + // Shell and full-access agent scopes already confer access and relay authority. export const AuthStandardClientScopes = [ AuthOrchestrationReadScope, @@ -179,6 +210,8 @@ export const ServerAuthDescriptor = Schema.Struct({ sessionCookieName: TrimmedNonEmptyString, /** Older servers omit this and authorize self-updates with orchestration:operate. */ serverUpdateScope: Schema.optionalKey(Schema.Literal(AuthEnvironmentMaintainScope)), + /** Present when the server signs people in through its OIDC provider at `/auth/oidc/start`. */ + oidcSignIn: Schema.optionalKey(Schema.Literal(true)), }); export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index d3139f2eeff2..bcfcade104d2 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -62,6 +62,10 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, // Force stop kills agent processes, as Stop on a terminal does. [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope, + // Sharing hands thread access to another principal, so it needs the same scope as working in a thread. + [WS_METHODS.sessionAccessList]: AuthOrchestrationReadScope, + [WS_METHODS.sessionAccessThreadShares]: AuthOrchestrationReadScope, + [WS_METHODS.sessionAccessMutate]: AuthOrchestrationOperateScope, // A guest link hands thread access to someone outside, like a pairing link. [WS_METHODS.guestShareCreate]: AuthAccessWriteScope, [WS_METHODS.peerLinksLink]: AuthAccessWriteScope, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 896733c5197e..33474464a0fb 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -43,6 +43,7 @@ export * from "./guestStream.ts"; export * from "./applicationEvent.ts"; export * from "./orchestratorMcp.ts"; export * from "./peerLink.ts"; +export * from "./sessionAccess.ts"; export * from "./threadMetadataMcp.ts"; export * from "./threadPullRequest.ts"; export * from "./threadSearch.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index abf2b309858b..1b19fed62e8d 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 { StoredThreadTags, ThreadTag } from "./threadTags.ts"; @@ -456,6 +456,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( @@ -1288,6 +1290,7 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({ ...OrchestrationV2CreationFields, scheduledTaskId: Schema.optional(ScheduledTaskId), senderThreadId: Schema.optional(ThreadId), + senderPrincipal: Schema.optional(PrincipalId), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), /** * The message is the script a provider-native workflow run executes, not prose. Clients show @@ -1603,6 +1606,7 @@ export const OrchestrationV2TurnItem = Schema.Union([ messageId: MessageId, scheduledTaskId: Schema.optional(ScheduledTaskId), senderThreadId: Schema.optional(ThreadId), + senderPrincipal: Schema.optional(PrincipalId), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript, inputIntent: OrchestrationV2UserMessageInputIntent, @@ -2086,6 +2090,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)), @@ -2439,6 +2445,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ messageId: MessageId, scheduledTaskId: Schema.optional(ScheduledTaskId), senderThreadId: Schema.optional(ThreadId), + senderPrincipal: Schema.optional(PrincipalId), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript, inputIntent: OrchestrationV2UserMessageInputIntent, @@ -2916,6 +2923,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( @@ -3149,6 +3158,7 @@ export const OrchestrationV2Command = Schema.Union([ ...OrchestrationV2CreationFields, scheduledTaskId: Schema.optional(ScheduledTaskId), senderThreadId: Schema.optional(ThreadId), + senderPrincipal: Schema.optional(PrincipalId), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), commandId: CommandId, threadId: ThreadId, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 01989ff8a474..48ff9a03bc65 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -26,6 +26,13 @@ import { PeerLinkRequestError, PeerLinkSummary, } from "./peerLink.ts"; +import { + SessionAccessError, + SessionAccessMutation, + SessionAccessSnapshot, + SessionAccessThreadSharesInput, + SessionThreadShare, +} from "./sessionAccess.ts"; import { ChatGptReconnectProfileInput, ChatGptReconnectProfile, @@ -512,6 +519,9 @@ export const WS_METHODS = { peerLinksLink: "peerLinks.link", peerLinksUnlink: "peerLinks.unlink", peerLinksAnswerRequest: "peerLinks.answerRequest", + sessionAccessList: "sessionAccess.list", + sessionAccessThreadShares: "sessionAccess.threadShares", + sessionAccessMutate: "sessionAccess.mutate", serverUpdateSettings: "server.updateSettings", serverDiscoverSourceControl: "server.discoverSourceControl", serverSearchAcpRegistry: "server.searchAcpRegistry", @@ -819,6 +829,23 @@ const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]), }); +const WsSessionAccessListRpc = Rpc.make(WS_METHODS.sessionAccessList, { + payload: Schema.Struct({}), + success: SessionAccessSnapshot, + error: Schema.Union([SessionAccessError, EnvironmentAuthorizationError]), +}); + +const WsSessionAccessThreadSharesRpc = Rpc.make(WS_METHODS.sessionAccessThreadShares, { + payload: SessionAccessThreadSharesInput, + success: Schema.Struct({ shares: Schema.Array(SessionThreadShare) }), + error: Schema.Union([SessionAccessError, EnvironmentAuthorizationError]), +}); + +const WsSessionAccessMutateRpc = Rpc.make(WS_METHODS.sessionAccessMutate, { + payload: SessionAccessMutation, + error: Schema.Union([SessionAccessError, EnvironmentAuthorizationError]), +}); + const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, { payload: Schema.Struct({ patch: ServerSettingsPatch, @@ -2013,6 +2040,9 @@ export const WsRpcGroup = RpcGroup.make( WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, WsPeerLinksAnswerRequestRpc, + WsSessionAccessListRpc, + WsSessionAccessThreadSharesRpc, + WsSessionAccessMutateRpc, WsServerDiscoverSourceControlRpc, WsServerSearchAcpRegistryRpc, WsServerPrepareAcpRegistryAgentRpc, diff --git a/packages/contracts/src/sessionAccess.ts b/packages/contracts/src/sessionAccess.ts new file mode 100644 index 000000000000..ea53fb50bbec --- /dev/null +++ b/packages/contracts/src/sessionAccess.ts @@ -0,0 +1,96 @@ +import * as Schema from "effect/Schema"; + +import { PrincipalId } from "./auth.ts"; +import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** What a principal other than the owner may do in a session: read it, or also send and steer. */ +export const SessionRole = Schema.Literals(["viewer", "participant"]); +export type SessionRole = typeof SessionRole.Type; + +export const SessionGroupId = TrimmedNonEmptyString.pipe(Schema.brand("SessionGroupId")); +export type SessionGroupId = typeof SessionGroupId.Type; + +export const SessionGroupMember = Schema.Struct({ principal: PrincipalId, role: SessionRole }); +export type SessionGroupMember = typeof SessionGroupMember.Type; + +export const SessionGroup = Schema.Struct({ + id: SessionGroupId, + name: TrimmedNonEmptyString, + ownerPrincipal: PrincipalId, + createdAt: Schema.DateTimeUtc, + members: Schema.Array(SessionGroupMember), + threadIds: Schema.Array(ThreadId), + /** The caller's relation to the group: `owner`, or its role as a member. */ + callerRole: Schema.Literals(["owner", ...SessionRole.literals]), +}); +export type SessionGroup = typeof SessionGroup.Type; + +export const SessionThreadShare = Schema.Struct({ principal: PrincipalId, role: SessionRole }); +export type SessionThreadShare = typeof SessionThreadShare.Type; + +export const SessionAccessSnapshot = Schema.Struct({ + /** Groups the caller owns or belongs to. */ + groups: Schema.Array(SessionGroup), + /** Threads shared directly with the caller. */ + sharedThreads: Schema.Array(Schema.Struct({ threadId: ThreadId, role: SessionRole })), +}); +export type SessionAccessSnapshot = typeof SessionAccessSnapshot.Type; + +export const SessionAccessThreadSharesInput = Schema.Struct({ threadId: ThreadId }); +export type SessionAccessThreadSharesInput = typeof SessionAccessThreadSharesInput.Type; + +export const SessionAccessMutation = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("group.create"), + groupId: SessionGroupId, + name: TrimmedNonEmptyString, + }), + Schema.Struct({ + type: Schema.Literal("group.rename"), + groupId: SessionGroupId, + name: TrimmedNonEmptyString, + }), + Schema.Struct({ type: Schema.Literal("group.delete"), groupId: SessionGroupId }), + Schema.Struct({ + type: Schema.Literal("group.thread.add"), + groupId: SessionGroupId, + threadId: ThreadId, + }), + Schema.Struct({ + type: Schema.Literal("group.thread.remove"), + groupId: SessionGroupId, + threadId: ThreadId, + }), + Schema.Struct({ + type: Schema.Literal("group.member.invite"), + groupId: SessionGroupId, + principal: PrincipalId, + role: SessionRole, + }), + Schema.Struct({ + type: Schema.Literal("group.member.remove"), + groupId: SessionGroupId, + principal: PrincipalId, + }), + Schema.Struct({ + type: Schema.Literal("thread.share"), + threadId: ThreadId, + principal: PrincipalId, + role: SessionRole, + }), + Schema.Struct({ + type: Schema.Literal("thread.unshare"), + threadId: ThreadId, + principal: PrincipalId, + }), +]); +export type SessionAccessMutation = typeof SessionAccessMutation.Type; + +/** Another principal's group or thread fails as `not_found`, so its existence is not revealed. */ +export class SessionAccessError extends Schema.TaggedError()( + "SessionAccessError", + { + reason: Schema.Literals(["not_found", "forbidden", "conflict", "invalid", "storage"]), + message: Schema.String, + }, +) {}