feat(auth): separate source control write permissions (#9787)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-10-06 20:30:11 -07:00
1 parent 28ce9d1c17
commit 2eda8ac6a3
59 files changed
+3628 -315

No files matched your search

+1 -1
View File
@@ -203,7 +203,7 @@ export const requestGuarded = Effect.fn("EnvironmentRpc.request")(function* <
return yield* method(input).pipe(Effect.ensuring(completeObservation));
});
function runStreamGuarded<TTag extends EnvironmentStreamCommandRpcTag>(
export function runStreamGuarded<TTag extends EnvironmentStreamCommandRpcTag>(
tag: TTag,
input: EnvironmentRpcInput<TTag>,
): Stream.Stream<
@@ -2,6 +2,8 @@ import { describe, expect, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
ThreadId,
EnvironmentId,
ScheduledTaskId,
WS_METHODS,
@@ -150,3 +152,44 @@ describe("command permissions", () => {
}
});
});
it.effect(
"requires source control alone for git, and both grants when attaching a worktree to a thread",
() =>
Effect.scoped(
Effect.gen(function* () {
const registry = yield* setup;
registry.set(sessions(env), AsyncResult.success(grant(true)));
const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
expect((yield* git.authorize(registry, env).pipe(Effect.flip)).requiredScope).toBe(
AuthSourceControlWriteScope,
);
registry.set(
sessions(env),
AsyncResult.success({ ...grant(false), scopes: [AuthSourceControlWriteScope] }),
);
yield* git.authorize(registry, env);
const prepare = createCommandPermissions(runtime, WS_METHODS.gitPreparePullRequestThread);
const input = {
cwd: "/repo",
reference: "123",
mode: "worktree",
threadId: ThreadId.make("thread"),
};
expect(registry.get(prepare.permissionAtom(env, input))).toBe(false);
expect(
(yield* prepare.authorize(registry, env, input).pipe(Effect.flip)).requiredScope,
).toBe(AuthOrchestrationOperateScope);
yield* prepare.authorize(registry, env, { ...input, threadId: undefined });
registry.set(
sessions(env),
AsyncResult.success({
...grant(true),
scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
}),
);
expect(registry.get(prepare.permissionAtom(env, input))).toBe(true);
yield* prepare.authorize(registry, env, input);
}),
),
);
@@ -1,9 +1,14 @@
import { createCommandPermissions } from "./commandPermissions.ts";
import { RpcPermissionGuard } from "../rpc/client.ts";
import { vi } from "vite-plus/test";
import {
EnvironmentId,
AuthSourceControlWriteScope,
ProjectId,
PullRequestOperationError,
WS_METHODS,
type PullRequestStack,
type AuthSessionState,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Data from "effect/Data";
@@ -194,6 +199,7 @@ for (const scenario of [
: route(WS_METHODS.pullRequestsRunAction, input)
).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(GitHubRoutingPermissions, {
...trustedRouting,
get: () => Effect.succeed(trusted ? "read-write" : "off"),
@@ -301,6 +307,7 @@ it.effect("shares active read identity probes while keeping later reads and muta
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
);
}),
),
@@ -554,6 +561,7 @@ it.effect.each(["github", "gitlab", "bitbucket", "azure-devops"] as const)(
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
const environment = provider === "github" ? "local" : "origin";
@@ -720,10 +728,12 @@ it.effect.each(["default", "origin-off", "destination-off", "read-only"] as cons
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
);
yield* permission === "default"
? request
: request.pipe(
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(GitHubRoutingPermissions, {
...trustedRouting,
get: (entry) =>
@@ -842,6 +852,7 @@ it.effect.each(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
// This also represents a user enabling the stale catalog entry after re-resolution.
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
);
yield* stored === "unavailable"
? route
@@ -897,6 +908,7 @@ it.live.each(["origin", "alternate"] as const)(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.flip,
);
expect(error._tag).toBe("PullRequestOperationError");
@@ -958,6 +970,7 @@ it.effect.each(
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
const fiber = yield* request.pipe(Effect.forkChild);
@@ -1014,6 +1027,7 @@ it.live("keeps source workspace metadata when an alternate answers a detail read
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
expect(result).toEqual({
@@ -1101,6 +1115,7 @@ it.live(
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
}),
@@ -1649,6 +1664,7 @@ it.effect.each([false, true])(
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
expect(result).toEqual({ state: "open", checks: [] });
@@ -1980,3 +1996,78 @@ it.effect("refreshes stack state after reopening and head SHAs after a turn", ()
}),
),
);
// Transport fixtures have a source-control-only session; authorization edge cases
// are exercised by commandPermissions.test.ts.
vi.mock("./session.ts", () => ({
createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
}));
const grantedSessions = Atom.family((_id: EnvironmentId) =>
Atom.make<AsyncResult.AsyncResult<AuthSessionState>>(
AsyncResult.success({
authenticated: true,
auth: {
policy: "remote-reachable" as const,
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "test",
},
scopes: [AuthSourceControlWriteScope],
}),
),
);
it.effect("denies a routed write when only the origin has source-control permission", () =>
Effect.scoped(
Effect.gen(function* () {
let writes = 0;
const identity = { host: "github.com", provider: "github", viewer: "test", accountId: "123" };
const client = {
[WS_METHODS.pullRequestsRouting]: () => Effect.succeed(identity),
[WS_METHODS.pullRequestsRoutingIdentity]: () => Effect.succeed(identity),
[WS_METHODS.pullRequestsRunAction]: () =>
Effect.sync(() => {
writes++;
}),
} as unknown as WsRpcProtocolClient;
const fixture = yield* makeTestRuntime(client, client);
const local = EnvironmentId.make("local-environment");
const stop = fixture.registry.mount(grantedSessions(local));
yield* Effect.addFinalizer(() => Effect.sync(stop));
fixture.registry.set(
grantedSessions(local),
AsyncResult.success({
authenticated: true,
scopes: [],
auth: {
policy: "remote-reachable" as const,
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "test",
},
}),
);
const error = yield* createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
projectId: ProjectId.make("project"),
repository: "acme/repo",
number: 1,
action: "merge",
}).pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, fixture.environmentRegistry),
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, fixture.supervisor),
Effect.provideService(GitHubRoutingPermissions, trustedRouting),
Effect.provideService(RpcPermissionGuard, {
authorize: (id, method, input) =>
createCommandPermissions(fixture.runtime, method).authorize(
fixture.registry,
id,
input,
),
}),
Effect.flip,
);
expect(error._tag).toBe("EnvironmentAuthorizationError");
expect(writes).toBe(0);
}),
),
);
@@ -19,7 +19,6 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import {
createAtomCommandScheduler,
createEnvironmentCommand,
createEnvironmentRpcCommand,
createEnvironmentRpcQueryAtomFamily,
createEnvironmentRpcSubscriptionAtomFamily,
@@ -320,7 +319,8 @@ export function createPullRequestEnvironmentAtoms<R, E>(
JSON.stringify([environmentId, input.projectId, input.repository, input.number]),
},
}),
runAction: createEnvironmentCommand(runtime, {
runAction: createEnvironmentRpcCommand(runtime, {
tag: WS_METHODS.pullRequestsRunAction,
label: "environment-data:pull-requests:run-action",
// Preparation belongs to the write's lane. Refreshable queries would restart it after
// every preceding action, and preparing outside the lane could reorder the clicks.
@@ -328,8 +328,6 @@ export function createPullRequestEnvironmentAtoms<R, E>(
input: PullRequestActionInput & {
readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
},
registry,
environmentId,
) =>
Effect.gen(function* () {
const { resolveMergeMethod, ...actionInput } = input;
@@ -369,9 +367,10 @@ export function createPullRequestEnvironmentAtoms<R, E>(
});
preparedInput = { ...actionInput, mergeMethod };
}
yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
registry.refresh(preview({ environmentId, input: actionInput }));
return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
}),
onSuccess: ({ environmentId, input }, registry) =>
Effect.sync(() => registry.refresh(preview({ environmentId, input }))),
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
}),
+12 -7
View File
@@ -1,5 +1,5 @@
import { createCommandPermissions } from "./commandPermissions.ts";
import { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
import { followStreamInEnvironment } from "./environmentStreams.ts";
export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
import {
type ClientGuardedRpcTag,
@@ -717,13 +717,18 @@ export function createEnvironmentRpcSubscriptionAtomFamily<
});
}
export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryRpcTag>(
export function createEnvironmentRpcCommand<
R,
ER,
TTag extends EnvironmentUnaryRpcTag,
Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
>(
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
options: {
readonly label: string;
readonly tag: TTag;
readonly execute?: (
input: EnvironmentRpcInput<TTag>,
input: Input,
) => Effect.Effect<
EnvironmentRpcSuccess<TTag>,
EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
@@ -732,19 +737,19 @@ export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnary
readonly scheduler?: AtomCommandScheduler;
readonly concurrency?: AtomCommandConcurrency<{
readonly environmentId: EnvironmentIdType;
readonly input: EnvironmentRpcInput<TTag>;
readonly input: NoInfer<Input>;
}>;
readonly onSuccess?: (
target: {
readonly environmentId: EnvironmentIdType;
readonly input: EnvironmentRpcInput<TTag>;
readonly input: NoInfer<Input>;
},
registry: AtomRegistry.AtomRegistry,
) => Effect.Effect<void, never, R>;
readonly onSettled?: (
target: {
readonly environmentId: EnvironmentIdType;
readonly input: EnvironmentRpcInput<TTag>;
readonly input: NoInfer<Input>;
},
registry: AtomRegistry.AtomRegistry,
) => Effect.Effect<void, never, R>;
@@ -755,7 +760,7 @@ export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnary
label: options.label,
...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
execute: (input: EnvironmentRpcInput<TTag>, registry, environmentId) => {
execute: (input: Input, registry, environmentId) => {
const target = {
environmentId,
input,
@@ -1,5 +1,7 @@
import { vi } from "vite-plus/test";
import {
EnvironmentId,
AuthSourceControlWriteScope,
WS_METHODS,
type SourceControlPublishRepositoryResult,
} from "@t3tools/contracts";
@@ -168,3 +170,23 @@ describe("source control environment atoms", () => {
),
);
});
// Transport fixtures have a source-control-only session; authorization edge cases
// are exercised by commandPermissions.test.ts.
vi.mock("./session.ts", () => ({
createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
}));
const grantedSessions = Atom.family((_id: EnvironmentId) =>
Atom.make(
AsyncResult.success({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "test",
},
scopes: [AuthSourceControlWriteScope],
}),
),
);
@@ -1,5 +1,7 @@
import { vi } from "vite-plus/test";
import {
EnvironmentId,
AuthSourceControlWriteScope,
WS_METHODS,
type VcsListRefsInput,
type VcsListRefsResult,
@@ -643,3 +645,23 @@ describe("cached VCS refs", () => {
),
);
});
// Transport fixtures have a source-control-only session; authorization edge cases
// are exercised by commandPermissions.test.ts.
vi.mock("./session.ts", () => ({
createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
}));
const grantedSessions = Atom.family((_id: EnvironmentId) =>
Atom.make(
AsyncResult.success({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "test",
},
scopes: [AuthSourceControlWriteScope],
}),
),
);
@@ -1,5 +1,7 @@
import { vi } from "vite-plus/test";
import {
EnvironmentId,
AuthSourceControlWriteScope,
ThreadId,
ProjectId,
WS_METHODS,
@@ -718,3 +720,23 @@ describe("vcsActionState", () => {
),
);
});
// Transport fixtures have a source-control-only session; authorization edge cases
// are exercised by commandPermissions.test.ts.
vi.mock("./session.ts", () => ({
createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
}));
const grantedSessions = Atom.family((_id: EnvironmentId) =>
Atom.make(
AsyncResult.success({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: [],
sessionMethods: [],
sessionCookieName: "test",
},
scopes: [AuthSourceControlWriteScope],
}),
),
);
@@ -19,13 +19,14 @@ import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import * as Persistence from "../platform/persistence.ts";
import { runStream } from "../rpc/client.ts";
import { runStreamGuarded, RpcPermissionGuard } from "../rpc/client.ts";
import {
createRuntimeCommand,
runStreamInEnvironment,
type AtomCommand,
type AtomCommandResult,
} from "./runtime.ts";
import { createCommandPermissions } from "./commandPermissions.ts";
import { vcsCommandScheduler } from "./vcsCommandScheduler.ts";
import { invalidateCachedVcsRefs } from "./vcsRefInvalidation.ts";
@@ -483,7 +484,7 @@ export function createVcsActionManager<R, E>(
return consumeVcsActionProgress(
runStreamInEnvironment(
target.environmentId,
runStream(WS_METHODS.gitRunStackedAction, rpcInput),
runStreamGuarded(WS_METHODS.gitRunStackedAction, rpcInput),
),
{
target,
@@ -507,6 +508,10 @@ export function createVcsActionManager<R, E>(
}),
},
).pipe(
Effect.provideService(RpcPermissionGuard, {
authorize: (id, method, payload) =>
createCommandPermissions(runtime, method).authorize(registry, id, payload),
}),
Effect.ensuring(invalidateCachedVcsRefs(registry, target)),
Effect.tap(() => clearOwnedState),
Effect.tapError((error) =>