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.

fix(api): return closed-set database errors, log the detail server-side

Raul38143f08d9bd
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index d17112ec72..e4a65d3c30 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -311,20 +311,33 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separate
`{ data, error, count }` envelope is **unwrapped by the dispatch**:
`callOperation` returns `{ success: true, data, count? }` or
`{ success: false, error, errorKind: "database" | "execution" }`. The raw error
- rides on `ORPCError.data.supabase`, and the `Database error:` envelope carries
- one of two things depending on what failed:
- - A **PostgREST/Postgres** failure keeps MCP's exact
- `Database error: ${JSON.stringify(error)}` text, byte for byte (pinned by
- `dispatch-parity.test.ts`), and HTTP callers get the Postgres
- `code`/`details`/`hint` in the 400 body.
- - A **`FunctionsHttpError`** (an edge function answered non-2xx) carries the
- function's own message instead — `Database error: The process is not
- batchable` — read off the unread `Response` on `error.context` by
- `edgeFunctionMessage` (`call.server.ts`, wrapping `getEdgeFunctionErrorMessage`
- from `~/utils/error`). `JSON.stringify` empties that `Response`, so without
- the unwrap every edge failure — a broken business rule and a malformed payload
- alike — reached the caller as the same `{"name":"FunctionsHttpError","context":{}}`.
- Falls back to the stringified error when the body carries no usable message.
+ rides on `ORPCError.data.supabase`, and the two surfaces treat it differently:
+ - `CallResult.error` (MCP, the in-app agent, workflows) carries a **fixed
+ message from the closed set** in `api+/v1+/lib/database-errors.ts` —
+ `conflict`, `reference`, `required`, `permission`, `notFound`, `rule`,
+ `unknown`. `classifyDatabaseFailure` picks one from STRUCTURED fields only
+ (a Postgres SQLSTATE, or the `FunctionsHttpError` name); message text is never
+ parsed, since parsing it would make the public string a function of the private
+ one. It used to interpolate `JSON.stringify(error)`, which handed a caller the
+ column, constraint and value out of the PostgREST body, and later an edge
+ function's own text — CWE-209 either way.
+ - The **full detail is logged** instead (`logger.error("Operation failed", …)` in
+ `call.server.ts`) with the operation name, the classification, the raw Supabase
+ error, and — for an edge function — the message read off the unread `Response`
+ on `error.context` by `edgeFunctionMessage`. Without that read the log would
+ hold an empty `{"name":"FunctionsHttpError","context":{}}` rather than the rule
+ that fired ("The process is not batchable"), so a business-rule rejection and a
+ malformed payload would be indistinguishable in the log too.
+ - **HTTP is a separate path and is unchanged**: a 400 body is serialized from the
+ `ORPCError` by the oRPC handler, never from `CallResult`, so HTTP callers still
+ receive the Postgres `code`/`details`/`hint`. Narrowing that is a separate
+ decision about the public API.
+
+ The consequence is deliberate and worth knowing when debugging an agent: a
+ business rule an agent could act on ("already in a batch") now reads as the
+ generic `rule` message, and the specific cause is in the server log. An
+ enumerated code returned by the edge functions themselves, mapped to public
+ strings here, is the way to give that back without echoing server text.
- The dispatch behavior is pinned by
`api+/v1+/lib/dispatch-parity.test.ts` (golden cases carried over from the
deleted `executeFunction`) — a change there is a behavior change for MCP,
diff --git a/apps/erp/app/routes/api+/v1+/lib/call.server.ts b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
index 8de8cf69f4..8868be75f9 100644
--- a/apps/erp/app/routes/api+/v1+/lib/call.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
@@ -4,11 +4,16 @@
// server-side call(), and folds the outcome back into the { success, … } envelope
// the legacy executeFunction callers expect.
+import { getLogger } from "@carbon/logger";
import { call, ORPCError } from "@orpc/server";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { isMcpBlockedTool } from "../../mcp+/lib/mcp-blocked-tools";
import { unwrapArgsEnvelope } from "./args-envelope";
import type { AuthedContext } from "./base.server";
+import {
+ classifyDatabaseFailure,
+ publicDatabaseError
+} from "./database-errors";
import {
operationId,
operationsByName,
@@ -21,6 +26,8 @@ import {
type StandardIssue
} from "./validation-issues";
+const logger = getLogger("erp", "api", "call-operation");
+
export type CallResult =
| { success: true; data: unknown; count?: number }
| { success: false; error: string; errorKind: "database" | "execution" };
@@ -96,16 +103,24 @@ export async function callOperation(
? (err.data as { supabase?: unknown } | undefined)?.supabase
: undefined;
if (supabase) {
- // An edge-function failure carries its real message in an unread Response on
- // `context`, which JSON.stringify empties — every failure from "the process is
- // not batchable" to a missing field reached the caller as the same
- // `{"name":"FunctionsHttpError","context":{}}`. Unwrap it with the helper the
- // routes already use; anything else keeps the byte-exact legacy text, which
- // the dispatch parity tests assert.
+ // The caller gets a fixed message from the closed set in database-errors.ts
+ // — never the serialized PostgREST body (which names columns, constraints
+ // and values) and never an edge function's own text, both of which are
+ // server-authored strings this surface should not echo (CWE-209). The full
+ // detail goes to the server log instead, keyed by operation name, and an
+ // edge function's message is read off its unread Response so the log has
+ // the rule that actually fired ("The process is not batchable") rather than
+ // an empty `{"name":"FunctionsHttpError","context":{}}`.
const edgeMessage = await edgeFunctionMessage(supabase);
+ logger.error("Operation failed", {
+ name,
+ kind: classifyDatabaseFailure(supabase),
+ supabase,
+ ...(edgeMessage ? { edgeMessage } : {})
+ });
return {
success: false,
- error: `Database error: ${edgeMessage ?? JSON.stringify(supabase)}`,
+ error: publicDatabaseError(supabase),
errorKind: "database"
};
}
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
new file mode 100644
index 0000000000..5c45306d7b
--- /dev/null
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import {
+ classifyDatabaseFailure,
+ DATABASE_ERROR_MESSAGES,
+ publicDatabaseError
+} from "./database-errors";
+
+// The point of the closed set is that no server-authored text can reach an API
+// caller through it (CWE-209), so the tests that matter are the ones proving a
+// message with secrets in it cannot come back out.
+
+describe("classifyDatabaseFailure", () => {
+ it.each([
+ ["23505", "conflict"],
+ ["23503", "reference"],
+ ["23502", "required"],
+ ["42501", "permission"],
+ ["PGRST116", "notFound"]
+ ] as const)("maps SQLSTATE %s to %s", (code, kind) => {
+ expect(classifyDatabaseFailure({ code, message: "boom" })).toBe(kind);
+ });
+
+ it("maps an edge-function failure by its constructor name", () => {
+ expect(
+ classifyDatabaseFailure({ name: "FunctionsHttpError", context: {} })
+ ).toBe("rule");
+ });
+
+ it("falls back to unknown for an unrecognized or absent code", () => {
+ expect(classifyDatabaseFailure({ code: "XX000" })).toBe("unknown");
+ expect(classifyDatabaseFailure({ message: "boom" })).toBe("unknown");
+ expect(classifyDatabaseFailure(null)).toBe("unknown");
+ expect(classifyDatabaseFailure(undefined)).toBe("unknown");
+ expect(classifyDatabaseFailure("boom")).toBe("unknown");
+ });
+
+ it("classifies on structured fields, never on message text", () => {
+ // A message that looks like a conflict must not be read as one — parsing text
+ // is what makes a public string a function of a private one.
+ expect(
+ classifyDatabaseFailure({ message: "duplicate key value violates 23505" })
+ ).toBe("unknown");
+ });
+});
+
+describe("publicDatabaseError", () => {
+ it("returns only strings from the closed set", () => {
+ const allowed = Object.values(DATABASE_ERROR_MESSAGES);
+ for (const error of [
+ {
+ code: "23505",
+ message: "duplicate key value violates unique constraint"
+ },
+ {
+ code: "42501",
+ details: "user 48e8db84 lacks privilege on table employee"
+ },
+ { name: "FunctionsHttpError", context: {} },
+ { code: "XX000" },
+ null
+ ]) {
+ expect(allowed).toContain(publicDatabaseError(error));
+ }
+ });
+
+ it("leaks nothing from the underlying error", () => {
+ const error = {
+ code: "23505",
+ message:
+ 'duplicate key value violates unique constraint "employee_email_key"',
+ details: "Key (email)=([email protected]) already exists.",
+ hint: "try another email"
+ };
+ const publicMessage = publicDatabaseError(error);
+
+ expect(publicMessage).toBe(DATABASE_ERROR_MESSAGES.conflict);
+ for (const secret of [
+ "employee_email_key",
+ "duplicate key",
+ "email",
+ "hint"
+ ]) {
+ expect(publicMessage).not.toContain(secret);
+ }
+ });
+
+ it("never interpolates — every message is a constant", () => {
+ for (const message of Object.values(DATABASE_ERROR_MESSAGES)) {
+ expect(message).toMatch(/^Database error: [a-z]/);
+ expect(message).not.toMatch(/[${}]/);
+ }
+ });
+});
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
new file mode 100644
index 0000000000..5b36ef3ed3
--- /dev/null
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
@@ -0,0 +1,71 @@
+// The PUBLIC face of a failed operation, for `callOperation`'s callers (MCP, the
+// in-app agent, the workflow dispatcher). Kept out of call.server.ts so it can be
+// tested without loading the service registry, the same split as
+// validation-issues.ts and args-envelope.ts.
+//
+// Nothing from the underlying error reaches the caller: neither a serialized
+// PostgREST body (whose code/details/hint name columns, constraints and values)
+// nor an edge function's own message text. The caller gets one of the fixed
+// strings below, chosen from the error's STRUCTURED fields only, and the full
+// detail is logged server-side where support can read it (CWE-209).
+//
+// The HTTP surface is a different path and is unchanged: an HTTP caller's 400
+// body is serialized from the ORPCError by the oRPC handler, never from
+// `CallResult`.
+
+/** What went wrong, at the granularity a caller can act on. */
+export type DatabaseFailureKind =
+ | "conflict"
+ | "reference"
+ | "required"
+ | "permission"
+ | "notFound"
+ | "rule"
+ | "unknown";
+
+/**
+ * The closed set. Every message is a fixed string — no interpolation, ever, or
+ * this stops being a closed set.
+ */
+export const DATABASE_ERROR_MESSAGES: Record<DatabaseFailureKind, string> = {
+ conflict: "Database error: a record with these values already exists.",
+ reference: "Database error: a referenced record does not exist.",
+ required: "Database error: a required field was missing.",
+ permission:
+ "Database error: this credential is not permitted to perform that operation.",
+ notFound: "Database error: no matching record was found.",
+ rule: "Database error: the operation was rejected by a server-side rule.",
+ unknown: "Database error: the operation could not be completed."
+};
+
+/**
+ * Classify from structured fields only — a Postgres SQLSTATE, or the error's own
+ * constructor name for an edge-function failure. Message text is never parsed: it
+ * is the thing being withheld, and matching on it would make the public message a
+ * function of private text.
+ */
+export function classifyDatabaseFailure(error: unknown): DatabaseFailureKind {
+ const candidate = error as { code?: unknown; name?: unknown } | null;
+ if (candidate?.name === "FunctionsHttpError") return "rule";
+
+ const code = typeof candidate?.code === "string" ? candidate.code : "";
+ switch (code) {
+ case "23505":
+ return "conflict";
+ case "23503":
+ return "reference";
+ case "23502":
+ return "required";
+ case "42501":
+ return "permission";
+ case "PGRST116":
+ return "notFound";
+ default:
+ return "unknown";
+ }
+}
+
+/** The public message for a failure. */
+export function publicDatabaseError(error: unknown): string {
+ return DATABASE_ERROR_MESSAGES[classifyDatabaseFailure(error)];
+}
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index 56a590d89d..350f471522 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -92,6 +92,7 @@ vi.mock("@carbon/logger", () => ({
import { MCP_BLOCKED_TOOL_NAMES } from "../../mcp+/lib/mcp-blocked-tools";
import type { AuthedContext } from "./base.server";
import { callOperation } from "./call.server";
+import { DATABASE_ERROR_MESSAGES } from "./database-errors";
import {
type DispatchResult,
dispatchOperation,
@@ -494,8 +495,9 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
expect(r.dispatchError).toBeInstanceOf(ORPCError);
const orpcError = r.dispatchError as ORPCError<string, unknown>;
expect(orpcError.message).toBe("duplicate key value");
- // The raw error rides on the ORPCError so callOperation can reconstruct MCP's
- // byte-identical `Database error: ${JSON.stringify(error)}` text.
+ // The raw error rides on the ORPCError: callOperation classifies it into a
+ // public message and logs the detail, and the HTTP handler serializes it into
+ // the 400 body.
expect(
(orpcError.data as { supabase?: unknown } | undefined)?.supabase
).toEqual(supabaseError);
@@ -684,7 +686,11 @@ describe("callOperation (the MCP/agent/workflow entry point)", () => {
expect(idIn((asList as { data: unknown }).data)).toBe("rec_2");
});
- it("maps a Supabase error to the errorKind:database envelope with MCP's exact text", async () => {
+ it("maps a Supabase error to the errorKind:database envelope with a closed-set message", async () => {
+ // The envelope shape is the parity contract; the TEXT deliberately is not.
+ // It used to be `Database error: ${JSON.stringify(error)}`, which handed an
+ // API caller the column, constraint and value out of the PostgREST body
+ // (CWE-209). The detail now goes to the server log instead.
const supabaseError = { message: "boom", code: "XX000" };
spies.getAccountLedger.mockResolvedValue({
data: null,
@@ -698,7 +704,30 @@ describe("callOperation (the MCP/agent/workflow entry point)", () => {
expect(result).toEqual({
success: false,
errorKind: "database",
- error: `Database error: ${JSON.stringify(supabaseError)}`
+ error: DATABASE_ERROR_MESSAGES.unknown
+ });
+ expect(result).not.toMatchObject({
+ error: expect.stringContaining("boom")
+ });
+ });
+
+ it("classifies a recognized failure without echoing the error", async () => {
+ spies.getAccountLedger.mockResolvedValue({
+ data: null,
+ error: {
+ code: "23505",
+ message: 'duplicate key value violates unique constraint "ledger_pkey"'
+ }
+ });
+ const result = await callOperation(
+ "accounting_getAccountLedger",
+ ctx,
+ LEDGER_ARGS
+ );
+ expect(result).toEqual({
+ success: false,
+ errorKind: "database",
+ error: DATABASE_ERROR_MESSAGES.conflict
});
});
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
index e859bcea84..49a44890f6 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
@@ -366,9 +366,9 @@ export async function dispatchOperation(
if (result && typeof result === "object" && "data" in result) {
const r = result as { data: unknown; error?: unknown; count?: number };
if (r.error) {
- // The raw error rides along so callOperation can reconstruct MCP's
- // byte-identical `Database error: ${JSON.stringify(error)}` text, and HTTP
- // callers get the Postgres code/details/hint the way Supabase REST does.
+ // The raw error rides along so callOperation can classify it into a public
+ // message and log the detail, and so HTTP callers get the Postgres
+ // code/details/hint the way Supabase REST does.
throw new ORPCError("BAD_REQUEST", {
message: supabaseErrorMessage(r.error),
data: { supabase: r.error }