🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(eslint): flag unescaped values in SQL LIKE patterns (#19147)
Niklas Semmler7431f913d50a
diff --git a/packages/config-eslint/shared.js b/packages/config-eslint/shared.jsindex 72c3aa655b..166e411d17 100644--- a/packages/config-eslint/shared.js+++ b/packages/config-eslint/shared.js@@ -60,6 +60,16 @@ export default [},},+ // Prisma `contains`/`startsWith`/`endsWith` and raw `LIKE` treat `_`, `%` and `\` as wildcards.+ {+ name: "langfuse/shared/no-unescaped-prisma-like-pattern",+ files: ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],+ ignores: ["**/*.test.ts", "**/*.servertest.ts", "**/__tests__/**"],+ rules: {+ "@repo/no-unescaped-prisma-like-pattern": "warn",+ },+ },+{name: "langfuse/shared/repo-plugin",plugins: {diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.tsindex 60f6dec05b..00e49ac390 100644--- a/packages/eslint-plugin/src/index.ts+++ b/packages/eslint-plugin/src/index.ts@@ -4,6 +4,7 @@ import { default as noArbitraryColors } from "./rules/no-arbitrary-colors.js";import { default as noAbstractedOverlayTrigger } from "./rules/no-abstracted-overlay-trigger.js";import { default as noInSourceVitest } from "./rules/no-in-source-vitest.js";import { default as noExoticOperators } from "./rules/no-exotic-operators.js";+import { default as noUnescapedPrismaLikePattern } from "./rules/no-unescaped-prisma-like-pattern.js";import { default as noMarginOnRootElements } from "./rules/no-margin-on-root-elements.js";import { default as noNullRender } from "./rules/no-null-render.js";import { default as noLetAssignInReact } from "./rules/no-let-assign-in-react.js";@@ -34,6 +35,7 @@ const plugin = {"no-style-props": noStyleProps,"no-switch-statements": noSwitchStatements,"no-tailwind-overflow-scroll": noTailwindOverflowScroll,+ "no-unescaped-prisma-like-pattern": noUnescapedPrismaLikePattern,"no-unnecessary-cn": noUnnecessaryCn,"prefer-stories-over-client-tests": preferStoriesOverClientTests,"require-title-with-truncate": requireTitleWithTruncate,diff --git a/packages/eslint-plugin/src/rules/no-unescaped-prisma-like-pattern.test.ts b/packages/eslint-plugin/src/rules/no-unescaped-prisma-like-pattern.test.tsnew file mode 100644index 0000000000..b0996dbf52--- /dev/null+++ b/packages/eslint-plugin/src/rules/no-unescaped-prisma-like-pattern.test.ts@@ -0,0 +1,142 @@+import { RuleTester } from "@typescript-eslint/rule-tester";+import * as typescriptEslintParser from "@typescript-eslint/parser";+import rule from "./no-unescaped-prisma-like-pattern.js";++const ruleTester = new RuleTester({+ languageOptions: {+ parser: typescriptEslintParser,+ parserOptions: {+ ecmaVersion: 2022,+ sourceType: "module",+ },+ },+});++ruleTester.run("no-unescaped-prisma-like-pattern", rule, {+ valid: [+ `where({ name: { contains: escapeSqlLikePattern(query) } });`,+ `where({ name: { startsWith: \`\${escapeSqlLikePattern(path)}/\` } });`,+ `where({ name: { startsWith: escapeSqlLikePattern(name) + " (copy" } });`,+ `const escaped = escapeSqlLikePattern(query);+ where({ name: { contains: escaped, mode: "insensitive" } });`,+ `const op = { contains: "ILIKE", "starts with": "ILIKE" };`,+ `where({ name: { equals: name } });`,+ `where({ name: { equals: escapeSqlLikePattern(name), mode: "insensitive" } });`,+ `where({ name: { contains: q ? escapeSqlLikePattern(q) : "" } });`,+ `const prefix = p ? escapeSqlLikePattern(p) : undefined;+ where({ name: { startsWith: \`\${prefix}/\` } });`,+ `where({ name: { contains: escapeSqlLikePattern(q) as string } });`,+ `where({ name: { contains: escapeSqlLikePattern(q)! } });`,+ `const e = escapeSqlLikePattern(q);+ where({ name: { contains: exact ? e : \`%\${e}%\` } });`,+ `const e = escapeSqlLikePattern(q);+ where({ name: { startsWith: e + "/" + e } });`,+ `const insensitive = { mode: "insensitive" as const };+ where({ name: { equals: escapeSqlLikePattern(q), ...insensitive } });`,+ `const caseSensitive = { mode: "default" };+ where({ name: { equals: q, ...caseSensitive } });`,+ `const mode = "default";+ where({ name: { equals: q, mode } });`,+ `where({ name: { not: { contains: escapeSqlLikePattern(q) }, mode: "insensitive" } });`,+ `where({ name: { not: q } });`,+ `const { contains } = filter;`,+ `const byIndex = { 1: query };`,+ `makeTag()\`name ILIKE \${q}\`;`,+ `gql\`query { items(filter: "name ILIKE \${q}") }\`;`,+ `Prisma.sql\`AND d.name ILIKE \${\`%\${escapeSqlLikePattern(q)}%\`}\`;`,+ `Prisma.sql\`AND d.name = \${name}\`;`,+ `sql\`AND name ILIKE \${escapeSqlLikePattern(q)} AND id = \${id}\`;`,+ `Prisma.sql\`AND d.name LIKE '%/%' AND d.id = \${id}\`;`,+ `const pattern = \`%\${escapeSqlLikePattern(q)}%\`;+ prisma.$queryRaw\`SELECT 1 WHERE name ILIKE \${pattern}\`;`,+ ],+ invalid: [+ {+ code: `where({ name: { contains: query } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { startsWith: dataset.name + " (copy" } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { endsWith: \`\${suffix}\` } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { not: { contains: input.search } } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { equals: name, mode: "insensitive" } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { equals: name, mode: "insensitive" as const } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { equals: name, mode: Prisma.QueryMode.insensitive } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `const insensitive = { mode: "insensitive" as const };+ where({ name: { equals: name, ...insensitive } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { equals: name, ...modeFor(input) } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { equals: name, mode: modeFor(input) } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `const opts = makeOpts();+ where({ name: { equals: name, ...opts } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `function f(mode: string) { where({ name: { equals: q, mode } }); }`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { not: name, mode: "insensitive" } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `let q = escapeSqlLikePattern(raw);+ where({ name: { contains: q } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { contains: q ? escapeSqlLikePattern(q) : q } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `where({ name: { contains: helpers["escapeSqlLikePattern"](q) } });`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `Prisma.sql\`AND d.name ILIKE \${\`%\${q}%\`}\`;`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `sql\`AND tag NOT ILIKE '%' || \${q} || '%'\`;`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `sql\`AND name ILIKE \${escapeSqlLikePattern(prefix)} || \${q}\`;`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `sql\`AND name ILIKE ('%' || \${q})\`;`,+ errors: [{ messageId: "unescaped" }],+ },+ {+ code: `prisma.$queryRaw\`SELECT 1 WHERE name like \${pattern}\`;`,+ errors: [{ messageId: "unescaped" }],+ },+ ],+});diff --git a/packages/eslint-plugin/src/rules/no-unescaped-prisma-like-pattern.ts b/packages/eslint-plugin/src/rules/no-unescaped-prisma-like-pattern.tsnew file mode 100644index 0000000000..5dd0b9f92a--- /dev/null+++ b/packages/eslint-plugin/src/rules/no-unescaped-prisma-like-pattern.ts@@ -0,0 +1,211 @@+import {+ ASTUtils,+ AST_NODE_TYPES,+ type TSESLint,+ type TSESTree,+} from "@typescript-eslint/utils";+import { createRule } from "../util.js";+import { getStaticPropertyKeyValue } from "../rule-helpers/ast.js";++const ESCAPE_FUNCTION = "escapeSqlLikePattern";++// Prisma compiles these string filters to (I)LIKE on Postgres without escaping.+const PRISMA_LIKE_KEYS = new Set(["contains", "startsWith", "endsWith"]);+// With `mode: "insensitive"`, Prisma compiles these to ILIKE / NOT ILIKE too.+const PRISMA_INSENSITIVE_KEYS = new Set(["equals", "not"]);++const SQL_TAGS = new Set(["sql", "$queryRaw", "$executeRaw"]);++// Matches template text that ends right before a LIKE pattern operand, e.g.+// `name ILIKE `, `tag LIKE ('%' || `, `x NOT ILIKE ANY(`.+const LIKE_OPERAND_SUFFIX =+ /\bI?LIKE\s*(?:ANY\s*)?(?:\(\s*)?(?:'%'\s*\|\|\s*)?$/i;+// Matches template text that joins two values of the same pattern, e.g. ` || `.+const PATTERN_CONCAT = /^\s*(?:'%'\s*)?\|\|\s*(?:'%'\s*\|\|\s*)?$/;++type Context = Readonly<TSESLint.RuleContext<"unescaped", []>>;++function calleeName(callee: TSESTree.Expression): string | null {+ if (callee.type === AST_NODE_TYPES.Identifier) return callee.name;+ if (+ callee.type === AST_NODE_TYPES.MemberExpression &&+ callee.property.type === AST_NODE_TYPES.Identifier+ ) {+ return callee.property.name;+ }+ return null;+}++function constInit(+ node: TSESTree.Identifier,+ context: Context,+): TSESTree.Expression | null {+ const variable = ASTUtils.findVariable(+ context.sourceCode.getScope(node),+ node,+ );+ const def = variable?.defs.length === 1 ? variable.defs[0] : undefined;+ if (+ def?.node.type !== AST_NODE_TYPES.VariableDeclarator ||+ def.node.parent.kind !== "const" ||+ !def.node.init+ ) {+ return null;+ }+ return def.node.init;+}++function unwrap(node: TSESTree.Node): TSESTree.Node {+ if (+ node.type === AST_NODE_TYPES.TSAsExpression ||+ node.type === AST_NODE_TYPES.TSNonNullExpression+ ) {+ return unwrap(node.expression);+ }+ return node;+}++function isEscaped(+ node: TSESTree.Node,+ context: Context,+ seen: Set<TSESTree.Node> = new Set(),+): boolean {+ const recurse = (child: TSESTree.Node) => isEscaped(child, context, seen);++ if (node.type === AST_NODE_TYPES.Literal) return true;+ if (node.type === AST_NODE_TYPES.TemplateLiteral) {+ return node.expressions.every(recurse);+ }+ if (node.type === AST_NODE_TYPES.BinaryExpression) {+ return node.operator === "+" && recurse(node.left) && recurse(node.right);+ }+ if (node.type === AST_NODE_TYPES.ConditionalExpression) {+ return recurse(node.consequent) && recurse(node.alternate);+ }+ if (+ node.type === AST_NODE_TYPES.TSAsExpression ||+ node.type === AST_NODE_TYPES.TSNonNullExpression+ ) {+ return recurse(node.expression);+ }+ if (node.type === AST_NODE_TYPES.CallExpression) {+ return calleeName(node.callee) === ESCAPE_FUNCTION;+ }+ if (node.type !== AST_NODE_TYPES.Identifier) return false;+ if (node.name === "undefined") return true;++ // Follow a single `const` binding to its initializer. `seen` holds only the+ // bindings on the current path, so it stops cycles but allows reuse.+ const init = constInit(node, context);+ if (!init || seen.has(init)) return false;+ seen.add(init);+ const escaped = recurse(init);+ seen.delete(init);+ return escaped;+}++// A `mode` that cannot be resolved to a literal other than "insensitive"+// counts as insensitive.+function isInsensitiveMode(value: TSESTree.Node, context: Context): boolean {+ const node = unwrap(value);+ if (node.type === AST_NODE_TYPES.Literal) return node.value === "insensitive";+ if (node.type === AST_NODE_TYPES.Identifier) {+ const init = constInit(node, context);+ return init ? isInsensitiveMode(init, context) : true;+ }+ return true;+}++function isInsensitive(+ object: TSESTree.ObjectExpression,+ context: Context,+): boolean {+ return object.properties.some((p) => {+ if (p.type === AST_NODE_TYPES.SpreadElement) {+ const argument = unwrap(p.argument);+ const init =+ argument.type === AST_NODE_TYPES.Identifier+ ? constInit(argument, context)+ : null;+ const spread = init && unwrap(init);+ return spread?.type === AST_NODE_TYPES.ObjectExpression+ ? isInsensitive(spread, context)+ : true;+ }+ return (+ !p.computed &&+ getStaticPropertyKeyValue(p.key) === "mode" &&+ isInsensitiveMode(p.value, context)+ );+ });+}++function isSqlTag(tag: TSESTree.Expression): boolean {+ return SQL_TAGS.has(calleeName(tag) ?? "");+}++const rule = createRule<[], "unescaped">({+ name: "no-unescaped-prisma-like-pattern",+ meta: {+ type: "problem",+ docs: {+ description: `Require ${ESCAPE_FUNCTION}() on values used as SQL LIKE patterns, so _, % and \\ match literally.`,+ },+ messages: {+ unescaped: `{{where}} treats _, % and \\ in this value as wildcards. Wrap user input in ${ESCAPE_FUNCTION}().`,+ },+ schema: [],+ },+ defaultOptions: [],+ create(context) {+ return {+ Property(node) {+ if (+ node.computed ||+ node.parent.type !== AST_NODE_TYPES.ObjectExpression+ )+ return;+ const key = getStaticPropertyKeyValue(node.key) ?? "";++ const isLikeKey = PRISMA_LIKE_KEYS.has(key);+ const isInsensitiveMatch =+ PRISMA_INSENSITIVE_KEYS.has(key) &&+ node.value.type !== AST_NODE_TYPES.ObjectExpression &&+ isInsensitive(node.parent, context);+ if (!isLikeKey && !isInsensitiveMatch) return;++ if (isEscaped(node.value, context)) return;++ context.report({+ node: node.value,+ messageId: "unescaped",+ data: {+ where: isInsensitiveMatch+ ? `Prisma insensitive \`${key}\` (ILIKE)`+ : `Prisma \`${key}\``,+ },+ });+ },+ TaggedTemplateExpression(node) {+ if (!isSqlTag(node.tag)) return;+ const { quasis, expressions } = node.quasi;+ let inPattern = false;+ expressions.forEach((expression, i) => {+ const before = quasis[i].value.raw;+ inPattern =+ LIKE_OPERAND_SUFFIX.test(before) ||+ (inPattern && PATTERN_CONCAT.test(before));+ if (!inPattern) return;+ if (isEscaped(expression, context)) return;+ context.report({+ node: expression,+ messageId: "unescaped",+ data: { where: "SQL LIKE" },+ });+ });+ },+ };+ },+});++export default rule;diff --git a/web/src/features/ai-gateway/server/provider/connection/gatewayProviderRepository.ts b/web/src/features/ai-gateway/server/provider/connection/gatewayProviderRepository.tsindex 0ea00f1347..ffb9470013 100644--- a/web/src/features/ai-gateway/server/provider/connection/gatewayProviderRepository.ts+++ b/web/src/features/ai-gateway/server/provider/connection/gatewayProviderRepository.ts@@ -91,6 +91,7 @@ export class GatewayProviderRepository {const candidates = await this.prisma.gatewayAiConnection.findMany({where: {organizationId: params.organizationId,+ // eslint-disable-next-line @repo/no-unescaped-prisma-like-pattern -- re-checked by exact lowercase match belowname: { equals: params.name, mode: "insensitive" },...(params.excludeId ? { id: { not: params.excludeId } } : {}),},