feat(server): GitHub API transport that uses gh only for the token #16319
Mergedjuliusmarmingemerged 9 commits into
main fromrefs/pull/16319/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge changed the title
- apps/server/src/sourceControl/GitHubApi.ts line 577Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +394,21 @@394+ const { fingerprint } = yield* credential(host);395+ const scope = (yield* SourceControlRateLimit.CredentialScope) || fingerprint;396+ return yield* Effect.gen(function* () {397+ const query = yield* budget.query(398+ host,399+ input.query,400+ input.allowReserve === true ? { allowReserve: true } : undefined,401+ );402+ const response = yield* send({403+ host,404+ operation: input.operation,405+ request: HttpClientRequest.post(gitHubApiUrls(host).graphql).pipe(406+ HttpClientRequest.acceptJson,407+ HttpClientRequest.bodyJsonUnsafe({ query, variables: input.variables ?? {} }),408+ ),409+ maxResponseBytes: DEFAULT_MAX_RESPONSE_BYTES,410+ allowReserve: input.allowReserve === true,411+ acceptNotModified: false,412+ graphql: true,413+ });414+ yield* budget.observe(host, response.body);apps/server/src/sourceControl/GitHubCredentials.ts line 112OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +92,21 @@92+ return `${host}:${NodeCrypto.createHash("sha256").update(token).digest("hex")}`;93+}94+95+/** @public Service construction is part of the canonical Effect module API. */96+export const make = Effect.gen(function* () {97+ const process = yield* VcsProcess.VcsProcess;98+99+ const fromGh = (host: string) =>100+ process101+ .run({102+ operation: "GitHubCredentials.get",103+ command: "gh",104+ args: ["auth", "token", "--hostname", host],105+ cwd: globalThis.process.cwd(),106+ // Never let gh print the token into a debug log.107+ env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },108+ timeoutMs: 10_000,109+ })110+ .pipe(111+ Effect.map((output) => output.stdout.trim()),112+ Effect.catch((error) =>
- @@ -0,0 +100,21 @@100+ process101+ .run({102+ operation: "GitHubCredentials.get",103+ command: "gh",104+ args: ["auth", "token", "--hostname", host],105+ cwd: globalThis.process.cwd(),106+ // Never let gh print the token into a debug log.107+ env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },108+ timeoutMs: 10_000,109+ })110+ .pipe(111+ Effect.map((output) => output.stdout.trim()),112+ Effect.catch((error) =>113+ Effect.succeed(114+ error._tag === "VcsProcessSpawnError" &&115+ error.cause instanceof PlatformError.PlatformError &&116+ error.cause.reason._tag === "NotFound"117+ ? ("cli-missing" as const)118+ : "",119+ ),120+ ),@@ -0,0 +131,21 @@131+ }132+ return {133+ host,134+ token: Redacted.make(token),135+ source: fromEnv !== null ? "env" : "gh",136+ fingerprint: credentialFingerprint(host, token),137+ } satisfies GitHubCredential;138+ });139+140+ const cache = yield* Cache.makeWith(lookup, {141+ capacity: 32,142+ timeToLive: (exit) => (Exit.isSuccess(exit) ? TOKEN_TTL : MISSING_TTL),143+ });144+145+ return GitHubCredentials.of({146+ get: (host) => Cache.get(cache, normalizeHost(host)),147+ invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),148+ });149+});150+151+export const layer = Layer.effect(GitHubCredentials, make);
- @@ -0,0 +106,21 @@106+ const process = yield* VcsProcess.VcsProcess;107+108+ const fromGh = (host: string) =>109+ process110+ .run({111+ operation: "GitHubCredentials.get",112+ command: "gh",113+ args: ["auth", "token", "--hostname", host],114+ cwd: globalThis.process.cwd(),115+ // Never let gh print the token into a debug log.116+ env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },117+ timeoutMs: 10_000,118+ })119+ .pipe(120+ Effect.mapError((error) =>121+ error._tag === "VcsProcessSpawnError" &&122+ error.cause instanceof PlatformError.PlatformError &&123+ error.cause.reason._tag === "NotFound"124+ ? new GitHubCliMissingError({ host })125+ : new GitHubNotSignedInError({ host }),126+ ),
- @@ -0,0 +210,21 @@210+ const error = yield* Effect.flip(211+ api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),212+ ).pipe(213+ Effect.provideService(GitHubApi.PinnedGitHubCredential, {214+ host: "github.com",215+ token: Redacted.make("pinned"),216+ credentialFingerprint: "github.com:pinned",217+ }),218+ );219+ expect(error._tag).toBe("GitHubApiAuthenticationError");220+ expect(requests).toHaveLength(0);221+ }).pipe(Effect.provide(layer));222+ });223+});224+225+describe("GitHubCredentials", () => {226+ const credentialsWith = (run: VcsProcess.VcsProcess["Service"]["run"]) =>227+ GitHubCredentials.layer.pipe(228+ Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })),229+ Layer.provide(NodeServices.layer),230+ );@@ -0,0 +29,21 @@29+export const PinnedGitHubCredential = Context.Reference<{30+ readonly host: string;31+ readonly token: Redacted.Redacted<string>;32+ readonly credentialFingerprint: string;33+} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });34+35+export class GitHubApiRequestError extends Schema.TaggedError<GitHubApiRequestError>()(36+ "GitHubApiRequestError",37+ { host: Schema.String, operation: Schema.String, cause: Schema.Defect() },38+) {39+ override get message(): string {40+ return `Could not reach GitHub at ${this.host}.`;41+ }42+}43+44+export class GitHubApiAuthenticationError extends Schema.TaggedError<GitHubApiAuthenticationError>()(45+ "GitHubApiAuthenticationError",46+ { host: Schema.String, operation: Schema.String },47+) {48+ override get message(): string {49+ return `GitHub refused the credential for ${this.host}. Run \`gh auth login --hostname ${this.host}\` and retry.`;@@ -0,0 +68,21 @@68+ { host: Schema.String, operation: Schema.String },69+) {70+ override get message(): string {71+ return "GitHub could not find the requested resource, or the credential cannot see it.";72+ }73+}74+75+/**76+ * GitHub answered with a failure that is none of the above. `graphqlErrors` carries GitHub's own77+ * error messages for a GraphQL answer: they name the field and the reason, never a token.78+ */79+export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponseError>()(80+ "GitHubApiResponseError",81+ {82+ host: Schema.String,83+ operation: Schema.String,84+ status: Schema.Int,85+ graphqlErrors: Schema.optionalKey(Schema.Array(Schema.String)),86+ },87+) {88+ override get message(): string {@@ -0,0 +19,21 @@19+/** No credential is retried sooner, so a fresh `gh auth login` takes effect on the next read. */20+const MISSING_TTL = Duration.seconds(10);21+22+export const GitHubCredentialSource = Schema.Literals(["env", "gh"]);23+export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;24+25+export interface GitHubCredential {26+ readonly host: string;27+ readonly token: Redacted.Redacted<string>;28+ readonly source: GitHubCredentialSource;29+ /** A digest of host and token: safe for cache keys and rate-limit scopes, never the token. */30+ readonly fingerprint: string;31+}32+33+/** Nothing in the environment, and no `gh` on PATH to ask. */34+export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(35+ "GitHubCliMissingError",36+ { host: Schema.String },37+) {38+ override get message(): string {39+ return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
- @@ -0,0 +442,21 @@442+ const request =443+ input.body === undefined444+ ? withEtag445+ : withEtag.pipe(HttpClientRequest.bodyJsonUnsafe(input.body));446+ return AllowGitHubReserve.pipe(447+ Effect.flatMap((interactive) =>448+ send({449+ host: input.host,450+ operation: input.operation,451+ request,452+ maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,453+ allowReserve: input.allowReserve ?? interactive,454+ acceptNotModified: input.ifNoneMatch !== undefined,455+ }),456+ ),457+ );458+ };459+460+ const graphql: GitHubApi["Service"]["graphql"] = Effect.fn("GitHubApi.graphql")(461+ function* (input) {462+ const host = normalizeHost(input.host);@@ -0,0 +118,21 @@118+ const crypto = yield* Crypto.Crypto;119+ const environment = yield* HostProcessEnvironment;120+ const workingDirectory = yield* HostProcessWorkingDirectory;121+122+ /** `host:sha256(token)`, safe for cache keys and rate-limit scopes. */123+ const fingerprintOf = (host: string, token: string) =>124+ crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(125+ Effect.map((digest) => `${host}:${Hex.encode(digest)}`),126+ // Hashing a string in memory has no platform failure worth a typed error.127+ Effect.orDie,128+ );129+130+ const fromGh = (host: string) =>131+ process132+ .run({133+ operation: "GitHubCredentials.get",134+ command: "gh",135+ args: ["auth", "token", "--hostname", host],136+ cwd: workingDirectory,137+ // Never let gh print the token into a debug log.138+ env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
- @@ -0,0 +264,21 @@264+ readonly status: number;265+ readonly headers: Readonly<Record<string, string | undefined>>;266+ readonly body: string;267+ readonly graphql: boolean;268+ readonly acceptNotModified: boolean;269+}): Answer {270+ const { status, headers, body } = input;271+ const errors = input.graphql272+ ? Option.getOrUndefined(decodeGraphQlErrors(body))?.errors273+ : undefined;274+ const types = errors?.flatMap((error) => (error.type === undefined ? [] : [error.type])) ?? [];275+ const messages = errors?.flatMap((error) => (error.message === undefined ? [] : [error.message]));276+ if (277+ status === 429 ||278+ types.includes("RATE_LIMITED") ||279+ // An exhausted GraphQL quota can answer HTTP 200 with an untyped "API rate limit already280+ // exceeded" error; the headers say the same thing.281+ (input.graphql && errors !== undefined && headers["x-ratelimit-remaining"] === "0") ||282+ (input.graphql &&283+ messages !== undefined &&284+ messages.some((message) => /rate limit (already )?exceeded/i.test(message))) ||
- @@ -0,0 +532,21 @@532+ ),533+ );534+ };535+536+ const graphql: GitHubApi["Service"]["graphql"] = Effect.fn("GitHubApi.graphql")(537+ function* (input) {538+ const host = normalizeHost(input.host);539+ const { fingerprint } = yield* credential(host);540+ const scope = (yield* SourceControlRateLimit.CredentialScope) || fingerprint;541+ const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);542+ // The document, never its variables: user text (bodies, search terms) travels as variables.543+ yield* Effect.annotateCurrentSpan({544+ "github.operation": input.operation,545+ "github.graphql.query_hash": queryHash(input.query),546+ "github.graphql.query":547+ input.query.length > TRACED_QUERY_MAX_CHARS548+ ? `${input.query.slice(0, TRACED_QUERY_MAX_CHARS)}…`549+ : input.query,550+ });551+ return yield* Effect.gen(function* () {552+ const query = yield* budget.query(
juliusmarminge merged this1564aaa
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
4ae976d· PR result:1d17986· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.