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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
2 changes: 2 additions & 0 deletions apps/server/integration/transferBudgetV2.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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),
Expand Down
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 @@ -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;
Expand Down
153 changes: 117 additions & 36 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 @@ -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<AuthEnvironmentScope> | undefined,
Expand All @@ -485,11 +500,14 @@ 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 | ManagedLimits.ManagedPolicyRefusedError
| ServerAuthInternalError
| ManagedLimits.ManagedPolicyRefusedError
| ServerAuthScopeNotGrantedError
>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
Expand All @@ -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<AuthEnvironmentScope>;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
}) => Effect.Effect<
IssuedBearerSession,
ServerAuthInternalError | ServerAuthScopeNotGrantedError
>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
ServerAuthInternalError
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -1014,6 +1055,30 @@ 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 toPairingCredential = (issued: IssuedPairingLink): AuthPairingCredentialResult => ({
id: issued.id,
credential: issued.credential,
Expand All @@ -1023,10 +1088,11 @@ export const make = Effect.gen(function* () {

const issuePairingLink = Effect.fn("EnvironmentAuth.issuePairingLink")(
function* (input: Parameters<EnvironmentAuth["Service"]["createPairingLink"]>[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 } : {}),
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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"),
);
Expand All @@ -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"));
}
Expand Down Expand Up @@ -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,
),
Expand All @@ -1386,6 +1466,7 @@ export const make = Effect.gen(function* () {
}),
getSessionState,
createBrowserSession,
issuePrincipalBrowserSession,
exchangeBootstrapCredentialForAccessToken,
createPairingLink,
issuePairingCredential,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/EnvironmentAuthPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading