Compare commits

..

1 Commits

Author SHA1 Message Date
Claude Bot
742bc513cb fix(sql): validate array type parameter to prevent SQL injection
The `sql.array(values, type)` function interpolated the user-provided
type string directly into the SQL query without validation, allowing
SQL injection via crafted type names like `INT); DROP TABLE users--`.

Add character validation in `getArrayType()` to reject type names
containing characters outside [a-zA-Z0-9_ .], which covers all valid
PostgreSQL type names (including schema-qualified names like
`myschema.INTEGER`) while blocking injection payloads. Uses
`$ERR_INVALID_ARG_VALUE` for consistency with the rest of the codebase.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-12 04:53:43 +00:00
4 changed files with 143 additions and 43 deletions

View File

@@ -204,13 +204,47 @@ function arrayValueSerializer(type: ArrayType, is_numeric: boolean, is_json: boo
return `"${arrayEscape(JSON.stringify(value))}"`;
}
}
function validateArrayTypeName(type: string): void {
if (type.length === 0) {
throw $ERR_INVALID_ARG_VALUE("type", type, "must not be empty");
}
// Support schema-qualified names like "myschema.INTEGER" by splitting on dots
// and validating each segment individually.
const segments = type.split(".");
const lastIdx = segments.length - 1;
for (let s = 0; s <= lastIdx; s++) {
const seg = segments[s];
if (seg.length === 0) {
throw $ERR_INVALID_ARG_VALUE("type", type, "must not contain empty segments");
}
for (let i = 0; i < seg.length; i++) {
const c = seg.charCodeAt(i);
if (
(c >= 65 && c <= 90) || // A-Z
(c >= 97 && c <= 122) || // a-z
(c >= 48 && c <= 57) || // 0-9
c === 95 // _
) {
continue;
}
// Only the last segment may contain spaces (for "DOUBLE PRECISION")
if (c === 32 && s === lastIdx) {
continue;
}
throw $ERR_INVALID_ARG_VALUE("type", type, "contains invalid characters");
}
}
}
function getArrayType(typeNameOrID: number | ArrayType | undefined = undefined): ArrayType {
const typeOfType = typeof typeNameOrID;
if (typeOfType === "number") {
return getPostgresArrayType(typeNameOrID as number) ?? "JSON";
}
if (typeOfType === "string") {
return (typeNameOrID as string)?.toUpperCase();
const upper = (typeNameOrID as string).toUpperCase();
validateArrayTypeName(upper);
return upper;
}
// default to JSON so we accept most of the types
return "JSON";

View File

@@ -1154,7 +1154,7 @@ pub const Interpreter = struct {
_ = callframe; // autofix
if (this.setupIOBeforeRun().asErr()) |e| {
defer this.#derefRootShellAndIOIfNeeded(true);
defer this.#deinitFromExec();
const shellerr = bun.shell.ShellErr.newSys(e);
return try throwShellErr(&shellerr, .{ .js = globalThis.bunVM().event_loop });
}

View File

@@ -0,0 +1,107 @@
import { sql } from "bun";
import { describe, expect, test } from "bun:test";
// This test validates that sql.array() rejects malicious type parameters
// that could lead to SQL injection via the array type interpolation in
// normalizeQuery (src/js/internal/sql/postgres.ts line 1382).
//
// The vulnerability: sql.array(values, type) interpolates `type` directly
// into the query string as `$N::TYPE[]` without validation.
describe("sql.array type parameter validation", () => {
test("sql.array rejects type with SQL injection payload (semicolon)", () => {
expect(() => {
sql.array([1, 2, 3], "INT); DROP TABLE users--" as any);
}).toThrow();
});
test("sql.array rejects type with UNION injection", () => {
expect(() => {
sql.array([1, 2, 3], "INT[] UNION SELECT password FROM users--" as any);
}).toThrow();
});
test("sql.array rejects type with subquery injection", () => {
expect(() => {
sql.array([1, 2, 3], "INT[] (SELECT 1)" as any);
}).toThrow();
});
test("sql.array rejects type with parentheses", () => {
expect(() => {
sql.array([1, 2, 3], "INT()" as any);
}).toThrow();
});
test("sql.array rejects type with single quotes", () => {
expect(() => {
sql.array([1, 2, 3], "INT' OR '1'='1" as any);
}).toThrow();
});
test("sql.array rejects type with double quotes", () => {
expect(() => {
sql.array([1, 2, 3], 'INT" OR "1"="1' as any);
}).toThrow();
});
test("sql.array rejects empty type", () => {
expect(() => {
sql.array([1, 2, 3], "" as any);
}).toThrow();
});
test("sql.array rejects type with empty segment (leading dot)", () => {
expect(() => {
sql.array([1, 2, 3], ".INTEGER" as any);
}).toThrow();
});
test("sql.array rejects type with empty segment (trailing dot)", () => {
expect(() => {
sql.array([1, 2, 3], "myschema." as any);
}).toThrow();
});
test("sql.array rejects type with empty segment (consecutive dots)", () => {
expect(() => {
sql.array([1, 2, 3], "myschema..INTEGER" as any);
}).toThrow();
});
test("sql.array rejects space in schema segment", () => {
expect(() => {
sql.array([1, 2, 3], "my schema.INTEGER" as any);
}).toThrow();
});
test("sql.array accepts valid types", () => {
expect(() => sql.array([1, 2], "INTEGER")).not.toThrow();
expect(() => sql.array([1, 2], "INT")).not.toThrow();
expect(() => sql.array([1, 2], "BIGINT")).not.toThrow();
expect(() => sql.array(["a", "b"], "TEXT")).not.toThrow();
expect(() => sql.array(["a", "b"], "VARCHAR")).not.toThrow();
expect(() => sql.array([true, false], "BOOLEAN")).not.toThrow();
expect(() => sql.array([1.5, 2.5], "DOUBLE PRECISION")).not.toThrow();
expect(() => sql.array([1, 2], "INT2VECTOR")).not.toThrow();
expect(() => sql.array(["{}", "[]"], "JSON")).not.toThrow();
expect(() => sql.array(["{}", "[]"], "JSONB")).not.toThrow();
});
test("sql.array accepts lowercase valid types", () => {
expect(() => sql.array([1, 2], "integer")).not.toThrow();
expect(() => sql.array([1, 2], "int")).not.toThrow();
expect(() => sql.array(["a", "b"], "text")).not.toThrow();
expect(() => sql.array([1.5, 2.5], "double precision")).not.toThrow();
});
test("sql.array accepts schema-qualified type names", () => {
expect(() => sql.array([1, 2], "myschema.INTEGER" as any)).not.toThrow();
expect(() => sql.array([1, 2], "pg_catalog.int4" as any)).not.toThrow();
expect(() => sql.array([1, 2], "public.my_type" as any)).not.toThrow();
});
test("sql.array accepts schema-qualified type with space in last segment", () => {
expect(() => sql.array([1, 2], "myschema.DOUBLE PRECISION" as any)).not.toThrow();
});
});

View File

@@ -1,41 +0,0 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
// Regression test for https://github.com/oven-sh/bun/issues/26919
// When setupIOBeforeRun() fails in runFromJS (e.g., because stdout is closed),
// the error path used to call #deinitFromExec() which freed the interpreter struct.
// The GC would later finalize the already-freed JSShellInterpreter wrapper,
// causing a use-after-free / segfault.
test("issue #26919 - shell interpreter should not segfault when stdout is closed", async () => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const fs = require("fs");
// Close stdout so that the shell interpreter's setupIOBeforeRun() will fail
// when it tries to dup() stdout.
fs.closeSync(1);
try {
// This should throw an error (not segfault) because stdout is closed
await Bun.$\`echo hello\`;
} catch (e) {
// Write to stderr since stdout is closed
fs.writeSync(2, "caught: " + e.constructor.name + "\\n");
}
// Force GC to run - this would trigger the use-after-free crash before the fix
Bun.gc(true);
fs.writeSync(2, "done\\n");
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
// The process should not crash (segfault would give non-zero exit and no "done" message)
expect(stderr).toContain("done");
expect(exitCode).toBe(0);
});