From 783ac219e2159129a452d477e47d5ed20c61d7cc Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Fri, 13 Nov 2026 10:17:23 -0500
Subject: [PATCH 01/31] fix(python): pass only validated input to the
repository in generated routes (#566)
* fix(python): generated routes hand the repository only the validated input (1.2.1)
The generated FastAPI create, PATCH and PUT handlers validated the body against
Create / Patch and then passed the RAW body to the repository.
Pydantic ignores undeclared keys and the input models leave out server-owned
fields, so a client-sent id, a readOnly field and a made-up field such as
isAdmin all reached the write. Security fix.
Each handler (plain and TPH per-subtype) now rebinds dto to the keys the input
model validated, at every depth, before any repository call, as the TypeScript
routes do. Undeclared and non-settable keys are dropped silently, never 400'd,
so a client sending an extra harmless field keeps working; values stay the
body's own, so repositories see the same value types as in 1.2.0.
Python package version 1.2.1 only; CHANGELOG entry under Security.
Regression gate: tests/integration/test_generated_router_validated_input.py.
* no-mistakes(document): python routes pass only validated input
* no-mistakes(lint): regenerate showcase site payload for PyPI 1.2.1
---
CHANGELOG.md | 28 ++
docs/features/generated-mutations.md | 12 +-
.../.metaobjects/.gen-state/.hashes.json | 2 +-
.../generated/python/subscriber_router.py | 32 ++-
examples/showcase/site-payload.json | 2 +-
server/python/pyproject.toml | 2 +-
.../src/metaobjects/codegen/KNOWN_GAPS.md | 6 +-
.../codegen/generators/router_generator.py | 98 +++++--
.../test_generated_router_validated_input.py | 272 ++++++++++++++++++
server/python/uv.lock | 2 +-
10 files changed, 414 insertions(+), 42 deletions(-)
create mode 100644 server/python/tests/integration/test_generated_router_validated_input.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79042d8184..9fe7ecc774 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,34 @@ here.**
## [Unreleased]
+## [1.2.1] — Python only
+
+_PyPI `1.2.1` only. npm, NuGet and Maven Central stay at `1.2.0` (`8.2.0`): none of them has a
+product change. No vocabulary or `metamodelVersion` change._
+
+### Security
+
+- **The generated Python routes passed raw request input to the repository.** The FastAPI
+ create, PATCH and PUT handlers validated the body against `Create` / `Patch`
+ and then handed the repository the raw body, not what was validated. Pydantic ignores a key a
+ model does not declare, so a client could write fields it must never touch: a client-sent `id`
+ on create (or on update, changing the row's identity), a `@mutability: readOnly` field, and any
+ made-up field such as `isAdmin` all reached the repository. Found by an external review of
+ 1.2.0. Every Python adopter serving the generated routes should upgrade and regenerate; an
+ ejected (owned) router needs the same change made by hand.
+
+ The repository now receives only the validated input, as the TypeScript routes already do.
+ Each handler validates the body, then keeps only the keys the input model validated, at every
+ depth (a nested value object included), before any repository call, in the plain and the TPH
+ per-subtype handlers. A field the entity does not declare, a server-generated id, a `readOnly`
+ or derived field on create, and the id, `readOnly` and `writeOnce` fields on update are all
+ dropped silently. None of them is answered with a 400, so a client that sends an extra harmless
+ field keeps working; a malformed value on a field the client may set is still
+ `400 {"error": "validation"}`. An assigned key is still the caller's on create. Values are the
+ body's own, so a repository receives the same value types as in 1.2.0.
+
+ Gated by `server/python/tests/integration/test_generated_router_validated_input.py`.
+
## [1.2.0] — 2026-10-30
_npm `1.2.0` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._
diff --git a/docs/features/generated-mutations.md b/docs/features/generated-mutations.md
index 57aa6f409a..3a367bbb6f 100644
--- a/docs/features/generated-mutations.md
+++ b/docs/features/generated-mutations.md
@@ -41,7 +41,9 @@ but the semantics are one contract — call them **PATCH-1..7** (FR-035):
simply omits every non-settable field, and Zod drops unknown keys — so
`safeParse` succeeds and the key never reaches the `SET`. The TPH discriminator
is additionally deleted by hand after parse, the same convention. A malformed
- *value* on a settable key is still `400 {"error":"validation"}`.
+ *value* on a settable key is still `400 {"error":"validation"}`. A key the entity
+ does not declare at all is dropped the same way. The Python routes hand the
+ repository only the keys their input model validated.
This matters for `writeOnce` specifically: the generated edit form submits EVERY
registered field (`handleSubmit` passes all values, and 0.19.2 switched the
resolver to `UpdateSchema` on edit rather than diff-and-omit), so rejecting a
@@ -109,10 +111,10 @@ repo.patch(id) { it[Authors.bio] = "…" } // touches only what you set
the controller binds the partial JSON body via `Patch.fromJson` (presence-tracked)
and delegates to `repository.patch`, so an omitted key is never written.
-**Python** — the generated FastAPI route binds the raw JSON body (the set of
-*present* keys — the tristate signal) and validates the present values against the
-generated `Patch` model before delegating to the runtime `update`, which
-`SET`s only those keys.
+**Python** — the generated FastAPI route binds the JSON body (the set of
+*present* keys — the tristate signal), validates the present values against the
+generated `Patch` model, and hands the repository only the keys that model
+validated. The runtime `update` then `SET`s only those keys.
**C#** — the generated route runs a per-field merge loop over the present JSON keys
(the app's configured `JsonSerializerOptions`), writing only the columns the body
diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes.json
index 8a7a4f6bb9..131a0265b9 100644
--- a/examples/showcase/.metaobjects/.gen-state/.hashes.json
+++ b/examples/showcase/.metaobjects/.gen-state/.hashes.json
@@ -10,7 +10,7 @@
"generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5",
"generated/python/subscriber_filter_allowlist.py": "b0414cc95ff3982c80a0e1a06839f090c0b423e41f5a94275df93426cea09df5",
"generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561",
- "generated/python/subscriber_router.py": "5a354e50b1aab48239a4249b670a6d2351c1816cbca6d710ea688f252e9612e5",
+ "generated/python/subscriber_router.py": "f3c81be3c07a10a94afb6a6a0f87eb84b9bca40ead03dd989ebd019f71b97dfc",
"generated/ts/Subscriber.queries.ts": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562",
"generated/ts/Subscriber.routes.ts": "147d32ae658f985e024c3de6e8894ca7359f767eeaa765cec70756802e3bd300",
"generated/ts/Subscriber.ts": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96",
diff --git a/examples/showcase/generated/python/subscriber_router.py b/examples/showcase/generated/python/subscriber_router.py
index 47aaaab7ce..fe148c5e3e 100644
--- a/examples/showcase/generated/python/subscriber_router.py
+++ b/examples/showcase/generated/python/subscriber_router.py
@@ -91,6 +91,26 @@ async def _json_body(request: Request) -> dict[str, Any] | None:
return None
+def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]:
+ """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the
+ input model does not declare (an undeclared name, a server-generated id, a readOnly field)
+ is dropped silently and never reaches the repository; values stay the body's own."""
+ return {
+ _k: _validated_value(getattr(valid, _k), raw[_k])
+ for _k in valid.model_fields_set
+ }
+
+
+def _validated_value(valid: Any, raw: Any) -> Any:
+ if isinstance(valid, BaseModel) and isinstance(raw, dict):
+ return _validated_input(valid, raw)
+ if isinstance(valid, list) and isinstance(raw, list):
+ return [_validated_value(v, r) for v, r in zip(valid, raw)]
+ if isinstance(valid, dict) and isinstance(raw, dict):
+ return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw}
+ return raw
+
+
_FROZEN_FIELDS: frozenset[str] = frozenset()
@@ -198,9 +218,13 @@ def create_subscriber(
# FR-036: run the generated field constraints (length / pattern /
# numeric bounds) before persisting; a violation is the cross-port 400.
try:
- SubscriberCreate(**dto)
+ _valid = SubscriberCreate(**dto)
except ValidationError:
return JSONResponse(status_code=400, content={"error": "validation"})
+ # SECURITY (1.2.1): only what the input model validated reaches the repository. A key
+ # it does not declare (an undeclared name, a server-generated id, a readOnly or derived
+ # field, a frozen one on update) is dropped silently, never 400'd.
+ dto = _validated_input(_valid, dto)
# #203/ADR-0045: stamp @autoSet columns (server-owned; caller ignored).
_asnow = _dt.datetime.now(_dt.timezone.utc)
dto["createdAt"] = _asnow
@@ -239,9 +263,13 @@ def update_subscriber(
# FR-036: validate PRESENT, non-null values with the create rules (the
# all-optional patch model never fires required-checks on ABSENT fields).
try:
- SubscriberPatch(**dto)
+ _valid = SubscriberPatch(**dto)
except ValidationError:
return JSONResponse(status_code=400, content={"error": "validation"})
+ # SECURITY (1.2.1): only what the input model validated reaches the repository. A key
+ # it does not declare (an undeclared name, a server-generated id, a readOnly or derived
+ # field, a frozen one on update) is dropped silently, never 400'd.
+ dto = _validated_input(_valid, dto)
dto.pop("createdAt", None) # onCreate @autoSet is write-once (server-owned)
try:
saved = repo.update(subscriber_id, dto)
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index cc09d97e22..237e16a881 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -1,7 +1,7 @@
{
"registries": {
"npm": "1.2.0",
- "pypi": "1.2.0",
+ "pypi": "1.2.1",
"nuget": "1.2.0",
"maven": "8.2.0",
"metamodel": "1.2"
diff --git a/server/python/pyproject.toml b/server/python/pyproject.toml
index 2854f66cad..2366d3f4bc 100644
--- a/server/python/pyproject.toml
+++ b/server/python/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "metaobjects"
-version = "1.2.0"
+version = "1.2.1"
description = "Cross-language metadata standard: declare typed entities once, generate idiomatic drift-checked code across languages — Python port."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md
index 2cb454b8d7..1b300bfa6f 100644
--- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md
+++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md
@@ -36,9 +36,9 @@ The generated router takes `dto: dict[str, Any]` for `POST` / `PATCH` /
(`from . import , Patch`) and constructs them to enforce
field constraints over HTTP — POST validates `(**dto)`, PATCH validates
the all-optional `Patch(**dto)` (present values only) → `400 {"error":"validation"}`.
-The repository seam still receives the original `dict` (preserving the FR-035
-present-key tristate + wire values), so the strong-typing simplification below
-remains for the repo/response types; only the validation import was added.
+The repository seam receives only the keys the input model validated, as a `dict`
+(the FR-035 present-key tristate + wire values are kept), so the strong-typing
+simplification below remains for the repo/response types.
This keeps the router module decoupled from sibling generated files
(the entity-model generator emits one `@dataclass`/Pydantic model per
diff --git a/server/python/src/metaobjects/codegen/generators/router_generator.py b/server/python/src/metaobjects/codegen/generators/router_generator.py
index 227346832c..9e0586bcdb 100644
--- a/server/python/src/metaobjects/codegen/generators/router_generator.py
+++ b/server/python/src/metaobjects/codegen/generators/router_generator.py
@@ -434,10 +434,9 @@ def _frozen_names(entity: MetaObject) -> list[str]:
ADR-0045: the OUTERMOST generated write artifact enforces the mode, and for
FastAPI that is the ROUTER, not the ``Patch`` model — the handler binds
- ``dto`` (the raw body as a dict) and passes THAT to the repository, so a
- field merely absent from the patch model still reaches the row. @autoSet gets
- away with it because the router OVERWRITES its key server-side; a writeOnce
- field has no server value to overwrite, so it must be popped explicitly."""
+ ``dto`` as a dict. Since 1.2.1 the router hands the repository only the keys the
+ patch model validated (:func:`_validated_input_lines`), which already drops these;
+ the explicit pop stays as the FR-037 seam an owned router edits."""
return [
f.name
for f in entity.fields()
@@ -461,6 +460,49 @@ def _frozen_strip_lines(entity: MetaObject, indent: str = " ") -> list[str]:
]
+#: 1.2.1 security fix. The request body cut down to what the input model validated, emitted
+#: once per writable router. 1.2.0 validated the body and then handed the RAW body to the
+#: repository, so a client-sent server-generated id, a ``readOnly`` field or a name the entity
+#: does not declare (an ``isAdmin``) reached the write. Pydantic ignores a key a model does not
+#: declare, and the input models leave out every field a client may not set, so keeping only
+#: the keys the model validated (at every depth: a nested value object included) drops all of
+#: them silently, as the TypeScript routes do. The values stay the body's own (decimal-exact)
+#: values, so a repository receives the same value types as in 1.2.0.
+_VALIDATED_INPUT_LINES: list[str] = [
+ "def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]:",
+ ' """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the',
+ " input model does not declare (an undeclared name, a server-generated id, a readOnly field)",
+ ' is dropped silently and never reaches the repository; values stay the body\'s own."""',
+ " return {_k: _validated_value(getattr(valid, _k), raw[_k]) for _k in valid.model_fields_set}",
+ "",
+ "",
+ "def _validated_value(valid: Any, raw: Any) -> Any:",
+ " if isinstance(valid, BaseModel) and isinstance(raw, dict):",
+ " return _validated_input(valid, raw)",
+ " if isinstance(valid, list) and isinstance(raw, list):",
+ " return [_validated_value(v, r) for v, r in zip(valid, raw)]",
+ " if isinstance(valid, dict) and isinstance(raw, dict):",
+ " return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw}",
+ " return raw",
+]
+
+
+def _validated_input_lines(model: str, *comment: str) -> list[str]:
+ """Validate ``dto`` against the input *model*, then rebind it to what the model validated
+ (see :data:`_VALIDATED_INPUT_LINES`): the repository never sees any other key."""
+ return [
+ *(f" # {line}" for line in comment),
+ " try:",
+ f" _valid = {model}(**dto)",
+ " except ValidationError:",
+ ' return JSONResponse(status_code=400, content={"error": "validation"})',
+ " # SECURITY (1.2.1): only what the input model validated reaches the repository. A key",
+ " # it does not declare (an undeclared name, a server-generated id, a readOnly or derived",
+ " # field, a frozen one on update) is dropped silently, never 400'd.",
+ " dto = _validated_input(_valid, dto)",
+ ]
+
+
def _auto_set_split(entity: MetaObject) -> tuple[list[MetaField], list[MetaField]]:
"""The entity's ``@autoSet`` temporal fields split into ``(onCreate, onUpdate)``.
@@ -1083,12 +1125,11 @@ def _emit_route_handler(
") -> Any:",
*_DECIMAL_COERCE,
*denied_strip,
- " # FR-036: run the generated field constraints (length / pattern /",
- " # numeric bounds) before persisting; a violation is the cross-port 400.",
- " try:",
- f" {model_name}(**dto)",
- " except ValidationError:",
- ' return JSONResponse(status_code=400, content={"error": "validation"})',
+ *_validated_input_lines(
+ model_name,
+ "FR-036: run the generated field constraints (length / pattern /",
+ "numeric bounds) before persisting; a violation is the cross-port 400.",
+ ),
# #203/ADR-0045: the generated router (the API surface) stamps @autoSet columns
# ABOVE the consumer repo seam — onCreate + onUpdate both stamped from one instant
# (a fresh row's createdAt == updatedAt), ignoring any caller-supplied value.
@@ -1114,12 +1155,11 @@ def _emit_route_handler(
" for _k in _REQUIRED_FIELDS:",
" if _k in dto and dto[_k] is None:",
' return JSONResponse(status_code=400, content={"error": "validation"})',
- " # FR-036: validate PRESENT, non-null values with the create rules (the",
- " # all-optional patch model never fires required-checks on ABSENT fields).",
- " try:",
- f" {patch_model}(**dto)",
- " except ValidationError:",
- ' return JSONResponse(status_code=400, content={"error": "validation"})',
+ *_validated_input_lines(
+ patch_model,
+ "FR-036: validate PRESENT, non-null values with the create rules (the",
+ "all-optional patch model never fires required-checks on ABSENT fields).",
+ ),
# #203/ADR-0045: bump onUpdate @autoSet columns (server-owned) on EVERY patch,
# above the repo seam — a server-inserted present key (compatible with the PATCH
# present-key tristate); onCreate columns are never touched here.
@@ -1468,6 +1508,9 @@ def _render_tph_router(
parts.extend(_JSON_BODY_LINES)
parts.append("")
parts.append("")
+ parts.extend(_VALIDATED_INPUT_LINES)
+ parts.append("")
+ parts.append("")
# FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so
# the generated module always carries the seam (an entity that later gains a
# writeOnce field changes one literal, not the module's shape).
@@ -1547,11 +1590,9 @@ def list_sig(fn: str, route: str) -> list[str]:
parts.append(") -> Any:")
parts.extend(_DECIMAL_COERCE)
parts.extend(denied_strip_tph)
- parts.append(" # FR-036: run the subtype's field constraints before persisting.")
- parts.append(" try:")
- parts.append(f" {sub}Create(**dto)")
- parts.append(" except ValidationError:")
- parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})')
+ parts.extend(_validated_input_lines(
+ f"{sub}Create", "FR-036: run the subtype's field constraints before persisting."
+ ))
# #203/ADR-0045: stamp @autoSet columns ABOVE the repo seam (empty for a
# non-@autoSet hierarchy — byte-identical output).
parts.extend(create_autoset)
@@ -1584,11 +1625,9 @@ def list_sig(fn: str, route: str) -> list[str]:
parts.append(" for _k in _REQUIRED_FIELDS:")
parts.append(" if _k in dto and dto[_k] is None:")
parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})')
- parts.append(" # FR-036: validate PRESENT, non-null values with the subtype's create rules.")
- parts.append(" try:")
- parts.append(f" {sub}Patch(**dto)")
- parts.append(" except ValidationError:")
- parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})')
+ parts.extend(_validated_input_lines(
+ f"{sub}Patch", "FR-036: validate PRESENT, non-null values with the subtype's create rules."
+ ))
# #203/ADR-0045: pop the write-once onCreate column(s), bump onUpdate — ABOVE
# the repo seam (empty for a non-@autoSet hierarchy — byte-identical output).
parts.extend(update_autoset)
@@ -1857,6 +1896,9 @@ def render_router(
parts.extend(_JSON_BODY_LINES)
parts.append("")
parts.append("")
+ parts.extend(_VALIDATED_INPUT_LINES)
+ parts.append("")
+ parts.append("")
# FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so
# the generated module always carries the seam (an entity that later gains a
# writeOnce field changes one literal, not the module's shape).
@@ -1892,8 +1934,8 @@ def render_router(
create_autoset=create_autoset,
update_autoset=update_autoset,
# FR-037 R1 — ADR-0045: the ROUTER is the outermost write artifact for
- # FastAPI (the handler binds the RAW body dict and hands THAT to the
- # repository), so the strip has to live here, not in Patch.
+ # FastAPI (the handler binds the body as a dict), so the strip lives here,
+ # not in Patch.
frozen_strip=_frozen_strip_lines(entity),
denied_strip=_denied_strip_lines(denied_names),
)
diff --git a/server/python/tests/integration/test_generated_router_validated_input.py b/server/python/tests/integration/test_generated_router_validated_input.py
new file mode 100644
index 0000000000..b43ed21c08
--- /dev/null
+++ b/server/python/tests/integration/test_generated_router_validated_input.py
@@ -0,0 +1,272 @@
+"""1.2.1 security fix: a generated create / update hands the repository ONLY the validated input.
+
+The 1.2.0 router validated the request body against ``Create`` / ``Patch`` and
+then passed the RAW body to the repository. Pydantic ignores a key a model does not declare, and
+the input models leave out the server-owned fields, so a client-sent ``id``, a ``readOnly`` field
+and a made-up ``isAdmin`` all reached the write. Now the repository receives only what the input
+model validated, at every depth, as with the TypeScript routes: a name the entity does not
+declare, a server-generated id, a ``readOnly`` field and the id on update are all dropped
+silently. None of them is a 400: a client that sends an extra harmless field keeps working.
+
+The model is generated with the real Python codegen (``run_gen``: entity + filter-allowlist +
+routes), the emitted package is imported unmodified, and the only hand-written piece is a
+repository that records what it was handed. No database: the router is the artifact, as in the
+other generated-router lanes.
+"""
+from __future__ import annotations
+
+import importlib
+import json
+import sys
+import tempfile
+import uuid
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from metaobjects import MetaDataLoader
+from metaobjects.codegen.config import GenConfig
+from metaobjects.codegen.generators.entity_model import entity_model
+from metaobjects.codegen.generators.filter_allowlist_generator import filter_allowlist_generator
+from metaobjects.codegen.generators.router_generator import router_generator
+from metaobjects.codegen.runner import run_gen
+
+from .generated_tph_app import build_generated_tph_app
+
+_META = {
+ "metadata.root": {
+ "package": "acme::secfix",
+ "children": [
+ {"object.value": {
+ "name": "Address",
+ "children": [
+ {"field.string": {"name": "city", "@maxLength": 40}},
+ ],
+ }},
+ {"object.entity": {
+ "name": "Member",
+ "children": [
+ {"source.rdb": {"@table": "members"}},
+ {"field.long": {"name": "id"}},
+ {"field.string": {"name": "name", "@required": True, "@maxLength": 80}},
+ {"field.string": {"name": "role", "@maxLength": 20, "@mutability": "readOnly"}},
+ {"field.string": {"name": "tenant", "@maxLength": 20, "@mutability": "writeOnce"}},
+ {"field.object": {"name": "address", "@objectRef": "Address", "@storage": "jsonb"}},
+ {"field.timestamp": {"name": "createdAt", "@autoSet": "onCreate"}},
+ {"identity.primary": {"name": "id", "@fields": "id", "@generation": "increment"}},
+ ],
+ }},
+ {"object.entity": {
+ "name": "Account",
+ "children": [
+ {"source.rdb": {"@table": "accounts"}},
+ {"field.string": {"name": "code", "@maxLength": 20}},
+ {"field.string": {"name": "label", "@maxLength": 80}},
+ {"identity.primary": {"name": "code", "@fields": "code"}},
+ ],
+ }},
+ ],
+ }
+}
+
+
+class _RecordingRepo:
+ """The generated repository seam, recording every write it is handed."""
+
+ def __init__(self, pk: str) -> None:
+ self.pk = pk
+ self.writes: list[tuple[str, dict[str, Any]]] = []
+
+ def create(self, dto: Any) -> Any:
+ self.writes.append(("create", dict(dto)))
+ return {self.pk: 1, **dto}
+
+ def update(self, id: Any, dto: Any) -> Any | None:
+ self.writes.append(("update", dict(dto)))
+ return {self.pk: id, **dto}
+
+
+def _generate_package() -> str:
+ """Run the real Python codegen for ``_META`` into a temp package; return its name."""
+ meta_dir = Path(tempfile.mkdtemp(prefix="secfix-meta-"))
+ (meta_dir / "meta.json").write_text(json.dumps(_META))
+ loaded = MetaDataLoader.from_directory(str(meta_dir))
+ assert not loaded.errors, "; ".join(f"{e.code}: {e.message}" for e in loaded.errors)
+ pkg = f"secfix_{uuid.uuid4().hex[:8]}"
+ root = Path(tempfile.mkdtemp(prefix="secfix-gen-"))
+ run_gen(
+ GenConfig(out_dir=str(root / pkg)),
+ loaded.root,
+ generators=[entity_model(), filter_allowlist_generator(), router_generator()],
+ )
+ sys.path.insert(0, str(root))
+ return pkg
+
+
+_PKG = _generate_package()
+
+
+def _client(router_module: str, pk: str) -> tuple[TestClient, _RecordingRepo, str]:
+ mod = importlib.import_module(f"{_PKG}.{router_module}")
+ repo = _RecordingRepo(pk)
+ app = FastAPI()
+ app.include_router(mod.router)
+ app.dependency_overrides[mod.get_repository] = lambda: repo
+ return TestClient(app), repo, mod.router.prefix
+
+
+@pytest.fixture()
+def member() -> tuple[TestClient, _RecordingRepo, str]:
+ return _client("member_router", "id")
+
+
+@pytest.fixture()
+def account() -> tuple[TestClient, _RecordingRepo, str]:
+ return _client("account_router", "code")
+
+
+# --- the reported defect: a client-sent id and a made-up isAdmin reach the repository -------
+
+
+def test_create_never_hands_the_repository_a_client_id_or_an_undeclared_field(member) -> None:
+ client, repo, base = member
+ resp = client.post(base, json={"id": 999, "name": "Mallory", "isAdmin": True})
+ assert resp.status_code == 201, resp.text
+ [(op, written)] = repo.writes
+ assert op == "create"
+ assert set(written) == {"name", "createdAt"} # createdAt is the router's own stamp
+ assert written["name"] == "Mallory"
+
+
+@pytest.mark.parametrize("method", ["PATCH", "PUT"])
+def test_update_never_hands_the_repository_an_undeclared_field(member, method: str) -> None:
+ client, repo, base = member
+ resp = client.request(method, f"{base}/1", json={"name": "M", "isAdmin": True})
+ assert resp.status_code == 200, resp.text
+ assert repo.writes == [("update", {"name": "M"})]
+
+
+def test_an_undeclared_key_inside_a_value_object_never_reaches_the_repository(member) -> None:
+ client, repo, base = member
+ resp = client.post(base, json={"name": "Mallory", "address": {"city": "Oslo", "isAdmin": True}})
+ assert resp.status_code == 201, resp.text
+ [(_op, written)] = repo.writes
+ assert written["address"] == {"city": "Oslo"}
+
+
+def test_a_malformed_value_on_a_settable_field_is_still_a_400(member) -> None:
+ client, repo, base = member
+ resp = client.post(base, json={"name": "x" * 81, "isAdmin": True})
+ assert resp.status_code == 400, resp.text
+ assert resp.json() == {"error": "validation"}
+ assert repo.writes == []
+
+
+# --- declared but not settable: dropped, never 400'd, and never handed to the repository ----
+
+
+def test_create_strips_the_client_id_and_a_read_only_field(member) -> None:
+ client, repo, base = member
+ resp = client.post(
+ base,
+ json={"id": 999, "name": "Mallory", "role": "admin", "tenant": "t1",
+ "address": {"city": "Oslo"}},
+ )
+ assert resp.status_code == 201, resp.text
+ [(op, written)] = repo.writes
+ assert op == "create"
+ # The server generates the id and owns `role`; `createdAt` is the router's own stamp.
+ assert set(written) == {"name", "tenant", "address", "createdAt"}
+ assert written["name"] == "Mallory"
+ assert written["tenant"] == "t1" # writeOnce is settable on create
+ assert written["address"] == {"city": "Oslo"}
+
+
+@pytest.mark.parametrize("method", ["PATCH", "PUT"])
+def test_update_never_hands_the_repository_the_id_or_a_frozen_field(member, method: str) -> None:
+ client, repo, base = member
+ resp = client.request(
+ method,
+ f"{base}/1",
+ json={"id": 999, "name": "M2", "role": "admin", "tenant": "t2", "createdAt": "2000-01-01T00:00:00Z"},
+ )
+ assert resp.status_code == 200, resp.text
+ assert repo.writes == [("update", {"name": "M2"})]
+
+
+def test_update_passes_a_present_null_through_as_a_clear(member) -> None:
+ """The PATCH present-key tristate is unchanged: an explicit null on a nullable field clears it."""
+ client, repo, base = member
+ resp = client.patch(f"{base}/1", json={"address": None})
+ assert resp.status_code == 200, resp.text
+ assert repo.writes == [("update", {"address": None})]
+
+
+def test_an_assigned_key_is_still_the_callers_on_create_and_route_owned_on_update(account) -> None:
+ client, repo, base = account
+ created = client.post(base, json={"code": "ACME", "label": "Acme"})
+ assert created.status_code == 201, created.text
+ updated = client.patch(f"{base}/ACME", json={"code": "EVIL", "label": "Acme 2"})
+ assert updated.status_code == 200, updated.text
+ assert repo.writes == [
+ ("create", {"code": "ACME", "label": "Acme"}),
+ ("update", {"label": "Acme 2"}),
+ ]
+
+
+# --- TPH: the per-subtype create / update handlers are a separate code path -----------------
+
+
+def _find_tph_dir() -> Path:
+ cur = Path(__file__).resolve()
+ while cur != cur.parent:
+ candidate = cur / "fixtures" / "api-contract-conformance" / "tph"
+ if candidate.is_dir():
+ return candidate
+ cur = cur.parent
+ raise RuntimeError("fixtures/api-contract-conformance/tph not found")
+
+
+@pytest.fixture()
+def tph() -> tuple[TestClient, list[tuple[str, str, dict[str, Any]]]]:
+ app, repo = build_generated_tph_app(_find_tph_dir())
+ writes: list[tuple[str, str, dict[str, Any]]] = []
+ create, update = repo.create, repo.update
+
+ def recording_create(subtype: str, dto: Any) -> Any:
+ writes.append(("create", subtype, dict(dto)))
+ return create(subtype, dto)
+
+ def recording_update(subtype: str, id: int, dto: Any) -> Any:
+ writes.append(("update", subtype, dict(dto)))
+ return update(subtype, id, dto)
+
+ repo.create, repo.update = recording_create, recording_update
+ return TestClient(app), writes
+
+
+def test_tph_subtype_create_drops_the_client_id_and_an_undeclared_field(tph) -> None:
+ client, writes = tph
+ resp = client.post(
+ "/api/auths/bridge", json={"id": 999, "reference": "R-1", "quantity": 2, "isAdmin": True}
+ )
+ assert resp.status_code == 201, resp.text
+ [(op, subtype, written)] = writes
+ assert (op, subtype) == ("create", "Bridge")
+ assert "id" not in written
+ assert "isAdmin" not in written
+ assert {"reference", "quantity"} <= set(written)
+
+
+def test_tph_subtype_update_drops_the_id_and_an_undeclared_field(tph) -> None:
+ client, writes = tph
+ # The store is unseeded, so the answer is a 404; what matters is what the write was handed.
+ client.patch("/api/auths/bridge/1", json={"id": 999, "quantity": 3, "isAdmin": True})
+ [(op, subtype, written)] = writes
+ assert (op, subtype) == ("update", "Bridge")
+ assert "id" not in written
+ assert "isAdmin" not in written
+ assert written["quantity"] == 3
diff --git a/server/python/uv.lock b/server/python/uv.lock
index 2999705817..a3b21881ca 100644
--- a/server/python/uv.lock
+++ b/server/python/uv.lock
@@ -399,7 +399,7 @@ wheels = [
[[package]]
name = "metaobjects"
-version = "1.2.0"
+version = "1.2.1"
source = { editable = "." }
dependencies = [
{ name = "pyyaml" },
From dbd3ba03fed3bc9c4c8644c08eb3f3e94e06ce54 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Fri, 13 Nov 2026 11:51:35 -0500
Subject: [PATCH 02/31] fix(codegen): generated routes drop server-owned and
undeclared input in every port
An audit after the Python 1.2.1 fix found the same request-input hole in the
other ports' generated create handlers. Each port now drops, silently and before
the write, a server-generated key, readOnly and derived fields, and on a TPH
per-subtype route the discriminator and sibling-subtype columns; undeclared keys
are dropped everywhere.
- Python: forward-port of the 1.2.1 fix; TPH create drops a body discriminator.
- Java: create nulls the dropped DTO components; DTOs ignore unknown properties.
- Kotlin: create writes only settable columns; entity classes ignore unknown keys.
- C#: create resets the generated key, discriminator and M:N navigations; every
readOnly property gets a private setter.
- TypeScript: an assigned primary key leaves the update schema.
Shared api-contract scenarios input-server-owned-dropped (core) and
tph-input-server-owned-dropped, a readOnly column in secret-fields, and an
`absent` assertion in every runner gate it.
---
CHANGELOG.md | 37 +++
docs/features/api-contract.md | 23 ++
docs/features/generated-mutations.md | 12 +-
.../codegen/templates/zod-validators.ts | 8 +
.../.metaobjects/.gen-state/.hashes.json | 28 +-
.../codegen/templates/zod-validators.ts | 8 +
.../generated/csharp/SubscriberRoutes.g.cs | 2 +
.../generated/java/acme/SubscriberDto.java | 1 +
.../generated/kotlin/acme/Subscriber.kt | 2 +
.../kotlin/acme/SubscriberBlurbPayload.kt | 2 +
.../generated/python/subscriber_router.py | 32 ++-
examples/showcase/site-payload.json | 12 +-
fixtures/api-contract-conformance/README.md | 10 +-
.../scenarios/input-server-owned-dropped.yaml | 86 ++++++
.../secret-fields/README.md | 5 +-
.../secret-fields/meta.json | 1 +
.../scenarios/read-omits-credential.yaml | 3 +
.../scenarios/write-ignores-excluded.yaml | 15 +-
.../secret-fields/seed.json | 4 +-
.../api-contract-conformance/tph/README.md | 3 +-
.../tph-input-server-owned-dropped.yaml | 64 +++++
.../m2m/expected/openapi.json | 77 +----
.../acme/social/AccountTag.update.schema.json | 11 +-
.../acme/social/Follow.update.schema.json | 11 +-
.../acme/social/Friendship.update.schema.json | 11 +-
.../MemberAccountTag.update.schema.json | 11 +-
.../social/PostReviewer.update.schema.json | 11 +-
.../acme/social/PostTag.update.schema.json | 11 +-
.../ScopedAccountTag.update.schema.json | 11 +-
.../secret-fields/expected/openapi.json | 10 +-
.../schemas/acme/secrets/Account.schema.json | 10 +-
.../ServerOwnedCreateInputTests.cs | 134 +++++++++
.../Generators/EntityGenerator.cs | 26 +-
.../Generators/RoutesGenerator.cs | 50 +++-
.../Api/ApiContractAssertions.cs | 12 +
.../ApiContractSecretFieldsConformanceTest.cs | 5 +-
.../Api/SecretFieldsFixture.cs | 3 +-
.../generator/kotlin/KotlinEntityGenerator.kt | 7 +
.../kotlin/KotlinSpringControllerGenerator.kt | 10 +-
.../kotlin/KotlinServerOwnedInputTest.kt | 91 ++++++
.../acme/blog/Author.kt | 2 +
.../acme/blog/Post.kt | 2 +
.../acme/blog/Author.kt | 2 +
.../acme/catalog/Product.kt | 2 +
.../acme/catalog/Product.kt | 2 +
.../entity-with-enum/acme/game/Player.kt | 2 +
.../entity-with-fk/acme/blog/Author.kt | 2 +
.../entity-with-fk/acme/blog/Post.kt | 2 +
.../acme/commerce/Address.kt | 2 +
.../acme/commerce/User.kt | 2 +
.../acme/commerce/UserMetadata.kt | 2 +
.../acme/commerce/Address.kt | 2 +
.../entity-with-storage/acme/commerce/User.kt | 2 +
.../acme/commerce/UserMetadata.kt | 2 +
.../acme/ops/OrderReport.kt | 2 +
.../acme/ops/OrderReportArgs.kt | 2 +
.../entity-with-tph/acme/auth/Auth.kt | 2 +
.../acme/auth/AuthController.kt | 6 -
.../entity-with-tph/acme/auth/AuthLine.kt | 2 +
.../acme/report/SalesReport.kt | 2 +
.../payload-with-origins/acme/ai/Author.kt | 2 +
.../acme/ai/AuthorReport.kt | 2 +
.../payload-with-origins/acme/ai/Post.kt | 2 +
.../acme/demo/Author.kt | 2 +
.../acme/ai/OpinionOutputPayload.kt | 2 +
.../acme/ai/Greeting.kt | 2 +
.../template-prompt-simple/acme/ai/Author.kt | 2 +
.../spring/SpringControllerGenerator.java | 57 +++-
.../generator/spring/SpringDtoGenerator.java | 3 +
.../spring/SpringSecretFieldsCodegenTest.java | 7 +-
.../SpringServerOwnedInputCodegenTest.java | 109 +++++++
.../expected/acme/shipping/CrateDto.java | 1 +
.../expected/acme/shipping/ParcelDto.java | 1 +
.../expected/acme/shipping/ShipmentDto.java | 1 +
.../acme/shipping/ShipmentSummaryDto.java | 1 +
.../kotlin/api/ApiContractAssertions.kt | 9 +
.../GeneratedSecretFieldsControllerHarness.kt | 6 +-
.../api/ApiContractAssertions.java | 11 +
.../InMemoryAccountRepositorySource.java | 11 +-
.../InMemoryAuthorRepositorySource.java | 6 +-
.../InMemoryAuthRepositorySource.java | 11 +-
.../src/metaobjects/codegen/KNOWN_GAPS.md | 6 +-
.../codegen/generators/router_generator.py | 102 +++++--
.../integration/api_contract_assertions.py | 13 +
.../generated_secret_fields_app.py | 2 +-
.../test_generated_router_validated_input.py | 272 ++++++++++++++++++
.../src/templates/zod-validators.ts | 8 +
.../__snapshots__/reporting-docs.test.ts.snap | 66 ++---
.../test/contract/contract-behaviours.test.ts | 2 +-
.../test/templates/zod-validators.test.ts | 16 ++
.../src/api-contract-scenario.ts | 11 +
...contract-secret-fields-generated-server.ts | 7 +-
.../src/api-contract-server.ts | 19 +-
.../src/templates/zod-validators.ts | 8 +
94 files changed, 1400 insertions(+), 294 deletions(-)
create mode 100644 fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml
create mode 100644 fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml
create mode 100644 server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs
create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt
create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java
create mode 100644 server/python/tests/integration/test_generated_router_validated_input.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 933b82d2c9..60079995e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,43 @@ here.**
**New metamodel vocabulary: `measure.derived` and its `@expr`.** It is additive: nothing that
loaded before stops loading. This vocabulary ships in 1.3.0 with `metamodelVersion` 1.3 if it merges before the 1.3.0 publish; if it lands after, the next release moves `metamodelVersion`.
+### Security
+
+- **Generated create routes wrote fields a client must never set, in Java, Kotlin, C# and
+ Python; the TypeScript update shape let a client re-key a row.** An external review of 1.2.0
+ found that the Python routes passed raw request input to the repository (fixed for Python in
+ 1.2.1). An audit of the other ports found the same class of hole on create, in the plain and
+ the TPH per-subtype handlers:
+ - **Java** (`codegen-spring`): create forwarded a client-sent generated `id`, `readOnly` and
+ derived fields to `repository.create`, and in TPH also the discriminator and a sibling
+ subtype's columns to `createWithType`.
+ - **Kotlin** (`codegen-kotlin`): create wrote `readOnly` columns, and TPH create wrote every
+ column of the union table, a sibling subtype's included.
+ - **C#** (`MetaObjects.Codegen`): create bound the request to the entity and added it as
+ sent, so a client-sent generated `id` was inserted, a POST to one subtype's route with
+ another subtype's `type` created a row of that other subtype, M:N navigation collections in
+ the body were inserted with the row, and a `readOnly` field other than a plain scalar (an
+ enum, array, value object or map, or any TPH subtype field) had a public setter. A `readOnly`
+ property now has a private setter on every shape.
+ - **TypeScript** (`codegen-ts`): an ASSIGNED primary key stayed in `UpdateSchema`, so
+ PATCH or PUT could change the row's key. A generated key was already refused.
+
+ Every port now drops these keys silently before the write, as the TypeScript create already
+ did: a server-generated key, a `readOnly` or derived field, and in TPH the discriminator (the
+ route's subtype is its only source) and every column the route's subtype does not declare. An
+ assigned key is still the caller's on create. No port answers them with a 400. A key the
+ entity does not declare is also dropped, never rejected, in every port: Java DTOs and Kotlin
+ entity classes now carry `@JsonIgnoreProperties(ignoreUnknown = true)`, so the answer no
+ longer depends on the host's `ObjectMapper` (a plain one answered 400). The Python 1.2.1 fix
+ is carried forward to this line, and the Python TPH create now drops a body's discriminator
+ instead of answering 400 for a foreign one.
+
+ Gated by two new shared api-contract scenarios, `input-server-owned-dropped` (generated and
+ reference lanes) and `tph/tph-input-server-owned-dropped` (both TPH lanes), which send a
+ client `id`, a foreign discriminator, a `writeOnce` change and a made-up `isAdmin`, and by a
+ `readOnly` `role` column in the `secret-fields` corpus. Scenarios gain an `absent: [keys]`
+ assertion. Adopters with ejected (owned) generators need the same change made by hand.
+
### Added
- **Report measures over Money and other value-object members (FR-044 R12).** A dimension's or
diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md
index 461dacf19b..9a516d1b7f 100644
--- a/docs/features/api-contract.md
+++ b/docs/features/api-contract.md
@@ -559,6 +559,29 @@ set (`@mutability: writeOnce` on PATCH, the TPH discriminator, `@autoSet: onCrea
a generated edit form submits every field it was given, so a `400` would fail every save. A required field
that is also ignored can never be created through the API, so mark such a field optional.
+The same rule covers every key a client never sets, in every port, on the plain and the TPH per-subtype
+routes:
+
+| Key in the body | Create | PATCH, PUT |
+|---|---|---|
+| a server-generated primary key (`@generation`) | dropped | dropped (the URL names the row) |
+| an assigned primary key | **kept** (the caller chooses it) | dropped (the URL names the row) |
+| `@mutability: readOnly`, a derived field | dropped | dropped |
+| `@mutability: writeOnce` | kept | dropped |
+| the TPH discriminator | dropped (the route's subtype is its only source) | dropped |
+| a column only a sibling TPH subtype declares | dropped | dropped |
+| a key the entity does not declare | dropped | dropped |
+
+None of these is a `400`, and none reaches the repository. Each port does it in its own idiom: TypeScript
+parses with the Zod input schema (which drops unknown keys) and writes the parsed value; Python keeps only
+the keys its input model validated; Java nulls the dropped components of the bound DTO before
+`repository.create` and its DTOs carry `@JsonIgnoreProperties(ignoreUnknown = true)`, so the answer does not
+depend on the host's `ObjectMapper`; Kotlin writes only the route's settable columns; C# resets the bound
+entity's generated key, TPH discriminator and M:N navigations before `Add`, and gives a `readOnly` property
+a private setter, which System.Text.Json never binds. The shared scenarios `input-server-owned-dropped` and
+`tph/tph-input-server-owned-dropped` pin it, and `secret-fields/` pins a `readOnly` column beside the
+credential.
+
Only the generated HTTP boundary changes. The entity, its DTO and the generated queries still carry the
field, so your own code writes a hash or token and reads it back. Allowlists are unchanged: a field is
filterable or sortable only if you wrote `@filterable` or `@sortable` on it, so do not put those on a credential
diff --git a/docs/features/generated-mutations.md b/docs/features/generated-mutations.md
index 57aa6f409a..3a367bbb6f 100644
--- a/docs/features/generated-mutations.md
+++ b/docs/features/generated-mutations.md
@@ -41,7 +41,9 @@ but the semantics are one contract — call them **PATCH-1..7** (FR-035):
simply omits every non-settable field, and Zod drops unknown keys — so
`safeParse` succeeds and the key never reaches the `SET`. The TPH discriminator
is additionally deleted by hand after parse, the same convention. A malformed
- *value* on a settable key is still `400 {"error":"validation"}`.
+ *value* on a settable key is still `400 {"error":"validation"}`. A key the entity
+ does not declare at all is dropped the same way. The Python routes hand the
+ repository only the keys their input model validated.
This matters for `writeOnce` specifically: the generated edit form submits EVERY
registered field (`handleSubmit` passes all values, and 0.19.2 switched the
resolver to `UpdateSchema` on edit rather than diff-and-omit), so rejecting a
@@ -109,10 +111,10 @@ repo.patch(id) { it[Authors.bio] = "…" } // touches only what you set
the controller binds the partial JSON body via `Patch.fromJson` (presence-tracked)
and delegates to `repository.patch`, so an omitted key is never written.
-**Python** — the generated FastAPI route binds the raw JSON body (the set of
-*present* keys — the tristate signal) and validates the present values against the
-generated `Patch` model before delegating to the runtime `update`, which
-`SET`s only those keys.
+**Python** — the generated FastAPI route binds the JSON body (the set of
+*present* keys — the tristate signal), validates the present values against the
+generated `Patch` model, and hands the repository only the keys that model
+validated. The runtime `update` then `SET`s only those keys.
**C#** — the generated route runs a per-field merge loop over the present JSON keys
(the app's configured `JsonSerializerOptions`), writing only the columns the body
diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts
index 2e421a0819..3d0a9e52fd 100644
--- a/examples/advanced-modeling/codegen/templates/zod-validators.ts
+++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts
@@ -719,6 +719,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] {
*/
export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
const autoGenPkFields = autoGenPkFieldNames(obj);
+ const pkFields = primaryKeyFieldNames(obj);
const tphPin = tphDiscriminatorPin(obj);
const out: SchemaFieldShape[] = [];
for (const child of flatSurfaceFields(obj)) {
@@ -734,6 +735,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
// edit form for an entity carrying one. Clearing counts as a write, so the
// FR-035 present-null arm never reaches it either.
if (isWriteOnceMutability(child)) continue;
+ // A primary-key field is the row's identity, which the URL names: an ASSIGNED key is
+ // omitted from the update shape exactly like a generated one, so a client-sent id is
+ // stripped and can never re-key the row.
+ if (pkFields.has(child.name)) continue;
// TPH subtype discriminator: omitted from the update schema entirely.
if (tphPin !== undefined && child.name === tphPin.fieldName) continue;
const autoSet = child.attr(FIELD_ATTR_AUTO_SET);
@@ -818,6 +823,9 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
// below; a value presented on PATCH is stripped, not 400'd (see
// updateSchemaFields for the grounding).
if (isWriteOnceMutability(child)) continue;
+ // The row's identity is the URL's: an ASSIGNED primary key leaves the update shape too
+ // (a generated one never entered it), so a client-sent id is stripped, never a re-key.
+ if (pkFields.has(child.name)) continue;
// Update schema: @autoSet onCreate → omit entirely; onUpdate → transform
if (autoSet === AUTO_SET_ON_CREATE) {
diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes.json
index 1d4aa83726..3f9fca7aab 100644
--- a/examples/showcase/.metaobjects/.gen-state/.hashes.json
+++ b/examples/showcase/.metaobjects/.gen-state/.hashes.json
@@ -4,17 +4,33 @@
"generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed",
"generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5",
"generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732",
- "generated/csharp/SubscriberRoutes.g.cs": "15450e230d396a739d789340c42488da354c22265193b5ac61b074b0ba6fb1ff",
+ "generated/csharp/SubscriberRoutes.g.cs": "d05912d0a76b52334857796a42b2919be8709997d6c073c11d2c44590fe686a9",
"generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762",
"generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd",
"generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5",
"generated/python/subscriber_filter_allowlist.py": "b0414cc95ff3982c80a0e1a06839f090c0b423e41f5a94275df93426cea09df5",
"generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561",
- "generated/python/subscriber_router.py": "5f219b6e46c913ae30bb46ca80f68713a427c954139a950400eb4d88a776b614",
- "generated/ts/Subscriber.queries.ts": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562",
- "generated/ts/Subscriber.routes.ts": "147d32ae658f985e024c3de6e8894ca7359f767eeaa765cec70756802e3bd300",
- "generated/ts/Subscriber.ts": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96",
- "generated/ts/SubscriberBlurbPayload.ts": "83272130c428ad0cc68190cb63e32b418a0bcfd05345804def9bf22e79b55fcc",
+ "generated/python/subscriber_router.py": "021768a4ed1fe24c2432087bba8b350579f60595728a95c6d43a528c3fdcb1be",
+ "generated/ts/Subscriber.queries.ts": {
+ "hash": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562",
+ "generatedBy": "queries-file",
+ "sourceNode": "acme::Subscriber"
+ },
+ "generated/ts/Subscriber.routes.ts": {
+ "hash": "147d32ae658f985e024c3de6e8894ca7359f767eeaa765cec70756802e3bd300",
+ "generatedBy": "routes-file",
+ "sourceNode": "acme::Subscriber"
+ },
+ "generated/ts/Subscriber.ts": {
+ "hash": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96",
+ "generatedBy": "entity-file",
+ "sourceNode": "acme::Subscriber"
+ },
+ "generated/ts/SubscriberBlurbPayload.ts": {
+ "hash": "83272130c428ad0cc68190cb63e32b418a0bcfd05345804def9bf22e79b55fcc",
+ "generatedBy": "entity-file",
+ "sourceNode": "acme::SubscriberBlurbPayload"
+ },
"generated/ts/index.ts": "2c915565fd8711503dbcd0b0139c657bb927c7f0f502d8d2a8b51e026b257694",
"generated/ts/prompts.ts": "9eec821ec8cb6063f98b52b78ae1758cfd22c81a71cbb90b0555dee347a687af",
"generated/ts/requirements/subscriberCanBePausedWithoutErasingHistory.field.enum.test.ts": "a5d2494ce5340673da43f2ee3ef13d7505ee349724e8d85f377a84eafeea50ae"
diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts
index 2e421a0819..3d0a9e52fd 100644
--- a/examples/showcase/codegen/templates/zod-validators.ts
+++ b/examples/showcase/codegen/templates/zod-validators.ts
@@ -719,6 +719,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] {
*/
export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
const autoGenPkFields = autoGenPkFieldNames(obj);
+ const pkFields = primaryKeyFieldNames(obj);
const tphPin = tphDiscriminatorPin(obj);
const out: SchemaFieldShape[] = [];
for (const child of flatSurfaceFields(obj)) {
@@ -734,6 +735,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
// edit form for an entity carrying one. Clearing counts as a write, so the
// FR-035 present-null arm never reaches it either.
if (isWriteOnceMutability(child)) continue;
+ // A primary-key field is the row's identity, which the URL names: an ASSIGNED key is
+ // omitted from the update shape exactly like a generated one, so a client-sent id is
+ // stripped and can never re-key the row.
+ if (pkFields.has(child.name)) continue;
// TPH subtype discriminator: omitted from the update schema entirely.
if (tphPin !== undefined && child.name === tphPin.fieldName) continue;
const autoSet = child.attr(FIELD_ATTR_AUTO_SET);
@@ -818,6 +823,9 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
// below; a value presented on PATCH is stripped, not 400'd (see
// updateSchemaFields for the grounding).
if (isWriteOnceMutability(child)) continue;
+ // The row's identity is the URL's: an ASSIGNED primary key leaves the update shape too
+ // (a generated one never entered it), so a client-sent id is stripped, never a re-key.
+ if (pkFields.has(child.name)) continue;
// Update schema: @autoSet onCreate → omit entirely; onUpdate → transform
if (autoSet === AUTO_SET_ON_CREATE) {
diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs
index ffb1ed369c..9987f12b3c 100644
--- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs
+++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs
@@ -100,6 +100,8 @@ await db.Subscribers.FindAsync(id) is { } found
try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); }
catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); }
if (input is null) return Results.BadRequest(new { error = "validation" });
+ // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored.
+ input.Id = default!;
var __vr = new System.Collections.Generic.List();
if (!System.ComponentModel.DataAnnotations.Validator.TryValidateObject(
input, new System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true))
diff --git a/examples/showcase/generated/java/acme/SubscriberDto.java b/examples/showcase/generated/java/acme/SubscriberDto.java
index f77826cf41..8304cf25aa 100644
--- a/examples/showcase/generated/java/acme/SubscriberDto.java
+++ b/examples/showcase/generated/java/acme/SubscriberDto.java
@@ -3,6 +3,7 @@
import jakarta.validation.constraints.*;
/** GENERATED — wire DTO for Subscriber. Do not hand-edit; regenerated from metadata. */
+@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)
public record SubscriberDto(
Long id,
@NotNull @Size(min = 1, max = 320) String email,
diff --git a/examples/showcase/generated/kotlin/acme/Subscriber.kt b/examples/showcase/generated/kotlin/acme/Subscriber.kt
index e91e6d0f21..e8c40e6d0d 100644
--- a/examples/showcase/generated/kotlin/acme/Subscriber.kt
+++ b/examples/showcase/generated/kotlin/acme/Subscriber.kt
@@ -1,5 +1,6 @@
package acme
+import com.fasterxml.jackson.`annotation`.JsonIgnoreProperties
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Size
import java.time.Instant
@@ -10,6 +11,7 @@ import kotlin.jvm.JvmStatic
/**
* GENERATED — do not hand-edit. Regenerated from metadata.
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public data class Subscriber(
public val id: Long? = null,
@field:NotNull
diff --git a/examples/showcase/generated/kotlin/acme/SubscriberBlurbPayload.kt b/examples/showcase/generated/kotlin/acme/SubscriberBlurbPayload.kt
index acb1c79b0a..fc048fbf6b 100644
--- a/examples/showcase/generated/kotlin/acme/SubscriberBlurbPayload.kt
+++ b/examples/showcase/generated/kotlin/acme/SubscriberBlurbPayload.kt
@@ -1,5 +1,6 @@
package acme
+import com.fasterxml.jackson.`annotation`.JsonIgnoreProperties
import jakarta.validation.constraints.NotNull
import kotlin.String
import kotlin.jvm.JvmStatic
@@ -7,6 +8,7 @@ import kotlin.jvm.JvmStatic
/**
* GENERATED — do not hand-edit. Regenerated from metadata.
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public data class SubscriberBlurbPayload(
public val name: String? = null,
@field:NotNull
diff --git a/examples/showcase/generated/python/subscriber_router.py b/examples/showcase/generated/python/subscriber_router.py
index f5deb0e491..9db0b29b63 100644
--- a/examples/showcase/generated/python/subscriber_router.py
+++ b/examples/showcase/generated/python/subscriber_router.py
@@ -92,6 +92,26 @@ async def _json_body(request: Request) -> dict[str, Any] | None:
return None
+def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]:
+ """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the
+ input model does not declare (an undeclared name, a server-generated id, a readOnly field)
+ is dropped silently and never reaches the repository; values stay the body's own."""
+ return {
+ _k: _validated_value(getattr(valid, _k), raw[_k])
+ for _k in valid.model_fields_set
+ }
+
+
+def _validated_value(valid: Any, raw: Any) -> Any:
+ if isinstance(valid, BaseModel) and isinstance(raw, dict):
+ return _validated_input(valid, raw)
+ if isinstance(valid, list) and isinstance(raw, list):
+ return [_validated_value(v, r) for v, r in zip(valid, raw)]
+ if isinstance(valid, dict) and isinstance(raw, dict):
+ return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw}
+ return raw
+
+
_FROZEN_FIELDS: frozenset[str] = frozenset()
@@ -199,9 +219,13 @@ def create_subscriber(
# FR-036: run the generated field constraints (length / pattern /
# numeric bounds) before persisting; a violation is the cross-port 400.
try:
- SubscriberCreate(**dto)
+ _valid = SubscriberCreate(**dto)
except ValidationError:
return JSONResponse(status_code=400, content={"error": "validation"})
+ # SECURITY (1.2.1): only what the input model validated reaches the repository. A key
+ # it does not declare (an undeclared name, a server-generated id, a readOnly or derived
+ # field, a frozen one on update) is dropped silently, never 400'd.
+ dto = _validated_input(_valid, dto)
# #203/ADR-0045: stamp @autoSet columns (server-owned; caller ignored).
_asnow = _dt.datetime.now(_dt.timezone.utc)
dto["createdAt"] = _asnow
@@ -240,9 +264,13 @@ def update_subscriber(
# FR-036: validate PRESENT, non-null values with the create rules (the
# all-optional patch model never fires required-checks on ABSENT fields).
try:
- SubscriberPatch(**dto)
+ _valid = SubscriberPatch(**dto)
except ValidationError:
return JSONResponse(status_code=400, content={"error": "validation"})
+ # SECURITY (1.2.1): only what the input model validated reaches the repository. A key
+ # it does not declare (an undeclared name, a server-generated id, a readOnly or derived
+ # field, a frozen one on update) is dropped silently, never 400'd.
+ dto = _validated_input(_valid, dto)
dto.pop("createdAt", None) # onCreate @autoSet is write-once (server-owned)
try:
saved = repo.update(subscriber_id, dto)
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index c716780b2b..93a11d0e23 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -38,15 +38,15 @@
},
"java-dto": {
"lang": "java",
- "inline": "…\n/** GENERATED — wire DTO for Subscriber. Do not hand-edit; regenerated from metadata. */\npublicrecordSubscriberDto(\n Long id,\n @NotNull @Size(min = 1, max = 320) String email,\n String name,\n @NotNull SubscriberStatus status,\n java.time.Instant createdAt\n) {\n publicenumSubscriberStatus { active, paused, cancelled }\n\n /** Issue #203 @autoSet: a copy with every @autoSet column (onCreate AND onUpdate) stamped to now() on insert (the model value is ignored; a fresh row's updated_at equals its created_at). */\n publicstaticSubscriberDtostampForInsert(SubscriberDto dto) {\n java.time.Instant__nowInstant= java.time.Instant.now();\n returnnewSubscriberDto(\n dto.id(),\n dto.email(),\n dto.name(),\n dto.status(),\n __nowInstant\n );\n }\n…\n}\n…",
- "full": "package acme;\n\nimport jakarta.validation.constraints.*;\n\n/** GENERATED — wire DTO for Subscriber. Do not hand-edit; regenerated from metadata. */\npublicrecordSubscriberDto(\n Long id,\n @NotNull @Size(min = 1, max = 320) String email,\n String name,\n @NotNull SubscriberStatus status,\n java.time.Instant createdAt\n) {\n publicenumSubscriberStatus { active, paused, cancelled }\n\n /** Issue #203 @autoSet: a copy with every @autoSet column (onCreate AND onUpdate) stamped to now() on insert (the model value is ignored; a fresh row's updated_at equals its created_at). */\n publicstaticSubscriberDtostampForInsert(SubscriberDto dto) {\n java.time.Instant__nowInstant= java.time.Instant.now();\n returnnewSubscriberDto(\n dto.id(),\n dto.email(),\n dto.name(),\n dto.status(),\n __nowInstant\n );\n }\n\n /** Issue #203 @autoSet: a copy with @autoSet onUpdate columns stamped to now(); onCreate columns are preserved (never rewrites created_at — the full-DTO update path). */\n publicstaticSubscriberDtostampForUpdate(SubscriberDto dto) {\n returnnewSubscriberDto(\n dto.id(),\n dto.email(),\n dto.name(),\n dto.status(),\n dto.createdAt()\n );\n }\n\n /** Issue #203 @autoSet escape hatch: the DTO written VERBATIM (import/restore/replication). */\n publicstaticSubscriberDtoinsertPreserving(SubscriberDto dto) { return dto; }\n\n /** A fluent builder, so a caller can set a subset of the components. */\n publicstaticBuilderbuilder() { returnnewBuilder(); }\n\n /** Builds a {@link SubscriberDto}; an unset component stays null. */\n publicstaticfinalclassBuilder {\n private Long id;\n private String email;\n private String name;\n private SubscriberStatus status;\n private java.time.Instant createdAt;\n\n privateBuilder() {}\n\n publicBuilderid(Long v) { this.id = v; returnthis; }\n publicBuilderemail(String v) { this.email = v; returnthis; }\n publicBuildername(String v) { this.name = v; returnthis; }\n publicBuilderstatus(SubscriberStatus v) { this.status = v; returnthis; }\n publicBuildercreatedAt(java.time.Instant v) { this.createdAt = v; returnthis; }\n\n publicSubscriberDtobuild() { returnnewSubscriberDto(id, email, name, status, createdAt); }\n }\n}\n",
- "lineCount": 62
+ "inline": "…\n/** GENERATED — wire DTO for Subscriber. Do not hand-edit; regenerated from metadata. */\n…\npublicrecordSubscriberDto(\n Long id,\n @NotNull @Size(min = 1, max = 320) String email,\n String name,\n @NotNull SubscriberStatus status,\n java.time.Instant createdAt\n) {\n publicenumSubscriberStatus { active, paused, cancelled }\n\n /** Issue #203 @autoSet: a copy with every @autoSet column (onCreate AND onUpdate) stamped to now() on insert (the model value is ignored; a fresh row's updated_at equals its created_at). */\n publicstaticSubscriberDtostampForInsert(SubscriberDto dto) {\n java.time.Instant__nowInstant= java.time.Instant.now();\n returnnewSubscriberDto(\n dto.id(),\n dto.email(),\n dto.name(),\n dto.status(),\n __nowInstant\n );\n }\n…\n}\n…",
+ "full": "package acme;\n\nimport jakarta.validation.constraints.*;\n\n/** GENERATED — wire DTO for Subscriber. Do not hand-edit; regenerated from metadata. */\n@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)\npublicrecordSubscriberDto(\n Long id,\n @NotNull @Size(min = 1, max = 320) String email,\n String name,\n @NotNull SubscriberStatus status,\n java.time.Instant createdAt\n) {\n publicenumSubscriberStatus { active, paused, cancelled }\n\n /** Issue #203 @autoSet: a copy with every @autoSet column (onCreate AND onUpdate) stamped to now() on insert (the model value is ignored; a fresh row's updated_at equals its created_at). */\n publicstaticSubscriberDtostampForInsert(SubscriberDto dto) {\n java.time.Instant__nowInstant= java.time.Instant.now();\n returnnewSubscriberDto(\n dto.id(),\n dto.email(),\n dto.name(),\n dto.status(),\n __nowInstant\n );\n }\n\n /** Issue #203 @autoSet: a copy with @autoSet onUpdate columns stamped to now(); onCreate columns are preserved (never rewrites created_at — the full-DTO update path). */\n publicstaticSubscriberDtostampForUpdate(SubscriberDto dto) {\n returnnewSubscriberDto(\n dto.id(),\n dto.email(),\n dto.name(),\n dto.status(),\n dto.createdAt()\n );\n }\n\n /** Issue #203 @autoSet escape hatch: the DTO written VERBATIM (import/restore/replication). */\n publicstaticSubscriberDtoinsertPreserving(SubscriberDto dto) { return dto; }\n\n /** A fluent builder, so a caller can set a subset of the components. */\n publicstaticBuilderbuilder() { returnnewBuilder(); }\n\n /** Builds a {@link SubscriberDto}; an unset component stays null. */\n publicstaticfinalclassBuilder {\n private Long id;\n private String email;\n private String name;\n private SubscriberStatus status;\n private java.time.Instant createdAt;\n\n privateBuilder() {}\n\n publicBuilderid(Long v) { this.id = v; returnthis; }\n publicBuilderemail(String v) { this.email = v; returnthis; }\n publicBuildername(String v) { this.name = v; returnthis; }\n publicBuilderstatus(SubscriberStatus v) { this.status = v; returnthis; }\n publicBuildercreatedAt(java.time.Instant v) { this.createdAt = v; returnthis; }\n\n publicSubscriberDtobuild() { returnnewSubscriberDto(id, email, name, status, createdAt); }\n }\n}\n",
+ "lineCount": 63
},
"kotlin-entity": {
"lang": "kotlin",
- "inline": "…\n/**\n * GENERATED — do not hand-edit. Regenerated from metadata.\n */\npublicdataclassSubscriber(\n publicval id: Long? = null,\n @field:NotNull\n @field:Size(min = 1, max = 320)\n publicval email: String,\n publicval name: String? = null,\n @field:NotNull\n publicval status: SubscriberStatus,\n publicval createdAt: Instant? = null,\n…\n)\n…",
- "full": "package acme\n\nimport jakarta.validation.constraints.NotNull\nimport jakarta.validation.constraints.Size\nimport java.time.Instant\nimport kotlin.Long\nimport kotlin.String\nimport kotlin.jvm.JvmStatic\n\n/**\n * GENERATED — do not hand-edit. Regenerated from metadata.\n */\npublicdataclassSubscriber(\n publicval id: Long? = null,\n @field:NotNull\n @field:Size(min = 1, max = 320)\n publicval email: String,\n publicval name: String? = null,\n @field:NotNull\n publicval status: SubscriberStatus,\n publicval createdAt: Instant? = null,\n) {\n /**\n * Fluent builder — lets a JAVA caller set a subset of properties.\n */\n publicclassBuilder {\n privatevar id: Long? = null\n\n privatevar email: String? = null\n\n privatevar name: String? = null\n\n privatevar status: SubscriberStatus? = null\n\n privatevar createdAt: Instant? = null\n\n publicfunid(v: Long?): Builder {\n this.id = v\n returnthis\n }\n\n publicfunemail(v: String?): Builder {\n this.email = v\n returnthis\n }\n\n publicfunname(v: String?): Builder {\n this.name = v\n returnthis\n }\n\n publicfunstatus(v: SubscriberStatus?): Builder {\n this.status = v\n returnthis\n }\n\n publicfuncreatedAt(v: Instant?): Builder {\n this.createdAt = v\n returnthis\n }\n\n publicfunbuild(): Subscriber = Subscriber(\n id = id,\n email = requireNotNull(email) { "email is required" },\n name = name,\n status = requireNotNull(status) { "status is required" },\n createdAt = createdAt\n )\n }\n\n publiccompanionobject {\n @JvmStatic\n publicfunbuilder(): Builder = Builder()\n }\n}\n",
- "lineCount": 75
+ "inline": "…\n/**\n * GENERATED — do not hand-edit. Regenerated from metadata.\n */\n…\npublicdataclassSubscriber(\n publicval id: Long? = null,\n @field:NotNull\n @field:Size(min = 1, max = 320)\n publicval email: String,\n publicval name: String? = null,\n @field:NotNull\n publicval status: SubscriberStatus,\n publicval createdAt: Instant? = null,\n…\n)\n…",
+ "full": "package acme\n\nimport com.fasterxml.jackson.`annotation`.JsonIgnoreProperties\nimport jakarta.validation.constraints.NotNull\nimport jakarta.validation.constraints.Size\nimport java.time.Instant\nimport kotlin.Long\nimport kotlin.String\nimport kotlin.jvm.JvmStatic\n\n/**\n * GENERATED — do not hand-edit. Regenerated from metadata.\n */\n@JsonIgnoreProperties(ignoreUnknown = true)\npublicdataclassSubscriber(\n publicval id: Long? = null,\n @field:NotNull\n @field:Size(min = 1, max = 320)\n publicval email: String,\n publicval name: String? = null,\n @field:NotNull\n publicval status: SubscriberStatus,\n publicval createdAt: Instant? = null,\n) {\n /**\n * Fluent builder — lets a JAVA caller set a subset of properties.\n */\n publicclassBuilder {\n privatevar id: Long? = null\n\n privatevar email: String? = null\n\n privatevar name: String? = null\n\n privatevar status: SubscriberStatus? = null\n\n privatevar createdAt: Instant? = null\n\n publicfunid(v: Long?): Builder {\n this.id = v\n returnthis\n }\n\n publicfunemail(v: String?): Builder {\n this.email = v\n returnthis\n }\n\n publicfunname(v: String?): Builder {\n this.name = v\n returnthis\n }\n\n publicfunstatus(v: SubscriberStatus?): Builder {\n this.status = v\n returnthis\n }\n\n publicfuncreatedAt(v: Instant?): Builder {\n this.createdAt = v\n returnthis\n }\n\n publicfunbuild(): Subscriber = Subscriber(\n id = id,\n email = requireNotNull(email) { "email is required" },\n name = name,\n status = requireNotNull(status) { "status is required" },\n createdAt = createdAt\n )\n }\n\n publiccompanionobject {\n @JvmStatic\n publicfunbuilder(): Builder = Builder()\n }\n}\n",
+ "lineCount": 77
},
"sql-migration": {
"lang": "sql",
diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md
index b012a9ed08..452f71d00a 100644
--- a/fixtures/api-contract-conformance/README.md
+++ b/fixtures/api-contract-conformance/README.md
@@ -27,6 +27,7 @@ fixtures/api-contract-conformance/
├── get-by-id.yaml
├── get-by-id-not-found.yaml
├── create-201.yaml
+ ├── input-server-owned-dropped.yaml # a client id, a made-up key and a writeOnce change are dropped, never 400
├── create-constraint-violation-400.yaml # FR-036 POST field-constraint → 400 {error:"validation"}
├── update-patch-and-put.yaml
├── update-constraint-violation-400.yaml # FR-036 PATCH present-value constraint → 400
@@ -52,17 +53,17 @@ fixtures/api-contract-conformance/
└── filter-invalid-value.yaml # uncoercible value → 400; the fourth envelope, previously ungated
```
-Beside the 31 core scenarios above sit ten **sub-corpora**, each a directory with its
-own `meta.json`, `seed.json`, `scenarios/` and `README.md` (92 scenarios in all, 123 with the
+Beside the 32 core scenarios above sit ten **sub-corpora**, each a directory with its
+own `meta.json`, `seed.json`, `scenarios/` and `README.md` (93 scenarios in all, 125 with the
core):
| Directory | Scenarios | Gates | Lanes |
|---|---|---|---|
-| `tph/` | 10 | single-table inheritance | both |
+| `tph/` | 11 | single-table inheritance | both |
| `m2m/` | 9 | M:N traversal, and TPH x M:N together | both |
| `jsonb/` | 5 | typed value-object columns, and the numbers inside them (a double stays a JSON number; a decimal is a canonical string, option A of the 1.1.0 review) | both |
| `write-through/` | 2 | an entity that writes a table and reads a view | generated only |
-| `secret-fields/` | 2 | #484: a `@formExclude` or credential (`view.password`) field is ignored on create, PATCH and PUT, and a credential is never returned | generated only |
+| `secret-fields/` | 2 | #484: a `@formExclude` or credential (`view.password`) field is ignored on create, PATCH and PUT, and a credential is never returned; a `readOnly` field is ignored the same way and still returned | generated only |
| `enum-default/` | 2 | a create that omits a `field.enum` carrying `@default` stores the default (echo and GET by id), and a supplied member is kept | generated only |
| `projection/` | 12 | a read-only `object.projection`: reads served, every write `405`; no declared identity means no `/{id}` route; a key not named `id` addresses the row; decimal and float filters. Its `docs-routes.json` pins the routes each port documents | generated only |
| `report/` | 37 | a view-backed `object.report` (FR-044): list, filter, sort and paging on derived fields, `POST` is `405`, no `/{id}` route; a `@spine` report keeps a row with no facts, and a measure with `@default` filters and sorts as its default; a dimension over an array or a map is neither filterable nor sortable. Also carries `schema.postgres.sql`, the TypeScript-produced table and views the C# lane executes | generated only |
@@ -121,6 +122,7 @@ requests:
| `error` | the response body has `error: ""` |
| `field` | **only meaningful alongside `error`** — the envelope's `field` names the rejected filter/sort field. Declared as a sibling of `error` and checked inside that branch, because the `error` branch returns; a runner that checked it as an independent key would skip it whenever `error` matched first. |
| `empty` | the response body is empty / null (204 No Content) |
+| `absent` | the response body is an object; none of the listed keys is present (not even as `null`). Pins that a key a client sent but may not set never comes back. |
| `fieldsEqual`| the response body is an object; assert the listed field names are all equal to **each other** (raw, field-vs-field — no literal, so timestamp non-determinism is a non-issue). Used by the `@autoSet` gate (#203/ADR-0045). |
| `fieldsNotEqual`| the response body is an object; assert the two listed fields **differ** from each other. Used by the `@autoSet` gate (e.g. after a PATCH, `autoCreatedAt` (onCreate, preserved) != `autoUpdatedAt` (onUpdate, bumped)). |
diff --git a/fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml b/fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml
new file mode 100644
index 0000000000..0e71b5fa3a
--- /dev/null
+++ b/fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml
@@ -0,0 +1,86 @@
+name: input-server-owned-dropped
+description: >
+ A write route hands storage only what the client may set. A client-sent `id` on a
+ server-generated key, a key the entity does not declare (`isAdmin`) and, on update, a
+ `writeOnce` field are all DROPPED SILENTLY: the request answers as if the key were absent
+ (201/200, never 400), and none of them reaches storage. This is the rule TypeScript has
+ always followed and Python adopted in 1.2.1, where the generated routes handed the
+ repository the raw request body.
+
+ Each body carries an ordinary settable field DELIBERATELY: it is applied, and that pairing
+ is what makes the assertion about the server-owned keys and not about the request being
+ ignored whole. `absent` asserts the undeclared key is not echoed back (a stored key would
+ be), and the GETs of the client's ids prove no row was written or re-keyed under them.
+requests:
+ - id: r1
+ method: POST
+ path: /api/authors
+ body:
+ id: 999
+ name: "Barbara Liskov"
+ createdAt: "2026-02-01T10:00:00"
+ isAdmin: true
+ expect:
+ status: 201
+ body:
+ row:
+ name: "Barbara Liskov"
+ hasId: true
+ absent: [isAdmin]
+ - id: r2
+ method: GET
+ path: /api/authors/999
+ expect:
+ status: 404
+ - id: r3
+ method: PATCH
+ path: /api/authors/1
+ body:
+ id: 998
+ name: "Ada L. (input probe)"
+ isAdmin: true
+ expect:
+ status: 200
+ body:
+ row:
+ id: 1
+ name: "Ada L. (input probe)"
+ absent: [isAdmin]
+ - id: r4
+ method: PUT
+ path: /api/authors/2
+ body:
+ id: 997
+ name: "Alan T. (input probe)"
+ createdAt: "2026-01-02T10:00:00"
+ issuedCurrency: "JPY"
+ isAdmin: true
+ expect:
+ status: 200
+ body:
+ row:
+ id: 2
+ name: "Alan T. (input probe)"
+ # writeOnce: frozen after create, so the PUT's value never lands.
+ issuedCurrency: "GBP"
+ absent: [isAdmin]
+ - id: r5
+ method: GET
+ path: /api/authors/998
+ expect:
+ status: 404
+ - id: r6
+ method: GET
+ path: /api/authors/997
+ expect:
+ status: 404
+ - id: r7
+ method: GET
+ path: /api/authors/1
+ expect:
+ status: 200
+ body:
+ row:
+ id: 1
+ name: "Ada L. (input probe)"
+ absent: [isAdmin]
diff --git a/fixtures/api-contract-conformance/secret-fields/README.md b/fixtures/api-contract-conformance/secret-fields/README.md
index 29bc632038..b7108083c7 100644
--- a/fixtures/api-contract-conformance/secret-fields/README.md
+++ b/fixtures/api-contract-conformance/secret-fields/README.md
@@ -11,6 +11,7 @@ The model is one `Account`:
| `name` | (nothing) | accepted | returned |
| `tokenHash` | `@formExclude: true` | **ignored** | returned |
| `pinHash` | child `view.password` | **ignored** | **never returned** |
+| `role` | `@mutability: readOnly` | **ignored** | returned |
## The contract
@@ -22,6 +23,8 @@ The model is one `Account`:
- **A present `null` is a write**, so it does not reach a denied column either.
- **A credential is never returned**: not by list, not by get, not in the echo of a create or
an update. The key is absent from the object, not `null`.
+- **A `readOnly` field is ignored on every write the same way**, and returned like any other
+ field: the server owns its value (here, the seeded `role`), so a create leaves it `null`.
- **`@formExclude` alone does not hide a field.** It says how the field is written, and the
field is still part of the resource.
- The application still writes these fields through its own code (the generated queries, the
@@ -43,7 +46,7 @@ secret-fields/
├── seed.json # two rows, both secrets set
└── scenarios/
├── read-omits-credential.yaml # GET by id and list: pinHash absent, tokenHash present
- └── write-ignores-excluded.yaml # POST / PATCH / PUT / present-null leave tokenHash alone
+ └── write-ignores-excluded.yaml # POST / PATCH / PUT / present-null leave tokenHash and the readOnly role alone
```
Generated lane only: what is under test is whether each port's GENERATOR emits routes that
diff --git a/fixtures/api-contract-conformance/secret-fields/meta.json b/fixtures/api-contract-conformance/secret-fields/meta.json
index d47906d8ad..d000a949a6 100644
--- a/fixtures/api-contract-conformance/secret-fields/meta.json
+++ b/fixtures/api-contract-conformance/secret-fields/meta.json
@@ -10,6 +10,7 @@
{ "field.string": { "name": "name", "@required": true, "@maxLength": 100, "@filterable": true, "@sortable": true } },
{ "field.string": { "name": "tokenHash", "@maxLength": 100, "@formExclude": true } },
{ "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } },
+ { "field.string": { "name": "role", "@maxLength": 20, "@mutability": "readOnly" } },
{ "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }
]
}}
diff --git a/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml b/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml
index 92f48eb50f..f62e03a4dc 100644
--- a/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml
+++ b/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml
@@ -18,6 +18,7 @@ requests:
id: 1
name: "Ada Lovelace"
tokenHash: "token-hash-1"
+ role: "member"
- id: r2
method: GET
path: /api/accounts?sort=id
@@ -28,6 +29,8 @@ requests:
- id: 1
name: "Ada Lovelace"
tokenHash: "token-hash-1"
+ role: "member"
- id: 2
name: "Alan Turing"
tokenHash: "token-hash-2"
+ role: "owner"
diff --git a/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml b/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml
index 05f5e36306..214947fbd0 100644
--- a/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml
+++ b/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml
@@ -1,8 +1,8 @@
name: write-ignores-excluded
description: >
- A field excluded from forms (`@formExclude`) or marked as a credential (`view.password`)
- is not writable through the generated routes: create, PATCH and PUT all leave it as it
- was. The value is IGNORED, never rejected (HTTP 200/201, not 400), the same rule as
+ A field excluded from forms (`@formExclude`), marked as a credential (`view.password`) or
+ declared `@mutability: readOnly` is not writable through the generated routes: create,
+ PATCH and PUT all leave it as it was. The value is IGNORED, never rejected (HTTP 200/201, not 400), the same rule as
`@mutability: writeOnce` on PATCH (`writeonce-patch-stripped`), because a generated
edit form submits every field it was given.
@@ -19,6 +19,7 @@ requests:
name: "Ada L. (probe)"
tokenHash: "forged"
pinHash: "forged"
+ role: "admin"
expect:
status: 200
body:
@@ -26,6 +27,7 @@ requests:
id: 1
name: "Ada L. (probe)"
tokenHash: "token-hash-1"
+ role: "member"
- id: r2
method: PUT
path: /api/accounts/2
@@ -33,6 +35,7 @@ requests:
name: "Alan T. (probe)"
tokenHash: "forged"
pinHash: "forged"
+ role: "admin"
expect:
status: 200
body:
@@ -40,6 +43,7 @@ requests:
id: 2
name: "Alan T. (probe)"
tokenHash: "token-hash-2"
+ role: "owner"
- id: r3
method: POST
path: /api/accounts
@@ -47,6 +51,7 @@ requests:
name: "Grace Hopper"
tokenHash: "forged"
pinHash: "forged"
+ role: "admin"
expect:
status: 201
body:
@@ -54,6 +59,8 @@ requests:
name: "Grace Hopper"
# Never written: the column stays null, and `forged` never landed.
tokenHash: null
+ # readOnly is server-owned: a create cannot set it either.
+ role: null
hasId: true
- id: r4
method: PATCH
@@ -63,6 +70,7 @@ requests:
name: "Ada L. (probe 2)"
tokenHash: null
pinHash: null
+ role: null
expect:
status: 200
body:
@@ -70,3 +78,4 @@ requests:
id: 1
name: "Ada L. (probe 2)"
tokenHash: "token-hash-1"
+ role: "member"
diff --git a/fixtures/api-contract-conformance/secret-fields/seed.json b/fixtures/api-contract-conformance/secret-fields/seed.json
index 6697ba1fcb..13b7225941 100644
--- a/fixtures/api-contract-conformance/secret-fields/seed.json
+++ b/fixtures/api-contract-conformance/secret-fields/seed.json
@@ -1,6 +1,6 @@
{
"rows": [
- { "id": 1, "name": "Ada Lovelace", "tokenHash": "token-hash-1", "pinHash": "pin-hash-1" },
- { "id": 2, "name": "Alan Turing", "tokenHash": "token-hash-2", "pinHash": "pin-hash-2" }
+ { "id": 1, "name": "Ada Lovelace", "tokenHash": "token-hash-1", "pinHash": "pin-hash-1", "role": "member" },
+ { "id": 2, "name": "Alan Turing", "tokenHash": "token-hash-2", "pinHash": "pin-hash-2", "role": "owner" }
]
}
diff --git a/fixtures/api-contract-conformance/tph/README.md b/fixtures/api-contract-conformance/tph/README.md
index 5c45a2231f..d058058cf4 100644
--- a/fixtures/api-contract-conformance/tph/README.md
+++ b/fixtures/api-contract-conformance/tph/README.md
@@ -49,7 +49,8 @@ tph/
├── tph-writeonce-patch-stripped.yaml # FR-037: inherited @mutability "writeOnce" stripped on the per-subtype PATCH
├── tph-update-explicit-null-clears.yaml # FR-035 tristate: present null clears; omitted @required untouched; null on @required → 400
├── tph-create-constraint-violation.yaml # FR-036: per-subtype CREATE validates against the annotated Dto
- └── tph-update-constraint-violation.yaml # FR-036: per-subtype PATCH validates each PRESENT value
+ ├── tph-update-constraint-violation.yaml # FR-036: per-subtype PATCH validates each PRESENT value
+ └── tph-input-server-owned-dropped.yaml # a client id, a foreign `type`, a writeOnce change and a made-up key are dropped, never 400
```
`meta.json` declares the `acme::auth` package:
diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml
new file mode 100644
index 0000000000..f340d90be7
--- /dev/null
+++ b/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml
@@ -0,0 +1,64 @@
+name: tph-input-server-owned-dropped
+description: >
+ The per-subtype write routes hand storage only what the client may set, the same rule as
+ `input-server-owned-dropped` in the core corpus. A client-sent `id` on the generated key, a
+ key the hierarchy does not declare (`isAdmin`), the discriminator (`type`) and, on update, a
+ `writeOnce` field are all DROPPED SILENTLY (201/200, never 400): the row keeps its
+ server-assigned id, its subtype comes from the URL, and nothing undeclared is echoed back.
+requests:
+ - id: r1
+ method: POST
+ path: /api/auths/bridge
+ body:
+ id: 999
+ type: "Copay"
+ reference: "REF-INPUT"
+ quantity: 3
+ isAdmin: true
+ expect:
+ status: 201
+ body:
+ row: { type: "Bridge", reference: "REF-INPUT", quantity: 3 }
+ hasId: true
+ absent: [isAdmin]
+ - id: r2
+ method: GET
+ path: /api/auths/999
+ expect:
+ status: 404
+ - id: r3
+ method: PATCH
+ path: /api/auths/bridge/1
+ body:
+ id: 998
+ type: "Copay"
+ reference: "REF-1-INPUT"
+ issuedCurrency: "JPY"
+ isAdmin: true
+ expect:
+ status: 200
+ body:
+ row: { id: 1, type: "Bridge", reference: "REF-1-INPUT", issuedCurrency: "USD" }
+ absent: [isAdmin]
+ - id: r4
+ method: PUT
+ path: /api/auths/copay/2
+ body:
+ id: 997
+ reference: "REF-2-INPUT"
+ isAdmin: true
+ expect:
+ status: 200
+ body:
+ row: { id: 2, type: "Copay", reference: "REF-2-INPUT" }
+ absent: [isAdmin]
+ - id: r5
+ method: GET
+ path: /api/auths/998
+ expect:
+ status: 404
+ - id: r6
+ method: GET
+ path: /api/auths/997
+ expect:
+ status: 404
diff --git a/fixtures/contract-conformance/m2m/expected/openapi.json b/fixtures/contract-conformance/m2m/expected/openapi.json
index 28d59f6255..813d6036ee 100644
--- a/fixtures/contract-conformance/m2m/expected/openapi.json
+++ b/fixtures/contract-conformance/m2m/expected/openapi.json
@@ -5030,16 +5030,7 @@
"AccountTagUpdate": {
"title": "AccountTagUpdate",
"type": "object",
- "properties": {
- "accountId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"ApiError": {
"title": "ApiError",
@@ -5126,16 +5117,7 @@
"FollowUpdate": {
"title": "FollowUpdate",
"type": "object",
- "properties": {
- "followerId": {
- "type": "integer",
- "format": "int64"
- },
- "followeeId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"Friendship": {
"title": "Friendship",
@@ -5202,16 +5184,7 @@
"FriendshipUpdate": {
"title": "FriendshipUpdate",
"type": "object",
- "properties": {
- "personAId": {
- "type": "integer",
- "format": "int64"
- },
- "personBId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"GuestAccount": {
"title": "GuestAccount",
@@ -5444,16 +5417,7 @@
"MemberAccountTagUpdate": {
"title": "MemberAccountTagUpdate",
"type": "object",
- "properties": {
- "accountId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"MemberAccountUpdate": {
"title": "MemberAccountUpdate",
@@ -5734,16 +5698,7 @@
"PostReviewerUpdate": {
"title": "PostReviewerUpdate",
"type": "object",
- "properties": {
- "postId": {
- "type": "integer",
- "format": "int64"
- },
- "accountId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"PostTag": {
"title": "PostTag",
@@ -5810,16 +5765,7 @@
"PostTagUpdate": {
"title": "PostTagUpdate",
"type": "object",
- "properties": {
- "postId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"PostUpdate": {
"title": "PostUpdate",
@@ -5897,16 +5843,7 @@
"ScopedAccountTagUpdate": {
"title": "ScopedAccountTagUpdate",
"type": "object",
- "properties": {
- "accountId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
},
"Tag": {
"title": "Tag",
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json
index 8b7cec3207..b1176800e4 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/AccountTag.update.schema.json",
"title": "AccountTag.update",
"type": "object",
- "properties": {
- "accountId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json
index bafa370de5..301ee27b86 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/Follow.update.schema.json",
"title": "Follow.update",
"type": "object",
- "properties": {
- "followerId": {
- "type": "integer",
- "format": "int64"
- },
- "followeeId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json
index b7afbad306..f3fce52a55 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/Friendship.update.schema.json",
"title": "Friendship.update",
"type": "object",
- "properties": {
- "personAId": {
- "type": "integer",
- "format": "int64"
- },
- "personBId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json
index 3ab529a36e..9f43d28345 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/MemberAccountTag.update.schema.json",
"title": "MemberAccountTag.update",
"type": "object",
- "properties": {
- "accountId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json
index 851406cef3..962ddd08a5 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/PostReviewer.update.schema.json",
"title": "PostReviewer.update",
"type": "object",
- "properties": {
- "postId": {
- "type": "integer",
- "format": "int64"
- },
- "accountId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json
index 1eaac8f6fc..7387ae2891 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/PostTag.update.schema.json",
"title": "PostTag.update",
"type": "object",
- "properties": {
- "postId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json
index 28422b417b..fe3409645e 100644
--- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json
+++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json
@@ -3,14 +3,5 @@
"$id": "schemas/acme/social/ScopedAccountTag.update.schema.json",
"title": "ScopedAccountTag.update",
"type": "object",
- "properties": {
- "accountId": {
- "type": "integer",
- "format": "int64"
- },
- "tagId": {
- "type": "integer",
- "format": "int64"
- }
- }
+ "properties": {}
}
diff --git a/fixtures/contract-conformance/secret-fields/expected/openapi.json b/fixtures/contract-conformance/secret-fields/expected/openapi.json
index b2cd08f362..5be082d05d 100644
--- a/fixtures/contract-conformance/secret-fields/expected/openapi.json
+++ b/fixtures/contract-conformance/secret-fields/expected/openapi.json
@@ -459,12 +459,20 @@
"null"
],
"maxLength": 100
+ },
+ "role": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "maxLength": 20
}
},
"required": [
"id",
"name",
- "tokenHash"
+ "tokenHash",
+ "role"
]
},
"AccountCreate": {
diff --git a/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json b/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json
index e66a8f1d5b..0250ddfb7b 100644
--- a/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json
+++ b/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json
@@ -18,11 +18,19 @@
"null"
],
"maxLength": 100
+ },
+ "role": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "maxLength": 20
}
},
"required": [
"id",
"name",
- "tokenHash"
+ "tokenHash",
+ "role"
]
}
diff --git a/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs
new file mode 100644
index 0000000000..4fb3855300
--- /dev/null
+++ b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs
@@ -0,0 +1,134 @@
+// ServerOwnedCreateInputTests — a generated create hands storage ONLY what the client may set.
+// The HTTP behaviour is gated by the api-contract corpus (`input-server-owned-dropped`,
+// `tph-input-server-owned-dropped`, secret-fields); this pins the emission: the generated key,
+// the TPH discriminator and the M:N navigations are reset before `Add`, and a readOnly field of
+// EVERY shape (including a TPH subtype's own) is declared with a private setter.
+
+using MetaObjects.Codegen;
+using MetaObjects.Codegen.Generators;
+using MetaObjects.Loader;
+using MetaObjects.Meta;
+using Xunit;
+
+namespace MetaObjects.Codegen.Tests;
+
+public class ServerOwnedCreateInputTests
+{
+ private const string PlainModel = """
+ { "metadata.root": { "package": "acme::input", "children": [
+ { "object.entity": { "name": "Post", "children": [
+ { "source.rdb": { "@table": "posts" } },
+ { "field.long": { "name": "id" } },
+ { "field.string": { "name": "title", "@maxLength": 100 } },
+ { "field.string": { "name": "role", "@maxLength": 20, "@mutability": "readOnly" } },
+ { "field.enum": { "name": "stage", "@values": ["Draft", "Live"], "@mutability": "readOnly" } },
+ { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "PostTag" } },
+ { "identity.primary": { "@fields": "id", "@generation": "increment" } }
+ ]}},
+ { "object.entity": { "name": "Tag", "children": [
+ { "source.rdb": { "@table": "tags" } },
+ { "field.long": { "name": "id" } },
+ { "identity.primary": { "@fields": "id", "@generation": "increment" } }
+ ]}},
+ { "object.entity": { "name": "PostTag", "children": [
+ { "source.rdb": { "@table": "post_tags" } },
+ { "field.long": { "name": "postId" } },
+ { "field.long": { "name": "tagId" } },
+ { "identity.primary": { "@fields": ["postId", "tagId"] } },
+ { "identity.reference": { "name": "fkPost", "@fields": "postId", "@references": "Post" } },
+ { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } }
+ ]}}
+ ]}}
+ """;
+
+ private const string AssignedKeyModel = """
+ { "metadata.root": { "package": "acme::input", "children": [
+ { "object.entity": { "name": "Code", "children": [
+ { "source.rdb": { "@table": "codes" } },
+ { "field.string": { "name": "id", "@maxLength": 20 } },
+ { "identity.primary": { "@fields": "id", "@generation": "assigned" } }
+ ]}}
+ ]}}
+ """;
+
+ private const string TphModel = """
+ { "metadata.root": { "package": "acme::input", "children": [
+ { "object.entity": { "name": "Thing", "@discriminator": "kind", "children": [
+ { "source.rdb": { "@table": "things" } },
+ { "field.long": { "name": "id" } },
+ { "field.enum": { "name": "kind", "@values": ["A", "B"] } },
+ { "identity.primary": { "@fields": "id", "@generation": "increment" } }
+ ]}},
+ { "object.entity": { "name": "AThing", "extends": "Thing", "@discriminatorValue": "A", "children": [
+ { "field.string": { "name": "note", "@maxLength": 20 } },
+ { "field.string": { "name": "grade", "@maxLength": 20, "@mutability": "readOnly" } }
+ ]}},
+ { "object.entity": { "name": "BThing", "extends": "Thing", "@discriminatorValue": "B", "children": [
+ { "field.int": { "name": "qty" } }
+ ]}}
+ ]}}
+ """;
+
+ private static string Emit(string model, string generator, string file)
+ {
+ var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "input.json")]);
+ Assert.Empty(r.Errors);
+ var ctx = new GenContext
+ {
+ Entities = r.Root.Objects(),
+ Root = r.Root,
+ Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal },
+ };
+ IGenerator g = generator == "routes" ? new RoutesGenerator() : new EntityGenerator();
+ return g.Generate(ctx).Single(f => f.Path == file).Content;
+ }
+
+ [Fact]
+ public void Create_resets_a_generated_key_and_empties_navigations_before_Add()
+ {
+ var src = Emit(PlainModel, "routes", "PostRoutes.g.cs");
+ var post = src[src.IndexOf("app.MapPost(", StringComparison.Ordinal)..];
+ var reset = post.IndexOf("input.Id = default!;", StringComparison.Ordinal);
+ var tags = post.IndexOf("input.Tags = new System.Collections.Generic.List();", StringComparison.Ordinal);
+ var add = post.IndexOf("db.Posts.Add(input);", StringComparison.Ordinal);
+ Assert.True(reset >= 0 && tags >= 0 && add > reset && add > tags, post);
+ }
+
+ [Fact]
+ public void An_assigned_key_is_the_callers_and_is_not_reset()
+ {
+ var src = Emit(AssignedKeyModel, "routes", "CodeRoutes.g.cs");
+ Assert.DoesNotContain("input.Id = default!;", src);
+ Assert.DoesNotContain("Server-owned", src);
+ }
+
+ [Fact]
+ public void A_readOnly_field_of_every_shape_has_a_private_setter()
+ {
+ var src = Emit(PlainModel, "entity", "Post.g.cs");
+ Assert.Contains("Role { get; private set; }", src);
+ Assert.Contains("Stage { get; private set; }", src);
+ Assert.Contains("Title { get; set; }", src);
+ }
+
+ [Fact]
+ public void A_tph_subtype_readOnly_field_has_a_private_setter()
+ {
+ var src = Emit(TphModel, "entity", "AThing.g.cs");
+ Assert.Contains("Grade { get; private set; }", src);
+ Assert.Contains("Note { get; set; }", src);
+ }
+
+ [Fact]
+ public void Tph_subtype_create_resets_the_key_and_pins_the_discriminator_to_the_route_subtype()
+ {
+ var src = Emit(TphModel, "routes", "ThingRoutes.g.cs");
+ var start = src.IndexOf("app.MapPost(prefix + \"/things/a\"", StringComparison.Ordinal);
+ var end = src.IndexOf("app.MapPost(prefix + \"/things/b\"", StringComparison.Ordinal);
+ Assert.True(start >= 0 && end > start, src);
+ var a = src[start..end];
+ Assert.Contains("input.Id = default!;", a);
+ Assert.Contains("input.Kind = default!;", a);
+ Assert.True(a.IndexOf("input.Kind = default!;", StringComparison.Ordinal) < a.IndexOf(".Add(input);", StringComparison.Ordinal), a);
+ }
+}
diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs
index c6a59fcd7f..4e298e5958 100644
--- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs
+++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs
@@ -603,6 +603,16 @@ protected virtual void EmitClassDeclarationLine(
private static string MappedBaseClause(MetaObject entity, GenContext ctx) =>
DirectMappedParent(entity, ctx.Config) is { } parent ? $" : {CSharpNaming.Pascal(parent.Name)}" : "";
+ // FR-037 R1 / input hardening — the accessor pair of a mapped property. A `readOnly` field takes a
+ // PRIVATE setter on EVERY property shape (scalar, enum, array, value object, map; plain entity
+ // or TPH subtype): EF materializes it on read and application code cannot write it, so the
+ // generated create route's body binding (System.Text.Json skips a non-public setter) can never
+ // hand a client-supplied value to storage. Chosen over resetting the member in each route
+ // because it holds for every writer of the class, not just the routes, and needs no per-shape
+ // reset code. `writeOnce` keeps a PUBLIC setter on purpose (the caller supplies it on insert).
+ private static string SetterFor(MetaField field) =>
+ field.IsReadOnlyMutability ? "get; private set;" : "get; set;";
+
// A M:N navigation collection property on the source entity. The collection is
// the relationship name PascalCased; its element type is the target entity.
//
@@ -749,7 +759,7 @@ protected virtual string TphSubtypeScalarProperty(
AppendDurationConverterAttribute(arr, field, _wire);
// A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted
// POST value stays a NULL column instead of failing as a required collection.
- arr.Append(PropertyDeclaration(entity, field, propName, "get; set;"));
+ arr.Append(PropertyDeclaration(entity, field, propName, SetterFor(field)));
return arr.ToString();
}
@@ -772,7 +782,7 @@ protected virtual string TphSubtypeScalarProperty(
// life at the CLR default (false/0/null) on `new Sub()` instead of the declared
// @default value — every OTHER scalar-property path in this generator already
// applies DefaultInitializer; this one was the one gap.
- sb.Append(PropertyDeclaration(entity, field, propName, "get; set;"));
+ sb.Append(PropertyDeclaration(entity, field, propName, SetterFor(field)));
return sb.ToString();
}
@@ -783,7 +793,7 @@ protected virtual string TphSubtypeEnumProperty(MetaObject entity, MetaField fie
_site = new PropertySite(ValueObject: false, TphSubtype: true, null);
var propName = PropertyName(field);
var colAttr = ColumnAttributeLine(entity, field, strategy, config.IncludeNames) is { } column ? column + "\n" : "";
- return colAttr + PropertyDeclaration(entity, field, propName, "get; set;");
+ return colAttr + PropertyDeclaration(entity, field, propName, SetterFor(field));
}
// An enum ARRAY property is IList with an empty-list initializer, except a
@@ -2623,7 +2633,7 @@ protected virtual string EnumProperty(
var colAttr = withAttributes && ColumnAttributeLine(entity, field, strategy, config.IncludeNames) is { } column
? column + "\n"
: "";
- return colAttr + PropertyDeclaration(entity, field, propName, "get; set;");
+ return colAttr + PropertyDeclaration(entity, field, propName, SetterFor(field));
}
// A scalar property. withAttributes adds the EF-mapping annotations ([Key] for a
@@ -2683,7 +2693,7 @@ protected virtual string ScalarProperty(
// POST value stays a NULL column instead of failing as a required collection; a
// NON-required value-object array is nullable so a null member is omitted on the wire.
// (That rule is the default of the PropertyClrType / PropertyInitializer hooks.)
- arr.Append(PropertyDeclaration(owner, field, propName, "get; set;"));
+ arr.Append(PropertyDeclaration(owner, field, propName, SetterFor(field)));
return arr.ToString();
}
@@ -2752,7 +2762,7 @@ protected virtual string ScalarProperty(
// the column from UPDATE). `writeOnce` keeps a PUBLIC setter on purpose — the caller
// must be able to supply it on insert; freezing it afterwards is the DbContext's
// SetAfterSaveBehavior(Ignore), not the property's job.
- var setter = field.IsReadOnlyMutability ? "get; private set;" : "get; set;";
+ var setter = SetterFor(field);
sb.Append(PropertyDeclaration(owner, field, propName, setter));
return sb.ToString();
}
@@ -3021,7 +3031,7 @@ protected static string EscapeAttrString(string s)
// single-VO nullability below. A non-null empty-list default would erase that
// null-vs-empty distinction (EF re-serializes the empty list to `[]` on write).
// (The type and initializer are the PropertyClrType / PropertyInitializer defaults.)
- return PropertyDeclaration(owner, field, propName, "get; set;", ctx);
+ return PropertyDeclaration(owner, field, propName, SetterFor(field), ctx);
}
// A property for a field.map (an open-keyed map). Emits a single
@@ -3051,7 +3061,7 @@ protected string MapProperty(MetaObject owner, MetaField field, GenContext ctx,
&& ColumnAttributeLine(owner, field, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, ctx) is { } column
? column + "\n"
: "";
- return colAttr + PropertyDeclaration(owner, field, propName, "get; set;", ctx);
+ return colAttr + PropertyDeclaration(owner, field, propName, SetterFor(field), ctx);
}
// The CLR scalar type for a projection field whose value is a MIN/MAX aggregate:
diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs
index 6d439938a3..53ff2ce597 100644
--- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs
+++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs
@@ -429,7 +429,8 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte
AppendCreateHandler(sb, "/" + route, cls, dbSet, requiredKeys,
CreatedResult("prefix + \"/" + route + "\"", "input", credentials), voFields, mapVoFields, autoSetFields,
writeThrough ? (readDbSet, pkProp!, route) : null, parseBody: HasDecimalField(entity) || HasIsoDurationField(entity, ctx.Root),
- deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials);
+ deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials,
+ ServerOwnedCreateResets(entity, ctx.Root, _ => { }));
// PATCH + PUT share the same handler — TS reference exposes both verbs, and both
// return the updated row (HTTP 200), matching the cross-port api-contract.
@@ -999,7 +1000,8 @@ private static void AppendCreateHandler(
(string ReadDbSet, string PkProp, string Route)? reRead = null,
bool parseBody = false,
IReadOnlyList? deniedNavs = null,
- IReadOnlyList? credentials = null)
+ IReadOnlyList? credentials = null,
+ IReadOnlyList? serverOwned = null)
{
// A decimal field can refuse its value while the body is bound (out of declared range, not a
// number). The framework's own binding answers that with a bare 400 and no body, so an entity
@@ -1008,6 +1010,7 @@ private static void AppendCreateHandler(
{
sb.AppendLine($" app.MapPost(prefix + \"{mapPath}\", async ({cls} input, AppDbContext db) =>");
sb.AppendLine(" {");
+ AppendCreateServerOwned(sb, serverOwned);
AppendCreateIgnoreDenied(sb, deniedNavs);
AppendCreateValidation(sb);
AppendCreateVoValidation(sb, voFields, mapVoFields);
@@ -1044,6 +1047,7 @@ private static void AppendCreateHandler(
sb.AppendLine(" try { input = System.Text.Json.JsonSerializer.Deserialize<" + cls + ">(__body.RootElement.GetRawText(), jsonOpts); }");
sb.AppendLine(" catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = \"validation\" }); }");
sb.AppendLine(" if (input is null) return Results.BadRequest(new { error = \"validation\" });");
+ AppendCreateServerOwned(sb, serverOwned);
AppendCreateIgnoreDenied(sb, deniedNavs);
AppendCreateValidation(sb);
AppendCreateVoValidation(sb, voFields, mapVoFields);
@@ -1078,6 +1082,45 @@ private static void AppendCreatePersist(
}
}
+ // Input hardening — a generated create hands storage ONLY what the client may set. The body is
+ // bound straight onto the EF entity, so every member the server owns is reset to its CLR default
+ // before validation and `Add`, and the request answers as if the key were absent (never a 400):
+ // - a server-generated primary key (@generation increment|uuid): default, so EF generates it;
+ // - the TPH discriminator on a per-subtype route: default, so EF's discriminator generator
+ // stamps the subtype's own @discriminatorValue (the route's subtype is its only source);
+ // - M:N navigation collections: emptied, else `Add` would insert a client-sent related graph.
+ // @readOnly fields need no line here: the entity declares them with a private setter, which
+ // System.Text.Json never binds (see EntityGenerator.SetterFor). Each statement is a complete line.
+ private static void AppendCreateServerOwned(StringBuilder sb, IReadOnlyList? statements)
+ {
+ if (statements is null || statements.Count == 0) return;
+ sb.AppendLine(" // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored.");
+ foreach (var st in statements) sb.AppendLine(" " + st);
+ }
+
+ // The reset statements AppendCreateServerOwned emits for one entity (empty when it has none, which
+ // keeps the output byte-identical for an entity without a generated key, navigation or discriminator).
+ private static List ServerOwnedCreateResets(MetaObject entity, MetaRoot root, Action onWarn, string? discProp = null, MetaObject? navOwner = null)
+ {
+ var list = new List();
+ if (entity.PrimaryIdentity() is MetaPrimaryIdentity
+ {
+ Generation: MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT
+ or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID,
+ Fields: [var keyName],
+ } && entity.Fields().FirstOrDefault(f => f.Name == keyName) is { } keyField)
+ list.Add($"input.{CSharpNaming.Pascal(keyField.Name)} = default!;");
+ if (discProp is not null) list.Add($"input.{discProp} = default!;");
+ // A TPH subtype class declares no M:N property of its own: the navigations that exist are those of the
+ // discriminator base class (navOwner), so a subtype route resets exactly those.
+ foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, onWarn))
+ {
+ var target = CSharpNaming.Pascal(nav.Target.Name);
+ list.Add($"input.{CSharpNaming.Pascal(nav.Name)} = new System.Collections.Generic.List<{target}>();");
+ }
+ return list;
+ }
+
// #484 — a write-denied key (@formExclude or credential) on a create body is IGNORED, never
// rejected: the bound value is reset to the CLR default (unset / null) before validation.
private static void AppendCreateIgnoreDenied(StringBuilder sb, IReadOnlyList? deniedNavs)
@@ -1493,7 +1536,8 @@ private static void AppendTphSubtypeRoutes(
AppendCreateHandler(sb, "/" + subRoute, subCls, dbSet, requiredKeys,
CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields,
parseBody: HasDecimalField(st.Entity) || HasIsoDurationField(st.Entity, root),
- deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials);
+ deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials,
+ serverOwned: ServerOwnedCreateResets(st.Entity, root, _ => { }, discProp, hierarchy[0]));
// Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped
// entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404.
diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs
index e6bc127b54..2e8ee64f3d 100644
--- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs
+++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs
@@ -151,6 +151,18 @@ public static void AssertResponse(string scenarioName, ApiRequest request, int s
$"{scenarioName} / {request.Id}: expected row.{kvp.Key}={Render(kvp.Value)}, got {Render(actual)}");
}
}
+ // The listed keys must not be on the object at all (not even as null): a key the client
+ // may not set never reached storage and so never comes back in the echo.
+ if (want.TryGetValue("absent", out var absentObj) && absentObj is List
*/
final class InMemoryAuthRepositorySource {
@@ -100,7 +100,9 @@ public Optional findByIdAndType(Long id, String discriminator) {
@Override
public AuthDto createWithType(String discriminator, AuthDto dto) {
- // Discriminator injected from the URL — dto.type() is intentionally ignored.
+ // A naive adopter repository: it trusts what it is handed (the id and the DTO's own
+ // discriminator when present, falling back to the URL's), so a value the controller
+ // forwarded from the request body is stored and the shared scenarios can see it.
// `type` is a value-constrained enum (field.enum discriminator), so coerce the
// String URL discriminator into the generated AuthType (its members ARE the
// discriminator values).
@@ -109,7 +111,8 @@ public AuthDto createWithType(String discriminator, AuthDto dto) {
// AuthDto.stampForInsert(dto) before calling createWithType — the repo just
// persists the incoming (already-stamped) autoCreatedAt/autoUpdatedAt verbatim.
AuthDto saved = new AuthDto(
- nextId.getAndIncrement(), AuthDto.AuthType.valueOf(discriminator), dto.reference(),
+ dto.id() != null ? dto.id() : Long.valueOf(nextId.getAndIncrement()),
+ dto.type() != null ? dto.type() : AuthDto.AuthType.valueOf(discriminator), dto.reference(),
// FR-037 R1: writeOnce IS bound on create — settable exactly once.
dto.issuedCurrency(),
dto.autoCreatedAt(), dto.autoUpdatedAt(),
diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md
index 2cb454b8d7..1b300bfa6f 100644
--- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md
+++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md
@@ -36,9 +36,9 @@ The generated router takes `dto: dict[str, Any]` for `POST` / `PATCH` /
(`from . import , Patch`) and constructs them to enforce
field constraints over HTTP — POST validates `(**dto)`, PATCH validates
the all-optional `Patch(**dto)` (present values only) → `400 {"error":"validation"}`.
-The repository seam still receives the original `dict` (preserving the FR-035
-present-key tristate + wire values), so the strong-typing simplification below
-remains for the repo/response types; only the validation import was added.
+The repository seam receives only the keys the input model validated, as a `dict`
+(the FR-035 present-key tristate + wire values are kept), so the strong-typing
+simplification below remains for the repo/response types.
This keeps the router module decoupled from sibling generated files
(the entity-model generator emits one `@dataclass`/Pydantic model per
diff --git a/server/python/src/metaobjects/codegen/generators/router_generator.py b/server/python/src/metaobjects/codegen/generators/router_generator.py
index 175d3beff3..6323db2384 100644
--- a/server/python/src/metaobjects/codegen/generators/router_generator.py
+++ b/server/python/src/metaobjects/codegen/generators/router_generator.py
@@ -486,10 +486,9 @@ def _frozen_names(entity: MetaObject) -> list[str]:
ADR-0045: the OUTERMOST generated write artifact enforces the mode, and for
FastAPI that is the ROUTER, not the ``Patch`` model — the handler binds
- ``dto`` (the raw body as a dict) and passes THAT to the repository, so a
- field merely absent from the patch model still reaches the row. @autoSet gets
- away with it because the router OVERWRITES its key server-side; a writeOnce
- field has no server value to overwrite, so it must be popped explicitly."""
+ ``dto`` as a dict. Since 1.2.1 the router hands the repository only the keys the
+ patch model validated (:func:`_validated_input_lines`), which already drops these;
+ the explicit pop stays as the FR-037 seam an owned router edits."""
return [
f.name
for f in entity.fields()
@@ -513,6 +512,49 @@ def _frozen_strip_lines(entity: MetaObject, indent: str = " ") -> list[str]:
]
+#: 1.2.1 security fix. The request body cut down to what the input model validated, emitted
+#: once per writable router. 1.2.0 validated the body and then handed the RAW body to the
+#: repository, so a client-sent server-generated id, a ``readOnly`` field or a name the entity
+#: does not declare (an ``isAdmin``) reached the write. Pydantic ignores a key a model does not
+#: declare, and the input models leave out every field a client may not set, so keeping only
+#: the keys the model validated (at every depth: a nested value object included) drops all of
+#: them silently, as the TypeScript routes do. The values stay the body's own (decimal-exact)
+#: values, so a repository receives the same value types as in 1.2.0.
+_VALIDATED_INPUT_LINES: list[str] = [
+ "def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]:",
+ ' """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the',
+ " input model does not declare (an undeclared name, a server-generated id, a readOnly field)",
+ ' is dropped silently and never reaches the repository; values stay the body\'s own."""',
+ " return {_k: _validated_value(getattr(valid, _k), raw[_k]) for _k in valid.model_fields_set}",
+ "",
+ "",
+ "def _validated_value(valid: Any, raw: Any) -> Any:",
+ " if isinstance(valid, BaseModel) and isinstance(raw, dict):",
+ " return _validated_input(valid, raw)",
+ " if isinstance(valid, list) and isinstance(raw, list):",
+ " return [_validated_value(v, r) for v, r in zip(valid, raw)]",
+ " if isinstance(valid, dict) and isinstance(raw, dict):",
+ " return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw}",
+ " return raw",
+]
+
+
+def _validated_input_lines(model: str, *comment: str) -> list[str]:
+ """Validate ``dto`` against the input *model*, then rebind it to what the model validated
+ (see :data:`_VALIDATED_INPUT_LINES`): the repository never sees any other key."""
+ return [
+ *(f" # {line}" for line in comment),
+ " try:",
+ f" _valid = {model}(**dto)",
+ " except ValidationError:",
+ ' return JSONResponse(status_code=400, content={"error": "validation"})',
+ " # SECURITY (1.2.1): only what the input model validated reaches the repository. A key",
+ " # it does not declare (an undeclared name, a server-generated id, a readOnly or derived",
+ " # field, a frozen one on update) is dropped silently, never 400'd.",
+ " dto = _validated_input(_valid, dto)",
+ ]
+
+
def _auto_set_split(entity: MetaObject) -> tuple[list[MetaField], list[MetaField]]:
"""The entity's ``@autoSet`` temporal fields split into ``(onCreate, onUpdate)``.
@@ -1135,12 +1177,11 @@ def _emit_route_handler(
") -> Any:",
*_DECIMAL_COERCE,
*denied_strip,
- " # FR-036: run the generated field constraints (length / pattern /",
- " # numeric bounds) before persisting; a violation is the cross-port 400.",
- " try:",
- f" {model_name}(**dto)",
- " except ValidationError:",
- ' return JSONResponse(status_code=400, content={"error": "validation"})',
+ *_validated_input_lines(
+ model_name,
+ "FR-036: run the generated field constraints (length / pattern /",
+ "numeric bounds) before persisting; a violation is the cross-port 400.",
+ ),
# #203/ADR-0045: the generated router (the API surface) stamps @autoSet columns
# ABOVE the consumer repo seam — onCreate + onUpdate both stamped from one instant
# (a fresh row's createdAt == updatedAt), ignoring any caller-supplied value.
@@ -1166,12 +1207,11 @@ def _emit_route_handler(
" for _k in _REQUIRED_FIELDS:",
" if _k in dto and dto[_k] is None:",
' return JSONResponse(status_code=400, content={"error": "validation"})',
- " # FR-036: validate PRESENT, non-null values with the create rules (the",
- " # all-optional patch model never fires required-checks on ABSENT fields).",
- " try:",
- f" {patch_model}(**dto)",
- " except ValidationError:",
- ' return JSONResponse(status_code=400, content={"error": "validation"})',
+ *_validated_input_lines(
+ patch_model,
+ "FR-036: validate PRESENT, non-null values with the create rules (the",
+ "all-optional patch model never fires required-checks on ABSENT fields).",
+ ),
# #203/ADR-0045: bump onUpdate @autoSet columns (server-owned) on EVERY patch,
# above the repo seam — a server-inserted present key (compatible with the PATCH
# present-key tristate); onCreate columns are never touched here.
@@ -1521,6 +1561,9 @@ def _render_tph_router(
parts.extend(_JSON_BODY_LINES)
parts.append("")
parts.append("")
+ parts.extend(_VALIDATED_INPUT_LINES)
+ parts.append("")
+ parts.append("")
# FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so
# the generated module always carries the seam (an entity that later gains a
# writeOnce field changes one literal, not the module's shape).
@@ -1600,11 +1643,13 @@ def list_sig(fn: str, route: str) -> list[str]:
parts.append(") -> Any:")
parts.extend(_DECIMAL_COERCE)
parts.extend(denied_strip_tph)
- parts.append(" # FR-036: run the subtype's field constraints before persisting.")
- parts.append(" try:")
- parts.append(f" {sub}Create(**dto)")
- parts.append(" except ValidationError:")
- parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})')
+ # The route's subtype is the only source of the discriminator: a body value is
+ # dropped silently before validation (as the TypeScript route's `.omit` does), so
+ # a foreign tag is never a 400 and never reaches the repository.
+ parts.append(f' dto.pop("{plan.discriminator_field}", None)')
+ parts.extend(_validated_input_lines(
+ f"{sub}Create", "FR-036: run the subtype's field constraints before persisting."
+ ))
# #203/ADR-0045: stamp @autoSet columns ABOVE the repo seam (empty for a
# non-@autoSet hierarchy — byte-identical output).
parts.extend(create_autoset)
@@ -1637,11 +1682,9 @@ def list_sig(fn: str, route: str) -> list[str]:
parts.append(" for _k in _REQUIRED_FIELDS:")
parts.append(" if _k in dto and dto[_k] is None:")
parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})')
- parts.append(" # FR-036: validate PRESENT, non-null values with the subtype's create rules.")
- parts.append(" try:")
- parts.append(f" {sub}Patch(**dto)")
- parts.append(" except ValidationError:")
- parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})')
+ parts.extend(_validated_input_lines(
+ f"{sub}Patch", "FR-036: validate PRESENT, non-null values with the subtype's create rules."
+ ))
# #203/ADR-0045: pop the write-once onCreate column(s), bump onUpdate — ABOVE
# the repo seam (empty for a non-@autoSet hierarchy — byte-identical output).
parts.extend(update_autoset)
@@ -1911,6 +1954,9 @@ def render_router(
parts.extend(_JSON_BODY_LINES)
parts.append("")
parts.append("")
+ parts.extend(_VALIDATED_INPUT_LINES)
+ parts.append("")
+ parts.append("")
# FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so
# the generated module always carries the seam (an entity that later gains a
# writeOnce field changes one literal, not the module's shape).
@@ -1946,8 +1992,8 @@ def render_router(
create_autoset=create_autoset,
update_autoset=update_autoset,
# FR-037 R1 — ADR-0045: the ROUTER is the outermost write artifact for
- # FastAPI (the handler binds the RAW body dict and hands THAT to the
- # repository), so the strip has to live here, not in Patch.
+ # FastAPI (the handler binds the body as a dict), so the strip lives here,
+ # not in Patch.
frozen_strip=_frozen_strip_lines(entity),
denied_strip=_denied_strip_lines(denied_names),
)
diff --git a/server/python/tests/integration/api_contract_assertions.py b/server/python/tests/integration/api_contract_assertions.py
index 11a6f33445..4d700250b9 100644
--- a/server/python/tests/integration/api_contract_assertions.py
+++ b/server/python/tests/integration/api_contract_assertions.py
@@ -202,6 +202,19 @@ def assert_response(
f"but both = {a_value!r}"
)
+ if "absent" in expect_body:
+ # The listed keys must not be on the object at all (not even as null): a key the
+ # client may not set never reached storage and so never comes back in the echo.
+ if not isinstance(body, dict):
+ raise AssertionError(
+ f"{scenario_name} / {request_id}: expected object for absent, got: {body!r}"
+ )
+ present = [k for k in expect_body["absent"] if k in body]
+ if present:
+ raise AssertionError(
+ f"{scenario_name} / {request_id}: expected no {present!r} in body, got: {body!r}"
+ )
+
if expect_body.get("hasId") is True:
if not isinstance(body, dict):
raise AssertionError(
diff --git a/server/python/tests/integration/generated_secret_fields_app.py b/server/python/tests/integration/generated_secret_fields_app.py
index 61d9eb9a4e..3a6a1f2f1c 100644
--- a/server/python/tests/integration/generated_secret_fields_app.py
+++ b/server/python/tests/integration/generated_secret_fields_app.py
@@ -28,7 +28,7 @@
from .corpus_config import attach_corpus_wire
from .generated_router_app import InMemoryAuthorRepository
-COLUMNS = ("id", "name", "tokenHash", "pinHash")
+COLUMNS = ("id", "name", "tokenHash", "pinHash", "role")
def load_account(meta_json: Path) -> MetaObject:
diff --git a/server/python/tests/integration/test_generated_router_validated_input.py b/server/python/tests/integration/test_generated_router_validated_input.py
new file mode 100644
index 0000000000..b43ed21c08
--- /dev/null
+++ b/server/python/tests/integration/test_generated_router_validated_input.py
@@ -0,0 +1,272 @@
+"""1.2.1 security fix: a generated create / update hands the repository ONLY the validated input.
+
+The 1.2.0 router validated the request body against ``Create`` / ``Patch`` and
+then passed the RAW body to the repository. Pydantic ignores a key a model does not declare, and
+the input models leave out the server-owned fields, so a client-sent ``id``, a ``readOnly`` field
+and a made-up ``isAdmin`` all reached the write. Now the repository receives only what the input
+model validated, at every depth, as with the TypeScript routes: a name the entity does not
+declare, a server-generated id, a ``readOnly`` field and the id on update are all dropped
+silently. None of them is a 400: a client that sends an extra harmless field keeps working.
+
+The model is generated with the real Python codegen (``run_gen``: entity + filter-allowlist +
+routes), the emitted package is imported unmodified, and the only hand-written piece is a
+repository that records what it was handed. No database: the router is the artifact, as in the
+other generated-router lanes.
+"""
+from __future__ import annotations
+
+import importlib
+import json
+import sys
+import tempfile
+import uuid
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from metaobjects import MetaDataLoader
+from metaobjects.codegen.config import GenConfig
+from metaobjects.codegen.generators.entity_model import entity_model
+from metaobjects.codegen.generators.filter_allowlist_generator import filter_allowlist_generator
+from metaobjects.codegen.generators.router_generator import router_generator
+from metaobjects.codegen.runner import run_gen
+
+from .generated_tph_app import build_generated_tph_app
+
+_META = {
+ "metadata.root": {
+ "package": "acme::secfix",
+ "children": [
+ {"object.value": {
+ "name": "Address",
+ "children": [
+ {"field.string": {"name": "city", "@maxLength": 40}},
+ ],
+ }},
+ {"object.entity": {
+ "name": "Member",
+ "children": [
+ {"source.rdb": {"@table": "members"}},
+ {"field.long": {"name": "id"}},
+ {"field.string": {"name": "name", "@required": True, "@maxLength": 80}},
+ {"field.string": {"name": "role", "@maxLength": 20, "@mutability": "readOnly"}},
+ {"field.string": {"name": "tenant", "@maxLength": 20, "@mutability": "writeOnce"}},
+ {"field.object": {"name": "address", "@objectRef": "Address", "@storage": "jsonb"}},
+ {"field.timestamp": {"name": "createdAt", "@autoSet": "onCreate"}},
+ {"identity.primary": {"name": "id", "@fields": "id", "@generation": "increment"}},
+ ],
+ }},
+ {"object.entity": {
+ "name": "Account",
+ "children": [
+ {"source.rdb": {"@table": "accounts"}},
+ {"field.string": {"name": "code", "@maxLength": 20}},
+ {"field.string": {"name": "label", "@maxLength": 80}},
+ {"identity.primary": {"name": "code", "@fields": "code"}},
+ ],
+ }},
+ ],
+ }
+}
+
+
+class _RecordingRepo:
+ """The generated repository seam, recording every write it is handed."""
+
+ def __init__(self, pk: str) -> None:
+ self.pk = pk
+ self.writes: list[tuple[str, dict[str, Any]]] = []
+
+ def create(self, dto: Any) -> Any:
+ self.writes.append(("create", dict(dto)))
+ return {self.pk: 1, **dto}
+
+ def update(self, id: Any, dto: Any) -> Any | None:
+ self.writes.append(("update", dict(dto)))
+ return {self.pk: id, **dto}
+
+
+def _generate_package() -> str:
+ """Run the real Python codegen for ``_META`` into a temp package; return its name."""
+ meta_dir = Path(tempfile.mkdtemp(prefix="secfix-meta-"))
+ (meta_dir / "meta.json").write_text(json.dumps(_META))
+ loaded = MetaDataLoader.from_directory(str(meta_dir))
+ assert not loaded.errors, "; ".join(f"{e.code}: {e.message}" for e in loaded.errors)
+ pkg = f"secfix_{uuid.uuid4().hex[:8]}"
+ root = Path(tempfile.mkdtemp(prefix="secfix-gen-"))
+ run_gen(
+ GenConfig(out_dir=str(root / pkg)),
+ loaded.root,
+ generators=[entity_model(), filter_allowlist_generator(), router_generator()],
+ )
+ sys.path.insert(0, str(root))
+ return pkg
+
+
+_PKG = _generate_package()
+
+
+def _client(router_module: str, pk: str) -> tuple[TestClient, _RecordingRepo, str]:
+ mod = importlib.import_module(f"{_PKG}.{router_module}")
+ repo = _RecordingRepo(pk)
+ app = FastAPI()
+ app.include_router(mod.router)
+ app.dependency_overrides[mod.get_repository] = lambda: repo
+ return TestClient(app), repo, mod.router.prefix
+
+
+@pytest.fixture()
+def member() -> tuple[TestClient, _RecordingRepo, str]:
+ return _client("member_router", "id")
+
+
+@pytest.fixture()
+def account() -> tuple[TestClient, _RecordingRepo, str]:
+ return _client("account_router", "code")
+
+
+# --- the reported defect: a client-sent id and a made-up isAdmin reach the repository -------
+
+
+def test_create_never_hands_the_repository_a_client_id_or_an_undeclared_field(member) -> None:
+ client, repo, base = member
+ resp = client.post(base, json={"id": 999, "name": "Mallory", "isAdmin": True})
+ assert resp.status_code == 201, resp.text
+ [(op, written)] = repo.writes
+ assert op == "create"
+ assert set(written) == {"name", "createdAt"} # createdAt is the router's own stamp
+ assert written["name"] == "Mallory"
+
+
+@pytest.mark.parametrize("method", ["PATCH", "PUT"])
+def test_update_never_hands_the_repository_an_undeclared_field(member, method: str) -> None:
+ client, repo, base = member
+ resp = client.request(method, f"{base}/1", json={"name": "M", "isAdmin": True})
+ assert resp.status_code == 200, resp.text
+ assert repo.writes == [("update", {"name": "M"})]
+
+
+def test_an_undeclared_key_inside_a_value_object_never_reaches_the_repository(member) -> None:
+ client, repo, base = member
+ resp = client.post(base, json={"name": "Mallory", "address": {"city": "Oslo", "isAdmin": True}})
+ assert resp.status_code == 201, resp.text
+ [(_op, written)] = repo.writes
+ assert written["address"] == {"city": "Oslo"}
+
+
+def test_a_malformed_value_on_a_settable_field_is_still_a_400(member) -> None:
+ client, repo, base = member
+ resp = client.post(base, json={"name": "x" * 81, "isAdmin": True})
+ assert resp.status_code == 400, resp.text
+ assert resp.json() == {"error": "validation"}
+ assert repo.writes == []
+
+
+# --- declared but not settable: dropped, never 400'd, and never handed to the repository ----
+
+
+def test_create_strips_the_client_id_and_a_read_only_field(member) -> None:
+ client, repo, base = member
+ resp = client.post(
+ base,
+ json={"id": 999, "name": "Mallory", "role": "admin", "tenant": "t1",
+ "address": {"city": "Oslo"}},
+ )
+ assert resp.status_code == 201, resp.text
+ [(op, written)] = repo.writes
+ assert op == "create"
+ # The server generates the id and owns `role`; `createdAt` is the router's own stamp.
+ assert set(written) == {"name", "tenant", "address", "createdAt"}
+ assert written["name"] == "Mallory"
+ assert written["tenant"] == "t1" # writeOnce is settable on create
+ assert written["address"] == {"city": "Oslo"}
+
+
+@pytest.mark.parametrize("method", ["PATCH", "PUT"])
+def test_update_never_hands_the_repository_the_id_or_a_frozen_field(member, method: str) -> None:
+ client, repo, base = member
+ resp = client.request(
+ method,
+ f"{base}/1",
+ json={"id": 999, "name": "M2", "role": "admin", "tenant": "t2", "createdAt": "2000-01-01T00:00:00Z"},
+ )
+ assert resp.status_code == 200, resp.text
+ assert repo.writes == [("update", {"name": "M2"})]
+
+
+def test_update_passes_a_present_null_through_as_a_clear(member) -> None:
+ """The PATCH present-key tristate is unchanged: an explicit null on a nullable field clears it."""
+ client, repo, base = member
+ resp = client.patch(f"{base}/1", json={"address": None})
+ assert resp.status_code == 200, resp.text
+ assert repo.writes == [("update", {"address": None})]
+
+
+def test_an_assigned_key_is_still_the_callers_on_create_and_route_owned_on_update(account) -> None:
+ client, repo, base = account
+ created = client.post(base, json={"code": "ACME", "label": "Acme"})
+ assert created.status_code == 201, created.text
+ updated = client.patch(f"{base}/ACME", json={"code": "EVIL", "label": "Acme 2"})
+ assert updated.status_code == 200, updated.text
+ assert repo.writes == [
+ ("create", {"code": "ACME", "label": "Acme"}),
+ ("update", {"label": "Acme 2"}),
+ ]
+
+
+# --- TPH: the per-subtype create / update handlers are a separate code path -----------------
+
+
+def _find_tph_dir() -> Path:
+ cur = Path(__file__).resolve()
+ while cur != cur.parent:
+ candidate = cur / "fixtures" / "api-contract-conformance" / "tph"
+ if candidate.is_dir():
+ return candidate
+ cur = cur.parent
+ raise RuntimeError("fixtures/api-contract-conformance/tph not found")
+
+
+@pytest.fixture()
+def tph() -> tuple[TestClient, list[tuple[str, str, dict[str, Any]]]]:
+ app, repo = build_generated_tph_app(_find_tph_dir())
+ writes: list[tuple[str, str, dict[str, Any]]] = []
+ create, update = repo.create, repo.update
+
+ def recording_create(subtype: str, dto: Any) -> Any:
+ writes.append(("create", subtype, dict(dto)))
+ return create(subtype, dto)
+
+ def recording_update(subtype: str, id: int, dto: Any) -> Any:
+ writes.append(("update", subtype, dict(dto)))
+ return update(subtype, id, dto)
+
+ repo.create, repo.update = recording_create, recording_update
+ return TestClient(app), writes
+
+
+def test_tph_subtype_create_drops_the_client_id_and_an_undeclared_field(tph) -> None:
+ client, writes = tph
+ resp = client.post(
+ "/api/auths/bridge", json={"id": 999, "reference": "R-1", "quantity": 2, "isAdmin": True}
+ )
+ assert resp.status_code == 201, resp.text
+ [(op, subtype, written)] = writes
+ assert (op, subtype) == ("create", "Bridge")
+ assert "id" not in written
+ assert "isAdmin" not in written
+ assert {"reference", "quantity"} <= set(written)
+
+
+def test_tph_subtype_update_drops_the_id_and_an_undeclared_field(tph) -> None:
+ client, writes = tph
+ # The store is unseeded, so the answer is a 404; what matters is what the write was handed.
+ client.patch("/api/auths/bridge/1", json={"id": 999, "quantity": 3, "isAdmin": True})
+ [(op, subtype, written)] = writes
+ assert (op, subtype) == ("update", "Bridge")
+ assert "id" not in written
+ assert "isAdmin" not in written
+ assert written["quantity"] == 3
diff --git a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts
index 714f11d277..4035e3f9c4 100644
--- a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts
+++ b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts
@@ -719,6 +719,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] {
*/
export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
const autoGenPkFields = autoGenPkFieldNames(obj);
+ const pkFields = primaryKeyFieldNames(obj);
const tphPin = tphDiscriminatorPin(obj);
const out: SchemaFieldShape[] = [];
for (const child of flatSurfaceFields(obj)) {
@@ -734,6 +735,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
// edit form for an entity carrying one. Clearing counts as a write, so the
// FR-035 present-null arm never reaches it either.
if (isWriteOnceMutability(child)) continue;
+ // A primary-key field is the row's identity, which the URL names: an ASSIGNED key is
+ // omitted from the update shape exactly like a generated one, so a client-sent id is
+ // stripped and can never re-key the row.
+ if (pkFields.has(child.name)) continue;
// TPH subtype discriminator: omitted from the update schema entirely.
if (tphPin !== undefined && child.name === tphPin.fieldName) continue;
const autoSet = child.attr(FIELD_ATTR_AUTO_SET);
@@ -818,6 +823,9 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
// below; a value presented on PATCH is stripped, not 400'd (see
// updateSchemaFields for the grounding).
if (isWriteOnceMutability(child)) continue;
+ // The row's identity is the URL's: an ASSIGNED primary key leaves the update shape too
+ // (a generated one never entered it), so a client-sent id is stripped, never a re-key.
+ if (pkFields.has(child.name)) continue;
// Update schema: @autoSet onCreate → omit entirely; onUpdate → transform
if (autoSet === AUTO_SET_ON_CREATE) {
diff --git a/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap b/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap
index 52ec2cdb9c..2ed61838bc 100644
--- a/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap
+++ b/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap
@@ -205,36 +205,36 @@ Generated API reference for this project; call these exactly as written. Imports
\`import { Program, ProgramInsertSchema, ProgramUpdateSchema } from "./Program"\`
- \`interface Program { id: number; title?: string; createdAt?: string }\` — The typed shape of a Program row, generated from its metadata.
- \`ProgramInsertSchema: ZodType<{ id: number; title?: string; createdAt?: string }>\` — Zod schema validating the body of a create / POST request (auto-generated PKs excluded).
-- \`ProgramUpdateSchema: ZodType<{ id?: number; title?: string; createdAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional).
+- \`ProgramUpdateSchema: ZodType<{ title?: string; createdAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional).
\`import { findProgramById, listPrograms, createProgram, updateProgram, deleteProgramById } from "./Program.queries"\`
- \`findProgramById(db: Db, id: number): Promise\` — Fetch a single Program by its primary key; null when not found.
- \`listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise\` — List Program rows with optional limit/offset paging.
- \`createProgram(db: Db, data: { id: number; title?: string; createdAt?: string }): Promise\` — Validate (via ProgramInsertSchema) and insert a new Program. [throws: ZodError when data fails ProgramInsertSchema validation.]
-- \`updateProgram(db: Db, id: number, patch: { id?: number; title?: string; createdAt?: string }): Promise\` — Partially update a Program by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails ProgramUpdateSchema validation.]
+- \`updateProgram(db: Db, id: number, patch: { title?: string; createdAt?: string }): Promise\` — Partially update a Program by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails ProgramUpdateSchema validation.]
- \`deleteProgramById(db: Db, id: number): Promise\` — Delete a Program by primary key; true when a row was removed.
\`import { programRoutes } from "./Program.routes"\`
- \`GET /api/programs -> { id: number; title?: string; createdAt?: string }\` — List Program (supports filter/sort/paging query params).
- \`GET /api/programs/:id -> { id: number; title?: string; createdAt?: string }\` — Fetch a single Program by id (404 when not found).
- \`POST /api/programs body: { id: number; title?: string; createdAt?: string }\` — Create a Program (body validated by ProgramInsertSchema).
-- \`PATCH /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — Partially update a Program by id (body validated by ProgramUpdateSchema).
-- \`PUT /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema).
+- \`PATCH /api/programs/:id body: { title?: string; createdAt?: string }\` — Partially update a Program by id (body validated by ProgramUpdateSchema).
+- \`PUT /api/programs/:id body: { title?: string; createdAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema).
- \`DELETE /api/programs/:id\` — Delete a Program by id.
\`import { registerProgramRoutes } from "./Program.routes.hono"\`
- \`GET /api/programs -> { id: number; title?: string; createdAt?: string }\` — [Hono] List Program (filter/sort/paging query params).
- \`GET /api/programs/:id -> { id: number; title?: string; createdAt?: string }\` — [Hono] Fetch a single Program by id (404 when not found).
- \`POST /api/programs body: { id: number; title?: string; createdAt?: string }\` — [Hono] Create a Program (body validated by ProgramInsertSchema).
-- \`PATCH /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — [Hono] Partially update a Program by id (body validated by ProgramUpdateSchema).
-- \`PUT /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema).
+- \`PATCH /api/programs/:id body: { title?: string; createdAt?: string }\` — [Hono] Partially update a Program by id (body validated by ProgramUpdateSchema).
+- \`PUT /api/programs/:id body: { title?: string; createdAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema).
- \`DELETE /api/programs/:id\` — [Hono] Delete a Program by id.
Example:
\`\`\`ts
const created = await createProgram(db, { id: 1 });
const found = await findProgramById(db, created.id);
-const updated = await updateProgram(db, created.id, { id: 1 });
+const updated = await updateProgram(db, created.id, { title: "…" });
const removed = await deleteProgramById(db, created.id);
\`\`\`
@@ -243,37 +243,37 @@ const removed = await deleteProgramById(db, created.id);
\`import { Purchase, PurchaseInsertSchema, PurchaseUpdateSchema, purchasesRelations } from "./Purchase"\`
- \`interface Purchase { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — The typed shape of a Purchase row, generated from its metadata.
- \`PurchaseInsertSchema: ZodType<{ id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }>\` — Zod schema validating the body of a create / POST request (auto-generated PKs excluded).
-- \`PurchaseUpdateSchema: ZodType<{ id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional).
+- \`PurchaseUpdateSchema: ZodType<{ programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional).
- \`const purchasesRelations { program?: Program (1:1 / N:1) }\` — Drizzle relations() for Purchase — register it with your schema, then traverse via the relational query API (db.query.purchases.findMany({ with: { … } })).
\`import { findPurchaseById, listPurchases, createPurchase, updatePurchase, deletePurchaseById } from "./Purchase.queries"\`
- \`findPurchaseById(db: Db, id: number): Promise\` — Fetch a single Purchase by its primary key; null when not found.
- \`listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise\` — List Purchase rows with optional limit/offset paging.
- \`createPurchase(db: Db, data: { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }): Promise\` — Validate (via PurchaseInsertSchema) and insert a new Purchase. [throws: ZodError when data fails PurchaseInsertSchema validation.]
-- \`updatePurchase(db: Db, id: number, patch: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }): Promise\` — Partially update a Purchase by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails PurchaseUpdateSchema validation.]
+- \`updatePurchase(db: Db, id: number, patch: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }): Promise\` — Partially update a Purchase by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails PurchaseUpdateSchema validation.]
- \`deletePurchaseById(db: Db, id: number): Promise\` — Delete a Purchase by primary key; true when a row was removed.
\`import { purchaseRoutes } from "./Purchase.routes"\`
- \`GET /api/purchases -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — List Purchase (supports filter/sort/paging query params).
- \`GET /api/purchases/:id -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Fetch a single Purchase by id (404 when not found).
- \`POST /api/purchases body: { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Create a Purchase (body validated by PurchaseInsertSchema).
-- \`PATCH /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Partially update a Purchase by id (body validated by PurchaseUpdateSchema).
-- \`PUT /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema).
+- \`PATCH /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Partially update a Purchase by id (body validated by PurchaseUpdateSchema).
+- \`PUT /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema).
- \`DELETE /api/purchases/:id\` — Delete a Purchase by id.
\`import { registerPurchaseRoutes } from "./Purchase.routes.hono"\`
- \`GET /api/purchases -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] List Purchase (filter/sort/paging query params).
- \`GET /api/purchases/:id -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Fetch a single Purchase by id (404 when not found).
- \`POST /api/purchases body: { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Create a Purchase (body validated by PurchaseInsertSchema).
-- \`PATCH /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Partially update a Purchase by id (body validated by PurchaseUpdateSchema).
-- \`PUT /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema).
+- \`PATCH /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Partially update a Purchase by id (body validated by PurchaseUpdateSchema).
+- \`PUT /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema).
- \`DELETE /api/purchases/:id\` — [Hono] Delete a Purchase by id.
Example:
\`\`\`ts
const created = await createPurchase(db, { id: 1 });
const found = await findPurchaseById(db, created.id);
-const updated = await updatePurchase(db, created.id, { id: 1 });
+const updated = await updatePurchase(db, created.id, { programId: 1 });
const removed = await deletePurchaseById(db, created.id);
\`\`\`
@@ -282,36 +282,36 @@ const removed = await deletePurchaseById(db, created.id);
\`import { WorkoutEvent, WorkoutEventInsertSchema, WorkoutEventUpdateSchema } from "./WorkoutEvent"\`
- \`interface WorkoutEvent { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — The typed shape of a WorkoutEvent row, generated from its metadata.
- \`WorkoutEventInsertSchema: ZodType<{ id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }>\` — Zod schema validating the body of a create / POST request (auto-generated PKs excluded).
-- \`WorkoutEventUpdateSchema: ZodType<{ id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional).
+- \`WorkoutEventUpdateSchema: ZodType<{ programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional).
\`import { findWorkoutEventById, listWorkoutEvents, createWorkoutEvent, updateWorkoutEvent, deleteWorkoutEventById } from "./WorkoutEvent.queries"\`
- \`findWorkoutEventById(db: Db, id: number): Promise\` — Fetch a single WorkoutEvent by its primary key; null when not found.
- \`listWorkoutEvents(db: Db, opts?: { limit?: number; offset?: number }): Promise\` — List WorkoutEvent rows with optional limit/offset paging.
- \`createWorkoutEvent(db: Db, data: { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }): Promise\` — Validate (via WorkoutEventInsertSchema) and insert a new WorkoutEvent. [throws: ZodError when data fails WorkoutEventInsertSchema validation.]
-- \`updateWorkoutEvent(db: Db, id: number, patch: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }): Promise\` — Partially update a WorkoutEvent by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails WorkoutEventUpdateSchema validation.]
+- \`updateWorkoutEvent(db: Db, id: number, patch: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }): Promise\` — Partially update a WorkoutEvent by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails WorkoutEventUpdateSchema validation.]
- \`deleteWorkoutEventById(db: Db, id: number): Promise\` — Delete a WorkoutEvent by primary key; true when a row was removed.
\`import { workoutEventRoutes } from "./WorkoutEvent.routes"\`
- \`GET /api/workout_events -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — List WorkoutEvent (supports filter/sort/paging query params).
- \`GET /api/workout_events/:id -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Fetch a single WorkoutEvent by id (404 when not found).
- \`POST /api/workout_events body: { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Create a WorkoutEvent (body validated by WorkoutEventInsertSchema).
-- \`PATCH /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema).
-- \`PUT /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema).
+- \`PATCH /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema).
+- \`PUT /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema).
- \`DELETE /api/workout_events/:id\` — Delete a WorkoutEvent by id.
\`import { registerWorkoutEventRoutes } from "./WorkoutEvent.routes.hono"\`
- \`GET /api/workout_events -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] List WorkoutEvent (filter/sort/paging query params).
- \`GET /api/workout_events/:id -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Fetch a single WorkoutEvent by id (404 when not found).
- \`POST /api/workout_events body: { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Create a WorkoutEvent (body validated by WorkoutEventInsertSchema).
-- \`PATCH /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema).
-- \`PUT /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema).
+- \`PATCH /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema).
+- \`PUT /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema).
- \`DELETE /api/workout_events/:id\` — [Hono] Delete a WorkoutEvent by id.
Example:
\`\`\`ts
const created = await createWorkoutEvent(db, { id: 1 });
const found = await findWorkoutEventById(db, created.id);
-const updated = await updateWorkoutEvent(db, created.id, { id: 1 });
+const updated = await updateWorkoutEvent(db, created.id, { programId: 1 });
const removed = await deleteWorkoutEventById(db, created.id);
\`\`\`
"
@@ -344,7 +344,7 @@ import { createProgram, findProgramById, updateProgram, deleteProgramById } from
const created = await createProgram(db, { id: 1 });
const found = await findProgramById(db, created.id);
-const updated = await updateProgram(db, created.id, { id: 1 });
+const updated = await updateProgram(db, created.id, { title: "…" });
const removed = await deleteProgramById(db, created.id);
\`\`\`
@@ -414,7 +414,6 @@ Request body (data):
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`title\` | \`string\` | | |
| \`createdAt\` | \`string\` | | |
@@ -496,7 +495,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`title\` | \`string\` | | |
| \`createdAt\` | \`string\` | | |
@@ -514,7 +512,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`title\` | \`string\` | | |
| \`createdAt\` | \`string\` | | |
@@ -598,7 +595,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`title\` | \`string\` | | |
| \`createdAt\` | \`string\` | | |
@@ -616,7 +612,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`title\` | \`string\` | | |
| \`createdAt\` | \`string\` | | |
@@ -662,7 +657,6 @@ Accepted fields:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`title\` | \`string\` | | |
| \`createdAt\` | \`string\` | | |
"
@@ -695,7 +689,7 @@ import { createPurchase, findPurchaseById, updatePurchase, deletePurchaseById }
const created = await createPurchase(db, { id: 1 });
const found = await findPurchaseById(db, created.id);
-const updated = await updatePurchase(db, created.id, { id: 1 });
+const updated = await updatePurchase(db, created.id, { programId: 1 });
const removed = await deletePurchaseById(db, created.id);
\`\`\`
@@ -791,7 +785,6 @@ Request body (data):
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`amountCents\` | \`number\` | | |
@@ -893,7 +886,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`amountCents\` | \`number\` | | |
@@ -916,7 +908,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`amountCents\` | \`number\` | | |
@@ -1020,7 +1011,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`amountCents\` | \`number\` | | |
@@ -1043,7 +1033,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`amountCents\` | \`number\` | | |
@@ -1099,7 +1088,6 @@ Accepted fields:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`amountCents\` | \`number\` | | |
@@ -1151,7 +1139,7 @@ import { createWorkoutEvent, findWorkoutEventById, updateWorkoutEvent, deleteWor
const created = await createWorkoutEvent(db, { id: 1 });
const found = await findWorkoutEventById(db, created.id);
-const updated = await updateWorkoutEvent(db, created.id, { id: 1 });
+const updated = await updateWorkoutEvent(db, created.id, { programId: 1 });
const removed = await deleteWorkoutEventById(db, created.id);
\`\`\`
@@ -1229,7 +1217,6 @@ Request body (data):
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`weekNumber\` | \`number\` | | |
@@ -1327,7 +1314,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`weekNumber\` | \`number\` | | |
@@ -1349,7 +1335,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`weekNumber\` | \`number\` | | |
@@ -1449,7 +1434,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`weekNumber\` | \`number\` | | |
@@ -1471,7 +1455,6 @@ Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`weekNumber\` | \`number\` | | |
@@ -1525,7 +1508,6 @@ Accepted fields:
| Field | Type | Required | Notes |
|---|---|---|---|
-| \`id\` | \`number\` | | |
| \`programId\` | \`number\` | | |
| \`customerEmail\` | \`string\` | | |
| \`weekNumber\` | \`number\` | | |
diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts
index 7a8f6ff382..3fd6e9be60 100644
--- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts
+++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts
@@ -255,7 +255,7 @@ describe("the three shapes", () => {
const tree = await contractTree(corpusCase("secret-fields"));
const keysOf = (path: string): string[] => Object.keys(jsonAt(tree, path)["properties"] as JsonDoc);
const account = "schemas/acme/secrets/Account";
- expect(keysOf(`${account}.schema.json`)).toEqual(["id", "name", "tokenHash"]);
+ expect(keysOf(`${account}.schema.json`)).toEqual(["id", "name", "tokenHash", "role"]);
expect(keysOf(`${account}.create.schema.json`)).toEqual(["name"]);
expect(keysOf(`${account}.update.schema.json`)).toEqual(["name"]);
expect(tree.get("openapi.json")).not.toContain("pinHash");
diff --git a/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts b/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts
index 0082254cd4..4ad3748b3e 100644
--- a/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts
+++ b/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts
@@ -356,6 +356,22 @@ describe("renderZodValidators", () => {
expect(update).toContain("name");
});
+ test("an ASSIGNED primary key is in the Insert schema and OUT of the Update schema", () => {
+ // The URL names the row on PUT/PATCH. An assigned key (no @generation) is the caller's on
+ // create, but leaving it in the update shape let a client-sent `code` re-key the row.
+ const coupon = metaObject(OBJECT_SUBTYPE_ENTITY, "Coupon");
+ coupon.addChild(metaField(FIELD_SUBTYPE_STRING, "code"));
+ coupon.addChild(metaField(FIELD_SUBTYPE_STRING, "label"));
+ const primary = meta(new TypeId(TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY), "primary");
+ primary.setAttr("fields", ["code"]);
+ coupon.addChild(primary);
+ const out = renderZodValidators(coupon).toString();
+ expect(schemaBody(out, "CouponInsertSchema")).toContain("code");
+ const update = schemaBody(out, "CouponUpdateSchema");
+ expect(update).not.toContain("code");
+ expect(update).toContain("label");
+ });
+
test("FR-037 R1: no @mutability (⇒ readWrite) is in BOTH schemas — the no-churn default", () => {
const out = customerWithMutability(undefined, "lifetimeValue");
expect(schemaBody(out, "CustomerInsertSchema")).toContain("lifetimeValue");
diff --git a/server/typescript/packages/integration-tests/src/api-contract-scenario.ts b/server/typescript/packages/integration-tests/src/api-contract-scenario.ts
index ba4019d47d..9c65eb2be0 100644
--- a/server/typescript/packages/integration-tests/src/api-contract-scenario.ts
+++ b/server/typescript/packages/integration-tests/src/api-contract-scenario.ts
@@ -26,6 +26,10 @@ export interface ExpectBody {
namesUnordered?: string[];
row?: Record;
hasId?: boolean;
+ /** The response body is an object and NONE of the listed keys is present on it (not even as
+ * `null`). Used by the input scenarios to prove a key the client may not set never reached
+ * storage and came back in the echo. */
+ absent?: string[];
/** Assert the listed RESPONSE fields all equal EACH OTHER (never a literal) —
* format-agnostic. Used by @autoSet scenarios to prove two stamped columns
* hold the same value without pinning the exact timestamp. */
@@ -288,6 +292,13 @@ export function assertResponse(
if (typeof row["id"] !== "number")
throw new Error(`${scenarioName} / ${request.id}: expected numeric id in body, got: ${stringify(body)}`);
}
+ if (want.absent) {
+ if (body === null || typeof body !== "object" || Array.isArray(body))
+ throw new Error(`${scenarioName} / ${request.id}: expected object for absent, got: ${stringify(body)}`);
+ const present = want.absent.filter((k) => Object.hasOwn(body, k));
+ if (present.length > 0)
+ throw new Error(`${scenarioName} / ${request.id}: expected no ${present.join(", ")} in body, got: ${stringify(body)}`);
+ }
if (want.fieldsEqual) {
const row = body as Record;
// Compare the raw response fields to EACH OTHER (format-agnostic) — every
diff --git a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts
index 59885dde10..dbf642ed62 100644
--- a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts
+++ b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts
@@ -65,7 +65,7 @@ const READ_PATHS = {
};
export interface SecretFieldsSeed {
- rows: Array<{ id: number; name: string; tokenHash: string; pinHash: string }>;
+ rows: Array<{ id: number; name: string; tokenHash: string; pinHash: string; role: string }>;
}
export interface GeneratedSecretFieldsServerHandle {
@@ -124,7 +124,8 @@ export const db = drizzle(pool);
"id" bigserial PRIMARY KEY,
"name" varchar(100) NOT NULL,
"token_hash" varchar(100),
- "pin_hash" varchar(100)
+ "pin_hash" varchar(100),
+ "role" varchar(20)
);
CREATE OR REPLACE VIEW "v_account" AS SELECT "id", "name", "pin_hash" FROM "accounts";
CREATE TABLE IF NOT EXISTS "payers" ("id" bigserial PRIMARY KEY);
@@ -165,7 +166,7 @@ export const db = drizzle(pool);
for (const r of seed.rows)
await executeSql(
connectionUri,
- `INSERT INTO "accounts" ("id","name","token_hash","pin_hash") VALUES (${r.id}, ${str(r.name)}, ${str(r.tokenHash)}, ${str(r.pinHash)})`,
+ `INSERT INTO "accounts" ("id","name","token_hash","pin_hash","role") VALUES (${r.id}, ${str(r.name)}, ${str(r.tokenHash)}, ${str(r.pinHash)}, ${str(r.role)})`,
);
// The seed names ids explicitly; keep the sequence ahead of them for the POST scenarios.
await executeSql(connectionUri, `SELECT setval(pg_get_serial_sequence('accounts','id'), (SELECT MAX("id") FROM "accounts"));`);
diff --git a/server/typescript/packages/integration-tests/src/api-contract-server.ts b/server/typescript/packages/integration-tests/src/api-contract-server.ts
index 32cc2b3661..4342322804 100644
--- a/server/typescript/packages/integration-tests/src/api-contract-server.ts
+++ b/server/typescript/packages/integration-tests/src/api-contract-server.ts
@@ -188,6 +188,16 @@ export async function startServer(connectionUri: string, root: MetaRoot): Promis
return reply;
});
+ // The keys a client may write, as the generated routes' Insert/Update schemas have them: the
+ // server-generated `id`, the @autoSet columns and any key the entity does not declare are
+ // DROPPED silently (never 400'd), and `issuedCurrency` (writeOnce) is settable on create only.
+ const CREATE_KEYS = ["name", "bio", "createdAt", "issuedCurrency"] as const;
+ const UPDATE_KEYS = ["name", "bio", "createdAt"] as const;
+ const pick = (body: unknown, keys: readonly string[]): Record => {
+ const src = (body ?? {}) as Record;
+ return Object.fromEntries(keys.filter((k) => Object.hasOwn(src, k)).map((k) => [k, src[k]]));
+ };
+
// POST /api/authors
fastify.post(ROUTE_BASE, async (req, reply) => {
// #203 / ADR-0045 — the TS runtime ObjectManager does NOT stamp @autoSet
@@ -195,7 +205,7 @@ export async function startServer(connectionUri: string, root: MetaRoot): Promis
// the generated lane's InsertSchema. Both onCreate + onUpdate columns get the
// SAME captured now() on create; any caller-supplied value is ignored.
const now = new Date().toISOString();
- const body = { ...(req.body as Record), autoCreatedAt: now, autoUpdatedAt: now };
+ const body = { ...pick(req.body, CREATE_KEYS), autoCreatedAt: now, autoUpdatedAt: now };
const row = await om.create(ENTITY, body);
reply.code(201).send(row);
return reply;
@@ -215,12 +225,7 @@ export async function startServer(connectionUri: string, root: MetaRoot): Promis
// plain z.object() discards unknown keys). Dropping it also covers the
// present-NULL arm for free: clearing is a write, so an explicit null must
// not reach the column either.
- const {
- autoCreatedAt: _dropOnCreate,
- issuedCurrency: _dropWriteOnce,
- ...rest
- } = (req.body as Record) ?? {};
- const body = { ...rest, autoUpdatedAt: new Date().toISOString() };
+ const body = { ...pick(req.body, UPDATE_KEYS), autoUpdatedAt: new Date().toISOString() };
// A ValidationError (e.g. FR-035 present-null on a @required field) propagates
// to the shared setErrorHandler above → 400 {error:"validation"}.
const row = await om.update(ENTITY, Number(id), body, { ifMissing: "ignore" });
diff --git a/server/typescript/packages/test-generators/src/templates/zod-validators.ts b/server/typescript/packages/test-generators/src/templates/zod-validators.ts
index 2e421a0819..3d0a9e52fd 100644
--- a/server/typescript/packages/test-generators/src/templates/zod-validators.ts
+++ b/server/typescript/packages/test-generators/src/templates/zod-validators.ts
@@ -719,6 +719,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] {
*/
export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
const autoGenPkFields = autoGenPkFieldNames(obj);
+ const pkFields = primaryKeyFieldNames(obj);
const tphPin = tphDiscriminatorPin(obj);
const out: SchemaFieldShape[] = [];
for (const child of flatSurfaceFields(obj)) {
@@ -734,6 +735,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] {
// edit form for an entity carrying one. Clearing counts as a write, so the
// FR-035 present-null arm never reaches it either.
if (isWriteOnceMutability(child)) continue;
+ // A primary-key field is the row's identity, which the URL names: an ASSIGNED key is
+ // omitted from the update shape exactly like a generated one, so a client-sent id is
+ // stripped and can never re-key the row.
+ if (pkFields.has(child.name)) continue;
// TPH subtype discriminator: omitted from the update schema entirely.
if (tphPin !== undefined && child.name === tphPin.fieldName) continue;
const autoSet = child.attr(FIELD_ATTR_AUTO_SET);
@@ -818,6 +823,9 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
// below; a value presented on PATCH is stripped, not 400'd (see
// updateSchemaFields for the grounding).
if (isWriteOnceMutability(child)) continue;
+ // The row's identity is the URL's: an ASSIGNED primary key leaves the update shape too
+ // (a generated one never entered it), so a client-sent id is stripped, never a re-key.
+ if (pkFields.has(child.name)) continue;
// Update schema: @autoSet onCreate → omit entirely; onUpdate → transform
if (autoSet === AUTO_SET_ON_CREATE) {
From fc9145aeb8f898e231688c0979bb2d6373e27d17 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Fri, 13 Nov 2026 13:34:13 -0500
Subject: [PATCH 03/31] feat(codegen): a validation 400 lists every issue in
every port
The same model answered a failed create or update differently by language:
TypeScript listed each problem, while C#, Java, Kotlin and Python returned a
bare {"error":"validation"}. Every port's generated routes and its hand-rolled
reference servers now answer 400 {"error":"validation","issues":[{code,path,
message}]} with every failure, codes in Zod's vocabulary and path as an array of
wire names.
- C#: ValidationIssues runtime file (ejected with routes); create reads the
body itself so an unbindable body lists its issue; PATCH collects instead of
returning on the first failure.
- Java: ValidationIssues runtime helper; a Patch binds every field before it
throws. Kotlin: per-package MetaValidationIssues.kt; create lists every
absent required value.
- Python: every Pydantic error mapped in constraint_errors; decimal failures
carry their wire path.
Shared scenarios validation-lists-issues and tph-validation-lists-issues, with a
new `issues` assertion in every runner, gate it in both lanes.
---
docs/features/field-types.md | 2 +-
docs/features/generated-mutations.md | 2 +-
docs/features/own-your-codegen.md | 10 +-
.../.metaobjects/.gen-state/.hashes.json | 4 +-
.../generated/csharp/SubscriberRoutes.g.cs | 36 +--
.../generated/java/acme/SubscriberPatch.java | 10 +-
.../generated/python/subscriber_router.py | 47 ++-
examples/showcase/site-payload.json | 2 +-
.../scenarios/validation-lists-issues.yaml | 51 ++++
.../tph-validation-lists-issues.yaml | 47 +++
.../EntityGeneratorTests.cs | 6 +-
.../MapFieldCodegenTests.cs | 8 +-
.../ValidationIssuesTests.cs | 105 +++++++
.../ValueObjectValidationCodegenTests.cs | 4 +-
.../Generators/KNOWN_GAPS.md | 2 +-
.../Generators/RoutesGenerator.cs | 134 +++++----
.../MetaObjects.Codegen/HelperRuntime.cs | 1 +
.../MetaObjects.Codegen.csproj | 1 +
.../Runtime/ValidationIssues.cs | 279 ++++++++++++++++++
.../Runtime/ValueObjectValidator.cs | 38 ++-
.../Api/ApiContractAssertions.cs | 37 ++-
.../Api/ApiContractRequiredValueTypeTest.cs | 12 +
.../Api/AuthorApiServer.cs | 35 ++-
.../Api/JsonbReferenceServer.cs | 27 +-
.../Api/ReferenceValidation.cs | 40 +++
.../Api/TphReferenceServer.cs | 67 +++--
server/java/codegen-kotlin/pom.xml | 1 +
.../generator/kotlin/GeneratorRegistry.kt | 5 +-
.../generator/kotlin/KNOWN_GAPS.md | 3 +-
.../kotlin/KotlinDecimalWireEmitter.kt | 47 ++-
.../kotlin/KotlinSpringControllerGenerator.kt | 161 ++++++----
.../kotlin/KotlinValidationIssuesEmitter.kt | 135 +++++++++
.../kotlin/KotlinAutoSetStampingTest.kt | 6 +-
.../generator/kotlin/KotlinDecimalWireTest.kt | 38 ++-
.../kotlin/KotlinSecretFieldsTest.kt | 2 +-
.../kotlin/KotlinServerOwnedInputTest.kt | 28 +-
.../kotlin/KotlinValidationIssuesTest.kt | 95 ++++++
.../acme/blog/AuthorController.kt | 35 ++-
.../acme/blog/MetaDecimalWire.kt | 47 ++-
.../acme/blog/MetaValidationIssues.kt | 105 +++++++
.../acme/catalog/MetaDecimalWire.kt | 47 ++-
.../acme/catalog/MetaValidationIssues.kt | 105 +++++++
.../acme/catalog/ProductController.kt | 60 ++--
.../acme/catalog/MetaDecimalWire.kt | 47 ++-
.../acme/catalog/MetaValidationIssues.kt | 105 +++++++
.../acme/catalog/ProductController.kt | 60 ++--
.../acme/auth/AuthController.kt | 82 ++---
.../acme/auth/AuthLineController.kt | 31 +-
.../acme/auth/MetaDecimalWire.kt | 47 ++-
.../acme/auth/MetaValidationIssues.kt | 105 +++++++
.../acme/report/MetaDecimalWire.kt | 47 ++-
.../acme/report/MetaValidationIssues.kt | 105 +++++++
server/java/codegen-spring/pom.xml | 11 +
.../generator/GeneratorRegistry.java | 2 +-
.../generator/spring/KNOWN_GAPS.md | 3 +-
.../spring/SpringControllerGenerator.java | 205 ++++++-------
.../generator/spring/SpringDtoGenerator.java | 29 +-
.../spring/runtime/CanonicalDecimal.java | 19 +-
.../runtime/PatchValidationException.java | 103 ++++++-
.../spring/runtime/RecordComponentNames.java | 12 +
.../spring/runtime/UnreadableBody.java | 32 +-
.../spring/runtime/ValidationIssues.java | 184 ++++++++++++
.../spring/SpringControllerGeneratorTest.java | 2 +-
.../spring/SpringMapFieldCodegenTest.java | 12 +-
.../spring/runtime/ValidationIssuesTest.java | 158 ++++++++++
.../expected/acme/shipping/CratePatch.java | 6 +-
.../expected/acme/shipping/ParcelPatch.java | 6 +-
.../expected/acme/shipping/ShipmentPatch.java | 8 +-
.../acme/shipping/ShipmentSummaryPatch.java | 6 +-
.../kotlin/api/ApiContractAssertions.kt | 25 ++
.../integration/kotlin/api/AuthorApiServer.kt | 32 +-
.../kotlin/api/jsonb/DocumentApiServer.kt | 28 +-
.../api/ApiContractAssertions.java | 33 +++
.../integration/api/AuthorApiServer.java | 50 +++-
.../integration/api/JsonbReferenceServer.java | 16 +-
.../mojo/EjectRuntimeRoundTripTest.java | 10 +-
.../src/metaobjects/codegen/KNOWN_GAPS.md | 4 +-
.../codegen/generators/router_generator.py | 68 +++--
.../codegen/runtime/constraint_errors.py | 122 +++++++-
.../codegen/runtime/decimal_wire.py | 44 ++-
.../tests/codegen/test_router_generator.py | 15 +
.../integration/api_contract_assertions.py | 29 ++
.../tests/integration/api_contract_server.py | 45 ++-
.../test_generated_decimal_wire.py | 29 +-
.../test_generated_router_validated_input.py | 15 +-
.../tests/runtime/test_validation_issues.py | 137 +++++++++
.../src/api-contract-scenario.ts | 36 +++
.../src/api-contract-server.ts | 33 ++-
88 files changed, 3482 insertions(+), 643 deletions(-)
create mode 100644 fixtures/api-contract-conformance/scenarios/validation-lists-issues.yaml
create mode 100644 fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml
create mode 100644 server/csharp/MetaObjects.Codegen.Tests/ValidationIssuesTests.cs
create mode 100644 server/csharp/MetaObjects.Codegen/Runtime/ValidationIssues.cs
create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/ReferenceValidation.cs
create mode 100644 server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinValidationIssuesEmitter.kt
create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinValidationIssuesTest.kt
create mode 100644 server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/MetaValidationIssues.kt
create mode 100644 server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaValidationIssues.kt
create mode 100644 server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaValidationIssues.kt
create mode 100644 server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaValidationIssues.kt
create mode 100644 server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/MetaValidationIssues.kt
create mode 100644 server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/ValidationIssues.java
create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/runtime/ValidationIssuesTest.java
create mode 100644 server/python/tests/runtime/test_validation_issues.py
diff --git a/docs/features/field-types.md b/docs/features/field-types.md
index 4cd13888bd..b140fe95bd 100644
--- a/docs/features/field-types.md
+++ b/docs/features/field-types.md
@@ -84,7 +84,7 @@ Five rows need a footnote:
**Nested map values are validated on every write path, on every port.** A posted map value
that violates the referenced `object.value`'s own constraints is rejected with the cross-port
- `{"error":"validation"}` envelope before the row is written. Scalar-valued maps
+ `{"error":"validation", "issues": [...]}` envelope before the row is written. Scalar-valued maps
(`@valueType`) carry no nested bean, so nothing extra runs for them.
> This was a real hole until 1.0.1, and it is worth knowing what it was, because the failure
diff --git a/docs/features/generated-mutations.md b/docs/features/generated-mutations.md
index 3a367bbb6f..1adb3f2234 100644
--- a/docs/features/generated-mutations.md
+++ b/docs/features/generated-mutations.md
@@ -41,7 +41,7 @@ but the semantics are one contract — call them **PATCH-1..7** (FR-035):
simply omits every non-settable field, and Zod drops unknown keys — so
`safeParse` succeeds and the key never reaches the `SET`. The TPH discriminator
is additionally deleted by hand after parse, the same convention. A malformed
- *value* on a settable key is still `400 {"error":"validation"}`. A key the entity
+ *value* on a settable key is still `400 {"error":"validation", "issues": [...]}`. A key the entity
does not declare at all is dropped the same way. The Python routes hand the
repository only the keys their input model validated.
This matters for `writeOnce` specifically: the generated edit form submits EVERY
diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md
index 9f2ef99357..8a94d88f0e 100644
--- a/docs/features/own-your-codegen.md
+++ b/docs/features/own-your-codegen.md
@@ -1412,11 +1412,11 @@ on are yours too. Eject copies two kinds of source with a Java generator:
| Ejecting | Shared emit rules, beside the generator | Helper runtime its output imports |
|---|---|---|
-| `routes` | `SpringGeneratorSupport` | `CanonicalDecimal`, `ConstraintErrors`, `FilterParseResult`, `FilterParser`, `FilterPredicate`, `PatchValidationException`, `RecordComponentNames`, `UnreadableBody` |
-| `dto` | `SpringGeneratorSupport` | `CanonicalDecimal`, `CanonicalDecimalDeserializer`, `CanonicalDecimalSerializer`, `DeclaredDecimal`, `PatchValidationException` |
+| `routes` | `SpringGeneratorSupport` | `CanonicalDecimal`, `CanonicalDuration`, `ConstraintErrors`, `FilterParseResult`, `FilterParser`, `FilterPredicate`, `PatchValidationException`, `RecordComponentNames`, `ReportExport`, `UnreadableBody`, `ValidationIssues` |
+| `dto` | `SpringGeneratorSupport` | `CanonicalDecimal`, `CanonicalDecimalDeserializer`, `CanonicalDecimalSerializer`, `CanonicalDuration`, `CanonicalDurationDeserializer`, `CanonicalDurationSerializer`, `DeclaredDecimal`, `PatchValidationException` |
| `repository` | `SpringGeneratorSupport` | `FilterPredicate` |
-| `value-object` | `SpringGeneratorSupport` | `CanonicalDecimal`, `CanonicalDecimalDeserializer`, `CanonicalDecimalSerializer`, `DeclaredDecimal` |
-| any other Java generator, every Kotlin generator | nothing | nothing: its output imports only core (Kotlin writes its decimal wire into the output as `MetaDecimalWire.kt`) |
+| `value-object` | `SpringGeneratorSupport` | `CanonicalDecimal`, `CanonicalDecimalDeserializer`, `CanonicalDecimalSerializer`, `CanonicalDuration`, `CanonicalDurationDeserializer`, `CanonicalDurationSerializer`, `DeclaredDecimal` |
+| any other Java generator, every Kotlin generator | nothing | nothing: its output imports only core (Kotlin writes its decimal wire and its validation-issue list into the output, as `MetaDecimalWire.kt` and `MetaValidationIssues.kt`) |
**The shared emit rules.** `SpringGeneratorSupport` holds the rules those four generators
apply together: which fields a DTO and a patch carry, which of them are stamped for
@@ -1656,7 +1656,7 @@ Otherwise a bug in the filter parser would still mean waiting for a MetaObjects
`dotnet meta eject routes` therefore also writes their source to `codegen/runtime/`:
`FilterParser.cs`, `FilterParseResult.cs`, `FilterPredicate.cs`,
-`EfCoreFilterDispatch.cs`, `ValueObjectValidator.cs`, `ConstraintErrors.cs` and
+`EfCoreFilterDispatch.cs`, `ValueObjectValidator.cs`, `ValidationIssues.cs`, `ConstraintErrors.cs` and
`Iso8601TimestampConverter.cs`, the converter your host registers for the api contract's
timestamp spelling. Each file is the packaged source with one change: its namespace becomes
`Codegen.Runtime`, matching the folder the way `codegen/generators/` matches
diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes.json
index 3f9fca7aab..14608b3548 100644
--- a/examples/showcase/.metaobjects/.gen-state/.hashes.json
+++ b/examples/showcase/.metaobjects/.gen-state/.hashes.json
@@ -4,13 +4,13 @@
"generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed",
"generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5",
"generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732",
- "generated/csharp/SubscriberRoutes.g.cs": "d05912d0a76b52334857796a42b2919be8709997d6c073c11d2c44590fe686a9",
+ "generated/csharp/SubscriberRoutes.g.cs": "85969bbaf6a58ca2946c595d520e7ec48dcc5b5e21123e0340c5cc08aa8b9e04",
"generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762",
"generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd",
"generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5",
"generated/python/subscriber_filter_allowlist.py": "b0414cc95ff3982c80a0e1a06839f090c0b423e41f5a94275df93426cea09df5",
"generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561",
- "generated/python/subscriber_router.py": "021768a4ed1fe24c2432087bba8b350579f60595728a95c6d43a528c3fdcb1be",
+ "generated/python/subscriber_router.py": "9bb26702fc7ad041cf4bb52c5e588226a315a2b0a858555666060863795dcfc8",
"generated/ts/Subscriber.queries.ts": {
"hash": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562",
"generatedBy": "queries-file",
diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs
index 9987f12b3c..efdd5400ca 100644
--- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs
+++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs
@@ -87,25 +87,24 @@ await db.Subscribers.FindAsync(id) is { } found
.Value.SerializerOptions;
System.Text.Json.JsonDocument __body;
try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }
- catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); }
+ catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }
using var __bodyScope = __body;
if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object)
- return Results.BadRequest(new { error = "validation" });
+ return ValidationIssues.Unreadable();
+ var __issues = new ValidationIssues();
var __present = new System.Collections.Generic.HashSet(System.StringComparer.OrdinalIgnoreCase);
foreach (var __p in __body.RootElement.EnumerateObject())
if (__p.Value.ValueKind != System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name);
foreach (var __req in new[] { "email", "status" })
- if (!__present.Contains(__req)) return Results.BadRequest(new { error = "validation" });
- Subscriber? input;
+ if (!__present.Contains(__req)) __issues.AddRequired(__req);
+ Subscriber? input = null;
try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); }
- catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); }
- if (input is null) return Results.BadRequest(new { error = "validation" });
+ catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Subscriber)); }
+ if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable();
// Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored.
input.Id = default!;
- var __vr = new System.Collections.Generic.List();
- if (!System.ComponentModel.DataAnnotations.Validator.TryValidateObject(
- input, new System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true))
- return Results.BadRequest(new { error = "validation" });
+ __issues.ValidateObject(input, jsonOpts);
+ if (__issues.Any) return __issues.ToResult();
input.CreatedAt = System.DateTimeOffset.UtcNow;
db.Subscribers.Add(input);
try { await db.SaveChangesAsync(); }
@@ -126,8 +125,9 @@ async System.Threading.Tasks.Task UpdateSubscriber(long id, HttpContext
if (existing is null) return Results.NotFound(new { error = "not_found" });
System.Text.Json.JsonDocument body;
try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }
- catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); }
+ catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }
using var bodyScope = body;
+ if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();
// Deserialize each value with the app's CONFIGURED JSON options, not defaults —
// a field.timestamp binds to DateTimeOffset via a custom converter registered on
// ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500.
@@ -135,32 +135,34 @@ async System.Threading.Tasks.Task UpdateSubscriber(long id, HttpContext
http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)
.Value.SerializerOptions;
var entry = db.Entry(existing);
+ var __issues = new ValidationIssues();
foreach (var prop in body.RootElement.EnumerateObject())
{
var target = entry.Metadata.FindProperty(prop.Name)
?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase));
if (target is null) continue;
+ var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts);
if (target.IsPrimaryKey()) continue; // PK is route-authoritative
if (string.Equals(target.Name, "CreatedAt", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned
if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)
{
// FR-035 PATCH-2: explicit null clears a nullable column; on a
// NOT-NULL (@required) column it is a 400 (matching the cross-port contract).
- if (!target.IsNullable) return Results.BadRequest(new { error = "validation" });
+ if (!target.IsNullable) { __issues.AddRequired(__wire); continue; }
entry.CurrentValues[target] = null;
continue;
}
var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType;
- var __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts);
+ object? __val;
+ try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }
+ catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }
// FR-036 A2 — validate the PRESENT, non-null value with the same per-field
// DataAnnotations as create. This validates ONLY the present value (never the
// whole row) so an ABSENT @required field is untouched, not a 400.
- var __pr = new System.Collections.Generic.List();
- if (!System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(__val,
- new System.ComponentModel.DataAnnotations.ValidationContext(existing) { MemberName = target.Name }, __pr))
- return Results.BadRequest(new { error = "validation" });
+ if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue;
entry.CurrentValues[target] = __val;
}
+ if (__issues.Any) return __issues.ToResult();
try { await db.SaveChangesAsync(); }
catch (System.Exception __saveError)
{
diff --git a/examples/showcase/generated/java/acme/SubscriberPatch.java b/examples/showcase/generated/java/acme/SubscriberPatch.java
index 03b31a618b..aeeb00156f 100644
--- a/examples/showcase/generated/java/acme/SubscriberPatch.java
+++ b/examples/showcase/generated/java/acme/SubscriberPatch.java
@@ -38,9 +38,11 @@ public final class SubscriberPatch {
public static SubscriberPatch fromJson(JsonNode body, ObjectMapper mapper) {
if (!body.isObject()) throw new PatchValidationException("(request body)");
Map assigned = new LinkedHashMap<>();
- bind(body, mapper, assigned, "email", new TypeReference() {}, true);
- bind(body, mapper, assigned, "name", new TypeReference() {}, false);
- bind(body, mapper, assigned, "status", new TypeReference() {}, true);
+ java.util.List problems = PatchValidationException.newProblems();
+ PatchValidationException.collect(problems, () -> bind(body, mapper, assigned, "email", new TypeReference() {}, true));
+ PatchValidationException.collect(problems, () -> bind(body, mapper, assigned, "name", new TypeReference() {}, false));
+ PatchValidationException.collect(problems, () -> bind(body, mapper, assigned, "status", new TypeReference() {}, true));
+ if (!problems.isEmpty()) throw new PatchValidationException(problems, assigned);
return new SubscriberPatch(assigned);
}
@@ -56,7 +58,7 @@ private static void bind(JsonNode body, ObjectMapper mapper, Map
try {
assigned.put(field, mapper.treeToValue(node, type));
} catch (JsonProcessingException e) {
- throw new PatchValidationException(field);
+ throw new PatchValidationException(field, e);
}
}
}
diff --git a/examples/showcase/generated/python/subscriber_router.py b/examples/showcase/generated/python/subscriber_router.py
index 9db0b29b63..0823ed7798 100644
--- a/examples/showcase/generated/python/subscriber_router.py
+++ b/examples/showcase/generated/python/subscriber_router.py
@@ -21,6 +21,11 @@
from fastapi.responses import JSONResponse, Response
from metaobjects.codegen.runtime.constraint_errors import (
classify_constraint_error,
+ pydantic_issues,
+ required_null_issues,
+ unreadable_body_issues,
+ validation_envelope,
+ value_error_issues,
)
from metaobjects.codegen.runtime.decimal_wire import (
WireOutput,
@@ -209,19 +214,25 @@ def create_subscriber(
if (
dto is None
): # the body was not a JSON object: the cross-port 400, not FastAPI's 422
- return JSONResponse(status_code=400, content={"error": "validation"})
+ return JSONResponse(
+ status_code=400, content=validation_envelope(unreadable_body_issues())
+ )
try:
dto = coerce_decimal_fields(
dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS
)
- except ValueError:
- return JSONResponse(status_code=400, content={"error": "validation"})
+ except ValueError as _exc:
+ return JSONResponse(
+ status_code=400, content=validation_envelope(value_error_issues(_exc))
+ )
# FR-036: run the generated field constraints (length / pattern /
# numeric bounds) before persisting; a violation is the cross-port 400.
try:
_valid = SubscriberCreate(**dto)
- except ValidationError:
- return JSONResponse(status_code=400, content={"error": "validation"})
+ except ValidationError as _exc:
+ return JSONResponse(
+ status_code=400, content=validation_envelope(pydantic_issues(_exc.errors()))
+ )
# SECURITY (1.2.1): only what the input model validated reaches the repository. A key
# it does not declare (an undeclared name, a server-generated id, a readOnly or derived
# field, a frozen one on update) is dropped silently, never 400'd.
@@ -248,25 +259,29 @@ def update_subscriber(
if (
dto is None
): # the body was not a JSON object: the cross-port 400, not FastAPI's 422
- return JSONResponse(status_code=400, content={"error": "validation"})
+ return JSONResponse(
+ status_code=400, content=validation_envelope(unreadable_body_issues())
+ )
try:
dto = coerce_decimal_fields(
dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS
)
- except ValueError:
- return JSONResponse(status_code=400, content={"error": "validation"})
- # FR-035 PATCH-2: an explicit null on a @required field is a 400 —
- # a present null on a NON-required field falls through and clears it,
- # and an OMITTED required field is untouched (never a 400).
- for _k in _REQUIRED_FIELDS:
- if _k in dto and dto[_k] is None:
- return JSONResponse(status_code=400, content={"error": "validation"})
+ except ValueError as _exc:
+ return JSONResponse(
+ status_code=400, content=validation_envelope(value_error_issues(_exc))
+ )
+ # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present
+ # null on a NON-required field falls through and clears it, and an OMITTED
+ # required field is untouched (never a 400).
# FR-036: validate PRESENT, non-null values with the create rules (the
# all-optional patch model never fires required-checks on ABSENT fields).
+ _issues = required_null_issues(dto, _REQUIRED_FIELDS)
try:
_valid = SubscriberPatch(**dto)
- except ValidationError:
- return JSONResponse(status_code=400, content={"error": "validation"})
+ except ValidationError as _exc:
+ _issues += pydantic_issues(_exc.errors())
+ if _issues:
+ return JSONResponse(status_code=400, content=validation_envelope(_issues))
# SECURITY (1.2.1): only what the input model validated reaches the repository. A key
# it does not declare (an undeclared name, a server-generated id, a readOnly or derived
# field, a frozen one on update) is dropped silently, never 400'd.
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index 93a11d0e23..ab9e1aa587 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -74,7 +74,7 @@
},
"verify-transcript": {
"lang": "console",
- "inline": "meta verify — requirements: 1 entries (1 functional, 0 architectural) — 1 live; 1/1 entities claimed, counted over 1 metadata file(s).\nmeta verify — not run: schema (--db <url>), codegen (--codegen), deps (--deps), replay (--replay)\nmeta: [subscriberBlurb] (prompt) ERR_VAR_NOT_ON_PAYLOAD: name (templates/subscriber/blurb.mustache:1)\nmeta: meta verify — 1 drift error(s) across 1 template(s).",
+ "inline": "meta verify — requirements: 1 entries (1 functional, 0 architectural) — 1 live; 1/1 entities claimed, counted over 1 metadata file(s).\nmeta verify — not run: schema (--db <url>), codegen (--codegen), deps (--deps), replay (--replay)\nmeta: [subscriberBlurb] (prompt) ERR_VAR_NOT_ON_PAYLOAD: name (templates/subscriber/blurb.mustache:1)\nmeta: meta verify — 1 drift error(s) across 1 template(s).\nmeta: meta verify — generated list routes have no page size (advisory — does not fail the build):\nmeta: .metaobjects/config.json: routes-file is wired and the project sets no api.pagination, so a generated list route with no ?limit= returns the whole table and accepts any ?limit=. Add \"api\": { \"pagination\": { \"defaultLimit\": 50, \"maxLimit\": 1000 } } to give every list a default page size and answer a larger ?limit= with 400 limit_too_large.",
"full": null,
"lineCount": null
},
diff --git a/fixtures/api-contract-conformance/scenarios/validation-lists-issues.yaml b/fixtures/api-contract-conformance/scenarios/validation-lists-issues.yaml
new file mode 100644
index 0000000000..17da0bbf70
--- /dev/null
+++ b/fixtures/api-contract-conformance/scenarios/validation-lists-issues.yaml
@@ -0,0 +1,51 @@
+name: validation-lists-issues
+description: >
+ A body that fails validation is answered 400 with every issue listed, in the shape the
+ TypeScript routes already use: {"error": "validation", "issues": [...]}, where each issue
+ carries a `code` (Zod's names: invalid_type, too_small, too_big, invalid_format,
+ invalid_value, custom), a `path` (the field, as an array) and a `message` (the port's own
+ wording, never asserted). The `issues` assertion names the issues that must be present.
+
+ r1 breaks two rules at once (a name over its @maxLength and a missing @required createdAt), so
+ a port that stops at the first issue fails it. r3 sends a present null on a @required field.
+ r2 and r4 prove that nothing was written.
+requests:
+ - id: r1
+ method: POST
+ path: /api/authors
+ body:
+ name: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ expect:
+ status: 400
+ body:
+ error: "validation"
+ issues:
+ - { path: [name], code: too_big }
+ - { path: [createdAt], code: invalid_type }
+ - id: r2
+ method: GET
+ path: /api/authors
+ expect:
+ status: 200
+ body:
+ length: 5
+ - id: r3
+ method: PATCH
+ path: /api/authors/1
+ body:
+ name: null
+ expect:
+ status: 400
+ body:
+ error: "validation"
+ issues:
+ - { path: [name], code: invalid_type }
+ - id: r4
+ method: GET
+ path: /api/authors/1
+ expect:
+ status: 200
+ body:
+ row:
+ id: 1
+ name: "Ada Lovelace"
diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml
new file mode 100644
index 0000000000..cafe01af40
--- /dev/null
+++ b/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml
@@ -0,0 +1,47 @@
+name: tph-validation-lists-issues
+description: >
+ The per-subtype routes list every validation issue, in the shape of the core
+ `validation-lists-issues` scenario: {"error": "validation", "issues": [{code, path, message}]}.
+ r1 sends a reference over its @maxLength and omits the BridgeAuth subtype's @required
+ quantity. r2 nulls the base's @required reference and sends a PriorAuth approver over its
+ @maxLength. r3 and r4 prove that nothing was written.
+requests:
+ - id: r1
+ method: POST
+ path: /api/auths/bridge
+ body:
+ reference: "RXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+ expect:
+ status: 400
+ body:
+ error: "validation"
+ issues:
+ - { path: [reference], code: too_big }
+ - { path: [quantity], code: invalid_type }
+ - id: r2
+ method: PATCH
+ path: /api/auths/priorauth/3
+ body:
+ reference: null
+ approver: "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+ expect:
+ status: 400
+ body:
+ error: "validation"
+ issues:
+ - { path: [reference], code: invalid_type }
+ - { path: [approver], code: too_big }
+ - id: r3
+ method: GET
+ path: /api/auths
+ expect:
+ status: 200
+ body:
+ length: 3
+ - id: r4
+ method: GET
+ path: /api/auths/3
+ expect:
+ status: 200
+ body:
+ row: { id: 3, reference: "REF-3", approver: "Dr. Smith" }
diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs
index 119b12f826..eb97630dff 100644
--- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs
+++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs
@@ -125,10 +125,10 @@ public void Routes_generator_emits_crud_endpoints()
// not an unhandled 500) + DataAnnotations-validates.
Assert.Contains("app.MapPost(prefix + \"/subscribers\", async (HttpContext http, AppDbContext db) =>", src);
Assert.Contains("foreach (var __req in new[] { \"email\" })", src);
- Assert.Contains("if (!__present.Contains(__req)) return Results.BadRequest(new { error = \"validation\" });", src);
- Assert.Contains("Subscriber? input;", src);
+ Assert.Contains("if (!__present.Contains(__req)) __issues.AddRequired(__req);", src);
+ Assert.Contains("Subscriber? input = null;", src);
Assert.Contains("try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); }", src);
- Assert.Contains("catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = \"validation\" }); }", src);
+ Assert.Contains("catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Subscriber)); }", src);
// PATCH + PUT share the same update handler (matches TS reference). It takes the raw
// HttpContext (not a bound DTO) and PARTIAL-merges only the properties present in the
// JSON body — a bound DTO would fill omitted fields with CLR defaults and clobber them.
diff --git a/server/csharp/MetaObjects.Codegen.Tests/MapFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/MapFieldCodegenTests.cs
index 576c0ad06c..998d2c3c44 100644
--- a/server/csharp/MetaObjects.Codegen.Tests/MapFieldCodegenTests.cs
+++ b/server/csharp/MetaObjects.Codegen.Tests/MapFieldCodegenTests.cs
@@ -315,15 +315,15 @@ public void Both_write_paths_validate_the_values_of_a_value_object_map()
.Single(f => f.Path == "CustomerRoutes.g.cs").Content;
// Create: the map column joins the field.object columns in the validation preamble.
- Assert.Contains("ValueObjectValidator.Validate(input.Addresses)", routes);
+ Assert.Contains("ValueObjectValidator.Collect(input.Addresses, __issues, jsonOpts, \"addresses\")", routes);
// PATCH: a typed arm ahead of the generic path, so a present key is validated
// before assignment rather than after persistence (or never).
- Assert.Contains("if (!ValueObjectValidator.Validate(__map0)) return Results.BadRequest", routes);
+ Assert.Contains("if (!ValueObjectValidator.Collect(__map0, __issues, jsonOpts, \"addresses\")) continue;", routes);
// The control: a scalar-valued map has no nested bean and must reach NEITHER path.
// Without this, an implementation that validated every map would pass the two
// assertions above while doing something quite different.
- Assert.DoesNotContain("ValueObjectValidator.Validate(input.Labels)", routes);
- Assert.DoesNotContain("ValueObjectValidator.Validate(input.Channels)", routes);
+ Assert.DoesNotContain("ValueObjectValidator.Collect(input.Labels", routes);
+ Assert.DoesNotContain("ValueObjectValidator.Collect(input.Channels", routes);
}
}
diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValidationIssuesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValidationIssuesTests.cs
new file mode 100644
index 0000000000..a3a00e2b8e
--- /dev/null
+++ b/server/csharp/MetaObjects.Codegen.Tests/ValidationIssuesTests.cs
@@ -0,0 +1,105 @@
+// ValidationIssues — the Zod-named code mapping of the 400 validation envelope, per DataAnnotations attribute.
+
+using System.ComponentModel.DataAnnotations;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using MetaObjects.Codegen.Runtime;
+using Xunit;
+
+namespace MetaObjects.Codegen.Tests;
+
+public class ValidationIssuesTests
+{
+ public enum Colour { Red, Green }
+
+ public sealed class Doc
+ {
+ [Required, MaxLength(5)] public string? Name { get; set; }
+ [StringLength(8, MinimumLength = 3)] public string? Code { get; set; }
+ [MinLength(2)] public string? Tag { get; set; }
+ [Range(1, 10)] public int Rank { get; set; }
+ [RegularExpression("^[a-z]+$")] public string? Slug { get; set; }
+ [EmailAddress] public string? Email { get; set; }
+ [JsonPropertyName("wireOnly"), MaxLength(1)] public string? Renamed { get; set; }
+ public Colour Shade { get; set; }
+ public Guid Ref { get; set; }
+ public decimal Amount { get; set; }
+ }
+
+ private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web);
+
+ private static List<(string Code, string Path)> Run(Doc doc)
+ {
+ var issues = new ValidationIssues();
+ issues.ValidateObject(doc, Web);
+ return issues.Issues.Select(i => ((string)i["code"]!, string.Join(".", (List