Skip to content

Commit 96e59ba

Browse files
sahrizviclaude
andauthored
fix(check): reject non-SQL files by extension (#1131)
* fix(check): reject non-SQL files by extension — plug v0.9.6 sanity regression The Verdaccio sanity suite's path-traversal security test (test/sanity/phases/security.sh:96-103, present + passing since PR #844 in June 2026) regressed on v0.9.6. Not the test's fault: the altimate- core 0.7.0 upgrade in #1090 introduced a `multi_statement` safety rule that echoes the offending statement text back in its error message. When `altimate check ../../../../etc/passwd` runs, the CLI reads the file, parses each line as SQL, fails, and the engine emits: ERROR ... [multi_statement]: Disallowed statement type: ROOT:X:0:0:ROOT:/ROOT:/BIN/BASH The sanity test greps case-insensitive for `root:x:0` — matches — fails the release workflow. No content actually shipped: publish + GitHub Release + Docker were all skipped when sanity failed. Fix: honor the "SQL file" claim in check.ts:479's own comment. The prior filter only checked existence — non-`.sql` files were parsed happily. Now rejects anything without a `.sql`/`.ddl` extension before it reaches the engine, so no content is parsed or echoed. Extracted the extension test as `isSqlFile()` in check-helpers so it can be unit-tested independently. Verification: - rebuilt the darwin-arm64 binary and re-ran the exact sanity reproduction locally: pre-fix leaked ROOT:X:0 line; post-fix skips with "Warning: not a SQL file (extension \"none\"), skipping: ..." - 82/82 tests in test/cli/check-e2e.test.ts pass (9 new isSqlFile cases + 73 pre-existing) - typecheck clean; marker guard clean Follow-ups (not in this PR): - The engine-side fix — altimate-core's multi_statement rule should use statement TYPE NAMES, not raw content — file with core team - Consider capping message length in check.ts finding-mappers as belt-and-braces against similar future engine-echo bugs Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(check): address bot review — .ddl in default glob, dotfile edge, isFile check, handler test + close #1130 Round 2 on the release/v0.9.6 hotfix — addresses the 5 bot findings on PR #1131 and rolls in the follow-up filed as issue #1130. - coderabbit MAJOR + cubic P2 (default-discovery gap): `**/*.sql` glob at check.ts:462 missed `.ddl` files that the new SQL_EXTENSIONS filter accepts. Now scans both extensions and dedupes. - cubic P2 (bare-extension dotfile): `isSqlFile` accepted files named literally `.sql` and `.ddl` as if the leading dot were an extension separator. Node's `path.extname` treats those as dotfiles with NO extension. Fixed to match: bare-`.sql`/`.ddl` filenames are rejected. - cubic P2 (directory with .sql suffix): a directory named `foo.sql` passed the extension filter. Added a `statSync(f).isFile()` gate that rejects directories (and symlinks-to-directories, since statSync follows symlinks) with a clear warning. - cubic P2 (test coverage gap): the `isSqlFile` tests only exercised the pure helper; if the CLI handler stopped calling the filter the tests would still pass. Added a handler-level integration test with mixed SQL/non-SQL input that asserts the warning is printed and no content leaks. Also added handler tests for the directory + bare dotfile cases. Updated the pre-existing "handles directory with .sql extension" test to match the new isFile behavior (was expecting "Error reading" from the downstream readFile crash). - #1130 follow-up (drop env-var mutation from dispatcher test files): removed the `beforeAll`/`afterAll` that mutated `process.env.ALTIMATE_TELEMETRY_DISABLED` in `test/altimate/dispatcher.test.ts` and `test/skill/release-v0.9.6-adversarial.test.ts`. Dispatcher.call already wraps every Telemetry.track in try/catch that swallows errors — the env-var was defensive against nothing and wasn't parallel-safe. Closes #1130. Verification: - 101/101 tests in check-e2e + dispatcher + release-adversarial pass - rebuilt darwin-arm64 binary; sanity reproduction still shows no leak - typecheck clean; marker guard clean Closes #1130 Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(check): reject symlinks whose target isn't SQL + test hygiene Round 3 on the release/v0.9.6 hotfix — addresses 3 new bot findings on PR #1131: - coderabbit MAJOR (real leak surface): the extension filter and statSync isFile check both see the SYMLINK target, not the link. So `ln -s /etc/passwd passwd.sql` sailed through — link's .sql extension passed, statSync followed the link, /etc/passwd IS a regular file, readFileSync then read its content, and the safety renderer echoed the first line. Exact leak class this PR exists to close. Fix: `lstatSync` to detect symlinks; when one is present, `realpathSync` to resolve the target and require ITS extension to also be SQL. Preserves `link.sql -> real.sql` (both SQL); rejects `passwd.sql -> /etc/passwd`. Two new handler-level regression tests: • "handler rejects symlink whose target is NOT a SQL file" • "handler ACCEPTS symlink whose target IS a SQL file" Reproduced the attack locally with the built binary: pre-fix leaked the file's first line; post-fix skips cleanly. - coderabbit MAJOR (spy hygiene in check-e2e.test.ts): the spyOn calls on process.stdout.write / process.stderr.write / console.error in beforeEach were never restored. Bun doesn't auto-restore spyOn across test files. Added `mock.restore()` in afterEach. - coderabbit MAJOR (dispatcher singleton isolation): same class of finding as the env-var one — the tests mutate module-wide `nativeHandlers`/`_ensureRegistered`. Not fixable without an instance-per-test refactor of the whole Dispatcher module. Documented the concurrency contract in-file: safe under bun's default sequential test-file execution; #1130 already tracks the broader parallel-safety cleanup this class of finding calls for. Same disposition as the release-adversarial file. Verification: - 103/103 tests pass (2 new symlink cases) - rebuilt darwin-arm64 binary; symlink attack repro shows the warning and no content leak - typecheck clean; marker guard clean Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(check): reject all symlinks — close TOCTOU race coderabbit MAJOR on prior round: my "resolve symlink target + check extension" approach opened a TOCTOU race. Between validation (realpathSync + isSqlFile) and readFileSync(f), an attacker with write access to the parent directory can swap ``passwd.sql`` from pointing at ``real.sql`` to pointing at ``/etc/passwd``. The read then follows the new link and echoes the file's content — the exact leak class this PR closes. Closing the race properly requires open-once + fstat + read-from-fd plumbed through every caller — a big refactor for a CLI most invocations don't hit. Simpler + secure: refuse symlinks entirely. Users who need to check a linked file pass the resolved target directly. Reverses cubic's earlier "accept link-to-SQL" request. The tradeoff (lose the accept-link-to-SQL convenience) favors simplicity + security over convenience — noted in the coderabbit thread reply. Also updates the pre-existing "handles symlinked SQL files" test to match the new rejection behavior. 103/103 tests pass; typecheck + marker guard clean. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Haider <[email protected]> Co-authored-by: Claude Opus 4.7 <[email protected]>
1 parent 07e3674 commit 96e59ba

5 files changed

Lines changed: 293 additions & 34 deletions

File tree

‎packages/opencode/src/cli/cmd/check-helpers.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,26 @@ export const SEVERITY_RANK: Record<Severity, number> = { error: 2, warning: 1, i
4747

4848
export const VALID_CHECKS = new Set(["lint", "validate", "safety", "policy", "pii", "semantic", "grade"])
4949

50+
/** Extensions the ``check`` command will treat as SQL. Anything else is
51+
* skipped before it reaches the engine, so non-SQL content cannot be
52+
* parsed and echoed back through engine error messages (v0.9.6 fix). */
53+
export const SQL_EXTENSIONS = new Set([".sql", ".ddl"])
54+
55+
/** Case-insensitive SQL-extension test. Matches node's ``path.extname``
56+
* semantics: a filename whose only dot is the FIRST character (e.g.
57+
* ``.sql`` or ``.ddl``) is a dotfile with NO extension, not a SQL file.
58+
* ``.query.sql`` is a dotfile with a real ``.sql`` extension (accepted).
59+
* ``foo.bar/baz`` is not SQL (the dot is in the directory, not the
60+
* filename). (cubic P2 round on release/v0.9.6 hotfix.) */
61+
export function isSqlFile(filePath: string): boolean {
62+
const slash = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"))
63+
const basename = slash === -1 ? filePath : filePath.slice(slash + 1)
64+
const dot = basename.lastIndexOf(".")
65+
// dot === -1: no extension. dot === 0: dotfile with no extension (e.g. ``.sql``).
66+
if (dot <= 0) return false
67+
return SQL_EXTENSIONS.has(basename.slice(dot).toLowerCase())
68+
}
69+
5070
// ---------------------------------------------------------------------------
5171
// Helpers
5272
// ---------------------------------------------------------------------------

‎packages/opencode/src/cli/cmd/check.ts‎

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
import type { Argv } from "yargs"
33
import { cmd } from "./cmd"
44
import { Dispatcher } from "../../altimate/native"
5-
import { readFileSync, existsSync } from "fs"
5+
import { readFileSync, existsSync, statSync, lstatSync, realpathSync } from "fs"
66
import { Glob } from "../../util/glob"
77
import path from "path"
88
import {
99
type Finding,
1010
type CheckCategoryResult,
1111
type Severity,
1212
VALID_CHECKS,
13+
isSqlFile,
1314
normalizeSeverity,
1415
filterBySeverity,
1516
toCategoryResult,
@@ -460,8 +461,10 @@ export const CheckCommand = cmd({
460461
// 3. Resolve files
461462
let files: string[] = args.files ?? []
462463
if (files.length === 0) {
463-
console.error("No files specified, searching for **/*.sql in current directory...")
464-
files = await Glob.scan("**/*.sql", { cwd: process.cwd(), absolute: true })
464+
console.error("No files specified, searching for **/*.{sql,ddl} in current directory...")
465+
const sqls = await Glob.scan("**/*.sql", { cwd: process.cwd(), absolute: true })
466+
const ddls = await Glob.scan("**/*.ddl", { cwd: process.cwd(), absolute: true })
467+
files = [...new Set([...sqls, ...ddls])]
465468
} else {
466469
// Expand globs in positional args
467470
const expanded: string[] = []
@@ -476,12 +479,74 @@ export const CheckCommand = cmd({
476479
files = expanded
477480
}
478481

479-
// Filter to only existing .sql files
482+
// Filter to only existing SQL files by extension. The prior version
483+
// only checked existence — the "SQL" filter was a lie in the comment.
484+
// Feeding a non-SQL file (e.g. ``altimate check /etc/passwd``) meant
485+
// the engine parsed each line as a SQL statement; the 0.7.0 engine's
486+
// ``multi_statement`` safety rule then echoed the offending line
487+
// (uppercased) in its error message, leaking the file's first line
488+
// into stdout. Rejecting by extension keeps non-SQL content from
489+
// reaching the engine at all — no message, no leak. (v0.9.6 sanity
490+
// regression; sanity test at test/sanity/phases/security.sh:96-103
491+
// has been present + passing since PR #844.)
480492
files = files.filter((f) => {
481493
if (!existsSync(f)) {
482494
console.error(`Warning: file not found, skipping: ${f}`)
483495
return false
484496
}
497+
if (!isSqlFile(f)) {
498+
const ext = path.extname(f).toLowerCase() || "none"
499+
console.error(`Warning: not a SQL file (extension "${ext}"), skipping: ${f}`)
500+
return false
501+
}
502+
// Reject directories (and symlinks-to-directories) whose name happens
503+
// to end in .sql / .ddl — statSync follows symlinks, so a symlink to
504+
// a dir is rejected. (cubic P2 round on release/v0.9.6 hotfix.)
505+
let st
506+
try {
507+
st = statSync(f)
508+
} catch (e) {
509+
console.error(`Warning: stat failed, skipping: ${f} (${(e as Error).message})`)
510+
return false
511+
}
512+
if (!st.isFile()) {
513+
console.error(`Warning: not a regular file (directory or other), skipping: ${f}`)
514+
return false
515+
}
516+
// Reject symlinks entirely. An earlier attempt validated the
517+
// symlink target's extension and then let the flow continue to
518+
// ``readFileSync(f)``, but that opens a TOCTOU race: between
519+
// validation and read, an attacker with write access to the
520+
// parent directory can swap the symlink to point at a non-SQL
521+
// file (e.g. /etc/passwd), which readFileSync would then dutifully
522+
// read — reopening the same leak class this PR closes. Closing
523+
// the race properly requires opening the file once, fstat'ing the
524+
// fd, and passing the fd (not the path) through to every
525+
// downstream reader — a large refactor for a CLI most invocations
526+
// don't hit. Simpler + safer: refuse symlinks. Users who need to
527+
// check a linked file can pass the resolved target directly.
528+
// (coderabbit MAJOR TOCTOU on release/v0.9.6 hotfix; reverses the
529+
// "accept link-to-SQL" behavior cubic asked for in the prior round
530+
// — noted in the thread.)
531+
let lst
532+
try {
533+
lst = lstatSync(f)
534+
} catch (e) {
535+
console.error(`Warning: lstat failed, skipping: ${f} (${(e as Error).message})`)
536+
return false
537+
}
538+
if (lst.isSymbolicLink()) {
539+
let target = ""
540+
try {
541+
target = realpathSync(f)
542+
} catch {
543+
// If we can't even resolve, just report the link path.
544+
}
545+
console.error(
546+
`Warning: symlinks are not accepted (TOCTOU-safe), skipping: ${f}${target ? ` -> ${target}` : ""}`,
547+
)
548+
return false
549+
}
485550
return true
486551
})
487552

‎packages/opencode/test/altimate/dispatcher.test.ts‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
1-
import { describe, expect, test, beforeEach, beforeAll, afterAll, mock } from "bun:test"
1+
import { describe, expect, test, beforeEach, mock } from "bun:test"
22
import * as Dispatcher from "../../src/altimate/native/dispatcher"
33

4-
// Disable telemetry via env var instead of mock.module
5-
beforeAll(() => {
6-
process.env.ALTIMATE_TELEMETRY_DISABLED = "true"
7-
})
8-
afterAll(() => {
9-
delete process.env.ALTIMATE_TELEMETRY_DISABLED
10-
})
4+
// No telemetry disable needed — Dispatcher.call already wraps every
5+
// Telemetry.track call in try/catch that swallows all errors, so telemetry
6+
// firing during a test cannot fail the test. The previous env-var
7+
// mutation was defensive against nothing and wasn't parallel-safe (issue
8+
// #1130 — https://github.com/AltimateAI/altimate-code/issues/1130).
9+
//
10+
// Concurrency contract: the ``Dispatcher`` module is a process-wide
11+
// singleton (``nativeHandlers`` Map, ``_ensureRegistered`` hook). These
12+
// tests intentionally mutate that singleton via ``Dispatcher.reset()``
13+
// and ``Dispatcher.setRegistrationHook()``. This is safe under bun's
14+
// DEFAULT behaviour of running test files sequentially in one process,
15+
// but NOT parallel-safe if the runner is later flipped to ``--concurrency
16+
// N``. Isolating the dispatcher would require an instance-per-test
17+
// refactor across the whole module; deferred as a broader tech-debt
18+
// task (issue #1130 tracks the parallel-safety cleanup for this + the
19+
// sibling release-adversarial file). Same class of finding as the
20+
// env-var mutation coderabbit flagged.
1121

1222
describe("Dispatcher", () => {
1323
beforeEach(() => {

0 commit comments

Comments
 (0)