Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: honor pinned forge accounts throughout PR review intake (#13287)

[._.]/ Adam Eivy674619f8e276
diff --git a/server/services/prReviewerSecurity.js b/server/services/prReviewerSecurity.js
index 26f27ad89b..04818a27d0 100644
--- a/server/services/prReviewerSecurity.js
+++ b/server/services/prReviewerSecurity.js
@@ -11,6 +11,7 @@
import { createHash } from 'node:crypto';
import { execGh, ensureForgeReachable } from './github.js';
import { getSelfLogin } from './prWatcher.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
import { createGithubActorTrust } from './forgeActorTrust.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import { githubApiHost, githubRepoSpec } from '../lib/workTracker.js';
@@ -72,12 +73,7 @@ export function extractLinkedIssueNumbers(pr, repoFullName) {
* issues contribute intent — a closed issue is not a live requirement, and the
* pre-action recheck recomputes the fingerprint from the same open set.
*/
-async function resolveEligibilityFacts(pr, repoFullName, hostname, readIssue = async (number) => {
- const raw = await execGh([
- 'api', '--hostname', hostname, `repos/${repoFullName}/issues/${number}`,
- ]).catch(() => null);
- return safeJSONParse(raw, null);
-}) {
+async function resolveEligibilityFacts(pr, repoFullName, readIssue) {
const linkedIssueNumbers = extractLinkedIssueNumbers(pr, repoFullName);
if (linkedIssueNumbers.length === 0) {
return {
@@ -146,7 +142,7 @@ export async function assessPullRequestForAction({ pr, diff, repoFullName, readP
return failure('security-action-evidence-unavailable');
}
const readIntent = (row) => resolveEligibilityFacts(
- { ...row, authorLogin: row.author?.login }, repoFullName, null, readIssue,
+ { ...row, authorLogin: row.author?.login }, repoFullName, readIssue,
);
const intent = await readIntent(pr);
if (!intent.inputComplete || !intent.facts.issueLookupComplete) return failure('security-action-intent-unavailable');
@@ -181,6 +177,14 @@ export async function assessPullRequestForAction({ pr, diff, repoFullName, readP
return { ok: true, stillCurrent };
}
+// These closures stay local to an intake; target/pipeline records never carry
+// credential-bearing execution options, including when callers spread them.
+const forgeReader = ({ cwd, env }) => args => execGh(args, undefined, { cwd, env });
+const issueReader = (runGh, hostname, repoFullName) => async number => {
+ const raw = await runGh(['api', '--hostname', hostname, `repos/${repoFullName}/issues/${number}`]).catch(() => null);
+ return safeJSONParse(raw, null);
+};
+
/**
* The three facts that decide which of a repo's open PRs pr-reviewer may target:
* the `gh` repo selector, the default branch it reviews against, and the login
@@ -191,21 +195,28 @@ export async function assessPullRequestForAction({ pr, diff, repoFullName, readP
* rule and drifting from it.
*/
export async function resolvePrReviewerTargetScope(app) {
+ const forgeExec = await resolveForgeExecOptions(app?.repoPath, { forgeAccount: app?.forgeAccount });
+ return readPrReviewerTargetScope(app, forgeExec);
+}
+
+async function readPrReviewerTargetScope(app, forgeExec) {
+ const runGh = forgeReader(forgeExec);
const origin = await getOriginInfo(app?.repoPath).catch(() => null);
const repoSpec = githubRepoSpec(origin);
if (!repoSpec) return failure('security-scan-not-a-github-repo');
const forge = await ensureForgeReachable('pr-reviewer security scan', {
hostname: githubApiHost(origin.host),
+ ...(forgeExec.customEnv ? { env: forgeExec.customEnv } : {}),
});
if (!forge.ok) return failure('security-scan-forge-unreachable');
- const defaultBranch = await execGh([
+ const defaultBranch = await runGh([
'repo', 'view', repoSpec, '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name',
]).catch(() => null);
if (!defaultBranch?.trim()) return failure('security-scan-default-branch-unresolved');
- const selfLogin = await getSelfLogin(githubApiHost(origin.host));
+ const selfLogin = await getSelfLogin(githubApiHost(origin.host), { cwd: forgeExec.cwd, env: forgeExec.env });
if (!selfLogin) return failure('security-scan-self-login-unavailable');
return {
@@ -215,7 +226,7 @@ export async function resolvePrReviewerTargetScope(app) {
hostname: githubApiHost(origin.host),
defaultBranch: defaultBranch.trim(),
selfLogin,
- actorTrust: await createGithubActorTrust({ runGh: execGh, host: githubApiHost(origin.host), repoFullName: origin.fullName, currentUser: selfLogin }),
+ actorTrust: await createGithubActorTrust({ runGh, host: githubApiHost(origin.host), repoFullName: origin.fullName, currentUser: selfLogin }),
};
}
@@ -236,11 +247,17 @@ export async function isReviewablePullRequest(scope, pullRequest) {
}
export async function listExternalOpenPullRequests(app) {
- const scope = await resolvePrReviewerTargetScope(app);
+ const forgeExec = await resolveForgeExecOptions(app?.repoPath, { forgeAccount: app?.forgeAccount });
+ return readExternalOpenPullRequests(app, forgeExec);
+}
+
+async function readExternalOpenPullRequests(app, forgeExec) {
+ const runGh = forgeReader(forgeExec);
+ const scope = await readPrReviewerTargetScope(app, forgeExec);
if (!scope.ok) return scope;
const { repoSpec, repoFullName, hostname, defaultBranch, actorTrust } = scope;
- const raw = await execGh([
+ const raw = await runGh([
'pr', 'list', '--repo', repoSpec,
'--base', defaultBranch, '--state', 'open',
'--limit', String(SECURITY_SCAN_MAX_OPEN_PRS),
@@ -273,8 +290,9 @@ export async function listExternalOpenPullRequests(app) {
const trusted = await mapWithConcurrency(listedPrs, ELIGIBILITY_LOOKUP_CONCURRENCY, pr => actorTrust.isTrusted(pr.authorLogin));
const externalPrs = listedPrs.filter((_, index) => !trusted[index]);
+ const readIssue = issueReader(runGh, hostname, repoFullName);
const prs = await mapWithConcurrency(externalPrs, ELIGIBILITY_LOOKUP_CONCURRENCY, async (pr) => {
- const { facts, linkedIssues, inputComplete } = await resolveEligibilityFacts(pr, repoFullName, hostname);
+ const { facts, linkedIssues, inputComplete } = await resolveEligibilityFacts(pr, repoFullName, readIssue);
return { ...pr, eligibilityFacts: facts, linkedIssues, inputComplete };
});
@@ -351,8 +369,8 @@ const reportFor = (pr, diff, commits, verdict) => ({
* hit count, so at the 200-PR cap it trips the 500,000 potential-node ceiling
* and the whole listing is refused. Read the log per PR, in the scan.
*/
-async function fetchPullRequestCommits(number, repoSpec) {
- const raw = await execGh([
+async function fetchPullRequestCommits(number, repoSpec, runGh) {
+ const raw = await runGh([
'pr', 'view', String(number), '--repo', repoSpec, '--json', 'commits',
]).catch(() => null);
const parsed = safeJSONParse(raw, null);
@@ -366,7 +384,9 @@ async function fetchPullRequestCommits(number, repoSpec) {
* generic and are useful to the human-facing status view only.
*/
export async function runPrReviewerSecurityScan({ app, target = null, largeInputFallback = null } = {}) {
- const resolvedTarget = target || await listExternalOpenPullRequests(app);
+ const forgeExec = await resolveForgeExecOptions(app?.repoPath, { forgeAccount: app?.forgeAccount });
+ const runGh = forgeReader(forgeExec);
+ const resolvedTarget = target || await readExternalOpenPullRequests(app, forgeExec);
if (!resolvedTarget.ok) return resolvedTarget;
const scanKey = securityScanFingerprint(resolvedTarget);
if (!scanKey) return failure('security-scan-target-unidentifiable');
@@ -393,8 +413,8 @@ export async function runPrReviewerSecurityScan({ app, target = null, largeInput
for (const pr of resolvedTarget.prs) {
if (pr.inputComplete === false || pr.linkedIssues?.some(issue => issue.truncated)) return failure('security-scan-linked-issue-too-large', { reviewedPrs, scanKey });
const [diff, commits] = await Promise.all([
- execGh(['pr', 'diff', String(pr.number), '--repo', resolvedTarget.repoSpec]).catch(() => null),
- fetchPullRequestCommits(pr.number, resolvedTarget.repoSpec),
+ runGh(['pr', 'diff', String(pr.number), '--repo', resolvedTarget.repoSpec]).catch(() => null),
+ fetchPullRequestCommits(pr.number, resolvedTarget.repoSpec, runGh),
]);
if (diff === null) return failure('security-scan-diff-unavailable', { reviewedPrs, scanKey });
// Fail closed on an unreadable commit log: screening a PR as though it had
diff --git a/server/services/prReviewerSecurity.test.js b/server/services/prReviewerSecurity.test.js
index 440bed715a..552a9fa905 100644
--- a/server/services/prReviewerSecurity.test.js
+++ b/server/services/prReviewerSecurity.test.js
@@ -6,8 +6,11 @@ const getSelfLoginMock = vi.fn()
const getOriginInfoMock = vi.fn()
const runModelAbuseScanMock = vi.fn()
const isTrustedMock = vi.fn()
+const createActorTrustMock = vi.fn()
+const resolveForgeExecOptionsMock = vi.fn()
-vi.mock('./forgeActorTrust.js', () => ({ createGithubActorTrust: async () => ({ isTrusted: (...args) => isTrustedMock(...args) }) }))
+vi.mock('./forgeActorTrust.js', () => ({ createGithubActorTrust: (...args) => createActorTrustMock(...args) }))
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: (...args) => resolveForgeExecOptionsMock(...args) }))
vi.mock('./github.js', () => ({
execGh: (...args) => execGhMock(...args),
@@ -35,6 +38,8 @@ vi.mock('../lib/workTracker.js', async (importActual) => {
import { linkedIssueIntentFingerprint } from '../lib/modelAbuseGuard.js'
import {
listExternalOpenPullRequests,
+ resolvePrReviewerTargetScope,
+ isReviewablePullRequest,
runPrReviewerSecurityScan,
securityScanFingerprint,
summarizeSecurityScanReport,
@@ -108,6 +113,8 @@ const routeGh = ({ prs = [], commits = {}, issues = {}, diffs = {} } = {}) => {
beforeEach(() => {
vi.clearAllMocks()
+ createActorTrustMock.mockImplementation(async () => ({ isTrusted: (...args) => isTrustedMock(...args) }))
+ resolveForgeExecOptionsMock.mockResolvedValue({ cwd: app.repoPath, env: {}, customEnv: null })
isTrustedMock.mockImplementation(async login => ['maintainer', 'example', 'trusted-collaborator'].includes(login.toLowerCase()))
ensureForgeReachableMock.mockResolvedValue({ ok: true })
getOriginInfoMock.mockResolvedValue({ host: 'github.com', fullName: 'example/repo' })
@@ -140,7 +147,7 @@ describe('pr-reviewer model-abuse preflight', () => {
expect(execGhMock).toHaveBeenCalledWith([
'pr', 'list', '--repo', 'github.com/example/repo', '--base', 'main', '--state', 'open',
'--limit', '200', '--json', 'number,author,url,headRefOid,updatedAt,title,body',
- ])
+ ], undefined, { cwd: app.repoPath, env: {} })
expect(execGhMock.mock.calls.some(([args]) => args[0] === 'pr' && args[1] !== 'list')).toBe(false)
})
@@ -202,7 +209,7 @@ describe('pr-reviewer model-abuse preflight', () => {
})
expect(execGhMock).toHaveBeenLastCalledWith([
'api', '--hostname', 'github.com', 'repos/example/repo/issues/101',
- ])
+ ], undefined, { cwd: app.repoPath, env: {} })
})
it('fails the programmatic issue lookup fact closed when a linked issue cannot be read', async () => {
@@ -465,3 +472,78 @@ describe('screened-content fingerprint contract', () => {
expect(stamped).toEqual(expect.any(String))
})
})
+
+
+describe('account-scoped review intake', () => {
+ it('keeps every forge read on the pinned account without serializing credentials', async () => {
+ const { createGithubActorTrust } = await vi.importActual('./forgeActorTrust.js')
+ createActorTrustMock.mockImplementation(createGithubActorTrust)
+ resolveForgeExecOptionsMock.mockImplementation(async (cwd, { forgeAccount }) => {
+ const env = { GH_TOKEN: `synthetic-token-${forgeAccount}` }
+ return { cwd, env, customEnv: env }
+ })
+ getSelfLoginMock.mockImplementation((host, options) => execGhMock(
+ ['api', 'user', '--hostname', host, '--jq', '.login'], undefined, options,
+ ))
+ execGhMock.mockImplementation(async (args, timeout, options) => {
+ const account = options.env.GH_TOKEN.replace('synthetic-token-', '')
+ if (args[0] === 'repo') return 'main'
+ if (args[0] === 'api' && args.includes('user')) return account
+ if (args[0] === 'api' && args.at(-1).endsWith('/permission')) {
+ const login = args.at(-1).split('/').at(-2)
+ return JSON.stringify({ user: { login }, permission: 'read' })
+ }
+ if (args[0] === 'api') return JSON.stringify(openIssue())
+ if (args[1] === 'list') return JSON.stringify([
+ listedPr(11, account, 'a'.repeat(40)),
+ listedPr(12, 'contributor-a', 'b'.repeat(40), { title: 'Fixes #101' }),
+ ])
+ if (args[1] === 'diff') return 'diff --git a/example.js b/example.js\n+export const fixed = true'
+ if (args[1] === 'view') return JSON.stringify({ commits: [{ messageHeadline: 'fix: example' }] })
+ throw new Error('unexpected synthetic forge request')
+ })
+
+ for (const forgeAccount of ['example-reviewer-a', 'example-reviewer-b']) {
+ execGhMock.mockClear()
+ const scopedApp = { ...app, forgeAccount }
+ // The generator passes a spread/narrowed target across the intake/scan
+ // boundary; credentials must be resolved from the app again there.
+ const scope = await resolvePrReviewerTargetScope(scopedApp)
+ expect(scope.selfLogin).toBe(forgeAccount)
+ expect(await isReviewablePullRequest(scope, { author: forgeAccount, baseBranch: 'main' })).toBe(false)
+ expect(await isReviewablePullRequest(scope, { author: 'contributor-a', baseBranch: 'main' })).toBe(true)
+ const target = await listExternalOpenPullRequests(scopedApp)
+ expect(target.prs.map(pr => pr.number)).toEqual([12])
+ const result = await runPrReviewerSecurityScan({ app: scopedApp, target: { ...target } })
+ expect(result).toMatchObject({ ok: true, passed: true })
+ expect(resolveForgeExecOptionsMock).toHaveBeenCalledWith(app.repoPath, { forgeAccount })
+ const env = { GH_TOKEN: `synthetic-token-${forgeAccount}` }
+ expect(ensureForgeReachableMock).toHaveBeenLastCalledWith('pr-reviewer security scan', { hostname: 'github.com', env })
+ expect(execGhMock.mock.calls.length).toBeGreaterThanOrEqual(7)
+ for (const [, , options] of execGhMock.mock.calls) expect(options).toEqual({ cwd: app.repoPath, env })
+ for (const value of [scope, target, result, runModelAbuseScanMock.mock.calls]) {
+ expect(JSON.stringify(value)).not.toMatch(/synthetic-token|GH_TOKEN|"env"|"cwd"/)
+ }
+ expect(runModelAbuseScanMock).toHaveBeenLastCalledWith({ content: expect.any(String), source: 'github-pr' })
+ }
+ })
+
+ it('does not read as the ambient account when a pin cannot be resolved', async () => {
+ resolveForgeExecOptionsMock.mockRejectedValue(Object.assign(new Error('Synthetic account unavailable'), { code: 'FORGE_ACCOUNT_UNAVAILABLE' }))
+ await expect(listExternalOpenPullRequests({ ...app, forgeAccount: 'example-reviewer-b' }))
+ .rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' })
+ expect(execGhMock).not.toHaveBeenCalled()
+ expect(getSelfLoginMock).not.toHaveBeenCalled()
+ })
+
+ it('withholds private repository intake when the pinned account lacks access', async () => {
+ const env = { GH_TOKEN: 'synthetic-unavailable-token' }
+ resolveForgeExecOptionsMock.mockResolvedValue({ cwd: app.repoPath, env, customEnv: env })
+ execGhMock.mockRejectedValue(new Error('Synthetic private repository unavailable'))
+ expect(await listExternalOpenPullRequests({ ...app, forgeAccount: 'example-reviewer-b' }))
+ .toMatchObject({ ok: false, code: 'security-scan-default-branch-unresolved' })
+ expect(execGhMock).toHaveBeenCalledTimes(1)
+ expect(execGhMock.mock.calls[0][2]).toEqual({ cwd: app.repoPath, env })
+ expect(getSelfLoginMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 975a831938..ebcc4ca289 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -94,17 +94,21 @@ const _selfLoginCache = new Map();
* Resolve the gh-authenticated user's login on `host` (e.g. "alice" on
* github.com, "alice_corp" on an enterprise host). Returns null when `host` is
* falsy or gh isn't authenticated there — callers that need it for an author
- * gate must treat null as "can't gate, don't fire blindly".
+ * gate must treat null as "can't gate, don't fire blindly". Optional scoped
+ * `{ cwd, env }` execution options bypass the ambient host-only cache.
*/
-export async function getSelfLogin(host) {
+export async function getSelfLogin(host, forgeExec) {
if (!host) return null;
- if (_selfLoginCache.has(host)) return _selfLoginCache.get(host);
+ // Scoped credentials can select another account on the same host. Never
+ // consume or populate the ambient cache (or key it by a secret).
+ const cacheable = !forgeExec;
+ if (cacheable && _selfLoginCache.has(host)) return _selfLoginCache.get(host);
// `--hostname` is required: without it `gh api` targets github.com regardless
// of cwd, resolving the wrong identity for an enterprise repo.
const login = await execGh(
['api', 'user', '--hostname', host, '--jq', '.login'],
undefined,
- { backoffKey: host }
+ { ...forgeExec, backoffKey: host }
).catch((err) => {
// Log rather than swallow (#3358): without this a firewalled/unauthenticated
// gh is indistinguishable from "this host has no login", and every self/others
@@ -117,7 +121,7 @@ export async function getSelfLogin(host) {
// later self/others gate on this host into 'self-login-unavailable' until
// process restart; leaving it unset lets the next tick retry once auth recovers.
const trimmed = login && login.trim();
- if (trimmed) _selfLoginCache.set(host, trimmed);
+ if (cacheable && trimmed) _selfLoginCache.set(host, trimmed);
return trimmed || null;
}
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 588e6e1044..e2eb5e891c 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -979,6 +979,28 @@ describe('getSelfLogin', () => {
expect(execGhMock).toHaveBeenCalledTimes(2);
});
+ it('isolates scoped viewers on one host from each other and the ambient cache', async () => {
+ const first = { cwd: '/example/repo', env: { GH_TOKEN: 'synthetic-token-a' } };
+ const second = { cwd: '/example/repo', env: { GH_TOKEN: 'synthetic-token-b' } };
+ execGhMock.mockImplementation(async (args, timeout, options) => {
+ if (options.env === first.env) return 'example-reviewer-a';
+ if (options.env === second.env) return 'example-reviewer-b';
+ return 'ambient-viewer';
+ });
+ expect(await getSelfLogin('github.com')).toBe('ambient-viewer');
+ expect(await getSelfLogin('github.com', first)).toBe('example-reviewer-a');
+ expect(await getSelfLogin('github.com', second)).toBe('example-reviewer-b');
+ execGhMock.mockRejectedValueOnce(new Error('Synthetic scoped account unavailable'));
+ expect(await getSelfLogin('github.com', second)).toBeNull();
+ expect(await getSelfLogin('github.com', second)).toBe('example-reviewer-b');
+ expect(await getSelfLogin('github.com')).toBe('ambient-viewer');
+ expect(execGhMock).toHaveBeenCalledTimes(5);
+ expect(execGhMock).toHaveBeenCalledWith(
+ ['api', 'user', '--hostname', 'github.com', '--jq', '.login'],
+ undefined, { ...second, backoffKey: 'github.com' },
+ );
+ });
+
it('returns null with no host and never shells out', async () => {
expect(await getSelfLogin()).toBe(null);
expect(await getSelfLogin('')).toBe(null);