Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Security and behavior changes

- Allow an explicit, bounded operator request budget only for the exact disposable acceptance tenant. Preserve all counters, other quotas, authorization, protected policy and native review requirements; disabled by default.

- Parse real JS/TS import syntax with the existing pinned TypeScript compiler when selecting essential context. Generated-code strings/comments no longer cause false missing-dependency failures; actual missing imports/exports/require calls remain fail-closed.

- Honor public read access for authorized non-collaborator PR events only when explicitly assigned to a consenting repository admin. Private repositories, manual commands, tenant identity checks and separate merge authorization are unchanged.
Expand Down
2 changes: 2 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,5 @@ Apply additive migration 0006 before deploying the owner-consent code. CLI sessi
While `MERGE_DEPLOYMENT_AUTHORIZED=false`, the operator can temporarily configure **both** `MERGE_ACCEPTANCE_REPOSITORY_ID` and `MERGE_ACCEPTANCE_INSTALLATION_ID` for the one disposable acceptance repository. Empty/missing or mismatched scope remains closed. The caller cannot supply this scope. All normal review, native approval, owner consent, merge authorization, OIDC, GitHub rules, exact-head and CI checks still apply. This permits a real happy-path test before globally authorizing merging. Clear the temporary scope after acceptance; enable the global gate only after the required live evidence passes. Keep browser and hosted website inference flags false for the CLI release.

No human approval is required by CodexBot in Fully Autonomous mode when the compatible GitHub rules also require zero humans. Human-in-the-Loop and stricter GitHub review/CODEOWNER/last-push requirements are independently enforced. Never relax valuable-repository protection or manufacture a reviewer to complete a live gate. If an actual account sign-in or independent reviewer is unavailable, record that exact acceptance as blocked and complete independent validation/deployment; do not publish a verified full release.

The operator may explicitly set `ACCEPTANCE_USER_PER_DAY` (1–1000, empty by default) only alongside both exact disposable acceptance installation/repository IDs. This is trusted operator configuration for admission, not authorization or a caller input. It changes only that tenant’s per-user rolling request budget, retains every counter and all other limits, and reports the effective limit on rejection. Snapshot policy remains the protected default-branch policy for publication/merge checks. Clear the override after the reviewed repository quota is in place. No GitHub protection or AI approval is bypassed.
8 changes: 5 additions & 3 deletions src/worker/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class Store {
.bind(Date.now(), Date.now(), MAX_RECOVERY_ATTEMPTS).all<{ id: string }>();
return results.map(x => x.id);
}
async create(snapshot: RequestSnapshot, trustedWorkflow = '', feedback = false): Promise<RequestSnapshot> {
async create(snapshot: RequestSnapshot, trustedWorkflow = '', feedback = false, operatorUserQuota?: number): Promise<RequestSnapshot> {
const existingRequest = () => this.db.prepare(`SELECT snapshot FROM requests WHERE id=? OR (installation_id=? AND repository_id=? AND actor_id=? AND json_extract(snapshot,'$.commandId')=?)`).bind(snapshot.id,snapshot.installationId,snapshot.repositoryId,snapshot.actorId,snapshot.commandId ?? null).first<{ snapshot: string }>();
const existing = await existingRequest();
if (existing) return JSON.parse(existing.snapshot) as RequestSnapshot;
Expand All @@ -57,7 +57,9 @@ export class Store {
const key = await sha256(JSON.stringify({ installation: snapshot.installationId, repository: snapshot.repositoryId, owner: snapshot.ownerId,
actor: snapshot.actorId, pr: snapshot.pr, head: snapshot.head, base: snapshot.base, branch: snapshot.defaultBranch,
workflow: snapshot.workflowSha, trustedWorkflow, config: snapshot.config, command, mergeIntent: snapshot.mergeIntent ?? null, automaticGrantId:snapshot.automaticGrantId ?? null, rerun: snapshot.command.rerun ? snapshot.commandId ?? snapshot.id : null }));
const now = Date.now(), q = snapshot.config.quotas, day = now - 86_400_000, cooldown = now - q.cooldown_seconds * 1000;
requireCondition(operatorUserQuota===undefined || (Number.isSafeInteger(operatorUserQuota) && operatorUserQuota>=1 && operatorUserQuota<=1000),'invalid_operator_request_quota',503);
const q=operatorUserQuota===undefined?snapshot.config.quotas:{...snapshot.config.quotas,user_per_day:operatorUserQuota};
const now = Date.now(), day = now - 86_400_000, cooldown = now - q.cooldown_seconds * 1000;
const insert = this.db.prepare(`INSERT OR IGNORE INTO requests(id,installation_id,repository_id,actor_id,snapshot,created_at,request_key,rerun)
SELECT ?,?,?,?,?,?,?,? WHERE
(SELECT count(*) FROM requests WHERE installation_id=? AND actor_id=? AND created_at>?)<? AND
Expand All @@ -72,7 +74,7 @@ export class Store {
snapshot.installationId, day, q.installation_per_day, snapshot.installationId, snapshot.repositoryId, now - REQUEST_LIFETIME_MS, q.concurrent_repository,
snapshot.installationId, now - REQUEST_LIFETIME_MS, q.concurrent_installation, snapshot.installationId, snapshot.repositoryId, snapshot.actorId, cooldown,
snapshot.installationId, snapshot.actorId, day, snapshot.command.rerun ? q.reruns_per_day : 1001);
const [result] = await this.db.batch([insert, await admissionRejection(this.db, snapshot, key, now, feedback)]);
const [result] = await this.db.batch([insert, await admissionRejection(this.db, {...snapshot,config:{...snapshot.config,quotas:q}}, key, now, feedback)]);
if (result!.meta.changes !== 1) {
const rejected = await getRejection(this.db, await rejectionId(snapshot));
if (!rejected) {
Expand Down
6 changes: 4 additions & 2 deletions src/worker/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { updateProgress } from './progress.js';
import { AdmissionError, recordRejection, type RejectionCode, type RejectionIdentity } from './admission.js';
import { publishRejection } from './rejections.js';

export interface BackendConfig extends GitHubCredentials { DB: D1Database; PUBLIC_URL: string; GITHUB_APP_SLUG: string; TRUSTED_WORKFLOW: string; CHATGPT_DEPLOYMENT_AUTHORIZED: string }
export interface BackendConfig extends GitHubCredentials { DB: D1Database; PUBLIC_URL: string; GITHUB_APP_SLUG: string; TRUSTED_WORKFLOW: string; CHATGPT_DEPLOYMENT_AUTHORIZED: string; MERGE_ACCEPTANCE_REPOSITORY_ID?:string; MERGE_ACCEPTANCE_INSTALLATION_ID?:string; ACCEPTANCE_USER_PER_DAY?:string }
/** Persist only fields needed for recovery; never copy issue/PR bodies or unrelated metadata. */
export function compactWebhook(event: string, payload: unknown): unknown {
const input = record(payload);
Expand Down Expand Up @@ -139,7 +139,9 @@ export async function ingest(event: string, payload: unknown, requestId: string,
repository: liveRepo.full_name, defaultBranch: liveRepo.default_branch, workflowSha: branch.commit.sha,
head: pr.head.sha, base: pr.base.sha, pr: prNumber, actor, actorId, ...(automaticGrantId ? {triggerActor:{login:sender.login,id:Number(sender.id),...(sender.type==='Bot'?{type:'Bot' as const}:{})},automaticGrantId} : {}), command, config, createdAt: Date.now(), ...(manual && Number.isSafeInteger(record(input.comment).id) ? {commandId:Number(record(input.comment).id)} : {}), commits: pr.commits, changedFiles: pr.changed_files
};
try { snapshot = await store.create(snapshot, env.TRUSTED_WORKFLOW, manual); }
const scopedQuota=env.MERGE_ACCEPTANCE_REPOSITORY_ID===String(snapshot.repositoryId) && env.MERGE_ACCEPTANCE_INSTALLATION_ID===String(snapshot.installationId) ? env.ACCEPTANCE_USER_PER_DAY : undefined;
requireCondition(!scopedQuota || (/^[1-9]\d{0,3}$/.test(scopedQuota) && Number(scopedQuota)<=1000),'invalid_operator_request_quota',503);
try { snapshot = await store.create(snapshot, env.TRUSTED_WORKFLOW, manual, scopedQuota ? Number(scopedQuota) : undefined); }
catch (error) {
if (!(error instanceof AdmissionError)) throw error;
if (manual) await publishRejection(env,error.rejection.id);
Expand Down
2 changes: 1 addition & 1 deletion tests/backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ await test('hosted config, manifest and generated callers agree on Workers.dev w
assert.equal(config.vars.PUBLIC_URL, DEFAULT_BACKEND); assert.equal(config.vars.MERGE_DEPLOYMENT_AUTHORIZED, 'false');
assert.equal(config.vars.TRUSTED_WORKFLOW, 'AppSolves/codexbot/.github/workflows/review.yml@f0086735a6dc62130ffa8aed9828cc9768b9da1e');
assert.equal(config.vars.WEB_ENABLED,'false');assert.equal(config.vars.OPENAI_HOSTED_INFERENCE_AUTHORIZED,'false');
assert.equal(config.vars.MERGE_ACCEPTANCE_REPOSITORY_ID,'');assert.equal(config.vars.MERGE_ACCEPTANCE_INSTALLATION_ID,'');
assert.equal(config.vars.ACCEPTANCE_USER_PER_DAY,'');assert.equal(config.vars.MERGE_ACCEPTANCE_REPOSITORY_ID,'');assert.equal(config.vars.MERGE_ACCEPTANCE_INSTALLATION_ID,'');
assert.deepEqual(config.routes, []);
const manifest = JSON.parse(await readFile('app-manifest.json', 'utf8'));
assert.equal(manifest.url, DEFAULT_BACKEND); assert.equal(manifest.hook_attributes.url, `${DEFAULT_BACKEND}/webhook`);
Expand Down
14 changes: 13 additions & 1 deletion tests/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function signed(input: unknown, secret: string, delivery = crypto.randomUUID()):
}
async function fixture<T>(action: (env: Env, github: ReturnType<typeof githubFixture>) => Promise<T>): Promise<T> {
const { db, sqlite } = database(), github = githubFixture(); github.config.credentials.mode = 'api-key';
const env: Env = { MERGE_ACCEPTANCE_REPOSITORY_ID:'',MERGE_ACCEPTANCE_INSTALLATION_ID:'',WEB_ENABLED: 'false', GITHUB_CLIENT_ID: '', OPENAI_WEB_CLIENT_ID: '', OPENAI_WEB_AUTH_METHOD: '', OPENAI_WEB_SCOPES: '', OPENAI_HOSTED_INFERENCE_AUTHORIZED: 'false', DB: db, PUBLIC_URL: 'https://broker.invalid', GITHUB_APP_ID: '42', GITHUB_APP_SLUG: 'codexbot', GITHUB_PRIVATE_KEY: pem, GITHUB_WEBHOOK_SECRET: 'fixture-webhook-secret'.repeat(2), TRUSTED_WORKFLOW: `operator/codexbot/.github/workflows/review.yml@${RELEASE}`, CHATGPT_DEPLOYMENT_AUTHORIZED: 'false', MERGE_DEPLOYMENT_AUTHORIZED: 'false' };
const env: Env = { ACCEPTANCE_USER_PER_DAY:'', MERGE_ACCEPTANCE_REPOSITORY_ID:'',MERGE_ACCEPTANCE_INSTALLATION_ID:'',WEB_ENABLED: 'false', GITHUB_CLIENT_ID: '', OPENAI_WEB_CLIENT_ID: '', OPENAI_WEB_AUTH_METHOD: '', OPENAI_WEB_SCOPES: '', OPENAI_HOSTED_INFERENCE_AUTHORIZED: 'false', DB: db, PUBLIC_URL: 'https://broker.invalid', GITHUB_APP_ID: '42', GITHUB_APP_SLUG: 'codexbot', GITHUB_PRIVATE_KEY: pem, GITHUB_WEBHOOK_SECRET: 'fixture-webhook-secret'.repeat(2), TRUSTED_WORKFLOW: `operator/codexbot/.github/workflows/review.yml@${RELEASE}`, CHATGPT_DEPLOYMENT_AUTHORIZED: 'false', MERGE_DEPLOYMENT_AUTHORIZED: 'false' };
const replacement: typeof fetch = async (input, init) => String(input).includes('token.actions.githubusercontent.com/.well-known/jwks') ? Response.json({ keys: [jwk] }) : github.fetcher(input, init);
const intercepted = mock.method(globalThis, 'fetch', replacement);
try { return await action(env, github); } finally { intercepted.mock.restore(); sqlite.close(); }
Expand Down Expand Up @@ -417,3 +417,15 @@ await test('unconnected automation contributor requires explicit owner assignmen
assert.equal((await worker.fetch(signed(manual,env.GITHUB_WEBHOOK_SECRET),env)).status,403);
assert.equal(f.calls.filter(call=>call.path.endsWith('/dispatches')).length,1);
}));

await test('explicit operator quota changes only the exact disposable tenant and preserves persisted policy and counters',async()=>fixture(async(env,f)=>{
f.config.quotas.user_per_day=1;f.config.quotas.cooldown_seconds=0;
const send=async(id:number)=>{const input=payload();return worker.fetch(signed({...input,comment:{...input.comment,id}},env.GITHUB_WEBHOOK_SECRET),env);};
assert.equal((await send(801)).status,202);const store=new Store(env.DB);const first=await env.DB.prepare('SELECT id FROM requests').first<{id:string}>();await store.transition(first!.id,'dispatched','failed');f.state.head='d'.repeat(40);
env.ACCEPTANCE_USER_PER_DAY='2';env.MERGE_ACCEPTANCE_REPOSITORY_ID='999';env.MERGE_ACCEPTANCE_INSTALLATION_ID='1';assert.equal((await send(802)).status,200);
env.MERGE_ACCEPTANCE_REPOSITORY_ID='2';env.MERGE_ACCEPTANCE_INSTALLATION_ID='999';assert.equal((await send(803)).status,200);
env.MERGE_ACCEPTANCE_INSTALLATION_ID='1';assert.equal((await send(804)).status,202);
assert.equal((await env.DB.prepare('SELECT count(*) AS n FROM requests').first<{n:number}>())!.n,2);
const saved=await env.DB.prepare("SELECT snapshot FROM requests WHERE state='dispatched'").first<{snapshot:string}>();assert.equal(JSON.parse(saved!.snapshot).config.quotas.user_per_day,1);assert.equal(f.config.quotas.user_per_day,1);
env.ACCEPTANCE_USER_PER_DAY='unbounded';assert.equal((await send(805)).status,503);
}));
1 change: 1 addition & 0 deletions wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"MERGE_DEPLOYMENT_AUTHORIZED": "false",
"MERGE_ACCEPTANCE_REPOSITORY_ID": "",
"MERGE_ACCEPTANCE_INSTALLATION_ID": "",
"ACCEPTANCE_USER_PER_DAY": "",
"WEB_ENABLED": "false",
"GITHUB_CLIENT_ID": "Iv23liRS1tl8zCodzTEr",
"OPENAI_WEB_CLIENT_ID": "",
Expand Down