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 150 additions and 104 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

@@ -26,7 +26,6 @@ pub const RedisError = error{
UnsupportedProtocol,
ConnectionTimeout,
IdleTimeout,
NestingTooDeep,
};
pub fn valkeyErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, err: RedisError) jsc.JSValue {
@@ -53,7 +52,6 @@ pub fn valkeyErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8,
error.InvalidCommand => .REDIS_INVALID_COMMAND,
error.InvalidArgument => .REDIS_INVALID_ARGUMENT,
error.UnsupportedProtocol => .REDIS_INVALID_RESPONSE,
error.NestingTooDeep => .REDIS_INVALID_RESPONSE,
error.InvalidResponseType => .REDIS_INVALID_RESPONSE_TYPE,
error.ConnectionTimeout => .REDIS_CONNECTION_TIMEOUT,
error.IdleTimeout => .REDIS_IDLE_TIMEOUT,
@@ -342,10 +340,6 @@ pub const ValkeyReader = struct {
buffer: []const u8,
pos: usize = 0,
/// Maximum allowed nesting depth for recursive RESP types (Array, Map, Set, etc.)
/// to prevent stack overflow from malicious deeply-nested responses.
const max_nesting_depth = 64;
pub fn init(buffer: []const u8) ValkeyReader {
return .{
.buffer = buffer,
@@ -427,10 +421,6 @@ pub const ValkeyReader = struct {
}
pub fn readValue(self: *ValkeyReader, allocator: std.mem.Allocator) RedisError!RESPValue {
return self.readValueDepth(allocator, 0);
}
fn readValueDepth(self: *ValkeyReader, allocator: std.mem.Allocator, depth: usize) RedisError!RESPValue {
const type_byte = try self.readByte();
return switch (RESPType.fromByte(type_byte) orelse return error.InvalidResponseType) {
@@ -461,7 +451,6 @@ pub const ValkeyReader = struct {
return RESPValue{ .BulkString = owned };
},
.Array => {
if (depth >= max_nesting_depth) return error.NestingTooDeep;
const len = try self.readInteger();
if (len < 0) return RESPValue{ .Array = &[_]RESPValue{} };
const array = try allocator.alloc(RESPValue, @as(usize, @intCast(len)));
@@ -473,7 +462,7 @@ pub const ValkeyReader = struct {
}
}
while (i < len) : (i += 1) {
array[i] = try self.readValueDepth(allocator, depth + 1);
array[i] = try self.readValue(allocator);
}
return RESPValue{ .Array = array };
},
@@ -506,7 +495,6 @@ pub const ValkeyReader = struct {
return RESPValue{ .VerbatimString = try self.readVerbatimString(allocator) };
},
.Map => {
if (depth >= max_nesting_depth) return error.NestingTooDeep;
const len = try self.readInteger();
if (len < 0) return error.InvalidMap;
@@ -520,12 +508,11 @@ pub const ValkeyReader = struct {
}
while (i < len) : (i += 1) {
entries[i] = .{ .key = try self.readValueDepth(allocator, depth + 1), .value = try self.readValueDepth(allocator, depth + 1) };
entries[i] = .{ .key = try self.readValue(allocator), .value = try self.readValue(allocator) };
}
return RESPValue{ .Map = entries };
},
.Set => {
if (depth >= max_nesting_depth) return error.NestingTooDeep;
const len = try self.readInteger();
if (len < 0) return error.InvalidSet;
@@ -538,12 +525,11 @@ pub const ValkeyReader = struct {
}
}
while (i < len) : (i += 1) {
set[i] = try self.readValueDepth(allocator, depth + 1);
set[i] = try self.readValue(allocator);
}
return RESPValue{ .Set = set };
},
.Attribute => {
if (depth >= max_nesting_depth) return error.NestingTooDeep;
const len = try self.readInteger();
if (len < 0) return error.InvalidAttribute;
@@ -556,9 +542,9 @@ pub const ValkeyReader = struct {
}
}
while (i < len) : (i += 1) {
var key = try self.readValueDepth(allocator, depth + 1);
var key = try self.readValue(allocator);
errdefer key.deinit(allocator);
const value = try self.readValueDepth(allocator, depth + 1);
const value = try self.readValue(allocator);
attrs[i] = .{ .key = key, .value = value };
}
@@ -567,7 +553,7 @@ pub const ValkeyReader = struct {
errdefer {
allocator.destroy(value_ptr);
}
value_ptr.* = try self.readValueDepth(allocator, depth + 1);
value_ptr.* = try self.readValue(allocator);
return RESPValue{ .Attribute = .{
.attributes = attrs,
@@ -575,12 +561,11 @@ pub const ValkeyReader = struct {
} };
},
.Push => {
if (depth >= max_nesting_depth) return error.NestingTooDeep;
const len = try self.readInteger();
if (len < 0 or len == 0) return error.InvalidPush;
// First element is the push type
const push_type = try self.readValueDepth(allocator, depth + 1);
const push_type = try self.readValue(allocator);
var push_type_str: []const u8 = "";
switch (push_type) {
@@ -609,7 +594,7 @@ pub const ValkeyReader = struct {
}
}
while (i < len - 1) : (i += 1) {
data[i] = try self.readValueDepth(allocator, depth + 1);
data[i] = try self.readValue(allocator);
}
return RESPValue{ .Push = .{

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,80 +0,0 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
// Test for security issue: ValkeyReader.readValue() unbounded recursion
// A malicious Redis/Valkey server can send deeply nested RESP structures
// that exhaust the call stack and crash the Bun process via stack overflow.
test("valkey RESP parser should reject deeply nested responses", async () => {
// Create a malicious server that sends deeply nested RESP arrays
// Each "*1\r\n" is a RESP array of length 1, nesting into the next level
const nestingDepth = 100_000;
using server = Bun.listen({
hostname: "127.0.0.1",
port: 0,
socket: {
open(socket) {
// Do nothing on open - wait for data
},
data(socket, data) {
const request = Buffer.from(data).toString();
// Respond to HELLO (RESP3 protocol negotiation) with a simple OK
if (request.includes("HELLO")) {
socket.write("+OK\r\n");
return;
}
// For any other command (e.g., GET), send a deeply nested RESP array
// *1\r\n repeated nestingDepth times, then a leaf value
let response = "";
for (let i = 0; i < nestingDepth; i++) {
response += "*1\r\n";
}
response += "$3\r\nfoo\r\n";
socket.write(response);
},
close() {},
error(socket, err) {},
},
});
const port = server.port;
// Use a subprocess so a crash doesn't take down the test runner
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const client = new Bun.RedisClient("redis://127.0.0.1:${port}");
try {
const result = await client.send("GET", ["test"]);
// If we get here without crashing, the parser handled it
console.log("RESULT:" + JSON.stringify(result));
} catch (e) {
console.log("ERROR:" + e.message);
} finally {
client.close();
}
`,
],
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 (exit code 0 or a handled error)
// Before the fix: process crashes with stack overflow (signal 11/SIGSEGV or similar)
// After the fix: parser returns an error about nesting depth exceeded
if (exitCode !== 0) {
console.log("stdout:", stdout);
console.log("stderr:", stderr);
console.log("exitCode:", exitCode);
}
expect(stdout).toContain("ERROR:");
expect(exitCode).toBe(0);
});