Files
OmniRoute/tests/unit/codex-connection-edit-6562.test.ts
Diego Rodrigues de Sa e Souza 3d4f3e4960 test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966) (#11968)
* test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966)

Two shards on release/v3.8.51 went red in one day with the same signature —
"ENOTEMPTY, Directory not empty: /tmp/omniroute-<test>-XXXXXX" — from
combo-same-provider-cascade (Unit Tests fast-path 4/4, on a PR that touches only
.github/) and auth-policy-embeddings-webfetch-7785 (the 20k-test TIA step). Both pass
alone and on re-run: the cleanup races something still writing into the directory
(SQLite WAL/-shm checkpoint, a worker, the backup) and under a loaded hosted runner
the window opens. 1154 test files do their own cleanup with
fs.rmSync(dir, { recursive: true, force: true }); 57 already asked for retries.

One-shot codemod (scripts/ad-hoc/codemod-rm-maxretries.mjs, kept for the record):
every rm / rmSync / rmdirSync option object with `recursive: true` and no
`maxRetries` gains `maxRetries: 5, retryDelay: 100` — Node itself then retries
ENOTEMPTY/EBUSY/EPERM for up to ~0.5 s before giving up. 2243 call sites in 1292
files under tests/, the shared tests/_setup/isolateDataDir.ts exit hook included.
Only the option object changes: no call site, assertion or import is touched.

Validation: prettier and ESLint (with the frozen suppressions) clean on all 1292
files; a random 20-file sample runs green (quota-redis-store hangs identically on
the untouched tree — it needs a Redis on localhost, an environment matter). The
four unit shards on this PR are the full run.

* fix(quality): let check-forgotten-sibling-tests read a 1,000-file diff

The gate shells out to `git diff` through execFileSync with Node's default 1 MB
maxBuffer; the 1,292-file codemod in this PR is the first diff large enough to
overflow it, and the gate died with `spawnSync git ENOBUFS` before comparing
anything. 64 MB is far above any real PR and costs nothing when unused.
2026-08-29 01:17:40 -03:00

211 lines
8.8 KiB
TypeScript

// Regression guard for #6562 — editing any existing OpenAI Codex provider
// connection returned "Invalid request" on save.
//
// Root cause: `createProviderConnection()` (src/lib/db/providers.ts) auto-
// increments a new connection's `priority` to `MAX(priority)+1` per provider,
// with NO upper bound — and OAuth-imported connections (Codex `codex-auth/
// import` and `import-bulk`, up to 50 accounts per call, callable repeatedly)
// never go through `createProviderSchema`'s Zod validation at all, so nothing
// ever capped that value at creation time. Codex's own bulk-account-rotation
// workflow (a common Codex workaround for per-account rate limits) routinely
// pushes a user well past 100 same-provider connections. `EditConnectionModal`
// always round-trips the connection's current `priority` unchanged on save
// (src/app/.../modals/EditConnectionModal.tsx `handleSubmit` — `priority:
// formData.priority` is unconditional), so the *existing, already-valid*
// priority gets resent as-is. `updateProviderConnectionSchema` capped
// `priority`/`globalPriority` at `max(100)` — a UI-only ceiling nothing on the
// create path ever enforced — so any connection whose priority had already
// grown past 100 failed re-validation on every single edit with "Invalid
// request", regardless of which field the user changed.
//
// Fix: raise the schema ceiling to `max(100_000)` — still bounded (a
// genuinely out-of-range value is rejected, see the control test below), just
// wide enough to accept priorities the app itself already produces.
//
// This test drives the real PUT handler with a realistic Codex OAuth edit
// payload (as EditConnectionModal.tsx actually builds it) against a
// connection whose priority already exceeds the old 100 cap, and asserts it
// validates + persists instead of 400ing with "Invalid request".
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-codex-edit-6562-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.APP_LOG_TO_FILE = "false";
process.env.JWT_SECRET = "test-jwt-secret-codex-edit-6562";
process.env.INITIAL_PASSWORD = "admin-secret";
const core = await import("../../src/lib/db/core.ts");
const { createProviderConnection, getProviderConnectionById } =
await import("../../src/lib/db/providers.ts");
const providerByIdRoute = await import("../../src/app/api/providers/[id]/route.ts");
function resetDb() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(() => {
resetDb();
});
test.after(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
async function createCodexConnection(
priority: number,
authType = "oauth",
providerSpecificData: Record<string, unknown> = {}
) {
// Mirrors createConnectionFromAuthFile()'s real Codex-import shape
// (src/lib/oauth/utils/codexAuthImport.ts) — an OAuth connection whose
// providerSpecificData already carries a normalized `requestDefaults`
// (e.g. from a prior edit) alongside the workspaceId/chatgptUserId/importedAt
// fields the importer writes. `priority` is passed explicitly here to
// simulate the auto-increment (`MAX(priority)+1`, unbounded) a real user's
// Nth bulk-imported Codex account would already carry.
return createProviderConnection({
provider: "codex",
authType,
name: "Codex (imported)",
email: "user@example.com",
priority,
accessToken: "access-token-value",
refreshToken: "refresh-token-value",
idToken: "id-token-value",
expiresAt: new Date(Date.now() + 3600_000).toISOString(),
isActive: true,
testStatus: "active",
providerSpecificData: {
workspaceId: "workspace-abc",
chatgptUserId: "user-123",
importedAt: new Date().toISOString(),
requestDefaults: { reasoningEffort: "medium", serviceTier: "fast" },
...providerSpecificData,
},
});
}
// Builds the exact `updates` body EditConnectionModal.tsx's handleSubmit()
// constructs for a Codex OAuth connection edit (isOAuth branch + isCodex
// block) — `priority` is always resent unchanged (line: `priority:
// formData.priority`), which is exactly what round-trips the pre-existing,
// already-persisted value that triggers #6562.
function buildCodexEditPayload(connection: Record<string, unknown>) {
return {
name: connection.name,
priority: connection.priority,
maxConcurrent: null,
healthCheckInterval: connection.healthCheckInterval ?? 60,
rateLimitOverrides: null,
providerSpecificData: {
...((connection.providerSpecificData as Record<string, unknown>) || {}),
tag: undefined,
tags: undefined,
excludedModels: undefined,
requestDefaults: { reasoningEffort: "high" },
openaiStoreEnabled: false,
disableCooling: undefined,
},
};
}
test("PUT /api/providers/[id] persists a Codex OAuth edit when priority already exceeds the old 100 cap (#6562 RED->GREEN)", async () => {
// Simulates the Nth connection from a Codex bulk-account-rotation user —
// auto-incremented priority with no upstream cap.
const connection = (await createCodexConnection(142)) as Record<string, unknown>;
assert.equal(connection.provider, "codex");
assert.equal(connection.authType, "oauth");
assert.equal(connection.priority, 142);
const payload = buildCodexEditPayload(connection);
const request = await makeManagementSessionRequest(
`http://localhost/api/providers/${connection.id}`,
{ method: "PUT", body: payload }
);
const response = await providerByIdRoute.PUT(request, {
params: Promise.resolve({ id: connection.id as string }),
});
const body = await response.json();
assert.equal(
response.status,
200,
`expected the Codex edit to validate + persist, got ${response.status}: ${JSON.stringify(body)}`
);
assert.notEqual(body?.error?.message, "Invalid request");
const persisted = (await getProviderConnectionById(connection.id as string)) as Record<
string,
unknown
>;
// `updateProviderConnection` renormalizes every same-provider connection's
// priority to a dense 1..N sequence whenever `priority` is part of the
// update (`_reorderConnections`, src/lib/db/providers.ts) — this is the
// connection's first successful edit, so it lands at rank 1 (only Codex
// connection in this test). The point of this assertion is that the save
// *persisted* at all instead of 400ing before ever reaching that step.
assert.equal(persisted.priority, 1);
const persistedPsd = persisted.providerSpecificData as Record<string, unknown>;
assert.deepEqual(persistedPsd.requestDefaults, { reasoningEffort: "high" });
});
test("PUT /api/providers/[id] removes fingerprint mode from Codex API-key connections", async () => {
const connection = (await createCodexConnection(5, "apikey", {
codexFingerprintMode: "full",
codex_fingerprint_mode: "device",
})) as Record<string, unknown>;
const existingPsd = connection.providerSpecificData as Record<string, unknown>;
assert.equal(existingPsd.codexFingerprintMode, "full");
assert.equal(existingPsd.codex_fingerprint_mode, "device");
const payload = buildCodexEditPayload(connection);
payload.providerSpecificData.codexFingerprintMode = null;
payload.providerSpecificData.codex_fingerprint_mode = null;
const request = await makeManagementSessionRequest(
`http://localhost/api/providers/${connection.id}`,
{ method: "PUT", body: payload }
);
const response = await providerByIdRoute.PUT(request, {
params: Promise.resolve({ id: connection.id as string }),
});
assert.equal(response.status, 200);
const persisted = (await getProviderConnectionById(connection.id as string)) as Record<
string,
unknown
>;
const persistedPsd = persisted.providerSpecificData as Record<string, unknown>;
assert.equal(persistedPsd.codexFingerprintMode, undefined);
assert.equal(persistedPsd.codex_fingerprint_mode, undefined);
});
test("PUT /api/providers/[id] still rejects a genuinely invalid priority (control)", async () => {
const connection = (await createCodexConnection(5)) as Record<string, unknown>;
const payload = { ...buildCodexEditPayload(connection), priority: 500_000 };
const request = await makeManagementSessionRequest(
`http://localhost/api/providers/${connection.id}`,
{ method: "PUT", body: payload }
);
const response = await providerByIdRoute.PUT(request, {
params: Promise.resolve({ id: connection.id as string }),
});
const body = await response.json();
assert.equal(response.status, 400);
assert.equal(body?.error?.message, "Invalid request");
});