Repository navigation
fix(aggregator): reject unsafe OpenChamber quota lib checkouts (#5721) #7133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import { execFile } from "node:child_process"; | ||
| import { existsSync } from "node:fs"; | ||
| import { resolve } from "node:path"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import type { OpenDesignCredentialLike } from "./opendesign-renewal.ts"; | ||
|
|
||
| export type GitRun = (cwd: string, args: string[]) => Promise<string>; | ||
|
|
||
| export interface OpenChamberCredentialsModule { | ||
| readManagedCredential: (providerId: string) => OpenDesignCredentialLike | null; | ||
| writeManagedCredential: (providerId: string, value: OpenDesignCredentialLike) => unknown; | ||
| } | ||
|
|
||
| export interface OpenChamberProviderModule { | ||
| fetchOpenDesignQuota: (credential: OpenDesignCredentialLike) => Promise<unknown>; | ||
| } | ||
|
|
||
| export interface ResolvedOpenChamberLib { | ||
| dir: string; | ||
| root: string; | ||
| revision: string; | ||
| credentials: OpenChamberCredentialsModule; | ||
| provider: OpenChamberProviderModule; | ||
| } | ||
|
|
||
| export interface ResolveLibOptions { | ||
| gitRun?: GitRun; | ||
| log?: (message: string) => void; | ||
| } | ||
|
|
||
| const REQUIRED_MODULE_EXPORTS = [ | ||
| { | ||
| path: "quota/credentials/providers.js", | ||
| names: ["readManagedCredential", "writeManagedCredential"], | ||
| }, | ||
| { path: "quota/providers/opendesign.js", names: ["fetchOpenDesignQuota"] }, | ||
| ] as const; | ||
|
|
||
| const defaultGitRun: GitRun = (cwd, args) => | ||
| new Promise((resolveOutput, reject) => { | ||
| execFile("git", args, { cwd, timeout: 10_000, maxBuffer: 1 << 20 }, (err, stdout) => { | ||
| if (err) reject(err); | ||
| else resolveOutput(stdout.trim()); | ||
| }); | ||
| }); | ||
|
|
||
| async function importRequiredModule(dir: string, path: string): Promise<Record<string, unknown>> { | ||
| try { | ||
| return (await import(pathToFileURL(resolve(dir, path)).href)) as Record<string, unknown>; | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : String(err); | ||
| const missing = | ||
| message.match(/does not provide an export named ['"]([^'"]+)['"]/i) ?? | ||
| message.match(/export named ['"]([^'"]+)['"] not found/i); | ||
| if (missing) { | ||
| throw new Error(`missing required export "${missing[1]}" while importing ${path}`); | ||
| } | ||
| throw new Error(`could not import ${path}: ${message}`); | ||
| } | ||
| } | ||
|
|
||
| async function validateExports(dir: string): Promise<{ | ||
| credentials: OpenChamberCredentialsModule; | ||
| provider: OpenChamberProviderModule; | ||
| }> { | ||
| const [credentials, provider] = await Promise.all( | ||
| REQUIRED_MODULE_EXPORTS.map(({ path }) => importRequiredModule(dir, path)), | ||
| ); | ||
| const modules = [credentials, provider]; | ||
| for (let index = 0; index < REQUIRED_MODULE_EXPORTS.length; index += 1) { | ||
| const required = REQUIRED_MODULE_EXPORTS[index]; | ||
| const module = modules[index]; | ||
| for (const name of required.names) { | ||
| if (typeof module[name] !== "function") { | ||
| throw new Error(`missing required export "${name}" in ${required.path}`); | ||
| } | ||
| } | ||
| } | ||
| return { | ||
| credentials: credentials as unknown as OpenChamberCredentialsModule, | ||
| provider: provider as unknown as OpenChamberProviderModule, | ||
| }; | ||
| } | ||
|
|
||
| async function inspectCandidate(dir: string, gitRun: GitRun): Promise<ResolvedOpenChamberLib> { | ||
| if (!existsSync(resolve(dir, "quota/index.js"))) { | ||
| throw new Error("quota/index.js is missing"); | ||
| } | ||
|
|
||
| const root = (await gitRun(dir, ["rev-parse", "--show-toplevel"])).trim(); | ||
| if (!root) throw new Error("Git returned an empty checkout root"); | ||
|
|
||
| const branch = (await gitRun(root, ["branch", "--show-current"])).trim(); | ||
| if (branch !== "main") { | ||
| throw new Error(`checkout is on ${branch ? `branch ${branch}` : "a detached HEAD"}, not main`); | ||
| } | ||
|
|
||
| const changes = (await gitRun(root, ["status", "--porcelain", "--untracked-files=normal"])).trim(); | ||
| if (changes) throw new Error("checkout has a dirty working tree"); | ||
|
|
||
| const revision = (await gitRun(root, ["rev-parse", "--verify", "HEAD^{commit}"])).trim(); | ||
| if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(revision)) { | ||
| throw new Error(`Git returned an invalid HEAD revision ${JSON.stringify(revision)}`); | ||
| } | ||
|
|
||
| const modules = await validateExports(dir); | ||
| return { dir, root, revision, ...modules }; | ||
| } | ||
|
|
||
| /** Pick the first clean main checkout with the credential APIs this gatherer uses. */ | ||
| export async function resolveLibDir( | ||
| candidates: string[], | ||
| { gitRun = defaultGitRun, log = console.warn }: ResolveLibOptions = {}, | ||
| ): Promise<ResolvedOpenChamberLib> { | ||
| const rejected: string[] = []; | ||
| const seen = new Set<string>(); | ||
|
|
||
| for (const candidate of candidates) { | ||
| const dir = resolve(candidate); | ||
| if (seen.has(dir)) continue; | ||
| seen.add(dir); | ||
| try { | ||
| const lib = await inspectCandidate(dir, gitRun); | ||
| log(`quota-gatherer: OpenChamber lib dir=${lib.dir} branch=main rev=${lib.revision}`); | ||
| return lib; | ||
| } catch (err) { | ||
| const reason = err instanceof Error ? err.message : String(err); | ||
| rejected.push(`${dir}: ${reason}`); | ||
| log(`quota-gatherer: rejected OpenChamber lib ${dir}: ${reason}`); | ||
| } | ||
| } | ||
|
|
||
| const detail = rejected.length ? rejected.join("; ") : "no candidates were configured"; | ||
| throw new Error(`no usable clean main OpenChamber lib checkout found (${detail})`); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import { afterEach, describe, expect, test } from "bun:test"; | ||
| import { resolveLibDir, type GitRun } from "../src/openchamber-lib.ts"; | ||
|
|
||
| const roots: string[] = []; | ||
| const REVISION = "a".repeat(40); | ||
|
|
||
| interface FixtureOptions { | ||
| missingExport?: string; | ||
| brokenDependencyExport?: string; | ||
| } | ||
|
|
||
| async function makeLib({ missingExport, brokenDependencyExport }: FixtureOptions = {}) { | ||
| const root = await mkdtemp(join(tmpdir(), "openchamber-lib-test-")); | ||
| roots.push(root); | ||
| const dir = join(root, "packages/web/server/lib"); | ||
| await mkdir(join(dir, "quota/credentials"), { recursive: true }); | ||
| await mkdir(join(dir, "quota/providers"), { recursive: true }); | ||
| await writeFile(join(dir, "quota/index.js"), "export {};\n"); | ||
|
|
||
| const credentialExports = ["readManagedCredential", "writeManagedCredential"].filter((name) => name !== missingExport); | ||
| const imports = brokenDependencyExport ? `import { ${brokenDependencyExport} } from "./auth.js";\nvoid ${brokenDependencyExport};\n` : ""; | ||
| await writeFile( | ||
| join(dir, "quota/credentials/providers.js"), | ||
| `${imports}${credentialExports.map((name) => `export function ${name}() { return null; }`).join("\n")}\n`, | ||
| ); | ||
| await writeFile(join(dir, "quota/providers/opendesign.js"), "export async function fetchOpenDesignQuota() {}\n"); | ||
| await writeFile(join(dir, "quota/credentials/auth.js"), "export {};\n"); | ||
| return { root, dir }; | ||
| } | ||
|
|
||
| function fakeGit(states: Array<{ root: string; dir: string; branch?: string; changes?: string }>): GitRun { | ||
| return async (cwd, args) => { | ||
| const state = states.find((candidate) => cwd === candidate.root || cwd === candidate.dir); | ||
| if (!state) throw new Error(`unexpected git cwd: ${cwd}`); | ||
| switch (args.join(" ")) { | ||
| case "rev-parse --show-toplevel": | ||
| return state.root; | ||
| case "branch --show-current": | ||
| return state.branch ?? "main"; | ||
| case "status --porcelain --untracked-files=normal": | ||
| return state.changes ?? ""; | ||
| case "rev-parse --verify HEAD^{commit}": | ||
| return REVISION; | ||
| default: | ||
| throw new Error(`unexpected git call: ${args.join(" ")}`); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| afterEach(async () => { | ||
| await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); | ||
| }); | ||
|
|
||
| describe("resolveLibDir", () => { | ||
| test("skips a dirty candidate and logs the selected path and revision", async () => { | ||
| const dirty = await makeLib(); | ||
| const clean = await makeLib(); | ||
| const messages: string[] = []; | ||
|
|
||
| const resolved = await resolveLibDir([dirty.dir, clean.dir], { | ||
| gitRun: fakeGit([ | ||
| { ...dirty, changes: "?? untracked.txt" }, | ||
| clean, | ||
| ]), | ||
| log: (message) => messages.push(message), | ||
| }); | ||
|
|
||
| expect(resolved.dir).toBe(clean.dir); | ||
| expect(resolved.revision).toBe(REVISION); | ||
| expect(messages.some((message) => message.includes(`${dirty.dir}: checkout has a dirty working tree`))).toBe(true); | ||
| expect(messages).toContain(`quota-gatherer: OpenChamber lib dir=${clean.dir} branch=main rev=${REVISION}`); | ||
| }); | ||
|
|
||
| test("skips a candidate checked out on a non-main branch", async () => { | ||
| const offMain = await makeLib(); | ||
| const clean = await makeLib(); | ||
| const messages: string[] = []; | ||
|
|
||
| const resolved = await resolveLibDir([offMain.dir, clean.dir], { | ||
| gitRun: fakeGit([{ ...offMain, branch: "queue/8357-224" }, clean]), | ||
| log: (message) => messages.push(message), | ||
| }); | ||
|
|
||
| expect(resolved.dir).toBe(clean.dir); | ||
| expect(messages.some((message) => message.includes(`${offMain.dir}: checkout is on branch queue/8357-224, not main`))).toBe(true); | ||
| }); | ||
|
|
||
| test("names a missing required export instead of exposing a bare import failure", async () => { | ||
| const incomplete = await makeLib({ missingExport: "readManagedCredential" }); | ||
| const messages: string[] = []; | ||
|
|
||
| await expect( | ||
| resolveLibDir([incomplete.dir], { | ||
| gitRun: fakeGit([incomplete]), | ||
| log: (message) => messages.push(message), | ||
| }), | ||
| ).rejects.toThrow('missing required export "readManagedCredential"'); | ||
|
|
||
| expect(messages.some((message) => message.includes('missing required export "readManagedCredential"'))).toBe(true); | ||
| }); | ||
|
|
||
| test("names a missing export imported by the required module", async () => { | ||
| const incomplete = await makeLib({ brokenDependencyExport: "openCodeLocalCredentialSource" }); | ||
|
|
||
| await expect( | ||
| resolveLibDir([incomplete.dir], { | ||
| gitRun: fakeGit([incomplete]), | ||
| log: () => {}, | ||
| }), | ||
| ).rejects.toThrow('missing required export "openCodeLocalCredentialSource"'); | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When no candidate OpenChamber checkout passes validation—for example, both laptop checkouts are dirty or on feature branches—this return aborts the entire quota tick before the independent
opencodequota subcommand runs. This also happens withOPENDESIGN_RENEWAL_DISABLED=1, since its guard is reached only afterward. Previously, these imports were inside the OpenDesign keeper's fail-soft handler, so unavailable credential plumbing did not stop other providers' readings. Keep rejecting unsafe imports, but resolve the library inside the optional keeper's fail-soft boundary so quota-current, snapshots, and Supabase readings continue updating.Useful? React with 👍 / 👎.