-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 NEFARIOUSPLAN-CANONICAL-V1 {"body_md":"## The pre-patch `visitJSONPathLeg` was three lines.\n\nThe entire JSON-path-leg emission in `src/query-compiler/default-query-compiler.ts` at v0.28.11 was:\n\n```typescript\nprotected override visitJSONPathLeg(node: JSONPathLegNode): void {\n const isArrayLocation = node.type === 'ArrayLocation'\n\n this.append(isArrayLocation ? '[' : '.')\n\n this.append(String(node.value))\n\n if (isArrayLocation) {\n this.append(']')\n }\n}\n```\n\n`node.value` is the `string | number` the caller passed to `.key()` or `.at()`. The leg sits inside a containing `visitJSONPath` that frames the whole expression in apostrophes:\n\n```typescript\nprotected override visitJSONPath(node: JSONPathNode): void {\n if (node.inOperator) {\n this.visitNode(node.inOperator)\n }\n\n this.append(\"'$\")\n\n for (const pathLeg of node.pathLegs) {\n this.visitNode(pathLeg)\n }\n\n this.append(\"'\")\n}\n```\n\nFor a normal call against a known-shape column:\n\n```typescript\ndb.selectFrom('person_metadata')\n .select(eb => eb.ref('profile', '->$').key('city').as('city'))\n```\n\nThe emitted SQL on MySQL is:\n\n```sql\nselect `profile`->'$.city' as `city` from `person_metadata`\n```\n\nThe dot before `city` is the JSON path's path-leg separator. The `$` is the path root. The whole path lives inside the SQL string literal `'...'`. The compiler concatenates the caller's key directly into that literal.\n\nA chained call writes the same way. `eb.ref('profile', '->$').key('address').key('city')` produces `'$.address.city'`. Two `visitJSONPathLeg` invocations, each writing `.` and then a member name. The output is one continuous JSON path.\n\n`.key('address.city')` produces the same string. The compiler ran `visitJSONPathLeg` exactly once. It wrote `.` and then `address.city`. The downstream database parser reads two path legs because there are two dots, and there is no way for the parser to tell from the SQL it received which dots the compiler wrote and which dots the caller did. The compiler decided that question by writing `String(node.value)`.\n\n## The first fix was titled \"is injectable.\" It escaped the wrong layer.\n\nOn March 4, 2026, commit 0a602bff landed in the same file. Title: `fix: eb.ref(col, '->$').key(key) is injectable`. The fix:\n\n```diff\n- this.append(String(node.value))\n+ this.append(\n+ typeof node.value === 'string'\n+ ? this.sanitizeStringLiteral(node.value)\n+ : String(node.value),\n+ )\n```\n\n`sanitizeStringLiteral` replaces each `'` in the value with `''`. That closes the SQL injection the same commit's test demonstrates:\n\n```typescript\nconst injection =\n `first' as ${identifierWrapper}first${identifierWrapper} from ${identifierWrapper}people${identifierWrapper}; drop table ${identifierWrapper}person${identifierWrapper} -- ` as never\n\nconst query = ctx.db\n .with('people', () =>\n ctx.db\n .selectFrom('person')\n .select(\n sql<{ first: string }>`json_object('first', first_name)`.as('data'),\n ),\n )\n .selectFrom('people')\n .select((eb) => eb.ref('data', '->$').key(injection).as('first'))\n```\n\nWithout the escape, the `'` in `first'` closes the apostrophe-bounded JSON path early, the tail of the string runs as appended SQL, and the test asserts that the resulting query attempts to drop the `person` table. With the escape, each `'` becomes `''` and the entire payload survives as one very long quoted JSON-path member name.\n\nWhat the fix does not touch is anything inside the path. The dot was already there because the compiler wrote it. The dot inside the caller's value is never quoted, escaped, or rejected. The 0.28.12 release on the same day shipped the patch as the only meaningful change. The release notes describe it as the closed bug.\n\nSixty days later, on May 3, 2026, commit dbb54058 landed with the title `feat: further harden JSON path .key(...) and .at(...) against SQL injections and exfiltrations`. The class names in the second title are not the class names in the first. The first patch closed SQL injection. The second patch closed exfiltrations, plural, by way of dots, brackets, wildcards, and quote escapes that the apostrophe escape never saw. CVE-2026-44635 names the gap.\n\n## `K extends string` is what gets typed when the column is what `.key()` is for.\n\n`.key()` in `src/query-builder/json-path-builder.ts` is typed:\n\n```typescript\nkey<\n K extends any[] extends O\n ? never\n : O extends object\n ? keyof NonNullable & string\n : never,\n O2 = undefined extends O\n ? null | NonNullable[K]>\n : null extends O\n ? null | NonNullable[K]>\n : // when the object has non-specific keys, e.g. Record, should infer `T | null`!\n string extends keyof NonNullable\n ? null | NonNullable[K]>\n : NonNullable[K],\n>(key: K): TraversedJSONPathBuilder\n```\n\nThe comment in the conditional acknowledges the case directly. When the column is `Record`, `keyof NonNullable` is `string`, the existing-key branch falls through, and the return type degrades to `T | null`. What the comment does not say is what happens to `K` itself in that branch. `K extends keyof NonNullable & string` is `K extends string & string`, which is `K extends string`. The TypeScript checker has nothing to refuse. Any string compiles.\n\nThe column shapes where this applies are not a corner. A `preferences` column whose contents are arbitrary user settings. A `profile` column the application accumulates field by field over years. A `metadata` column described in the schema as \"string-keyed scalar values.\" A feature-flag column with no enumerated flag set. A `settings` column whose schema is \"whatever the admin UI saves.\" The library's documentation tells the caller that `K` is bound to the column's key set. For columns whose key set is not knowable at compile time, and that is most JSON columns in any application that uses JSON columns for any practical reason, the bound is `string`.\n\nThe four exfiltration tests that landed with the May patch read off the bound:\n\n```typescript\nconst exfiltration = 'auth.login_count'\n// emits: 'profile'->'$.auth.login_count'\n// parses as: navigate $.auth, then $.auth.login_count\n\nconst exfiltration = 'auth\".\"login_count'\n// emits: 'profile'->'$.auth\".\"login_count'\n// breaks out of any per-leg quote wrap to reconstruct the dot path\n\nconst exfiltration = 'tags[0]'\n// emits: 'profile'->'$.tags[0]'\n// array-index access into a sibling key\n\nconst exfiltration = '*'\n// emits: 'profile'->'$.*'\n// every key at the current level\n```\n\nEach of those is a string. Each of those is the shape `req.query.field` takes in the route handlers that motivate `.key()` existing in the first place. Each of those, against a `Record` column, the TypeScript checker accepts without `as never`. The tests had to write `as never` because the test's column was typed as `{ first: string }` for SQL-injection demonstration purposes. The production code where the bug lives does not have that constraint.\n\nThe CVE description is explicit about the case: \"including type-safe code where the JSON column is shaped like `Record` so `K extends string` is the inferred type.\" The advisory writer named the gap. The type signature still says `keyof NonNullable & string` after the patch. The patch did not touch the type.\n\n## The second patch wraps the key in quotes. `.at()` got an allowlist. `.key()` did not.\n\nThe 0.28.17 emission for member legs is:\n\n```typescript\nif (isArrayLocation) {\n this.append('[')\n this.append(this.sanitizeStringLiteral(value))\n this.append(']')\n} else {\n this.append('.\"')\n this.append(this.sanitizeJSONPathMemberValue(value))\n this.append('\"')\n}\n```\n\n`.key('auth.login_count')` now compiles to `'profile'->'$.\"auth.login_count\"'`. The dot lives inside the double-quoted key. The JSON path parser reads the whole quoted string as one member name, looks for a key literally named `auth.login_count`, fails to find it, and returns null. The four exfiltration tests all assert `expect(result.exfiltrated).to.be.null`.\n\nThe default `sanitizeJSONPathMemberValue` escapes the two characters that could close the quote wrap:\n\n```typescript\nprotected sanitizeJSONPathMemberValue(value: string): string {\n return value.replace(JSON_PATH_MEMBER_WRAP_REGEX, (char) =>\n char === \"'\" ? \"''\" : '\\\\\"',\n )\n}\n```\n\nMySQL and SQLite override the method because the path string itself is wrapped in a SQL string literal whose backslash rules differ. MySQL needs `\\\\\\\\` for a single literal backslash because the SQL string parser eats one pair and the JSON path parser eats the other. SQLite needs `\\\\`. Each dialect ships its own table.\n\n`.at()` is handled differently. The same commit adds a runtime allowlist to `JSONPathBuilder.at`:\n\n```typescript\nconst HASH_NEGATIVE_INDEX_REGEX = /^#-\\d+$/\n\nat<...>(index: ...): TraversedJSONPathBuilder {\n if (\n (typeof index !== 'number' && typeof index !== 'string') ||\n (typeof index === 'number' && !Number.isInteger(index)) ||\n (typeof index === 'string' &&\n index !== 'last' &&\n !HASH_NEGATIVE_INDEX_REGEX.test(index))\n ) {\n throw new Error(`Unexpected index value in .at(...): ${index}`)\n }\n\n return this.#createBuilderWithPathLeg('ArrayLocation', index)\n}\n```\n\nThe set of accepted values is an integer, the literal string `'last'`, or the pattern `#-N`. Three named cases. Anything else throws at the point the value enters the builder. That is a true allowlist.\n\n`.key()` has no equivalent. The quote wrap is the gate. The set of accepted member-key values is whatever the database's quoted-key parser accepts inside `\"...\"`, which today across MySQL, PostgreSQL `->$`/`->>$`, and SQLite is any sequence of non-quote characters, including dots, brackets, wildcards, and the path-language question marks. The grammar happens to read those as literal characters inside a quoted key. The day the grammar changes, the day a future dialect adds path predicate syntax to its quoted-key parser, the day a maintainer needs to allow `$.\"..\".[?(@.x=='y')]` style filters, the set of inputs `.key()` accepts opens for that grammar without touching `JSONPathBuilder`.\n\n## Convention is the allowlist.\n\nKysely is a type-safe TypeScript SQL query builder. The library's value proposition is that the type system tells you which columns exist, which keys those columns can hold, and which operations apply to which types. For fixed object shapes the type system delivers on every part of that promise. The literal-union constraint on `K` for a column typed `{ city: string; country: string }` rejects `.key('city.country')` at compile time because the literal `'city.country'` is not in the union. That is the case the documentation's examples illustrate. That is the case the maintainer's SQL-injection test had to opt out of by appending `as never`.\n\nFor the other case, the case where the schema declares the column as `Record` because the keys are not knowable at the schema layer, the type collapses to `string` and the constraint resolves to \"accepts anything.\" The runtime then concatenates the accepted-anything string into a JSON path expression whose own grammar treats five characters as structural. The TypeScript convention \"this parameter is one property name\" lives in the developer's reading of the type signature and in the docstring's examples. The code never installed it.\n\nThis is the [Convention Is The Allowlist](/patterns/convention-is-the-allowlist) shape, on the type-system axis rather than the spec-RFC axis. [Streamlink CVE-2026-44353](/posts/streamlink-cve-2026-44353-fileadapter-mounted-parser-not-told) is the same shape on the URL-scheme axis: the m3u8 parser implemented what RFC 3986 grammar permits and trusted the convention that segment URIs are HTTP or HTTPS to do the constraining work. The convention did not. Kysely's `.key()` parameter is the same shape on the type-system axis: the type signature implemented what the conditional resolves to and trusted the convention that \"a key\" means one property name to do the constraining work. The convention did not.\n\nThe patch in each case narrows the implementation against the local context the maintainer can see today. Streamlink's patch installs a downgrade comparison against the playlist's own scheme. Kysely's patch wraps member keys in double quotes whose grammar today treats path metacharacters as literal. The set of accepted values for `.key()` is now whatever a future quoted-key parser accepts, on whatever dialect Kysely later adds. The convention that `K` is one property name remains in the type signature.\n\nThe 60 days between the March commit and the May commit are the part of the story the CVE record does not contain. The 0.28.12 release notes said \"is injectable\" because the maintainer's threat model at the time included SQL injection of the outer statement and did not include exfiltration through the inner path. The 0.28.17 release notes said \"further harden against SQL injections and exfiltrations\" because by then somebody had reported that the inner path was its own grammar. Two months of users running production code through `eb.ref(col, '->$').key(req.query.field)` against `Record` columns sat between the two namings.\n\nAdvisory: [GHSA-pv5w-4p9q-p3v2](https://github.com/advisories/GHSA-pv5w-4p9q-p3v2).","closing_line":"The test that demonstrated the SQL injection had to coerce its input to `never`. The production code where the JSON-path traversal lives does not.","hook_md":"Kysely 0.26.0 through 0.28.16 ship a JSON-path API whose member-key parameter is typed `K extends keyof NonNullable & string`. For a JSON column whose schema-declared shape is `Record`, that constraint resolves at compile time to `string`. The TypeScript checker reading `eb.ref('preferences', '->$').key(req.query.field)` against that column sees a well-typed access. The query compiler sees a JSON path leg whose value is whatever string the caller passed, writes it into the path expression between the apostrophes that frame the whole path, and lets the database's JSON path parser decide what the dots mean.\n\nCVE-2026-44635 is what `req.query.field = 'auth.api_key'` does after that.","post_id":537,"slug":"kysely-cve-2026-44635-k-extends-string-was-the-allowlist","title":"CVE-2026-44635: Kysely's `K extends string` Was The Allowlist. The JSON Path Parser Was Not Told.","type":"initial","unreadable_sentence":"The test that demonstrated the SQL injection had to coerce its input to `never`. The production code where the JSON-path traversal lives does not."} -----BEGIN PGP SIGNATURE----- iHUEARYIAB0WIQRf0htP5+SjynlxywneZjl4jgkQJgUCapsntQAKCRDeZjl4jgkQ JqneAQCSvzuHAexTtT1V+5V3B9p+INT1cmM9vo75rtQTYfO52AEAxCJOE7ON46DP t6AKlItYnZnsVqQs39Eb652404KL4ww= =/5D5 -----END PGP SIGNATURE-----