25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(redis): faithful raw byte command parsing and cluster crossslot prevention (#12892)
lxk955dbb833343f8a
diff --git a/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.ts b/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.tsindex 56b50233a0..751f1c5e4f 100644--- a/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.ts+++ b/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.ts@@ -31,8 +31,41 @@ describe("quoteRedisArg and quoteRedisBytes", () => {expect(quoteRedisBytes(binaryBytes)).toBe('"\\x00\\x01\\x1f\\x7f\\xff"');});- it("preserves valid UTF-8 sequences verbatim inside quotes", () => {+ it("preserves valid UTF-8 sequences verbatim inside quotes without swallowing adjacent ASCII or escaping", () => {expect(quoteRedisArg("用户:123:设置")).toBe('"用户:123:设置"');++ // Reproductions from zipg review [P1]:+ // 1) e4 b8 ad 5c 6e -> "中\n" in bytes, must escape backslash as \\ and preserve 'n', not produce "中\n"+ const zhongBackslashN = new Uint8Array([0xe4, 0xb8, 0xad, 0x5c, 0x6e]);+ expect(quoteRedisBytes(zhongBackslashN)).toBe('"中\\\\n"');++ // 2) c3 a9 22 0a -> "é\"\n" in bytes, must escape quote as \" and newline as \n, not produce unclosed quote+ const eAcuteQuoteNewline = new Uint8Array([0xc3, 0xa9, 0x22, 0x0a]);+ expect(quoteRedisBytes(eAcuteQuoteNewline)).toBe('"é\\"\\n"');++ // 3) Adjacent ASCII special characters before and after UTF-8 characters+ // Space:+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0x20]))).toBe('"中 "');+ expect(quoteRedisBytes(new Uint8Array([0x20, 0xe4, 0xb8, 0xad]))).toBe('" 中"');+ // Newline:+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0x0a]))).toBe('"中\\n"');+ expect(quoteRedisBytes(new Uint8Array([0x0a, 0xe4, 0xb8, 0xad]))).toBe('"\\n中"');+ // Quote:+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0x22]))).toBe('"中\\""');+ expect(quoteRedisBytes(new Uint8Array([0x22, 0xe4, 0xb8, 0xad]))).toBe('"\\"中"');+ // Backslash:+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0x5c]))).toBe('"中\\\\"');+ expect(quoteRedisBytes(new Uint8Array([0x5c, 0xe4, 0xb8, 0xad]))).toBe('"\\\\中"');+ // Controls:+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0x00]))).toBe('"中\\x00"');+ expect(quoteRedisBytes(new Uint8Array([0x00, 0xe4, 0xb8, 0xad]))).toBe('"\\x00中"');+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0x09]))).toBe('"中\\t"');+ // Binary bytes:+ expect(quoteRedisBytes(new Uint8Array([0xe4, 0xb8, 0xad, 0xff]))).toBe('"中\\xff"');+ expect(quoteRedisBytes(new Uint8Array([0xff, 0xe4, 0xb8, 0xad]))).toBe('"\\xff中"');+ expect(quoteRedisBytes(new Uint8Array([0x80, 0xe4, 0xb8, 0xad, 0x80]))).toBe('"\\x80中\\x80"');+ // Broken/truncated UTF-8 sequence followed by space:+ expect(quoteRedisBytes(new Uint8Array([0xc3, 0x20]))).toBe('"\\xc3 "');});it("quotes RedisBlob objects using raw_base64 bytes", () => {@@ -103,7 +136,35 @@ describe("redisDeleteKeysPreview", () => {const keys = ["k1", "k2"];expect(redisDeleteKeysPreview(keys, { database: 3 })).toBe("SELECT 3\nDEL k1 k2");expect(redisDeleteKeysPreview(keys, { database: 0 })).toBe("DEL k1 k2");- expect(redisDeleteKeysPreview(keys, { database: 3, isCluster: true })).toBe("DEL k1 k2");+ });++ it("groups keys strictly by CRC16 hash slot in Cluster mode to prevent CROSSSLOT", () => {+ // 1) Keys in different slots are segregated into separate DEL commands+ // 'k1' (slot 12706) and 'k2' (slot 449)+ expect(redisDeleteKeysPreview(["k1", "k2"], { isCluster: true })).toBe("DEL k1\nDEL k2");+ // SELECT is also omitted in Cluster mode+ expect(redisDeleteKeysPreview(["k1", "k2"], { database: 3, isCluster: true })).toBe("DEL k1\nDEL k2");++ // 2) Keys sharing the same hash tag {user} belong to the exact same slot and can be combined+ const sameSlotKeys = ["{user}:1", "{user}:2", "{user}:3"];+ expect(redisDeleteKeysPreview(sameSlotKeys, { isCluster: true })).toBe('DEL "{user}:1" "{user}:2" "{user}:3"');++ // 3) Mixed keys across multiple slots are grouped with their respective slot without cross-slot mixing+ const mixedKeys = ["{alpha}:1", "{beta}:1", "{alpha}:2", "{gamma}:1", "{beta}:2"];+ const clusterPreview = redisDeleteKeysPreview(mixedKeys, { isCluster: true });+ expect(clusterPreview).toBe('DEL "{alpha}:1" "{alpha}:2"\nDEL "{beta}:1" "{beta}:2"\nDEL "{gamma}:1"');++ // 4) Keys within the same slot exceeding chunkSize are chunked across lines+ const sevenSameSlotKeys = Array.from({ length: 7 }, (_, i) => `{slot}:item:${i + 1}`);+ const chunkedCluster = redisDeleteKeysPreview(sevenSameSlotKeys, { isCluster: true, chunkSize: 3 });+ expect(chunkedCluster).toBe('DEL "{slot}:item:1" "{slot}:item:2" "{slot}:item:3"\nDEL "{slot}:item:4" "{slot}:item:5" "{slot}:item:6"\nDEL "{slot}:item:7"');++ // 5) Base64 raw binary keys with hash tags in Cluster mode+ const rawTagKey1 = redisKeyTextToRaw("{tag}:bin\x00key1");+ const rawTagKey2 = redisKeyTextToRaw("{tag}:bin\x00key2");+ const rawOtherKey = redisKeyTextToRaw("other_slot_key");+ const rawClusterPreview = redisDeleteKeysPreview([rawTagKey1, rawTagKey2, rawOtherKey], { isCluster: true, raw: true });+ expect(rawClusterPreview).toBe('DEL "{tag}:bin\\x00key1" "{tag}:bin\\x00key2"\nDEL other_slot_key');});});diff --git a/apps/desktop/src/lib/redis/redisCommandPreview.ts b/apps/desktop/src/lib/redis/redisCommandPreview.tsindex 176d285207..35fe7d15a3 100644--- a/apps/desktop/src/lib/redis/redisCommandPreview.ts+++ b/apps/desktop/src/lib/redis/redisCommandPreview.ts@@ -116,28 +116,35 @@ export function quoteRedisBytes(bytes: Uint8Array): string {} else if (b >= 0x20 && b <= 0x7e) {result += String.fromCharCode(b);} else if (b >= 0x80) {- // Check if this byte starts a valid UTF-8 character sequence+ // Determine expected single UTF-8 codepoint length from lead byte+ let length = 0;+ if (b >= 0xc2 && b <= 0xdf) {+ length = 2;+ } else if (b >= 0xe0 && b <= 0xef) {+ length = 3;+ } else if (b >= 0xf0 && b <= 0xf4) {+ length = 4;+ }+let decodedChar: string | null = null;- let matchedLen = 0;- for (let len = 4; len >= 2; len--) {- if (i + len <= bytes.length) {- try {- const candidate = utf8Decoder.decode(bytes.subarray(i, i + len));- // Ensure no C1 control characters (U+0080 to U+009F)- if (!/[\u0080-\u009f]/.test(candidate)) {+ if (length > 0 && i + length <= bytes.length) {+ try {+ const candidate = utf8Decoder.decode(bytes.subarray(i, i + length));+ if (Array.from(candidate).length === 1) {+ const cp = candidate.codePointAt(0)!;+ // Reject C1 controls (0x80..0x9F) and invisible separators+ if (cp >= 0xa0 && cp !== 0x2028 && cp !== 0x2029 && cp !== 0xfeff) {decodedChar = candidate;- matchedLen = len;- break;}- } catch {- // Not a valid UTF-8 sequence of this length}+ } catch {+ // Invalid sequence of this length}}- if (decodedChar !== null && matchedLen > 0) {+ if (decodedChar !== null) {result += decodedChar;- i += matchedLen - 1;+ i += length - 1;} else {result += "\\x" + b.toString(16).padStart(2, "0");}@@ -198,10 +205,45 @@ export function redisFlushDbPreview(database?: string | number | null, isClusterreturn "FLUSHDB";}+/**+ * Computes the Redis Cluster CRC16 hash slot (0 - 16383) for a key,+ * respecting `{...}` hash tags according to the Redis Cluster specification.+ */+export function getRedisKeySlot(key: Uint8Array): number {+ let s = -1;+ let e = -1;+ for (let i = 0; i < key.length; i++) {+ if (key[i] === 0x7b /* '{' */ && s === -1) {+ s = i + 1;+ } else if (key[i] === 0x7d /* '}' */ && s !== -1) {+ e = i;+ break;+ }+ }+ const tag = s !== -1 && e > s ? key.subarray(s, e) : key;+ return crc16Xmodem(tag) % 16384;+}++function crc16Xmodem(bytes: Uint8Array): number {+ let crc = 0;+ for (let i = 0; i < bytes.length; i++) {+ crc ^= bytes[i]! << 8;+ for (let bit = 0; bit < 8; bit++) {+ if ((crc & 0x8000) !== 0) {+ crc = ((crc << 1) ^ 0x1021) & 0xffff;+ } else {+ crc = (crc << 1) & 0xffff;+ }+ }+ }+ return crc;+}+/*** Formats a list of Redis keys into `DEL` commands.* If keys exceed chunkSize, chunks them across multiple `DEL` lines.* In standalone mode with a non-zero database, prefixes with `SELECT <db>`.+ * In Cluster mode, omits `SELECT` and groups keys strictly by CRC16 hash slot to prevent CROSSSLOT errors.*/export function redisDeleteKeysPreview(keys: readonly (string | Uint8Array)[], options?: RedisDeleteKeysOptions | number): string {if (keys.length === 0) return "";@@ -211,12 +253,6 @@ export function redisDeleteKeysPreview(keys: readonly (string | Uint8Array)[], oconst isCluster = opts.isCluster ?? false;const isRaw = opts.raw ?? false;- const quoted = keys.map((key) => {- if (key instanceof Uint8Array) return quoteRedisBytes(key);- if (isRaw) return quoteRedisKeyRaw(key);- return quoteRedisArg(key);- });-const lines: string[] = [];if (!isCluster && opts.database != null && String(opts.database).trim() !== "") {const dbIndex = Number(String(opts.database).trim().replace(/^db/i, ""));@@ -225,8 +261,50 @@ export function redisDeleteKeysPreview(keys: readonly (string | Uint8Array)[], o}}- for (let i = 0; i < quoted.length; i += chunkSize) {- lines.push(`DEL ${quoted.slice(i, i + chunkSize).join(" ")}`);+ if (isCluster) {+ const slotGroups = new Map<number, string[]>();+ for (const key of keys) {+ let rawBytes: Uint8Array;+ let quotedKey: string;+ if (key instanceof Uint8Array) {+ rawBytes = key;+ quotedKey = quoteRedisBytes(key);+ } else if (isRaw) {+ try {+ rawBytes = base64ToBytes(key);+ } catch {+ rawBytes = new TextEncoder().encode(key);+ }+ quotedKey = quoteRedisKeyRaw(key);+ } else {+ rawBytes = new TextEncoder().encode(key);+ quotedKey = quoteRedisArg(key);+ }++ const slot = getRedisKeySlot(rawBytes);+ let group = slotGroups.get(slot);+ if (!group) {+ group = [];+ slotGroups.set(slot, group);+ }+ group.push(quotedKey);+ }++ for (const group of slotGroups.values()) {+ for (let i = 0; i < group.length; i += chunkSize) {+ lines.push(`DEL ${group.slice(i, i + chunkSize).join(" ")}`);+ }+ }+ } else {+ const quoted = keys.map((key) => {+ if (key instanceof Uint8Array) return quoteRedisBytes(key);+ if (isRaw) return quoteRedisKeyRaw(key);+ return quoteRedisArg(key);+ });++ for (let i = 0; i < quoted.length; i += chunkSize) {+ lines.push(`DEL ${quoted.slice(i, i + chunkSize).join(" ")}`);+ }}return lines.join("\n");@@ -343,20 +421,19 @@ export function redisDeleteGroupPreview(pattern: string, options?: RedisDeleteGr' elif x == 0x08: res.append("\\\\b")'," elif 0x20 <= x <= 0x7e: res.append(chr(x))"," elif x >= 0x80:",- " matched = False",- " for length in (4, 3, 2):",- " if i + length <= len(b):",- " try:",- ' ch = b[i:i+length].decode("utf-8")',- " if not any(0x80 <= ord(c) <= 0x9f for c in ch):",+ " length = 2 if 0xc2 <= x <= 0xdf else 3 if 0xe0 <= x <= 0xef else 4 if 0xf0 <= x <= 0xf4 else 0",+ " if length > 0 and i + length <= len(b):",+ " try:",+ ' ch = b[i:i+length].decode("utf-8")',+ " if len(ch) == 1:",+ " cp = ord(ch)",+ " if cp >= 0xa0 and cp not in (0x2028, 0x2029, 0xfeff):"," res.append(ch)"," i += length",- " matched = True",- " break",- " except UnicodeDecodeError: pass",- " if not matched:",- ' res.append(f"\\\\x{x:02x}")',- " i += 1",+ " continue",+ " except UnicodeDecodeError: pass",+ ' res.append(f"\\\\x{x:02x}")',+ " i += 1"," continue"," else:",' res.append(f"\\\\x{x:02x}")',diff --git a/crates/dbx-core/src/ai/agent_tools.rs b/crates/dbx-core/src/ai/agent_tools.rsindex a6b4067969..4b2ccd3551 100644--- a/crates/dbx-core/src/ai/agent_tools.rs+++ b/crates/dbx-core/src/ai/agent_tools.rs@@ -1267,7 +1267,7 @@ async fn execute_redis_command(// argument happened to be, and a refused command never reads run state.let argv = parse_command_argv(&command).map_err(|error| format!("{error} Send one Redis command, for example SCAN 0 MATCH session:* COUNT 100."))?;- let command_name = argv[0].to_ascii_uppercase();+ let command_name = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();if let Some(refusal) = redis_command_refusal(&argv) {return Err(refusal);}@@ -1287,8 +1287,8 @@ async fn execute_redis_command(/// Kept separate from the handler so the safety boundary is unit-testable/// without a live connection: every refusal happens before anything reaches the/// database.-fn redis_command_refusal(argv: &[String]) -> Option<String> {- let command_name = argv[0].to_ascii_uppercase();+fn redis_command_refusal(argv: &[Vec<u8>]) -> Option<String> {+ let command_name = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();if command_name == "SELECT" {return Some("Blocked: Redis SELECT is not available to the AI agent. Pass the db argument to choose the logical database instead."@@ -1301,7 +1301,7 @@ fn redis_command_refusal(argv: &[String]) -> Option<String> {// timeout (it awaits the connection directly), so one of these would hold// this connection's agent tool lock until the client goes away and stall// every other tool call on the same connection.- if command_name == "XREAD" && argv.iter().any(|argument| argument.eq_ignore_ascii_case("BLOCK")) {+ if command_name == "XREAD" && argv.iter().any(|argument| argument.eq_ignore_ascii_case(b"BLOCK")) {return Some("Blocked: XREAD BLOCK waits indefinitely and cannot be interrupted. Drop BLOCK to read the entries already in the stream.".to_string(),diff --git a/crates/dbx-core/src/query/redis_ops.rs b/crates/dbx-core/src/query/redis_ops.rsindex ccc6e2e855..80a9a6c6c7 100644--- a/crates/dbx-core/src/query/redis_ops.rs+++ b/crates/dbx-core/src/query/redis_ops.rs@@ -1242,7 +1242,7 @@ pub async fn redis_execute_command_core(let argv = cluster_console_argv(command)?;redis_driver::ensure_cluster_database(cluster, db).await?;let mut con = if command_may_target_first_key(&argv) {- redis_driver::cluster_key_connection_in_db(cluster, argv[1].as_bytes(), db).await?+ redis_driver::cluster_key_connection_in_db(cluster, &argv[1], db).await?} else {redis_driver::cluster_any_connection_in_db(cluster, db).await?};@@ -1253,9 +1253,9 @@ pub async fn redis_execute_command_core(}}-fn cluster_console_argv(command: &str) -> Result<Vec<String>, String> {+fn cluster_console_argv(command: &str) -> Result<Vec<Vec<u8>>, String> {let argv = redis_driver::parse_command_argv(command)?;- if argv.first().is_some_and(|name| name.eq_ignore_ascii_case("SELECT")) {+ if argv.first().is_some_and(|name| name.eq_ignore_ascii_case(b"SELECT")) {return Err("SELECT is not available on a shared cluster connection; switch databases using the database picker".to_string(),@@ -1264,12 +1264,13 @@ fn cluster_console_argv(command: &str) -> Result<Vec<String>, String> {Ok(argv)}-fn command_may_target_first_key(argv: &[String]) -> bool {+fn command_may_target_first_key(argv: &[Vec<u8>]) -> bool {if argv.len() < 2 {return false;}+ let cmd = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();!matches!(- argv[0].to_ascii_uppercase().as_str(),+ cmd.as_str(),"PING" | "INFO" | "DBSIZE" | "TIME" | "ROLE" | "CLUSTER" | "CLIENT" | "COMMAND" | "HELLO" | "AUTH" | "QUIT")}@@ -1445,7 +1446,7 @@ mod cluster_database_tests {assert!(error.contains("database picker"), "{command}: {error}");assert!(!error.contains("only supports db0"));}- assert_eq!(super::cluster_console_argv("GET key").unwrap(), ["GET", "key"]);+ assert_eq!(super::cluster_console_argv("GET key").unwrap(), [b"GET".to_vec(), b"key".to_vec()]);assert!(super::cluster_console_argv("\"").is_err());}}diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rsindex 78b96d1147..6414ac3838 100644--- a/crates/dbx-driver-redis/src/lib.rs+++ b/crates/dbx-driver-redis/src/lib.rs@@ -2562,11 +2562,11 @@ fn crc16_xmodem(bytes: &[u8]) -> u16 {crc}-pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {+pub fn parse_command_argv(command_text: &str) -> Result<Vec<Vec<u8>>, String> {// Strip trailing semicolons so commands like "HGETALL aaa;" work naturallylet command_text = command_text.trim_end().trim_end_matches(';');- let mut argv = Vec::new();- let mut current = String::new();+ let mut argv: Vec<Vec<u8>> = Vec::new();+ let mut current: Vec<u8> = Vec::new();let mut chars = command_text.chars().peekable();let mut quote: Option<char> = None;let mut escaping = false;@@ -2585,25 +2585,35 @@ pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {if h2.is_ascii_hexdigit() {chars.next();let byte = u8::from_str_radix(&format!("{h1}{h2}"), 16).unwrap();- current.push(byte as char);+ current.push(byte);escaping = false;continue;}}}}- current.push('x');+ current.push(b'x');} else {- current.push(match ch {- 'n' => '\n',- 'r' => '\r',- 't' => '\t',- 'a' => '\x07',- 'b' => '\x08',- 'f' => '\x0c',- 'v' => '\x0b',- other => other,- });+ let byte = match ch {+ 'n' => b'\n',+ 'r' => b'\r',+ 't' => b'\t',+ 'a' => b'\x07',+ 'b' => b'\x08',+ 'f' => b'\x0c',+ 'v' => b'\x0b',+ '\\' => b'\\',+ '"' => b'"',+ '\'' => b'\'',+ other => {+ let mut buf = [0u8; 4];+ let s = other.encode_utf8(&mut buf);+ current.extend_from_slice(s.as_bytes());+ escaping = false;+ continue;+ }+ };+ current.push(byte);}escaping = false;continue;@@ -2619,7 +2629,9 @@ pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {if ch == q {quote = None;} else {- current.push(ch);+ let mut buf = [0u8; 4];+ let s = ch.encode_utf8(&mut buf);+ current.extend_from_slice(s.as_bytes());}continue;}@@ -2642,11 +2654,13 @@ pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {}token_started = true;- current.push(ch);+ let mut buf = [0u8; 4];+ let s = ch.encode_utf8(&mut buf);+ current.extend_from_slice(s.as_bytes());}if escaping {- current.push('\\');+ current.push(b'\\');}if quote.is_some() {return Err("Redis command has an unterminated quote".to_string());@@ -2654,12 +2668,21 @@ pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {if token_started {argv.push(current);}- if argv.first().is_none_or(String::is_empty) {+ if argv.first().is_none_or(Vec::is_empty) {return Err("Redis command is empty".to_string());}Ok(argv)}+pub fn parse_command_raw_argv(command_text: &str) -> Result<Vec<Vec<u8>>, String> {+ parse_command_argv(command_text)+}++pub fn parse_command_argv_strings(command_text: &str) -> Result<Vec<String>, String> {+ let raw = parse_command_argv(command_text)?;+ Ok(raw.into_iter().map(|b| String::from_utf8_lossy(&b).into_owned()).collect())+}+pub fn classify_command(command: &str) -> RedisCommandSafety {// Read access is an explicit allowlist. Commands added by a newer Redis// version, module, or proxy remain high-risk until DBX reviews them.@@ -3041,7 +3064,7 @@ whereC: ConnectionLike + Send + Sync + Unpin,{let argv = parse_command_argv(command_text)?;- let command = argv[0].to_ascii_uppercase();+ let command = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();if command == "MONITOR" {return Err("MONITOR requires a dedicated streaming connection; run MONITOR alone in the query editor".to_string()@@ -3052,9 +3075,9 @@ wherereturn Err(format!("Redis command is blocked for safety: {command}"));}- let mut cmd = redis::cmd(&argv[0]);+ let mut cmd = redis::cmd(&command);for arg in argv.iter().skip(1) {- cmd.arg(arg);+ cmd.arg(arg.as_slice());}let raw: RedisRawValue = cmd.query_async(con).await.map_err(|e| e.to_string())?;@@ -10542,27 +10565,30 @@ mod tests {#[test]fn parses_command_text_with_quotes_and_escapes() {let argv = parse_command_argv(r#"SET "user:1" "Ada \"Lovelace\"""#).unwrap();- assert_eq!(argv, vec!["SET", "user:1", "Ada \"Lovelace\""]);+ assert_eq!(argv, vec![b"SET".to_vec(), b"user:1".to_vec(), b"Ada \"Lovelace\"".to_vec()]);let argv = parse_command_argv(r#"DEL "cache\\session""#).unwrap();- assert_eq!(argv, vec!["DEL", "cache\\session"]);+ assert_eq!(argv, vec![b"DEL".to_vec(), b"cache\\session".to_vec()]);let argv = parse_command_argv(r#"DEL "bin\x00key\xff""#).unwrap();- assert_eq!(argv, vec!["DEL", "bin\0key\u{ff}"]);+ assert_eq!(argv, vec![b"DEL".to_vec(), b"bin\0key\xff".to_vec()]);+ // Note: raw byte 0xff is preserved as a single byte 0xff, NOT UTF-8 encoded U+00FF (0xc3, 0xbf)+ assert_eq!(argv[1], vec![b'b', b'i', b'n', 0x00, b'k', b'e', b'y', 0xff]);}#[test]fn parses_empty_quoted_arguments() {let argv = parse_command_argv(r#"SET "" """#).unwrap();- assert_eq!(argv, vec!["SET", "", ""]);+ assert_eq!(argv, vec![b"SET".to_vec(), b"".to_vec(), b"".to_vec()]);}#[test]fn parses_quoted_and_escaped_command_names_before_classification() {for command_text in [r#""JSON.SET" user:1 $ {}"#, r#"JSON\.SET user:1 $ {}"#] {let argv = parse_command_argv(command_text).unwrap();- assert_eq!(classify_command(&argv[0]), RedisCommandSafety::Write);+ let cmd = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();+ assert_eq!(classify_command(&cmd), RedisCommandSafety::Write);}}@@ -10573,6 +10599,125 @@ mod tests {}}+ #[tokio::test]+ async fn raw_command_execution_preserves_binary_bytes_and_isolates_similar_text_keys() {+ use std::collections::HashSet;++ struct TargetIsolatingConnection {+ keys: HashSet<Vec<u8>>,+ captured_commands: Vec<Vec<u8>>,+ }++ impl ConnectionLike for TargetIsolatingConnection {+ fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, RedisRawValue> {+ let packed = cmd.get_packed_command();+ self.captured_commands.push(packed.clone());+ // Parse RESP array: *<count>\r\n$<len>\r\n<arg>\r\n...+ if packed.starts_with(b"*") {+ let mut pos = 0;+ if let Some(crlf) = packed[pos..].windows(2).position(|w| w == b"\r\n") {+ pos += crlf + 2;+ let mut args = Vec::new();+ while pos < packed.len() {+ if packed[pos] == b'$' {+ if let Some(len_end) = packed[pos..].windows(2).position(|w| w == b"\r\n") {+ let len_str = std::str::from_utf8(&packed[pos + 1..pos + len_end]).unwrap();+ let arg_len: usize = len_str.parse().unwrap();+ let start = pos + len_end + 2;+ let end = start + arg_len;+ args.push(packed[start..end].to_vec());+ pos = end + 2;+ } else {+ break;+ }+ } else {+ break;+ }+ }+ if args.first().is_some_and(|c| c.eq_ignore_ascii_case(b"DEL")) {+ for k in &args[1..] {+ self.keys.remove(k);+ }+ }+ }+ }+ Box::pin(async move { Ok(RedisRawValue::Int(1)) })+ }++ fn req_packed_commands<'a>(+ &'a mut self,+ cmd: &'a Pipeline,+ _offset: usize,+ count: usize,+ ) -> RedisFuture<'a, Vec<RedisRawValue>> {+ self.captured_commands.push(cmd.get_packed_pipeline());+ Box::pin(async move { Ok(vec![RedisRawValue::Int(1); count]) })+ }++ fn get_db(&self) -> i64 {+ 0+ }+ }++ let key_ff = vec![0xff];+ let key_utf8_y_diaeresis = "ÿ".as_bytes().to_vec(); // [0xc3, 0xbf]+ let key_80 = vec![0x80];+ let key_c2_80 = vec![0xc2, 0x80]; // U+0080 in UTF-8+ let key_nul = b"bin\x00key".to_vec();+ let key_zero = b"bin0key".to_vec();+ let key_zhong_n = vec![0xe4, 0xb8, 0xad, 0x5c, 0x6e]; // "中\n" in bytes+ let key_zhong_nl = vec![0xe4, 0xb8, 0xad, 0x0a]; // "中<newline>" in bytes++ let mut con = TargetIsolatingConnection {+ keys: HashSet::from([+ key_ff.clone(),+ key_utf8_y_diaeresis.clone(),+ key_80.clone(),+ key_c2_80.clone(),+ key_nul.clone(),+ key_zero.clone(),+ key_zhong_n.clone(),+ key_zhong_nl.clone(),+ ]),+ captured_commands: Vec::new(),+ };++ // 1. Delete binary 0xff key: DEL "\xff"+ super::execute_command(&mut con, r#"DEL "\xff""#, true).await.unwrap();+ // Verify wire bytes: bulk string length must be $1, containing single byte 0xff+ let last_cmd = con.captured_commands.last().unwrap();+ assert!(last_cmd.ends_with(b"$1\r\n\xff\r\n"), "must send raw byte 0xff with length 1");+ assert!(!con.keys.contains(&key_ff), "0xff key must be deleted");+ assert!(con.keys.contains(&key_utf8_y_diaeresis), "UTF-8 'ÿ' key [0xc3, 0xbf] must NOT be deleted");++ // 2. Delete UTF-8 'ÿ' key: DEL "ÿ"+ super::execute_command(&mut con, r#"DEL "ÿ""#, true).await.unwrap();+ let last_cmd = con.captured_commands.last().unwrap();+ assert!(last_cmd.ends_with(b"$2\r\n\xc3\xbf\r\n"), "must send UTF-8 bytes for 'ÿ' with length 2");+ assert!(!con.keys.contains(&key_utf8_y_diaeresis), "UTF-8 'ÿ' key must now be deleted");++ // 3. Delete binary 0x80 key: DEL "\x80"+ super::execute_command(&mut con, r#"DEL "\x80""#, true).await.unwrap();+ let last_cmd = con.captured_commands.last().unwrap();+ assert!(last_cmd.ends_with(b"$1\r\n\x80\r\n"), "must send raw byte 0x80 with length 1");+ assert!(!con.keys.contains(&key_80), "0x80 key must be deleted");+ assert!(con.keys.contains(&key_c2_80), "[0xc2, 0x80] key must NOT be deleted");++ // 4. Delete binary NUL key: DEL "bin\x00key"+ super::execute_command(&mut con, r#"DEL "bin\x00key""#, true).await.unwrap();+ let last_cmd = con.captured_commands.last().unwrap();+ assert!(last_cmd.ends_with(b"$7\r\nbin\x00key\r\n"), "must send raw NUL byte inside key");+ assert!(!con.keys.contains(&key_nul), "NUL key must be deleted");+ assert!(con.keys.contains(&key_zero), "bin0key must NOT be deleted");++ // 5. Delete "中\n" (bytes: e4 b8 ad 5c 6e): DEL "中\\n"+ super::execute_command(&mut con, r#"DEL "中\\n""#, true).await.unwrap();+ let last_cmd = con.captured_commands.last().unwrap();+ assert!(last_cmd.ends_with(b"$5\r\n\xe4\xb8\xad\\n\r\n"), "must send exact bytes for 中\\n");+ assert!(!con.keys.contains(&key_zhong_n), "中\\n key must be deleted");+ assert!(con.keys.contains(&key_zhong_nl), "中<newline> key must NOT be deleted");+ }+#[tokio::test]async fn raw_command_execution_fails_closed_before_sending_invalid_or_unknown_commands() {let mut con = FakeRedisConnection::new(Vec::new());diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rsindex c77d074857..aa162d08ad 100644--- a/crates/dbx-mcp/src/server.rs+++ b/crates/dbx-mcp/src/server.rs@@ -2500,13 +2500,14 @@ impl DbxMcpServer {Ok(argv) => argv,Err(error) => return tool_error("REDIS_COMMAND_BLOCKED", error),};- if argv[0].eq_ignore_ascii_case("SELECT") {+ let cmd_name = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();+ if cmd_name == "SELECT" {return tool_error("REDIS_DATABASE_SELECTION_REQUIRED","Redis SELECT is not available through MCP. Set the db argument to the logical database number instead; when db is omitted, DBX uses the current scoped database.",);}- let safety = classify_command(&argv[0]);+ let safety = classify_command(&cmd_name);let policy = effective_policy_for_database_with_groups(&resolved.policy,&resolved.group_ids,@@ -2531,7 +2532,7 @@ impl DbxMcpServer {"REDIS_COMMAND_BLOCKED",format!("Dangerous Redis command \"{}\" is disabled in DBX MCP settings.",- argv[0].to_ascii_uppercase()+ cmd_name),);}diff --git a/crates/dbx-web/src/routes/redis.rs b/crates/dbx-web/src/routes/redis.rsindex 4612fd925e..33823b01ef 100644--- a/crates/dbx-web/src/routes/redis.rs+++ b/crates/dbx-web/src/routes/redis.rs@@ -926,7 +926,7 @@ pub async fn execute_command(super::mcp_policy::ensure_scope(&state, &headers, &req.connection_id).await?;let argv = dbx_core::db::redis_driver::parse_command_argv(&req.command).map_err(|error| AppError::from(format!("Invalid Redis command: {error}")))?;- let cmd_name = argv[0].to_ascii_uppercase();+ let cmd_name = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();let safety = dbx_core::db::redis_driver::classify_command(&cmd_name);let is_mcp_request = super::mcp_policy::is_mcp_request(&headers);let centrally_approved_high_risk =diff --git a/src-tauri/src/commands/mcp_bridge.rs b/src-tauri/src/commands/mcp_bridge.rsindex e49e0eca68..030fa86fb1 100644--- a/src-tauri/src/commands/mcp_bridge.rs+++ b/src-tauri/src/commands/mcp_bridge.rs@@ -2694,7 +2694,7 @@ async fn handle_redis_execute_command_data(state: &Arc<AppState>, body: &str, streturn;}};- let cmd_name = argv[0].to_ascii_uppercase();+ let cmd_name = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();let safety = dbx_core::db::redis_driver::classify_command(&cmd_name);let centrally_approved_high_risk = safety == dbx_core::db::redis_driver::RedisCommandSafety::Blocked;if safety != dbx_core::db::redis_driver::RedisCommandSafety::Allowed {diff --git a/src-tauri/src/commands/redis_cmd.rs b/src-tauri/src/commands/redis_cmd.rsindex 935953b333..62e3bde8b1 100644--- a/src-tauri/src/commands/redis_cmd.rs+++ b/src-tauri/src/commands/redis_cmd.rs@@ -525,7 +525,7 @@ pub async fn redis_execute_command(skip_safety_check: Option<bool>,) -> Result<RedisCommandResult, String> {let argv = parse_command_argv(&command).map_err(|error| format!("Invalid Redis command: {error}"))?;- let cmd_name = argv[0].to_ascii_uppercase();+ let cmd_name = String::from_utf8_lossy(&argv[0]).to_ascii_uppercase();let safety = classify_command(&cmd_name);// In read-only mode, only allow safe read commands through the raw command interfaceif let Some(name) = dbx_core::query::connection_readonly_name(&state, &connection_id).await {