@@ -434,10 +434,9 @@ def _frozen_names(entity: MetaObject) -> list[str]:
434434
435435 ADR-0045: the OUTERMOST generated write artifact enforces the mode, and for
436436 FastAPI that is the ROUTER, not the ``<Entity>Patch`` model — the handler binds
437- ``dto`` (the raw body as a dict) and passes THAT to the repository, so a
438- field merely absent from the patch model still reaches the row. @autoSet gets
439- away with it because the router OVERWRITES its key server-side; a writeOnce
440- field has no server value to overwrite, so it must be popped explicitly."""
437+ ``dto`` as a dict. Since 1.2.1 the router hands the repository only the keys the
438+ patch model validated (:func:`_validated_input_lines`), which already drops these;
439+ the explicit pop stays as the FR-037 seam an owned router edits."""
441440 return [
442441 f .name
443442 for f in entity .fields ()
@@ -461,6 +460,49 @@ def _frozen_strip_lines(entity: MetaObject, indent: str = " ") -> list[str]:
461460 ]
462461
463462
463+ #: 1.2.1 security fix. The request body cut down to what the input model validated, emitted
464+ #: once per writable router. 1.2.0 validated the body and then handed the RAW body to the
465+ #: repository, so a client-sent server-generated id, a ``readOnly`` field or a name the entity
466+ #: does not declare (an ``isAdmin``) reached the write. Pydantic ignores a key a model does not
467+ #: declare, and the input models leave out every field a client may not set, so keeping only
468+ #: the keys the model validated (at every depth: a nested value object included) drops all of
469+ #: them silently, as the TypeScript routes do. The values stay the body's own (decimal-exact)
470+ #: values, so a repository receives the same value types as in 1.2.0.
471+ _VALIDATED_INPUT_LINES : list [str ] = [
472+ "def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]:" ,
473+ ' """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the' ,
474+ " input model does not declare (an undeclared name, a server-generated id, a readOnly field)" ,
475+ ' is dropped silently and never reaches the repository; values stay the body\' s own."""' ,
476+ " return {_k: _validated_value(getattr(valid, _k), raw[_k]) for _k in valid.model_fields_set}" ,
477+ "" ,
478+ "" ,
479+ "def _validated_value(valid: Any, raw: Any) -> Any:" ,
480+ " if isinstance(valid, BaseModel) and isinstance(raw, dict):" ,
481+ " return _validated_input(valid, raw)" ,
482+ " if isinstance(valid, list) and isinstance(raw, list):" ,
483+ " return [_validated_value(v, r) for v, r in zip(valid, raw)]" ,
484+ " if isinstance(valid, dict) and isinstance(raw, dict):" ,
485+ " return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw}" ,
486+ " return raw" ,
487+ ]
488+
489+
490+ def _validated_input_lines (model : str , * comment : str ) -> list [str ]:
491+ """Validate ``dto`` against the input *model*, then rebind it to what the model validated
492+ (see :data:`_VALIDATED_INPUT_LINES`): the repository never sees any other key."""
493+ return [
494+ * (f" # { line } " for line in comment ),
495+ " try:" ,
496+ f" _valid = { model } (**dto)" ,
497+ " except ValidationError:" ,
498+ ' return JSONResponse(status_code=400, content={"error": "validation"})' ,
499+ " # SECURITY (1.2.1): only what the input model validated reaches the repository. A key" ,
500+ " # it does not declare (an undeclared name, a server-generated id, a readOnly or derived" ,
501+ " # field, a frozen one on update) is dropped silently, never 400'd." ,
502+ " dto = _validated_input(_valid, dto)" ,
503+ ]
504+
505+
464506def _auto_set_split (entity : MetaObject ) -> tuple [list [MetaField ], list [MetaField ]]:
465507 """The entity's ``@autoSet`` temporal fields split into ``(onCreate, onUpdate)``.
466508
@@ -1083,12 +1125,11 @@ def _emit_route_handler(
10831125 ") -> Any:" ,
10841126 * _DECIMAL_COERCE ,
10851127 * denied_strip ,
1086- " # FR-036: run the generated field constraints (length / pattern /" ,
1087- " # numeric bounds) before persisting; a violation is the cross-port 400." ,
1088- " try:" ,
1089- f" { model_name } (**dto)" ,
1090- " except ValidationError:" ,
1091- ' return JSONResponse(status_code=400, content={"error": "validation"})' ,
1128+ * _validated_input_lines (
1129+ model_name ,
1130+ "FR-036: run the generated field constraints (length / pattern /" ,
1131+ "numeric bounds) before persisting; a violation is the cross-port 400." ,
1132+ ),
10921133 # #203/ADR-0045: the generated router (the API surface) stamps @autoSet columns
10931134 # ABOVE the consumer repo seam — onCreate + onUpdate both stamped from one instant
10941135 # (a fresh row's createdAt == updatedAt), ignoring any caller-supplied value.
@@ -1114,12 +1155,11 @@ def _emit_route_handler(
11141155 " for _k in _REQUIRED_FIELDS:" ,
11151156 " if _k in dto and dto[_k] is None:" ,
11161157 ' return JSONResponse(status_code=400, content={"error": "validation"})' ,
1117- " # FR-036: validate PRESENT, non-null values with the create rules (the" ,
1118- " # all-optional patch model never fires required-checks on ABSENT fields)." ,
1119- " try:" ,
1120- f" { patch_model } (**dto)" ,
1121- " except ValidationError:" ,
1122- ' return JSONResponse(status_code=400, content={"error": "validation"})' ,
1158+ * _validated_input_lines (
1159+ patch_model ,
1160+ "FR-036: validate PRESENT, non-null values with the create rules (the" ,
1161+ "all-optional patch model never fires required-checks on ABSENT fields)." ,
1162+ ),
11231163 # #203/ADR-0045: bump onUpdate @autoSet columns (server-owned) on EVERY patch,
11241164 # above the repo seam — a server-inserted present key (compatible with the PATCH
11251165 # present-key tristate); onCreate columns are never touched here.
@@ -1468,6 +1508,9 @@ def _render_tph_router(
14681508 parts .extend (_JSON_BODY_LINES )
14691509 parts .append ("" )
14701510 parts .append ("" )
1511+ parts .extend (_VALIDATED_INPUT_LINES )
1512+ parts .append ("" )
1513+ parts .append ("" )
14711514 # FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so
14721515 # the generated module always carries the seam (an entity that later gains a
14731516 # writeOnce field changes one literal, not the module's shape).
@@ -1547,11 +1590,9 @@ def list_sig(fn: str, route: str) -> list[str]:
15471590 parts .append (") -> Any:" )
15481591 parts .extend (_DECIMAL_COERCE )
15491592 parts .extend (denied_strip_tph )
1550- parts .append (" # FR-036: run the subtype's field constraints before persisting." )
1551- parts .append (" try:" )
1552- parts .append (f" { sub } Create(**dto)" )
1553- parts .append (" except ValidationError:" )
1554- parts .append (' return JSONResponse(status_code=400, content={"error": "validation"})' )
1593+ parts .extend (_validated_input_lines (
1594+ f"{ sub } Create" , "FR-036: run the subtype's field constraints before persisting."
1595+ ))
15551596 # #203/ADR-0045: stamp @autoSet columns ABOVE the repo seam (empty for a
15561597 # non-@autoSet hierarchy — byte-identical output).
15571598 parts .extend (create_autoset )
@@ -1584,11 +1625,9 @@ def list_sig(fn: str, route: str) -> list[str]:
15841625 parts .append (" for _k in _REQUIRED_FIELDS:" )
15851626 parts .append (" if _k in dto and dto[_k] is None:" )
15861627 parts .append (' return JSONResponse(status_code=400, content={"error": "validation"})' )
1587- parts .append (" # FR-036: validate PRESENT, non-null values with the subtype's create rules." )
1588- parts .append (" try:" )
1589- parts .append (f" { sub } Patch(**dto)" )
1590- parts .append (" except ValidationError:" )
1591- parts .append (' return JSONResponse(status_code=400, content={"error": "validation"})' )
1628+ parts .extend (_validated_input_lines (
1629+ f"{ sub } Patch" , "FR-036: validate PRESENT, non-null values with the subtype's create rules."
1630+ ))
15921631 # #203/ADR-0045: pop the write-once onCreate column(s), bump onUpdate — ABOVE
15931632 # the repo seam (empty for a non-@autoSet hierarchy — byte-identical output).
15941633 parts .extend (update_autoset )
@@ -1857,6 +1896,9 @@ def render_router(
18571896 parts .extend (_JSON_BODY_LINES )
18581897 parts .append ("" )
18591898 parts .append ("" )
1899+ parts .extend (_VALIDATED_INPUT_LINES )
1900+ parts .append ("" )
1901+ parts .append ("" )
18601902 # FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so
18611903 # the generated module always carries the seam (an entity that later gains a
18621904 # writeOnce field changes one literal, not the module's shape).
@@ -1892,8 +1934,8 @@ def render_router(
18921934 create_autoset = create_autoset ,
18931935 update_autoset = update_autoset ,
18941936 # FR-037 R1 — ADR-0045: the ROUTER is the outermost write artifact for
1895- # FastAPI (the handler binds the RAW body dict and hands THAT to the
1896- # repository), so the strip has to live here, not in <Entity>Patch.
1937+ # FastAPI (the handler binds the body as a dict), so the strip lives here,
1938+ # not in <Entity>Patch.
18971939 frozen_strip = _frozen_strip_lines (entity ),
18981940 denied_strip = _denied_strip_lines (denied_names ),
18991941 )
0 commit comments