feat(github): route pull request operations across matching accounts (#11367)

This commit is contained in:
maria authored and GitHub committed 2026-09-13 03:33:13 -03:00
1 parent 8b3ddf51c5
commit db6e0531e4
36 files changed
+3298 -148

No files matched your search

@@ -1,13 +1,18 @@
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import * as Cache from "effect/Cache";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
const encodeGitHubCliError = Schema.encodeEffect(Schema.fromJsonString(GitHubCli.GitHubCliError));
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
@@ -31,6 +36,111 @@ afterEach(() => {
});
describe("GitHubCli.layer", () => {
it.effect("pins concurrent cached commands to their own verified credentials", () =>
Effect.gen(function* () {
mockRun.mockImplementation((input) =>
Effect.succeed(processOutput(input.env?.GH_TOKEN ?? "ambient")),
);
const gh = yield* GitHubCli.GitHubCli;
// Constructed outside either request, like the PR service's read caches.
const cache = yield* Cache.make({
lookup: (host: string) =>
gh.execute({
cwd: "/repo",
args: ["api", "user", "--hostname", host],
env: { GH_DEBUG: "api", GH_TOKEN: "changed-after-verification" },
}),
capacity: 2,
timeToLive: "1 minute",
});
const results = yield* Effect.all(
["github.com", "github.example.test"].map((host, index) =>
Cache.get(cache, host).pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, {
host,
token: Redacted.make(`credential-${index}`),
credentialFingerprint: `fingerprint-${index}`,
}),
),
),
{ concurrency: 2 },
);
expect(results.map((result) => result.stdout)).toEqual(["credential-0", "credential-1"]);
for (const [input] of mockRun.mock.calls) {
expect(input.env).toMatchObject({
GH_HOST: input.args[3],
GH_DEBUG: "",
GH_TOKEN: input.env?.GITHUB_TOKEN,
GH_ENTERPRISE_TOKEN: input.env?.GH_TOKEN,
GITHUB_ENTERPRISE_TOKEN: input.env?.GH_TOKEN,
});
}
expect((yield* gh.execute({ cwd: "/repo", args: ["api", "user"] })).stdout).toBe("ambient");
}).pipe(Effect.provide(layer)),
);
it.effect("refuses other or implicit hosts before exposing a scoped credential to gh", () =>
Effect.gen(function* () {
const gh = yield* GitHubCli.GitHubCli;
for (const args of [
["api", "user", "--hostname", "other.example.test"],
["api", "user", "--hostname=other.example.test"],
["pr", "view", "1", "--repo", "other.example.test/owner/repo"],
["repo", "view", "other.example.test/owner/repo", "--json", "name"],
["api", "https://other.example.test/user", "--hostname", "github.com"],
["api", "user"],
]) {
const failure = yield* gh.execute({ cwd: "/repo", args }).pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, {
host: "github.com",
token: Redacted.make("secret-credential"),
credentialFingerprint: "fingerprint",
}),
Effect.flip,
);
expect(failure._tag).toBe("GitHubCliCommandError");
expect(yield* encodeGitHubCliError(failure)).not.toContain("secret-credential");
}
expect(mockRun).not.toHaveBeenCalled();
}).pipe(Effect.provide(layer)),
);
it.effect("pins repository-targeted writes on enterprise hosts", () =>
Effect.gen(function* () {
mockRun.mockReturnValue(Effect.succeed(processOutput("")));
const gh = yield* GitHubCli.GitHubCli;
yield* gh
.execute({
cwd: "/repo",
args: ["pr", "merge", "1", "--repo", "github.example.test/owner/repo"],
})
.pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, {
host: "github.example.test",
token: Redacted.make("enterprise-credential"),
credentialFingerprint: "fingerprint",
}),
);
yield* gh
.execute({
cwd: "/repo",
args: ["repo", "view", "github.example.test/owner/repo", "--json", "name"],
})
.pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, {
host: "github.example.test",
token: Redacted.make("enterprise-credential"),
credentialFingerprint: "fingerprint",
}),
);
expect(mockRun.mock.calls[0]?.[0].env).toMatchObject({
GH_HOST: "github.example.test",
GH_ENTERPRISE_TOKEN: "enterprise-credential",
GH_DEBUG: "",
});
}).pipe(Effect.provide(layer)),
);
it("does not classify a missing cwd as an unavailable gh executable", () => {
const context = { command: "gh", cwd: "/repo" } as const;
const missingCwd = new VcsProcessSpawnError({
+73 -12
View File
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -22,6 +23,40 @@ import {
const DEFAULT_TIMEOUT_MS = 30_000;
/** Server-local credential scope; never put its value in RPC payloads or cache keys. */
export const PinnedGitHubCredential = Context.Reference<{
readonly host: string;
readonly token: Redacted.Redacted<string>;
readonly credentialFingerprint: string;
} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });
function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean {
const hosts: Array<string | null> = [];
const repositoryHost = (repository: string | undefined) => {
if (repository === undefined) return null;
if (/^https?:\/\//i.test(repository)) {
try {
return new URL(repository).host.toLowerCase();
} catch {
return null;
}
}
const parts = repository.split("/");
return parts.length === 3 ? parts[0]!.toLowerCase() : null;
};
if (args[0] === "repo" && args[1] === "view") hosts.push(repositoryHost(args[2]));
for (let index = 0; index < args.length; index++) {
const arg = args[index]!;
if (arg === "--hostname") hosts.push(args[++index]?.toLowerCase() ?? null);
else if (arg.startsWith("--hostname=")) hosts.push(arg.slice(11).toLowerCase());
else if (arg === "--repo" || arg === "-R") hosts.push(repositoryHost(args[++index]));
else if (arg.startsWith("--repo=")) hosts.push(repositoryHost(arg.slice(7)));
else if (arg.startsWith("-R")) hosts.push(repositoryHost(arg.slice(2)));
else if (/^https?:\/\//i.test(arg)) hosts.push(repositoryHost(arg));
}
return hosts.length > 0 && hosts.every((target) => target === host);
}
const gitHubCliFailureFields = {
command: Schema.Literal("gh"),
cwd: Schema.String,
@@ -237,6 +272,7 @@ export class GitHubCli extends Context.Service<
readonly timeoutMs?: number;
/** Piped to the child's stdin, for payloads that must never appear in argv. */
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly maxOutputBytes?: number;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
@@ -342,18 +378,43 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
const execute: GitHubCli["Service"]["execute"] = (input) =>
process
.run({
operation: "GitHubCli.execute",
command: "gh",
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
})
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
function* (input) {
const credential = yield* PinnedGitHubCredential;
if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
return yield* new GitHubCliCommandError({
command: "gh",
cwd: input.cwd,
cause: new Error("The GitHub command does not target the verified credential's host."),
});
}
const token = credential === null ? undefined : Redacted.value(credential.token);
const env =
credential === null
? input.env
: {
...input.env,
GH_HOST: credential.host,
GH_TOKEN: token,
GITHUB_TOKEN: token,
GH_ENTERPRISE_TOKEN: token,
GITHUB_ENTERPRISE_TOKEN: token,
GH_DEBUG: "",
};
return yield* process
.run({
operation: "GitHubCli.execute",
command: "gh",
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(env !== undefined ? { env } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
})
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
},
);
return GitHubCli.of({
execute,