Skip to content
47 changes: 47 additions & 0 deletions .github/workflows/fork-principals.yml
Original file line number Diff line number Diff line change
@@ -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
40 changes: 39 additions & 1 deletion apps/server/src/auth/EnvironmentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -420,6 +424,40 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
}).pipe(Effect.provide(layerEnvironmentAuth())),
);

it.effect(
"caps a principal's credentials at orchestration scopes and keeps them out of MCP",
() =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const link = yield* serverAuth.createPairingLink({ principal: "alice" });
expect(link).toMatchObject({
subject: "principal:alice",
scopes: AuthPrincipalScopes,
});
const session = yield* serverAuth.issueSession({ principal: "alice" });
expect(session).toMatchObject({ subject: "principal:alice", scopes: AuthPrincipalScopes });

const tooWide = ["orchestration:read", "terminal:operate"] as const;
expect(
yield* serverAuth
.createPairingLink({ principal: "alice", scopes: tooWide })
.pipe(Effect.flip),
).toMatchObject({ _tag: "ServerAuthScopeNotGrantedError" });
expect(
yield* serverAuth.issueSession({ principal: "alice", scopes: tooWide }).pipe(Effect.flip),
).toMatchObject({ _tag: "ServerAuthScopeNotGrantedError" });
expect(
yield* serverAuth
.issueSession({ subject: "principal:alice", scopes: tooWide })
.pipe(Effect.flip),
).toMatchObject({ _tag: "ServerAuthScopeNotGrantedError" });

expect(
yield* serverAuth.consumeMcpApprovalCode(link.credential, "read-only").pipe(Effect.flip),
).toMatchObject({ _tag: "ServerAuthMcpApprovalCodeError", reason: "not_a_pairing_code" });
}).pipe(Effect.provide(layerEnvironmentAuth())),
);

it.effect("narrows seeded desktop grants to the requested scopes", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
Expand Down
117 changes: 82 additions & 35 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import {
AuthAccessTokenType,
AuthAccessWriteScope,
AuthOrchestrationOperateScope,
AuthPrincipalScopes,
AuthStandardClientScopes,
DEFAULT_PRINCIPAL_ID,
principalOfSubject,
principalSubject,
type AuthAccessTokenResult,
type AuthBrowserSessionResult,
type AuthClientMetadata,
Expand Down Expand Up @@ -482,9 +486,13 @@ export class EnvironmentAuth extends Context.Service<
readonly label?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly principal?: string;
readonly proofKeyThumbprint?: string;
readonly purpose?: "startup";
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
}) => Effect.Effect<
IssuedPairingLink,
ServerAuthInternalError | ServerAuthScopeNotGrantedError
>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
Expand All @@ -499,9 +507,13 @@ export class EnvironmentAuth extends Context.Service<
readonly issueSession: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly principal?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
}) => Effect.Effect<
IssuedBearerSession,
ServerAuthInternalError | ServerAuthScopeNotGrantedError
>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
ServerAuthInternalError
Expand Down Expand Up @@ -1016,6 +1028,7 @@ export const make = Effect.gen(function* () {
...(input.label ? { label: input.label } : {}),
...(input.purpose ? { purpose: input.purpose } : {}),
}).pipe(
Effect.catchTags({ ServerAuthScopeNotGrantedError: Effect.die }),
Effect.map(
(issued) =>
({
Expand All @@ -1027,14 +1040,39 @@ export const make = Effect.gen(function* () {
),
);

const resolveIssuance = (
input:
| {
readonly subject?: string;
readonly principal?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
}
| undefined,
fallbackSubject: string,
): Effect.Effect<
{ readonly subject: string; readonly scopes: ReadonlyArray<AuthEnvironmentScope> },
ServerAuthScopeNotGrantedError
> => {
const subject =
input?.principal === undefined || input.principal === DEFAULT_PRINCIPAL_ID
? (input?.subject ?? fallbackSubject)
: principalSubject(input.principal);
const isPrincipal = principalOfSubject(subject) !== DEFAULT_PRINCIPAL_ID;
const scopes = input?.scopes ?? (isPrincipal ? AuthPrincipalScopes : AuthStandardClientScopes);
return isPrincipal && !scopes.every((scope) => AuthPrincipalScopes.some((own) => own === scope))
? Effect.fail(new ServerAuthScopeNotGrantedError({}))
: Effect.succeed({ subject, scopes });
};

const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
"EnvironmentAuth.createPairingLink",
)(
function* (input) {
const { subject, scopes } = yield* resolveIssuance(input, "one-time-token");
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials.issueOneTimeToken({
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
scopes,
subject,
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
Expand All @@ -1043,14 +1081,18 @@ export const make = Effect.gen(function* () {
return {
id: issued.id,
credential: issued.credential,
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
scopes,
subject,
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
},
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
Effect.mapError((cause) =>
cause._tag === "ServerAuthScopeNotGrantedError"
? cause
: new ServerAuthPairingLinkCreationError({ cause }),
),
);

const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
Expand All @@ -1077,33 +1119,37 @@ export const make = Effect.gen(function* () {
);

const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
sessions
.issue({
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
method: "bearer-access-token",
scopes: input?.scopes ?? AuthStandardClientScopes,
client: {
...(input?.label ? { label: input.label } : {}),
deviceType: "bot",
},
...(input?.ttl ? { ttl: input.ttl } : {}),
})
.pipe(
Effect.map(
(issued) =>
({
sessionId: issued.sessionId,
token: issued.token,
method: "bearer-access-token",
scopes: issued.scopes,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
client: issued.client,
expiresAt: DateTime.toUtc(issued.expiresAt),
}) satisfies IssuedBearerSession,
),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueSession"),
);
resolveIssuance(input, DEFAULT_SESSION_SUBJECT).pipe(
Effect.flatMap(({ subject, scopes }) =>
sessions
.issue({
subject,
method: "bearer-access-token",
scopes,
client: {
...(input?.label ? { label: input.label } : {}),
deviceType: "bot",
},
...(input?.ttl ? { ttl: input.ttl } : {}),
})
.pipe(
Effect.map(
(issued) =>
({
sessionId: issued.sessionId,
token: issued.token,
method: "bearer-access-token",
scopes: issued.scopes,
subject,
client: issued.client,
expiresAt: DateTime.toUtc(issued.expiresAt),
}) satisfies IssuedBearerSession,
),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
),
),
Effect.withSpan("EnvironmentAuth.issueSession"),
);

const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
sessions.listActive().pipe(
Expand Down Expand Up @@ -1359,7 +1405,8 @@ export const make = Effect.gen(function* () {
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
}),
Effect.flatMap((grant) =>
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
(grant.method !== "one-time-token" && grant.method !== "reusable-dev-token") ||
principalOfSubject(grant.subject) !== DEFAULT_PRINCIPAL_ID
? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
: Effect.void,
),
Expand Down
52 changes: 52 additions & 0 deletions apps/server/src/auth/RpcAuthorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
AuthProvidersManageScope,
AuthSettingsWriteScope,
DEFAULT_SERVER_SETTINGS,
ORCHESTRATION_V2_WS_METHODS,
ProviderDriverKind,
ProviderInstanceId,
SecretProviderId,
Expand Down Expand Up @@ -401,3 +402,54 @@ it.effect("denies manual cleanup before the handler without settings permission"
expect(handled).toBe(false);
}).pipe(Effect.scoped),
);

describe("principal RPC allowlist", () => {
const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
const group = WsRpcGroup.omit(
...[...WsRpcGroup.requests.keys()].filter(
(tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
!(tested as ReadonlyArray<string>).includes(tag),
),
);

it("keeps only allowlisted methods and gives owner-only methods no principal path", () => {
expect(RpcAuthorization.PRINCIPAL_RPC_METHODS.has(WS_METHODS.serverProbe)).toBe(true);
for (const method of [
ORCHESTRATION_V2_WS_METHODS.launchThread,
ORCHESTRATION_V2_WS_METHODS.searchThread,
ORCHESTRATION_V2_WS_METHODS.searchThreadStream,
]) {
expect(RpcAuthorization.PRINCIPAL_RPC_METHODS.has(method)).toBe(true);
}
for (const method of RpcAuthorization.PRINCIPAL_RPC_METHODS) {
expect(Object.hasOwn(RPC_REQUIRED_SCOPES, method)).toBe(true);
}
expect(RpcAuthorization.PRINCIPAL_RPC_METHODS.has(WS_METHODS.terminalOpen)).toBe(false);
});

it.effect("rejects other methods for a principal before scope checks or the handler", () =>
Effect.gen(function* () {
const handled: Array<string> = [];
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
),
RpcAuthorization.layer(
[AuthOrchestrationReadScope, AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope],
undefined,
"alice",
),
),
),
);
expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
expect(
yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
).toMatchObject({ _tag: "EnvironmentAuthorizationError" });
expect(handled).toEqual([]);
}).pipe(Effect.scoped),
);
});
Loading
Loading