Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

6.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import type { ConformanceCheck, Violation } from "../check";

/**
 * RLS policies and the managed functions are authored only as files — the manifest and
 * packages/database/src/authz/helpers/<name>.sql for RLS, and
 * packages/database/src/event-system/functions/<name>.sql for the event system — and
 * `authz sync` applies them after migrations. A migration that creates or alters a policy,
 * or defines, alters or drops a managed function, would be silently overwritten at the next
 * sync — or reintroduce exactly the drift the files exist to stop (a redefinition once
 * turned get_companies_with_employee_permission from STABLE back to VOLATILE; a fork of
 * create_audit_log_table made every audit write run DDL).
 *
 * `DROP POLICY` stays allowed: dropping a column a policy uses needs the policy gone
 * first, and the next sync recreates the table's policies from the manifest.
 *
 * Only migrations after a set was taken over are checked; older ones are history.
 */
const SINCE = "20260927000000";
/** The migration that took over the event-system functions. */
const EVENT_SYSTEM_SINCE = "20261002114954";

/**
 * The migration that took over the table handlers (interceptors and statement
 * handlers) and the event triggers that attach them.
 */
const ATTACHMENTS_SINCE = "20261004194527";

/** The directories of managed function files, and the migration each set is checked from. */
export const MANAGED_FUNCTION_SETS = [
  { dir: "packages/database/src/authz/helpers", since: SINCE },
  {
    dir: "packages/database/src/event-system/functions",
    since: EVENT_SYSTEM_SINCE
  },
  {
    dir: "packages/database/src/event-system/handlers",
    since: ATTACHMENTS_SINCE
  }
];

// Each of these replaces a table's whole list of handlers, so a call that
// leaves one out detaches it. The lists live in one place instead:
// packages/database/src/event-system/attachments.ts.
const ATTACH_CALL =
  /\b(attach_event_trigger|attach_statement_handler|set_event_triggers)\s*\(/gi;

/** `file` is `<name>.sql` for public, `<schema>.<name>.sql` otherwise. */
export type ManagedFunction = {
  schema: string;
  name: string;
  /** Repo-relative path of the file that defines it. */
  file: string;
  since: string;
};

/**
 * The first line of a migration rendered from the manifest by `authz migration` — the WHOLE
 * line, equal to GENERATED_HEADER in packages/database/src/authz/migration.ts (pinned by this
 * check's test). Those files carry policy and helper DDL on purpose, and @carbon/database's
 * migration.test.ts verifies the contents of exactly the files that start with that full line.
 * Matching only a prefix here let a hand-written file with an edited suffix skip both.
 */
export const GENERATED_AUTHZ_MIGRATION =
  "-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.";

// Group 2 is the schema when the statement names one, group 3 the function.
const NAME = String.raw`(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?`;
// The target may be on a later line; group 2 is its schema, when it names one. The manifest
// owns public tables and realtime.messages (broadcast authorization); storage.objects
// (bucket) policies stay in migrations.
const MANIFEST_SCHEMAS = new Set(["public", "realtime"]);
const POLICY_DDL =
  /\b(?:CREATE|ALTER)\s+POLICY\s+(?:"[^"]*"|\S+)\s+ON\s+(?:"?(\w+)"?\s*\.\s*)?"?\w+"?/gi;
const FUNCTION_DDL = new RegExp(
  String.raw`\b(CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION|ALTER\s+FUNCTION|DROP\s+FUNCTION(?:\s+IF\s+EXISTS)?)\s+${NAME}`,
  "gi"
);

/** Blank out comments, keeping newlines so line numbers stay right. */
const stripComments = (sql: string) =>
  sql
    .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
    .replace(/--[^\n]*/g, (m) => " ".repeat(m.length));

export const noAuthzDdlInMigrations = (
  functions: ManagedFunction[]
): ConformanceCheck => ({
  id: "no-authz-ddl-in-migrations",
  description:
    "Policies, RLS helpers, event-system functions and event triggers are authored as files, not migrations.",
  provenance: {
    deprecates: "CREATE/ALTER POLICY and managed function DDL in migrations",
    replacedBy:
      "packages/database/src/authz (manifest.ts + helpers/*.sql) and packages/database/src/event-system/functions/*.sql",
    since: SINCE
  },
  scan(file, contents) {
    const timestamp = /^(\d{14})_/.exec(file)?.[1];
    if (
      !timestamp ||
      timestamp < SINCE ||
      contents.startsWith(GENERATED_AUTHZ_MIGRATION)
    )
      return [];

    const managed = new Map(
      functions.map((f) => [`${f.schema}.${f.name}`.toLowerCase(), f])
    );
    const sql = stripComments(contents);
    const line = (index: number) => sql.slice(0, index).split("\n").length;
    const violations: Violation[] = [];
    for (const m of sql.matchAll(POLICY_DDL)) {
      if (!MANIFEST_SCHEMAS.has((m[1] ?? "public").toLowerCase())) continue;
      violations.push({
        file,
        line: line(m.index),
        snippet: m[0].split("\n")[0] ?? m[0],
        message:
          "Author policies in packages/database/src/authz/manifest.ts, then run `pnpm --filter @carbon/database authz migration <name>`."
      });
    }
    if (timestamp >= ATTACHMENTS_SINCE) {
      for (const m of sql.matchAll(ATTACH_CALL)) {
        violations.push({
          file,
          line: line(m.index),
          snippet: m[0],
          message:
            "Declare event triggers in packages/database/src/event-system/attachments.ts, then run `pnpm --filter @carbon/database authz migration <name>`."
        });
      }
    }
    for (const m of sql.matchAll(FUNCTION_DDL)) {
      const fn = managed.get(`${m[2] ?? "public"}.${m[3]}`.toLowerCase());
      if (!fn || timestamp < fn.since) continue;
      violations.push({
        file,
        line: line(m.index),
        snippet: m[0],
        message: `${m[3]} is a managed function; edit ${fn.file}, then run \`pnpm --filter @carbon/database authz migration <name>\`.`
      });
    }
    return violations;
  }
});