fix(auth): ignore comment-only Codex project settings (#18559)

## Thinking Path

> - Paperclip lets agents use managed AI connections.
> - The server checks project files for conflicting authentication
settings.
> - Codex stores project settings in TOML.
> - A full-line TOML comment can contain an example authentication
setting.
> - The current text check rejects that comment as an active override.
> - This pull request excludes full comment lines in local and remote
checks.
> - Active overrides and file-read errors still block execution.

## Linked Issues or Issue Description

**What happened?**

A project or scanned ancestor `.codex/config.toml` containing only `#
model_provider = "example"` can cause `ai_connection_incompatible`. The
worker is rejected before provider execution.

**Expected behavior**

Ignore full TOML comment lines, including indented comments. Continue to
reject active authentication and provider overrides.

**Steps to reproduce**

1. Create a disposable project and a `.codex/config.toml` in its scanned
ancestry.
2. Add `# model_provider = "example"` without an active provider
override.
3. Call the managed OpenAI project-auth guard for that project.
4. The original guard rejects the comment. The new tests reproduce both
local and shell-backed remote checks.

**Paperclip version or commit**

Originally checked against upstream
`e1224783685405eb7d987ece2446962920ee0cf5`. Before publication, rebased
cleanly onto `c0550e7010b5b733b745f60433788db3e6fd2e2e`. The two
intervening commits do not change either fix's source or regression
files.

**Deployment mode**

Source checkout on macOS arm64. Node 24.21.0 and pnpm 9.15.4. Disposable
filesystem fixtures and a real local POSIX shell stand in for remote
transport. No provider call or live remote host was used.

Refs #17421. That open PR changes the scanned project boundary and probe
preparation. This patch handles full-line comments inside the existing
scan. The shared guard will need reconciliation if that PR lands first.
A public search found no separate comment-filtering repair.

## What Changed

- Exclude full comment lines before applying the existing local TOML
conflict pattern.
- Use a POSIX awk check for remote Codex TOML, preserving conflict and
read-error exit codes.
- Leave Claude JSON checking and explicit argument rejection in place.
- Add 23 filesystem and shell regression cases. Cover LF/CRLF, active
overrides, ancestor checks, read failures, argument rejection and Claude
settings. Skip POSIX-only checks on Windows and permission-denial checks
when running as root.

## Verification

- Publication recheck on the rebased branch: auth filesystem/shell and
Codex environment checks passed, **31 tests with one existing skip**.
Full workspace build/typecheck and broader-suite results below were
recorded before that rebase, at the original base. They were not rerun
after the two intervening upstream changes.

- Focused filesystem/shell and existing Codex environment tests: **31
passed, one existing Windows-only skip**.
- Complete connection, routing and hiring test files: **263 passed**.
Combined focused evidence: **294 passed and one conditional skip in five
files**.

```sh
pnpm exec vitest run --project @paperclipai/server server/src/__tests__/ai-connection-project-auth.test.ts server/src/__tests__/codex-local-adapter-environment.test.ts --maxWorkers=1
pnpm exec vitest run --project @paperclipai/server server/src/__tests__/ai-connections.test.ts server/src/__tests__/ai-connection-router.test.ts server/src/__tests__/agent-hire-ai-connections.test.ts --maxWorkers=1
```

- Full workspace typecheck passed: `pnpm -r --workspace-concurrency=1
typecheck`.
- Full workspace build passed: `pnpm build`.
- Module-boundary, runtime Git-push guard and diff-whitespace checks
passed.
- Initial pre-fix regressions: 4 failed and 19 passed cases. All four
failures were comment-only settings. The original failures were
retained.
- **Broader run:** all six chat shards and 22 of 24 general server
shards executed, selecting 1,229 general files (including
platform-conditional skips). Results: **27,547 passed, one failed**,
plus 180 conditional skips outside chat. Completed chat evidence was
reused unchanged when switching from the serial path to the standard
24-shard modes. The inventory check verified the full planned cover;
this partial execution is not a complete pass. The final two general
shards, five native suites, 20 workspace projects and 164 serialized
suites did not run after the failure.
- The failed Git-scan load case observed 126 joins instead of 498. The
identical failure reproduced in the focused case on unchanged upstream
at the stated base. Refs #17536 for the existing host-dependent fixture
repair. No load-test assertion was changed here.
- An initial incomplete dependency installation omitted the embedded
PostgreSQL library symlinks. Running its existing install hook restored
PostgreSQL 18.1 startup and the focused integration tests. This also
cleared the earlier misleading chat-discovery failure. Original failure
logs were retained.
- One parallel server group left a Node child beyond 30 seconds after a
successful test exit. It was stopped. The identical 59 files later
passed all 1,238 cases and drained normally on unchanged upstream. The
original orphan remains unattributed; a clean overall lifecycle run is
not claimed.
- Remote tests run a real POSIX shell locally with transport replaced.
No real remote host, live provider turn or installed production service
was qualified. Upstream CI, Greptile and merge readiness remain pending.

## Risks

This is a limited correction to the existing text guard, not a TOML
parser rewrite. It ignores only full comment lines. It does not change
project scanning boundaries or credentials. Remote checks require POSIX
awk and retain bounded subprocess timeouts. Windows was not exercised.
PR #17421 touches the same guard and can require rebasing.

## Model Used

OpenAI `gpt-6.1-sol` through Codex. Saved session metadata identifies
medium reasoning for the upstream adaptation and verification.
Capabilities used: source inspection, shell tools, patch editing,
regression testing, and build verification. The session-reported context
window is 475,000 tokens. This is the recorded model ID; no unrecorded
build version or nominal model maximum is asserted.

The local-tests, CI and Greptile completion boxes remain unchecked
because a complete repository pass is not claimed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Additional local test limitation: final cleanup found a detached
sibling-directory HTTP fixture from `workspace-runtime.test.ts`. Its
ownership was verified from its temporary-root cwd and exact fixture
command; it was stopped individually. This separate observation remains
outside the proposed changes.

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Paul BéglinandPaperclip authored and GitHub committed 2026-12-05 03:12:04 -08:00
1 parent ed262f2e9a
commit 8f6cf8b0d7
2 files changed
+132 -5

No files matched your search

@@ -0,0 +1,113 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { spawnSync } from "node:child_process";
import { chmod, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import * as executionTarget from "@paperclipai/adapter-utils/execution-target";
import { assertManagedAiProjectAuth } from "../services/ai-connection-runtime.js";
let root: string;
let cwd: string;
const commentKeys = ["model_provider =", "env_key =", "experimental_bearer_token", "cli_auth_credentials_store", "OPENAI_API_KEY"];
beforeEach(async () => {
const temporaryBase = process.platform === "darwin" ? "/private/tmp" : os.tmpdir();
root = await realpath(await mkdtemp(path.join(temporaryBase, "paperclip-project-auth-")));
await mkdir(path.join(root, ".git"));
cwd = path.join(root, "project", "nested");
await mkdir(cwd, { recursive: true });
});
afterEach(async () => { vi.restoreAllMocks(); await rm(root, { recursive: true, force: true }); });
async function configFile(relative: string, content: string, directory = root) {
const file = path.join(directory, relative);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, content, { mode: 0o600 });
return file;
}
function remoteCheck(provider: "openai" | "anthropic" = "openai") {
const target = { kind: "remote", transport: "sandbox", remoteCwd: cwd } as Parameters<typeof assertManagedAiProjectAuth>[2];
const execute = vi.spyOn(executionTarget, "runAdapterExecutionTargetProcess").mockImplementation(async (_id, _target, command, args, options) => {
expect(command).toBe("sh");
expect(options.timeoutSec).toBe(15);
const startedAt = new Date().toISOString();
const result = spawnSync("/bin/sh", args, { cwd, encoding: "utf8", timeout: 5000, env: { PATH: "/usr/bin:/bin" } });
if (result.error) throw result.error;
return { exitCode: result.status, stdout: result.stdout, stderr: result.stderr, signal: result.signal, timedOut: false, pid: result.pid, startedAt };
});
return { check: () => assertManagedAiProjectAuth({}, provider, target), execute };
}
describe("managed AI project authentication", () => {
it.each(["\n", "\r\n"])("ignores only TOML comment lines locally with %j line endings", async ending => {
await configFile(".codex/config.toml", commentKeys.map(key => ` \t# ${key} fixture`).concat('model = "fixture"').join(ending));
await expect(assertManagedAiProjectAuth({ cwd }, "openai")).resolves.toBeUndefined();
});
it.each([
'model_provider = "fixture"', 'env_key = "OPENAI_API_KEY"', 'experimental_bearer_token = "fixture"',
'cli_auth_credentials_store = "fixture"', 'OPENAI_API_KEY = "fixture"',
])("rejects active local TOML override %s after comment lines", async override => {
await configFile(".codex/config.toml", `# model_provider = "comment"\n${override} # trailing comment\n`);
await expect(assertManagedAiProjectAuth({ cwd }, "openai")).rejects.toMatchObject({ status: 422, details: { code: "ai_connection_incompatible" } });
});
it("continues to reject active ancestor overrides above a harmless project config", async () => {
await configFile(".codex/config.toml", '# model_provider = "comment"\n', cwd);
await configFile(".codex/config.toml", 'model_provider = "fixture"\n');
await expect(assertManagedAiProjectAuth({ cwd }, "openai")).rejects.toThrow("conflict");
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)("preserves local file read failures instead of treating them as harmless comments", async () => {
const file = await configFile(".codex/config.toml", '# model_provider = "comment"\n');
await chmod(file, 0);
try { await expect(assertManagedAiProjectAuth({ cwd }, "openai")).rejects.toMatchObject({ code: "EACCES" }); }
finally { await chmod(file, 0o600); }
});
it("preserves Claude JSON override checks", async () => {
await configFile(".claude/settings.json", '{"apiKeyHelper":"fixture"}');
await expect(assertManagedAiProjectAuth({ cwd }, "anthropic")).rejects.toThrow("conflict");
});
it.each(["--config=fixture", "-c", "--settings", "--setting-sources=fixture", "--api-key=fixture", "--auth-token=fixture"])("preserves argument override rejection for %s", async arg => {
const execute = vi.spyOn(executionTarget, "runAdapterExecutionTargetProcess");
await expect(assertManagedAiProjectAuth({ cwd, extraArgs: [arg] }, "openai")).rejects.toThrow("overrides");
expect(execute).not.toHaveBeenCalled();
});
it.skipIf(process.platform === "win32").each(["\n", "\r\n"])("runs the remote shell check against ancestor TOML comments with %j line endings", async ending => {
await configFile(".codex/config.toml", commentKeys.map(key => ` \t# ${key} fixture`).join(ending));
const { check, execute } = remoteCheck();
await expect(check()).resolves.toBeUndefined();
expect(execute).toHaveBeenCalledOnce();
const result = await execute.mock.results[0].value;
expect(result.exitCode).toBe(0); expect(result.stdout).toBe(""); expect(result.stderr).toBe("");
});
it.skipIf(process.platform === "win32").each(['model_provider = "fixture"', 'env_key = "fixture"', 'experimental_bearer_token = "fixture"'])("rejects active remote TOML override %s after comments", async override => {
await configFile(".codex/config.toml", `# model_provider = "comment"\n${override}\n`);
const { check, execute } = remoteCheck();
await expect(check()).rejects.toThrow("project authentication settings");
const result = await execute.mock.results[0].value;
expect(result.exitCode).toBe(42); expect(result.stdout).toBe(""); expect(result.stderr).toBe("");
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)("keeps remote TOML read errors fail closed without exposing content", async () => {
const file = await configFile(".codex/config.toml", '# model_provider = "comment"\n');
await chmod(file, 0);
try {
const { check, execute } = remoteCheck();
await expect(check()).rejects.toThrow("project authentication settings");
const result = await execute.mock.results[0].value;
expect(result.exitCode).toBe(43); expect(result.stdout).toBe(""); expect(result.stderr).not.toContain("model_provider");
} finally { await chmod(file, 0o600); }
});
it.skipIf(process.platform === "win32")("keeps remote Claude JSON override checks unchanged", async () => {
await configFile(".claude/settings.local.json", '{"ANTHROPIC_AUTH_TOKEN":"fixture"}');
const { check, execute } = remoteCheck("anthropic");
await expect(check()).rejects.toThrow("project authentication settings");
expect((await execute.mock.results[0].value).exitCode).toBe(42);
});
});
+19 -5
View File
@@ -159,10 +159,21 @@ while :; do
for relative in "$@"; do
file="$directory/$relative"
if test -f "$file"; then
grep -Eq "$pattern" "$file"
result=$?
if test "$result" -eq 0; then exit 42; fi
if test "$result" -ne 1; then exit 43; fi
if test "$relative" = ".codex/config.toml"; then
awk -v pattern="$pattern" '
/^[[:space:]]*#/ { next }
$0 ~ pattern { found=1 }
END { if (found) exit 42 }
' "$file"
result=$?
if test "$result" -eq 42; then exit 42; fi
if test "$result" -ne 0; then exit 43; fi
else
grep -Eq "$pattern" "$file"
result=$?
if test "$result" -eq 0; then exit 42; fi
if test "$result" -ne 1; then exit 43; fi
fi
fi
done
parent=$(dirname "$directory")
@@ -196,9 +207,12 @@ done`,
for (const relative of files) {
try {
const content = await readFile(path.join(directory, relative), "utf8");
const inspected = relative === ".codex/config.toml"
? content.split(/\r?\n/).filter(line => !/^\s*#/.test(line)).join("\n")
: content;
if (
/apiKeyHelper|ANTHROPIC_API_KEY|ANTHROPIC_AUTH_TOKEN|CLAUDE_CODE_OAUTH_TOKEN|OPENAI_API_KEY|model_provider\s*=|env_key\s*=|experimental_bearer_token|cli_auth_credentials_store/.test(
content,
inspected,
)
) {
throw projectAuthConflict([relative]);