diff --git a/server/eslint-rules/transactions-through-unit-of-work.mjs b/server/eslint-rules/transactions-through-unit-of-work.mjs new file mode 100644 index 000000000..8ffcb47fd --- /dev/null +++ b/server/eslint-rules/transactions-through-unit-of-work.mjs @@ -0,0 +1,62 @@ +/** + * trek/transactions-through-unit-of-work: every transaction under src/ goes + * through `UnitOfWork.transactional` (or `writeTransaction`, which it wraps). + * + * On SQLite one connection writes one transaction at a time, so a check read + * inside a transaction (a `MAX(...) + 1` position, a count under a cap, an + * existence before an insert) still held at the write that followed. On + * Postgres a pool runs transactions side by side, and only the engine's write + * lock (`DatabaseEngine.serializeWrites`), which `UnitOfWork` takes first, + * puts them one after the other again. A transaction opened any other way, + * `em.transactional(...)`, a repository's `getEntityManager().transactional(...)`, + * `em.begin()`, a connection's `transactional(...)` or Kysely's + * `db.transaction()`, does not take that lock, and its check can be raced. + * + * The rule reads the receiver's type: `transactional` is reported on anything + * but a `UnitOfWork` (an untyped receiver included, so it fails closed), and + * `begin`/`transaction` on an EntityManager, a connection or a Kysely + * instance (better-sqlite3's own `transaction()`, the plugin's private SQLite + * file, and unrelated `begin()` methods stay out of it). The engine and the + * boot-time schema files open their own transactions on purpose and are left + * out in eslint.config.mjs, each with its reason. + */ +const OPENERS = new Set(['transactional', 'begin', 'transaction']); +const DATABASE_HANDLE = /EntityManager|Connection|^Kysely\b/; + +export default { + meta: { + type: 'problem', + docs: { + description: + 'Open transactions only through UnitOfWork.transactional, which takes the engine write lock on Postgres', + }, + schema: [], + messages: { + direct: + '`.{{method}}(...)` opens a transaction without the engine write lock. Use `UnitOfWork.transactional` ' + + '(src/nest/database/unit-of-work.ts; outside the Nest container `writeTransaction` from ' + + 'src/db/engine/write-transaction.ts), and read every check its write relies on (a count, an existence, ' + + "a MAX + 1) inside it. A repository method runs inside its caller's unit of work instead of opening one. " + + 'See server/CLAUDE.md, "Transactions are not optional".', + }, + }, + create(context) { + const services = context.sourceCode.parserServices; + if (!services?.program) return {}; + const checker = services.program.getTypeChecker(); + + return { + CallExpression(node) { + const callee = node.callee; + if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier') return; + const method = callee.property.name; + if (!OPENERS.has(method)) return; + const type = services.getTypeAtLocation(callee.object); + const symbol = (type.getSymbol() ?? type.aliasSymbol)?.getName(); + if (symbol === 'UnitOfWork') return; + if (method !== 'transactional' && !DATABASE_HANDLE.test(checker.typeToString(type))) return; + context.report({ node, messageId: 'direct', data: { method } }); + }, + }; + }, +}; diff --git a/server/eslint.config.mjs b/server/eslint.config.mjs index ec3e9fa41..6c587bb38 100644 --- a/server/eslint.config.mjs +++ b/server/eslint.config.mjs @@ -1,13 +1,18 @@ +import noPromiseAsValue from './eslint-rules/no-promise-as-value.mjs'; +import transactionsThroughUnitOfWork from './eslint-rules/transactions-through-unit-of-work.mjs'; import js from '@eslint/js'; import gitignore from 'eslint-config-flat-gitignore'; import eslintConfigPrettier from 'eslint-config-prettier'; import tseslint from 'typescript-eslint'; -import noPromiseAsValue from './eslint-rules/no-promise-as-value.mjs'; - // Local rules live in eslint-rules/ and are exposed under the `trek/` prefix. -const trek = { rules: { 'no-promise-as-value': noPromiseAsValue } }; +const trek = { + rules: { + 'no-promise-as-value': noPromiseAsValue, + 'transactions-through-unit-of-work': transactionsThroughUnitOfWork, + }, +}; // The calls the outbound-timeout selectors below look at: the platform fetch and // the SSRF-guarded wrappers whose init is passed on to it. safeFetchLlm is not @@ -126,8 +131,15 @@ const STRING_SQL_SELECTORS = [ const APP_SETTING_MESSAGE = "Read an app setting through readAppSetting()/resolveAppSetting() from src/nest/common/app-settings.registry.ts, not getValue(''): the register types the key and owns its env override."; const APP_SETTING_SELECTORS = [ - { selector: "CallExpression[callee.property.name='getValue'] > Literal.arguments:first-child", message: APP_SETTING_MESSAGE }, - { selector: "CallExpression[callee.property.name='getValue'] > TemplateLiteral.arguments:first-child[expressions.length=0]", message: APP_SETTING_MESSAGE }, + { + selector: "CallExpression[callee.property.name='getValue'] > Literal.arguments:first-child", + message: APP_SETTING_MESSAGE, + }, + { + selector: + "CallExpression[callee.property.name='getValue'] > TemplateLiteral.arguments:first-child[expressions.length=0]", + message: APP_SETTING_MESSAGE, + }, ]; // The demo-mode write block runs once, in the MCP registry (trekDemoToolGate in @@ -136,7 +148,7 @@ const APP_SETTING_SELECTORS = [ const DEMO_GATE_MESSAGE = 'MCP tools do not check demo mode themselves: the registry gate (trekDemoToolGate) refuses every tool not annotated read-only. Annotate the tool instead.'; const MCP_DEMO_SELECTORS = [ - { selector: "CallExpression[callee.property.name=/^isDemoUser(Id)?$/]", message: DEMO_GATE_MESSAGE }, + { selector: 'CallExpression[callee.property.name=/^isDemoUser(Id)?$/]', message: DEMO_GATE_MESSAGE }, { selector: "CallExpression[callee.name='demoDenied']", message: DEMO_GATE_MESSAGE }, ]; @@ -278,13 +290,39 @@ export default tseslint.config( 'no-restricted-syntax': ['error', ...ENV_SELECTORS, ...FETCH_SELECTORS, ...APP_SETTING_SELECTORS], }, }, + { + // Every transaction goes through UnitOfWork.transactional (or writeTransaction, + // which it wraps), the only ones that take the engine's write lock: on + // Postgres a transaction opened any other way runs beside the others, and a + // check read inside it can be raced. See eslint-rules/transactions-through-unit-of-work.mjs. + files: ['src/**/*.ts'], + ignores: [ + // The engine: writeTransaction itself, the schema bootstrap, the parity + // diff, the move from SQLite and the plugin data schemas, each on a + // connection or database of its own. + 'src/db/engine/**', + // Boot-time schema steps on the raw connection, before the server takes a request. + 'src/db/email-case-index.ts', + 'src/db/legacy-baseline.ts', + ], + plugins: { trek }, + rules: { + 'trek/transactions-through-unit-of-work': 'error', + }, + }, { // Restates the config-access and app-setting guards above for *.mcp.ts // (a later block's options replace an earlier one's) and adds the // demo-gate wall. files: ['src/**/*.mcp.ts'], rules: { - 'no-restricted-syntax': ['error', ...ENV_SELECTORS, ...FETCH_SELECTORS, ...APP_SETTING_SELECTORS, ...MCP_DEMO_SELECTORS], + 'no-restricted-syntax': [ + 'error', + ...ENV_SELECTORS, + ...FETCH_SELECTORS, + ...APP_SETTING_SELECTORS, + ...MCP_DEMO_SELECTORS, + ], }, }, { diff --git a/server/tests/unit/eslint-rules/transactions-through-unit-of-work.test.ts b/server/tests/unit/eslint-rules/transactions-through-unit-of-work.test.ts new file mode 100644 index 000000000..3f1d49298 --- /dev/null +++ b/server/tests/unit/eslint-rules/transactions-through-unit-of-work.test.ts @@ -0,0 +1,77 @@ +import transactionsThroughUnitOfWork from '../../../eslint-rules/transactions-through-unit-of-work.mjs'; +import tsParser from '@typescript-eslint/parser'; + +import { RuleTester, type Rule } from 'eslint'; +import path from 'path'; + +// TXGATE: the rule reads the receiver's type, so the tester runs against a real +// TypeScript program, the fixture project no-promise-as-value.test.ts uses +// (eslint-rules/fixtures/, outside src/ and tests/). Per-file mode on CI too, +// for the reason given there. +const fixtureRoot = path.resolve(__dirname, '../../../eslint-rules/fixtures'); +const filename = path.join(fixtureRoot, 'file.ts'); + +const ruleTester = new RuleTester({ + languageOptions: { + parser: tsParser, + parserOptions: { + project: './tsconfig.json', + tsconfigRootDir: fixtureRoot, + disallowAutomaticSingleRunInference: true, + }, + }, +}); + +// Stand-ins named like the real classes: the rule goes by the receiver's type name. +const PRELUDE = ` +declare class UnitOfWork { transactional(fn: () => Promise): Promise; } +declare class EntityManager { + transactional(fn: (em: EntityManager) => Promise): Promise; + begin(): Promise; +} +declare class SqlEntityManager extends EntityManager {} +declare class AbstractSqlConnection { transactional(fn: (trx: unknown) => Promise): Promise; begin(): Promise; } +declare class Kysely { transaction(): { execute(fn: (trx: Kysely) => Promise): Promise }; readonly db?: DB; } +declare class Database { transaction unknown>(fn: F): F; } +declare class RouterState { begin(): void; } +declare function writeTransaction(em: EntityManager, engine: unknown, fn: (em: EntityManager) => Promise): Promise; +declare const uow: UnitOfWork; +declare const em: EntityManager; +declare const sqlEm: SqlEntityManager; +declare const connection: AbstractSqlConnection; +declare const kysely: Kysely<{ trips: { id: number } }>; +declare const pluginDb: Database; +declare const state: RouterState; +declare const repo: { getEntityManager(): EntityManager }; +declare const untyped: ReturnType; +`; + +const withPrelude = (code: string) => `${PRELUDE}${code}\n`; + +const valid = [ + // The unit of work, injected or held in a field. + `void uow.transactional(async () => 1);`, + `class S { constructor(private readonly uow: UnitOfWork) {} run() { return this.uow.transactional(async () => 1); } }`, + // The engine's own wrapper for code outside the container. + `void writeTransaction(em, null, async () => 1);`, + // better-sqlite3's transaction() on a plugin's private file, and an unrelated begin(). + `pluginDb.transaction(() => 1)();`, + `state.begin();`, +]; + +const invalid = [ + `void em.transactional(async () => 1);`, + `void sqlEm.transactional(async () => 1);`, + `void repo.getEntityManager().transactional(async () => 1);`, + `void connection.transactional(async () => 1);`, + `void em.begin();`, + `void connection.begin();`, + `void kysely.transaction().execute(async () => 1);`, + // An untyped receiver is reported too: the rule fails closed. + `void untyped.transactional(async () => 1);`, +]; + +ruleTester.run('trek/transactions-through-unit-of-work', transactionsThroughUnitOfWork as unknown as Rule.RuleModule, { + valid: valid.map((code) => ({ code: withPrelude(code), filename })), + invalid: invalid.map((code) => ({ code: withPrelude(code), filename, errors: [{ messageId: 'direct' }] })), +});