diff --git a/server/src/__tests__/github-repository-token-cache.test.ts b/server/src/__tests__/github-repository-token-cache.test.ts new file mode 100644 index 00000000000..457838bb1d8 --- /dev/null +++ b/server/src/__tests__/github-repository-token-cache.test.ts @@ -0,0 +1,217 @@ +import { generateKeyPairSync, randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { and, eq, sql } from "drizzle-orm"; +import { + agents, + chatEndpoints, + companies, + companySecretBindings, + createDb, + secretAccessEvents, + toolApplications, + toolConnections, +} from "@paperclipai/db"; +import type { ToolCredentialSecretRef } from "@paperclipai/shared"; +import { + githubBotRepositoryClient, + githubBotRepositoryToken, +} from "../services/chat-github-client.js"; +import { secretService } from "../services/secrets.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeDatabase = support.supported ? describe : describe.skip; + +const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString(); +const HOUR = 60 * 60_000; + +describeDatabase("GitHub repository token reuse", () => { + let database: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-github-token-cache-"); + db = createDb(database.connectionString); + }, 30_000); + afterEach(() => vi.restoreAllMocks()); + afterAll(async () => { + await db?.$client.end({ timeout: 0 }); + await database?.cleanup(); + }); + + async function fixture() { + const companyId = randomUUID(), applicationId = randomUUID(), connectionId = randomUUID(), endpointId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "GitHub token reuse", issuePrefix: randomUUID().slice(0, 8).toUpperCase() }); + const agentId = randomUUID(); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" }); + await db.insert(toolApplications).values({ id: applicationId, companyId, name: "GitHub", type: "chat" }); + const secrets = secretService(db); + const values = { appId: "1234", privateKey: privateKeyPem, installationId: "2468", webhookSecret: "webhook-secret" }; + const refs: ToolCredentialSecretRef[] = []; + const secretIds: Record = {}; + for (const [key, value] of Object.entries(values)) { + const secret = await secrets.create(companyId, { + name: `github.${key}.${randomUUID().slice(0, 8)}`, + key: `CHAT_GITHUB_${key}_${randomUUID()}`.replaceAll("-", "_").toUpperCase(), + provider: "local_encrypted", + value, + }); + secretIds[key] = secret.id; + refs.push({ secretId: secret.id, versionSelector: "latest", configPath: `credentials.${key}`, required: true }); + } + await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "GitHub", uid: connectionId, + transport: "chat_sdk", connectionPurpose: "channel", enabled: true, status: "active", credentialSecretRefs: refs }); + await db.insert(companySecretBindings).values(refs.map(ref => ({ companyId, secretId: ref.secretId, + targetType: "tool_connection", targetId: connectionId, configPath: ref.configPath }))); + await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "github", + publicId: endpointId, assignedAgentId: agentId, status: "active" }); + + const mints: Array<{ installationId: string; repositoryIds: number[]; permissions: unknown }> = []; + const requests: Array<{ path: string; token: string }> = []; + const rejected = new Set(); + let expiresIn = HOUR; + const fetchImpl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input)); + const token = String(new Headers(init?.headers).get("authorization") ?? "").replace(/^Bearer /, ""); + const mint = url.pathname.match(/^\/app\/installations\/(\d+)\/access_tokens$/); + if (mint) { + const body = JSON.parse(String(init?.body)) as { repository_ids: number[]; permissions: unknown }; + mints.push({ installationId: mint[1]!, repositoryIds: body.repository_ids, permissions: body.permissions }); + return Response.json({ token: `installation-token-${mints.length}`, + expires_at: new Date(Date.now() + expiresIn).toISOString() }, { status: 201 }); + } + requests.push({ path: url.pathname, token }); + if (rejected.has(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + return Response.json({ head: { sha: "abc" } }); + }) as unknown as typeof fetch & ReturnType; + const audits = async () => (await db.select({ configPath: secretAccessEvents.configPath }).from(secretAccessEvents) + .where(and(eq(secretAccessEvents.companyId, companyId), eq(secretAccessEvents.consumerId, connectionId)))) + .map(row => row.configPath).sort(); + const token = (repositoryId = "101") => githubBotRepositoryToken(db, companyId, endpointId, repositoryId, fetchImpl); + return { companyId, connectionId, endpointId, secretIds, mints, requests, rejected, fetchImpl, audits, token, + setExpiresIn: (ms: number) => { expiresIn = ms; } }; + } + + it("mints once and resolves the App's secrets only when it mints", async () => { + const f = await fixture(); + const first = await f.token(); + const second = await f.token(); + expect(second).toBe(first); + expect(f.mints).toEqual([{ installationId: "2468", repositoryIds: [101], + permissions: { contents: "read", metadata: "read", issues: "write", pull_requests: "write", checks: "write" } }]); + // One audited read per mint credential; the webhook secret is never read to mint. + expect(await f.audits()).toEqual(["credentials.appId", "credentials.installationId", "credentials.privateKey"]); + }); + + it("refreshes a token shortly before GitHub's expiry", async () => { + const f = await fixture(); + const start = Date.now(); + const now = vi.spyOn(Date, "now").mockReturnValue(start); + const first = await f.token(); + now.mockReturnValue(start + 54 * 60_000); + expect(await f.token()).toBe(first); + now.mockReturnValue(start + 56 * 60_000); + const refreshed = await f.token(); + expect(refreshed).not.toBe(first); + expect(f.mints).toHaveLength(2); + expect(await f.token()).toBe(refreshed); + }); + + it("never keeps a token GitHub issues for less than the safety margin", async () => { + const f = await fixture(); + f.setExpiresIn(2 * 60_000); + await f.token(); + await f.token(); + expect(f.mints).toHaveLength(2); + }); + + it("mints again after a credential rotation and uses the new credential", async () => { + const f = await fixture(); + const first = await f.token(); + await secretService(db).rotate(f.secretIds.installationId!, { value: "1357" }); + const rotated = await f.token(); + expect(rotated).not.toBe(first); + expect(f.mints.map(mint => mint.installationId)).toEqual(["2468", "1357"]); + expect(await f.token()).toBe(rotated); + expect(f.mints).toHaveLength(2); + }); + + it("mints again after the connection's credential refs change", async () => { + const f = await fixture(); + const first = await f.token(); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connectionId)); + // Same secrets under a pinned version: a different authority, so a different token. + await db.update(toolConnections).set({ credentialSecretRefs: connection!.credentialSecretRefs + .map(ref => ({ ...ref, versionSelector: 1 })) }).where(eq(toolConnections.id, f.connectionId)); + expect(await f.token()).not.toBe(first); + expect(f.mints).toHaveLength(2); + }); + + it("never serves a cached token across a pause, revoke or disabled connection", async () => { + const f = await fixture(); + const endpoint = eq(chatEndpoints.id, f.endpointId); + const first = await f.token(); + + await db.update(chatEndpoints).set({ status: "paused" }).where(endpoint); + await expect(f.token()).rejects.toThrow("GitHub bot connection is unavailable"); + await db.update(chatEndpoints).set({ status: "active" }).where(endpoint); + const afterPause = await f.token(); + expect(afterPause).not.toBe(first); + + // A pause and resume with no call in between still drops the token: pausing + // advances the endpoint's runtime generation. + await db.update(chatEndpoints).set({ status: "paused", + setup: sql`jsonb_set(${chatEndpoints.setup}, '{runtimeGeneration}', to_jsonb(coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::int, 0) + 1))` }) + .where(endpoint); + await db.update(chatEndpoints).set({ status: "active" }).where(endpoint); + const afterResume = await f.token(); + expect(afterResume).not.toBe(afterPause); + + await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId)); + await expect(f.token()).rejects.toThrow("GitHub bot connection is not active"); + await db.update(toolConnections).set({ enabled: true }).where(eq(toolConnections.id, f.connectionId)); + const afterDisable = await f.token(); + expect(afterDisable).not.toBe(afterResume); + + await db.update(chatEndpoints).set({ status: "revoked" }).where(endpoint); + await expect(f.token()).rejects.toThrow("GitHub bot connection is unavailable"); + expect(f.mints).toHaveLength(4); + }); + + it("mints a separate token for each repository", async () => { + const f = await fixture(); + const first = await f.token("101"); + const second = await f.token("202"); + expect(second).not.toBe(first); + expect(await f.token("101")).toBe(first); + expect(await f.token("202")).toBe(second); + expect(f.mints.map(mint => mint.repositoryIds)).toEqual([[101], [202]]); + }); + + it("replaces a cached token GitHub rejects and retries the request once", async () => { + const f = await fixture(); + const cached = await f.token(); + f.rejected.add(cached); + const request = await githubBotRepositoryClient(db, f.companyId, f.endpointId, "101", f.fetchImpl); + await expect(request<{ head: { sha: string } }>("/repos/o/r/pulls/1")).resolves.toEqual({ head: { sha: "abc" } }); + expect(f.requests).toEqual([ + { path: "/repos/o/r/pulls/1", token: cached }, + { path: "/repos/o/r/pulls/1", token: "installation-token-2" }, + ]); + // The replacement is the cached token from now on. + expect(await f.token()).toBe("installation-token-2"); + expect(f.mints).toHaveLength(2); + + // A freshly minted token that GitHub rejects is not retried. + const other = await fixture(); + other.rejected.add("installation-token-1"); + const fresh = await githubBotRepositoryClient(db, other.companyId, other.endpointId, "101", other.fetchImpl); + await expect(fresh("/repos/o/r/pulls/1")).rejects.toMatchObject({ details: { providerStatus: 401 } }); + expect(other.requests).toHaveLength(1); + expect(other.mints).toHaveLength(1); + }); +}); diff --git a/server/src/services/chat-github-checks.ts b/server/src/services/chat-github-checks.ts index be799375918..5a273636fa6 100644 --- a/server/src/services/chat-github-checks.ts +++ b/server/src/services/chat-github-checks.ts @@ -17,7 +17,7 @@ import { import type { GitHubReviewEventContext } from "@paperclipai/shared"; import { runtimePublicOrigin } from "./cloud-runtime-identity.js"; import { - githubBotRepositoryToken, + githubBotRepositoryClient, githubBotRequest, } from "./chat-github-client.js"; @@ -132,7 +132,7 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { : state === "running" ? "Agent is reviewing this commit" : "Waiting for the assigned agent"; - const token = await githubBotRepositoryToken( + const github = await githubBotRepositoryClient( db, action.companyId, action.endpointId, @@ -143,13 +143,7 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { const request = ( path: string, options?: Parameters[3], - ) => - githubBotRequest( - lease.fetch, - token, - `${prefix}${path}`, - options, - ); + ) => github(`${prefix}${path}`, options); const current = await request<{ head: { sha: string } }>( `/pulls/${event.pullNumber}`, ); diff --git a/server/src/services/chat-github-client.ts b/server/src/services/chat-github-client.ts index 65d93445111..25a1ea893e9 100644 --- a/server/src/services/chat-github-client.ts +++ b/server/src/services/chat-github-client.ts @@ -1,8 +1,14 @@ import { createPrivateKey, createSign } from "node:crypto"; -import { and, eq } from "drizzle-orm"; -import { chatEndpoints, toolConnections, type Db } from "@paperclipai/db"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { + chatEndpoints, + companySecretBindings, + companySecrets, + toolConnections, + type Db, +} from "@paperclipai/db"; import { secretService } from "./secrets.js"; -import { conflict, forbidden, unprocessable } from "../errors.js"; +import { HttpError, conflict, forbidden, unprocessable } from "../errors.js"; import { githubPublicationRetry, githubProviderRetry, GITHUB_INLINE_RETRY_WINDOW_MS, GITHUB_INLINE_MAX_ATTEMPTS } from "./chat-channels/github/retry.js"; export function githubAppJwt( @@ -200,7 +206,238 @@ export async function githubBotCredentials( }; } -/** Least-privilege short-lived token restricted to the single task repository. */ +const GITHUB_REPOSITORY_TOKEN_PERMISSIONS = { + contents: "read", + metadata: "read", + issues: "write", + pull_requests: "write", + checks: "write", +} as const; +/** Only these secrets are needed to mint; the App's other credentials are not read here. */ +const GITHUB_MINT_CREDENTIALS = ["appId", "privateKey", "installationId"] as const; +const GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS = 5 * 60_000; +const GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS = 60 * 60_000; +const GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT = 512; + +type CachedRepositoryToken = { token: string; endpointId: string; refreshAt: number }; +type RepositoryToken = { token: string; key: string; cached: boolean }; + +// Per process and in memory only. Tokens are never persisted or logged. +const repositoryTokens = new Map(); + +function forgetEndpointRepositoryTokens(endpointId: string) { + for (const [key, entry] of repositoryTokens) + if (entry.endpointId === endpointId) repositoryTokens.delete(key); +} + +function rememberRepositoryToken(key: string, entry: CachedRepositoryToken) { + repositoryTokens.delete(key); + if (repositoryTokens.size >= GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) { + const now = Date.now(); + for (const [stale, cached] of repositoryTokens) + if (cached.refreshAt <= now) repositoryTokens.delete(stale); + } + // Map order is least recently used first. + for (const oldest of repositoryTokens.keys()) { + if (repositoryTokens.size < GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) break; + repositoryTokens.delete(oldest); + } + repositoryTokens.set(key, entry); +} + +/** + * Current minting authority, read from the database on every call. The + * revision covers everything that changes what a token may do: the endpoint's + * runtime generation (bumped on pause, revoke and availability changes), the + * connection, and each mint credential's secret ref, selected version, state + * and binding. Any change makes every token cached under the old revision + * unreachable. Secret values are not read here. + */ +async function githubBotRepositoryAuthority( + db: Db, + companyId: string, + endpointId: string, +) { + const [row] = await db + .select({ + endpointStatus: chatEndpoints.status, + runtimeGeneration: sql`${chatEndpoints.setup}->'runtimeGeneration'`, + connectionId: toolConnections.id, + enabled: toolConnections.enabled, + connectionStatus: toolConnections.status, + refs: toolConnections.credentialSecretRefs, + }) + .from(chatEndpoints) + .innerJoin( + toolConnections, + and( + eq(toolConnections.id, chatEndpoints.connectionId), + eq(toolConnections.companyId, companyId), + ), + ) + .where( + and( + eq(chatEndpoints.companyId, companyId), + eq(chatEndpoints.id, endpointId), + eq(chatEndpoints.provider, "github"), + ), + ); + if (!row || ["archived", "revoked", "paused"].includes(row.endpointStatus)) + throw conflict("GitHub bot connection is unavailable"); + const [appId, privateKey, installationId] = GITHUB_MINT_CREDENTIALS.map( + (key) => row.refs.find((ref) => ref.configPath === `credentials.${key}`), + ); + if (!appId || !privateKey) + throw conflict("Connect the GitHub App before continuing"); + if ( + !row.enabled || + row.connectionStatus !== "active" || + !["active", "verifying"].includes(row.endpointStatus) + ) + throw conflict("GitHub bot connection is not active"); + if (!installationId) throw conflict("Verify the GitHub App installation first"); + const refs = [appId, privateKey, installationId]; + const secrets = await db + .select({ + id: companySecrets.id, + status: companySecrets.status, + latestVersion: companySecrets.latestVersion, + updatedAt: companySecrets.updatedAt, + bindingId: companySecretBindings.id, + bindingPath: companySecretBindings.configPath, + bindingSelector: companySecretBindings.versionSelector, + bindingUpdatedAt: companySecretBindings.updatedAt, + }) + .from(companySecrets) + .leftJoin( + companySecretBindings, + and( + eq(companySecretBindings.secretId, companySecrets.id), + eq(companySecretBindings.companyId, companyId), + eq(companySecretBindings.targetType, "tool_connection"), + eq(companySecretBindings.targetId, row.connectionId), + ), + ) + .where( + and( + eq(companySecrets.companyId, companyId), + inArray(companySecrets.id, [...new Set(refs.map((ref) => ref.secretId))]), + ), + ); + const revision = JSON.stringify([ + row.connectionId, + row.runtimeGeneration ?? 0, + refs.map((ref) => { + const selector = ref.versionSelector ?? "latest"; + const secret = secrets.find((candidate) => candidate.id === ref.secretId); + const binding = secrets.find( + (candidate) => + candidate.id === ref.secretId && candidate.bindingPath === ref.configPath, + ); + return [ + ref.configPath, + ref.secretId, + selector, + secret + ? [ + secret.status, + selector === "latest" ? secret.latestVersion : selector, + secret.updatedAt.getTime(), + ] + : null, + binding + ? [binding.bindingId, binding.bindingSelector, binding.bindingUpdatedAt?.getTime()] + : null, + ]; + }), + ]); + return { connectionId: row.connectionId, refs, revision }; +} + +async function githubBotRepositoryTokenFor( + db: Db, + companyId: string, + endpointId: string, + repositoryId: string, + fetchImpl: typeof fetch, + options: { refresh?: boolean } = {}, +): Promise { + let authority: Awaited>; + try { + authority = await githubBotRepositoryAuthority(db, companyId, endpointId); + } catch (error) { + // A connection that cannot mint must not keep its earlier tokens either. + forgetEndpointRepositoryTokens(endpointId); + throw error; + } + if (!/^[1-9][0-9]*$/.test(repositoryId) || !Number.isSafeInteger(Number(repositoryId))) + throw conflict("Verify the GitHub App installation first"); + const key = JSON.stringify([ + companyId, + endpointId, + repositoryId, + GITHUB_REPOSITORY_TOKEN_PERMISSIONS, + authority.revision, + ]); + const cached = repositoryTokens.get(key); + if (cached && !options.refresh && cached.refreshAt > Date.now()) { + rememberRepositoryToken(key, cached); + return { token: cached.token, key, cached: true }; + } + if (cached) repositoryTokens.delete(key); + // Resolve (and audit) the App's secrets only when a token is actually minted. + const secrets = secretService(db); + const values: string[] = []; + for (const ref of authority.refs) + values.push( + await secrets.resolveSecretValue( + companyId, + ref.secretId, + ref.versionSelector ?? "latest", + { + consumerType: "tool_connection", + consumerId: authority.connectionId, + configPath: ref.configPath, + actorType: "system", + actorId: null, + }, + ), + ); + const [appId, privateKey, installationId] = values; + if (!appId || !privateKey) + throw conflict("Connect the GitHub App before continuing"); + if (!installationId) throw conflict("Verify the GitHub App installation first"); + const issued = await githubBotRequest<{ token?: string; expires_at?: string }>( + fetchImpl, + githubAppJwt(appId, privateKey), + `/app/installations/${encodeURIComponent(installationId)}/access_tokens`, + { + method: "POST", + body: { + repository_ids: [Number(repositoryId)], + permissions: GITHUB_REPOSITORY_TOKEN_PERMISSIONS, + }, + }, + ); + if (!issued.token) + throw unprocessable("GitHub did not issue an installation token"); + const now = Date.now(); + const refreshAt = + Math.min( + Date.parse(issued.expires_at ?? ""), + now + GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS, + ) - GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS; + // Without a usable expiry the token serves this call only. + if (Number.isFinite(refreshAt) && refreshAt > now) + rememberRepositoryToken(key, { token: issued.token, endpointId, refreshAt }); + return { token: issued.token, key, cached: false }; +} + +/** + * Least-privilege short-lived token restricted to the single task repository. + * Reused until shortly before GitHub's expiry while the connection's current + * authority is unchanged. + */ export async function githubBotRepositoryToken( db: Db, companyId: string, @@ -208,38 +445,60 @@ export async function githubBotRepositoryToken( repositoryId: string, fetchImpl = fetch, ) { - const result = await githubBotCredentials(db, companyId, endpointId); - if ( - !result.connection.enabled || - result.connection.status !== "active" || - !["active", "verifying"].includes(result.endpoint.status) - ) - throw conflict("GitHub bot connection is not active"); - if ( - !result.credentials.installationId || - !/^[1-9][0-9]*$/.test(repositoryId) || - !Number.isSafeInteger(Number(repositoryId)) - ) - throw conflict("Verify the GitHub App installation first"); - const issued = await githubBotRequest<{ token?: string }>( - fetchImpl, - result.appJwt, - `/app/installations/${encodeURIComponent(result.credentials.installationId)}/access_tokens`, - { - method: "POST", - body: { - repository_ids: [Number(repositoryId)], - permissions: { - contents: "read", - metadata: "read", - issues: "write", - pull_requests: "write", - checks: "write", - }, - }, - }, + return ( + await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl) + ).token; +} + +export type GitHubBotRepositoryRequest = ( + path: string, + options?: Parameters[3], +) => Promise; + +function githubUnauthorized(error: unknown) { + return ( + error instanceof HttpError && + !!error.details && + typeof error.details === "object" && + (error.details as { providerStatus?: unknown }).providerStatus === 401 ); - if (!issued.token) - throw unprocessable("GitHub did not issue an installation token"); - return issued.token; +} + +/** + * GitHub requests with a repository token. When GitHub rejects a cached token + * (401), that token is dropped and the request is sent once more with a newly + * minted one. GitHub did not act on the rejected request, so the retry is safe. + */ +export async function githubBotRepositoryClient( + db: Db, + companyId: string, + endpointId: string, + repositoryId: string, + fetchImpl = fetch, +): Promise { + let current = Promise.resolve( + await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl), + ); + return async (path: string, options?: Parameters[3]) => { + const used = current; + const issued = await used; + try { + return await githubBotRequest(fetchImpl, issued.token, path, options); + } catch (error) { + if (!issued.cached || !githubUnauthorized(error)) throw error; + if (current === used) { + if (repositoryTokens.get(issued.key)?.token === issued.token) + repositoryTokens.delete(issued.key); + current = githubBotRepositoryTokenFor( + db, + companyId, + endpointId, + repositoryId, + fetchImpl, + { refresh: true }, + ); + } + return githubBotRequest(fetchImpl, (await current).token, path, options); + } + }; } diff --git a/server/src/services/chat-github-response-comments.ts b/server/src/services/chat-github-response-comments.ts index 2bb0ecbc5c1..a69812614bf 100644 --- a/server/src/services/chat-github-response-comments.ts +++ b/server/src/services/chat-github-response-comments.ts @@ -13,7 +13,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { conflict, forbidden, HttpError } from "../errors.js"; import { githubChatPrincipalAccess } from "./chat-github-access.js"; import { githubAutomaticAdmission } from "./chat-github-events.js"; -import { githubBotRepositoryToken, githubBotRequest } from "./chat-github-client.js"; +import { githubBotRepositoryClient } from "./chat-github-client.js"; import { withGitHubPublicationLease } from "./chat-github-publication-lease.js"; import { projectSafeChatPublicationText } from "./chat-publication-projection.js"; import type { GitHubAutomaticPolicyContext } from "./chat-github-review-policy.js"; @@ -276,9 +276,9 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) { ["pending", "retry"].includes(fast.publicationState ?? ""))))) return; } } - const token = await githubBotRepositoryToken(db, source.endpoint.companyId, source.endpoint.id, source.repositoryId, lease.fetch); + const github = await githubBotRepositoryClient(db, source.endpoint.companyId, source.endpoint.id, source.repositoryId, lease.fetch); const prefix = `/repos/${source.repository.split("/").map(encodeURIComponent).join("/")}`; - const api: Api = { request: (path, options) => githubBotRequest(lease.fetch, token, `${prefix}${path}`, options) }; + const api: Api = { request: (path, options) => github(`${prefix}${path}`, options) }; if (onlyExisting && !(await findResponseComment(source, api))) { const existing = await stageResponse(db, source); await lease.commit(async tx => { await tx.update(chatActions).set({ status: "cancelled", result: { final: true, code: "run_already_answered" }, updatedAt: new Date() }).where(eq(chatActions.id, existing.id)); }); diff --git a/server/src/services/chat-github-reviews.ts b/server/src/services/chat-github-reviews.ts index 77d4477fb20..ddd190aba1b 100644 --- a/server/src/services/chat-github-reviews.ts +++ b/server/src/services/chat-github-reviews.ts @@ -43,7 +43,7 @@ import { } from "@paperclipai/shared"; import { HttpError, conflict, forbidden, notFound } from "../errors.js"; import { - githubBotRepositoryToken, + githubBotRepositoryClient, githubBotRequest, } from "./chat-github-client.js"; import { githubChatPrincipalAccess } from "./chat-github-access.js"; @@ -316,7 +316,7 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) { source: Awaited>, requestFetch = fetchImpl, ) { - const token = await githubBotRepositoryToken( + const github = await githubBotRepositoryClient( db, source.endpoint.companyId, source.endpoint.id, @@ -330,7 +330,7 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) { path: string, options?: Parameters[3], ) => - githubBotRequest(requestFetch, token, `${prefix}${path}`, options), + github(`${prefix}${path}`, options), }; } async function reviewForHead(