import { describe, expect, test, vi } from "vitest"; import { PluginMigrationError, applyPluginMigration, findForbiddenKeyword, sanitizePluginIdForSql, splitStatements, tokenizeSqlIdentifiers, validatePluginMigration, } from "./migrations.js"; describe("sanitizePluginIdForSql", () => { test("dot-form ids become snake_case", () => { expect(sanitizePluginIdForSql("com.acme.slack")).toBe("com_acme_slack"); }); test("hyphens are replaced", () => { expect(sanitizePluginIdForSql("de.hivegrid.hello")).toBe("de_hivegrid_hello"); }); test("rejects identifiers that do not start with a-z", () => { expect(() => sanitizePluginIdForSql("1.bad.id")).toThrow(/cannot be sanitized/u); }); }); describe("splitStatements", () => { test("strips block + line comments and splits on semicolons", () => { const sql = ` -- header comment CREATE TABLE plugin_foo_a (tenantId TEXT NOT NULL); /* block */ CREATE INDEX plugin_foo_a_idx ON plugin_foo_a (tenantId); `; const stmts = splitStatements(sql); expect(stmts).toHaveLength(2); expect(stmts[0]).toMatch(/^CREATE TABLE plugin_foo_a/u); expect(stmts[1]).toMatch(/^CREATE INDEX plugin_foo_a_idx/u); }); }); describe("validatePluginMigration", () => { test("accepts a simple plugin-prefixed CREATE TABLE with tenantId column", () => { const result = validatePluginMigration({ pluginId: "com.acme.slack", sql: "CREATE TABLE plugin_com_acme_slack_messages (id TEXT NOT NULL, tenantId TEXT NOT NULL, body TEXT);", }); expect(result.statements).toHaveLength(1); expect(result.allowedPrefix).toBe("plugin_com_acme_slack_"); }); test("rejects CREATE TABLE without prefix", () => { expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql: "CREATE TABLE messages (id TEXT NOT NULL, tenantId TEXT NOT NULL);", }) ).toThrowError(PluginMigrationError); }); test("rejects CREATE TABLE missing tenantId column", () => { expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql: "CREATE TABLE plugin_com_acme_slack_data (id TEXT NOT NULL);", }) ).toThrow(/tenantId/u); }); test("rejects forbidden tokens", () => { expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql: "DROP DATABASE postgres;", }) ).toThrow(/forbidden token/u); expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql: "GRANT ALL ON plugin_com_acme_slack_data TO public;", }) ).toThrow(/forbidden token/u); }); test("rejects statements other than CREATE TABLE / CREATE INDEX", () => { expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql: "ALTER TABLE plugin_com_acme_slack_data ADD COLUMN x INT;", }) ).toThrow(/Only CREATE TABLE/u); }); test("rejects CREATE INDEX whose table is outside the prefix", () => { expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql: "CREATE INDEX bad_idx ON other_table (id);", }) ).toThrow(/must start with/u); }); }); describe("applyPluginMigration", () => { test("executes each statement via the injected seam", async () => { const executeRawUnsafe = vi.fn().mockResolvedValue(0); const result = await applyPluginMigration( { pluginId: "com.acme.slack", sql: "CREATE TABLE plugin_com_acme_slack_messages (id TEXT NOT NULL, tenantId TEXT NOT NULL);" + "CREATE INDEX plugin_com_acme_slack_messages_idx ON plugin_com_acme_slack_messages (tenantId);", }, { executeRawUnsafe } ); expect(executeRawUnsafe).toHaveBeenCalledTimes(2); expect(result.statements).toHaveLength(2); }); test("wraps execute failure as PluginMigrationError", async () => { const executeRawUnsafe = vi.fn().mockRejectedValue(new Error("relation already exists")); await expect( applyPluginMigration( { pluginId: "com.acme.slack", sql: "CREATE TABLE plugin_com_acme_slack_messages (id TEXT NOT NULL, tenantId TEXT NOT NULL);", }, { executeRawUnsafe } ) ).rejects.toBeInstanceOf(PluginMigrationError); }); // F-007 — per-statement audit log before execute. test("emits a per-statement audit info line before each execute (F-007)", async () => { const executeRawUnsafe = vi.fn().mockResolvedValue(0); const infoMock = vi.fn(); await applyPluginMigration( { pluginId: "com.acme.slack", sql: "CREATE TABLE plugin_com_acme_slack_a (id TEXT NOT NULL, tenantId TEXT NOT NULL);" + "CREATE TABLE plugin_com_acme_slack_b (id TEXT NOT NULL, tenantId TEXT NOT NULL);", }, { executeRawUnsafe, logger: { info: infoMock, error: vi.fn() } } ); const perStatementCalls = infoMock.mock.calls.filter( (call) => call[1] === "plugin.migration.execute_statement" ); expect(perStatementCalls).toHaveLength(2); expect(perStatementCalls[0]![0]).toMatchObject({ pluginId: "com.acme.slack", statementIndex: 0, statementCount: 2, }); expect(perStatementCalls[1]![0]).toMatchObject({ statementIndex: 1 }); // statementPreview is bounded to 200 chars. for (const call of perStatementCalls) { const preview = (call[0] as { statementPreview: string }).statementPreview; expect(preview.length).toBeLessThanOrEqual(200); } }); test("execute_failed log line includes the statement index (F-007)", async () => { const executeRawUnsafe = vi.fn().mockRejectedValue(new Error("boom")); const errorMock = vi.fn(); await expect( applyPluginMigration( { pluginId: "com.acme.slack", sql: "CREATE TABLE plugin_com_acme_slack_a (id TEXT NOT NULL, tenantId TEXT NOT NULL);", }, { executeRawUnsafe, logger: { info: vi.fn(), error: errorMock } } ) ).rejects.toBeInstanceOf(PluginMigrationError); expect(errorMock).toHaveBeenCalled(); expect(errorMock.mock.calls[0]![0]).toMatchObject({ pluginId: "com.acme.slack", statementIndex: 0, }); }); // F-021 — strict tenantId column check. describe("strict tenantId column check (F-021)", () => { test("rejects a table that only mentions tenantId inside a DEFAULT literal", () => { const sql = "CREATE TABLE plugin_com_acme_slack_messages (" + "id TEXT NOT NULL, " + "label TEXT DEFAULT 'has tenantId in the value but no real column'" + ")"; expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql })).toThrow( /tenantId column/ ); try { validatePluginMigration({ pluginId: "com.acme.slack", sql }); } catch (err) { expect((err as PluginMigrationError).code).toBe("missing_tenant_id_column"); } }); test("accepts a table where tenantId is the first column", () => { const sql = "CREATE TABLE plugin_com_acme_slack_messages (" + "tenantId TEXT NOT NULL, id TEXT NOT NULL" + ")"; const result = validatePluginMigration({ pluginId: "com.acme.slack", sql }); expect(result.statements).toHaveLength(1); }); test("accepts a table where tenantId is a later column", () => { const sql = "CREATE TABLE plugin_com_acme_slack_messages (" + "id TEXT NOT NULL, tenantId TEXT NOT NULL, body TEXT" + ")"; const result = validatePluginMigration({ pluginId: "com.acme.slack", sql }); expect(result.statements).toHaveLength(1); }); test("accepts a table with a quoted tenantId column name", () => { const sql = "CREATE TABLE plugin_com_acme_slack_messages (" + `id TEXT NOT NULL, "tenantId" TEXT NOT NULL` + ")"; const result = validatePluginMigration({ pluginId: "com.acme.slack", sql }); expect(result.statements).toHaveLength(1); }); test("still rejects when neither a column nor a default mentions tenantId", () => { const sql = "CREATE TABLE plugin_com_acme_slack_messages (" + "id TEXT NOT NULL, name TEXT NOT NULL" + ")"; expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql })).toThrow( /tenantId column/ ); }); }); // F-008 — statement-count cap. describe("statement-count cap (F-008)", () => { test("rejects migrations declaring more than DEFAULT_MAX_STATEMENTS_PER_MIGRATION (32) statements", () => { const stmts: string[] = []; for (let i = 0; i < 33; i++) { stmts.push(`CREATE TABLE plugin_com_acme_slack_t${i} (id TEXT NOT NULL, tenantId TEXT NOT NULL)`); } const sql = stmts.join(";") + ";"; expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql })).toThrow( PluginMigrationError ); try { validatePluginMigration({ pluginId: "com.acme.slack", sql }); } catch (err) { expect((err as PluginMigrationError).code).toBe("too_many_statements"); } }); test("accepts migrations exactly at the default cap", () => { const stmts: string[] = []; for (let i = 0; i < 32; i++) { stmts.push(`CREATE TABLE plugin_com_acme_slack_t${i} (id TEXT NOT NULL, tenantId TEXT NOT NULL)`); } const result = validatePluginMigration({ pluginId: "com.acme.slack", sql: stmts.join(";") + ";", }); expect(result.statements).toHaveLength(32); }); test("honours a per-call maxStatements override", () => { const sql = "CREATE TABLE plugin_com_acme_slack_a (id TEXT NOT NULL, tenantId TEXT NOT NULL);" + "CREATE TABLE plugin_com_acme_slack_b (id TEXT NOT NULL, tenantId TEXT NOT NULL);" + "CREATE TABLE plugin_com_acme_slack_c (id TEXT NOT NULL, tenantId TEXT NOT NULL);"; expect(() => validatePluginMigration({ pluginId: "com.acme.slack", sql, maxStatements: 2 }) ).toThrow(/cap is 2/); }); }); // F-006 — AST-lite tokenizer behaviour. describe("tokenizer-based forbidden-keyword scan (F-006)", () => { test("tokenizeSqlIdentifiers skips content inside single-quoted strings", () => { const tokens = tokenizeSqlIdentifiers("CREATE TABLE t (label TEXT DEFAULT 'no grant inside')"); const upper = tokens.map((t) => t.text); expect(upper).toContain("CREATE"); expect(upper).toContain("TABLE"); expect(upper).not.toContain("GRANT"); }); test("tokenizeSqlIdentifiers skips content inside dollar-quoted strings", () => { const tokens = tokenizeSqlIdentifiers("CREATE TABLE t (x TEXT DEFAULT $$GRANT something$$)"); expect(tokens.map((t) => t.text)).not.toContain("GRANT"); }); test("tokenizeSqlIdentifiers does descend into block comments / line comments", () => { const tokens = tokenizeSqlIdentifiers("CREATE TABLE t /* GRANT */ (id TEXT)"); expect(tokens.map((t) => t.text)).not.toContain("GRANT"); const tokens2 = tokenizeSqlIdentifiers("CREATE TABLE t (id TEXT) -- GRANT trick\n"); expect(tokens2.map((t) => t.text)).not.toContain("GRANT"); }); test("findForbiddenKeyword catches DROP DATABASE / GRANT / REVOKE / pg_*", () => { expect(findForbiddenKeyword(tokenizeSqlIdentifiers("DROP DATABASE x"))?.keyword).toBe("DROP DATABASE"); expect(findForbiddenKeyword(tokenizeSqlIdentifiers("REVOKE all on t from u"))?.keyword).toBe("REVOKE"); expect(findForbiddenKeyword(tokenizeSqlIdentifiers("SELECT pg_terminate_backend(1)"))?.keyword).toBe("PG_*"); }); test("findForbiddenKeyword returns null when GRANT only appears inside a string literal", () => { const tokens = tokenizeSqlIdentifiers( "CREATE TABLE plugin_demo_x (id TEXT, tenantId TEXT, note TEXT DEFAULT 'GRANT pattern in literal')", ); expect(findForbiddenKeyword(tokens)).toBeNull(); }); test("validatePluginMigration no longer false-positives when GRANT appears only in a DEFAULT literal", () => { const sql = "CREATE TABLE plugin_demo_x_notes (id TEXT NOT NULL, tenantId TEXT NOT NULL, " + "note TEXT NOT NULL DEFAULT 'mentions GRANT in the literal')"; const result = validatePluginMigration({ pluginId: "demo.x", sql }); expect(result.statements).toHaveLength(1); }); test("validatePluginMigration still rejects a real GRANT statement", () => { expect(() => validatePluginMigration({ pluginId: "demo.x", sql: "GRANT ALL ON ALL TABLES IN SCHEMA public TO postgres", }), ).toThrow(/forbidden token/); }); }); });