diff --git a/CHANGELOG.md b/CHANGELOG.md index 1359436c0b..c8b64b9347 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -143,7 +143,7 @@ next release moves `metamodelVersion`. generated code is the types and name constants its hand-written business rules use. Editing the metadata changes the grid, the form and the API with no regeneration. `docs/features/metadata-driven-runtime.md` measures it against the reference generators - for the same model (1,823 hand-written lines paid once, against 3,629 generated lines + for the same model (1,826 hand-written lines paid once, against 3,629 generated lines that grow by about 726 an entity), gives the per-row cost of the metadata lookups, and lists what the approach cannot do. It is an example on the TypeScript port, not a package. @@ -160,6 +160,39 @@ next release moves `metamodelVersion`. ### Fixed +- **A credential is never filterable or sortable, in every port.** A field that declares a + `view.password` and that a model also marked `@filterable` or `@sortable` was on the generated + filter and sort allowlists, so a client could learn its value by probing (`filter[pinHash][eq]=...`, + a `like` prefix one character at a time, or the order of a `sort`). The allowlists are now built + without a credential (in every port a column a sibling subtype of the same single table marks as one + counts too, whichever subtype is declared first, as it does for hiding the column from responses), + so a request that names it is refused like any other field they do not hold (`400` `invalid_filter_field` + or `invalid_sort`, naming the field). The client filter type, the OpenAPI parameters and the agent UI + page leave it out too. In Java, Kotlin and C#, whose sort allowlist lists every scalar field and never read `@sortable`, a + credential was sortable with no mark at all, so the generated routes change for any model with a + credential: regenerate. Your own code is unaffected. Gated by `filter-sort-refuses-credential` in the `secret-fields/` + sub-corpus of the api-contract conformance corpus, in the generated lane of all five ports, and by + `tph-sibling-credential` in `secret-fields/tph/` for the shared-column case. + +- **A numeric key is read only from canonical decimal text, in the TypeScript, Java and Python + ObjectManagers.** A path parameter or ref string for an integer, long, decimal, double or float + primary key went through the language's own number parser, which reads `0x1`, `1e0`, `0b1`, `+1`, + ` 1 ` and the empty string as numbers (and Java's and Python's also `1_0`, a Unicode digit, `NaN`): + text that is no key named row 1 (or row 0), and two different texts named one row. An integer key + is now an optional `-` and ASCII digits with no leading zero; a decimal key may add `.` and at + least one digit; nothing else is a key. TypeScript refuses it with `InvalidKeyError` (a + `ValidationError`), which the mounts answer `400 {"error":"invalid_id"}` like an id the column + cannot hold; the drizzle-fastify and hono mounts and the deprecated `parseId` read ids by the + same rule, and it also refuses an integer key that is not a safe integer (beyond 2^53) and a decimal + key that is not finite: a `field.long` key above 2^53 used to round silently to another row, where + Java accepts an integer key up to `Long.MAX_VALUE`. Java refuses a ref id with `IllegalArgumentException` and Python a key argument with + `ValueError`, the errors each already raised for an unusable argument. A string or uuid key is + untouched (`0123` stays `0123`). If you pass a key as text to `findById`, `update`, `delete` or + `load`, pass its decimal spelling. The read-only mount of a raw-SQL view, which has no column type to + consult, answers `400 invalid_id` for text that reads as a number without being its canonical spelling + (`01`, `1e0`), because SQLite would convert a quoted `'01'` back to row 1. Not changed: the numeric path parameters of the generated Spring + and FastAPI routes, which those frameworks parse before the ObjectManager sees them. + - **Fix, TypeScript: `DELETE` on a missing row answers `404`, not `500`, from the ObjectManager route mount.** `mountCrudRoutes` and `mountDeleteRoute` in `@metaobjectsdev/runtime-ts/fastify` called `ObjectManager.delete` in its default mode, which diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index b088cd05f3..00f808a08c 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 67 (55 query + 12 migration) | all 67; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 139 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 2 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings) | ✓ (Fastify reference + generated lane); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 141 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings) | ✓ (Fastify reference + generated lane); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | @@ -497,9 +497,9 @@ REAL, a MySQL `DECIMAL` keeps its scale, a MySQL `DATETIME` is the UTC wall cloc `report-relative-date` carries a per-engine seed (`seed-data-engine`). `op: relate` and the write ops stay Postgres-only. See [features/reporting.md](features/reporting.md#what-the-corpus-gates). -### `fixtures/api-contract-conformance/` (139) +### `fixtures/api-contract-conformance/` (141) -All 139 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port +All 141 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port REST API URL grammar + JSON wire format). Verifies every backend's emitted CRUD routes answer identically over HTTP — list / get / create / patch+put / delete, plus pagination (`limit`/`offset`), sort (`sort=field:dir`), the `withCount=1` @@ -517,7 +517,7 @@ inheritance; a subtype decimal filters and refuses extra digits, and the input r the whole hierarchy), `m2m/` (9 — 3 plain, 5 gating TPH x M:N together, the combination each corpus alone could not reach, and 1 pinning the collection-URL spelling), `jsonb/` (6, typed value-object columns; numbers inside them: a double stays a JSON number, a decimal is the canonical string; an undeclared member inside a value object is dropped), -`write-through/` (2, table-write + view-read entities), `secret-fields/` (2, #484: a `@formExclude` or credential `view.password` field is ignored on create, PATCH and PUT, and a credential is never returned), `enum-default/` (2, a create that omits a `field.enum` with `@default` stores the default, and a supplied value is kept), `projection/` (12, a +`write-through/` (2, table-write + view-read entities), `secret-fields/` (4, #484: a `@formExclude` or credential `view.password` field is ignored on create, PATCH and PUT, a credential is never returned, and a credential marked `@filterable` or `@sortable` is still on neither allowlist, so a filter or sort naming it is a 400; the `tph/` sub-directory is a TPH hierarchy whose subtypes share a column one of them marks as a credential, which is on no allowlist of the base or either subtype), `enum-default/` (2, a create that omits a `field.enum` with `@default` stores the default, and a supplied value is kept), `projection/` (12, a read-only view answers reads and refuses writes with 405; a projection with no declared identity has no item route; a projection keyed on a field not named `id` is addressed by it, whether its identity names `@fields` or derives them; decimal and float fields filter), `decimal/` (11, ADR-0019 Amendment 1: a decimal, array element and undeclared-precision column included, is one @@ -810,7 +810,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) The fixtures in the nine corpora mapped above (metamodel 574 + yaml 19 + verify 45 -+ render 18 + persistence 67 + api-contract 139 + source-resolution 28 + scope 10 + ++ render 18 + persistence 67 + api-contract 141 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index 0cddbe6ee5..df2c2f35d9 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -218,7 +218,7 @@ or Hono `onError` the adopter installed, answer exactly as they did before. | Response | When | |---|---| | malformed JSON body | a `POST`/`PATCH`/`PUT` body that does not parse as JSON (an empty body sent as `application/json` included) → HTTP 400 `{ "error": "invalid_json" }`. An EMPTY body on a method that takes none (`GET`, `DELETE`, `HEAD`) is accepted even when the request declares `content-type: application/json`, as many clients do on every request; a non-empty `DELETE` body is still parsed. Before, Fastify answered its own `{ "statusCode": 400, "code": "FST_ERR_CTP_INVALID_JSON_BODY", … }` and Hono a Zod `validation` error about a missing object | -| malformed id | a `:id` the key column cannot hold (a malformed uuid on a Postgres uuid key, a non-numeric id on an integer key) → HTTP 400 `{ "error": "invalid_id" }` on GET, PATCH and DELETE. A malformed uuid in a POST or PATCH body's foreign key → HTTP 400 `{ "error": "validation" }`, from the insert/update schema's `8-4-4-4-12` hex check. Postgres used to answer 500 for both. The check is TS-only | +| malformed id | a `:id` the key column cannot hold (a malformed uuid on a Postgres uuid key, a non-numeric id on an integer key, or numeric text that is not the canonical spelling of a number, such as `0x1` or `1e0`) → HTTP 400 `{ "error": "invalid_id" }` on GET, PATCH and DELETE. A malformed uuid in a POST or PATCH body's foreign key → HTTP 400 `{ "error": "validation" }`, from the insert/update schema's `8-4-4-4-12` hex check. Postgres used to answer 500 for both. The check is TS-only. The TypeScript, Java and Python ObjectManagers apply the numeric rule to a key passed as text to `findById`, `update`, `delete` and `load`: an optional `-` and ASCII digits with no leading zero (a decimal key may add `.` and digits), and no exponent, hex, plus sign, whitespace or negative zero, so the caller passes the decimal spelling. A string or uuid key is untouched | | malformed page bound | a `?limit=` or `?offset=` that is not a non-negative integer (`abc`, `-5`, `1.5`, an empty value) → HTTP 400 `{ "error": "pagination.invalid_value", "param": "limit", "value": "abc", "expected": "a non-negative integer (0 or more)" }`. Before, a non-numeric bound was dropped (every row came back) and a negative or fractional one reached SQL. An entity or a projection with declared columns has no page-size maximum unless the project sets `api.pagination` (see "A page size is a project setting" below, which answers `limit_too_large`); an opaque view (no declared columns, served by raw SQL) pages to at most 1000 rows, so there a `limit` above 1000 is refused too, with `"expected": "an integer from 0 to 1000"` (it used to be clamped silently). The same answer comes from the Drizzle mounts and the ObjectManager Fastify mount. The corpus sends a malformed bound only to a report (`report/bad-page-bound`), where every port answers this same envelope and also refuses `limit=0`; on an entity or a projection the other ports answer it as their framework does | | database constraint violation | a write the database itself rejects → `{ "error": "constraint_violation", "constraint": "" }`, HTTP **409** for `unique` and `foreign_key` (a conflict with another row) and HTTP **400** for `check` and `not_null` (the request's own value), per the status rule under "Error response". The body names the constraint KIND only — never the SQL, the table or the bound values. A `CHECK` the model derives (an enum, a `validator.numeric`/`length`/`regex` range) is normally refused earlier by the route's own validation, as the corpus's `{ "error": "validation" }` 400; this row is the database's backstop | | schema validation failure | a body that fails the insert/update schema → HTTP 400 `{ "error": "validation", "issues": [...] }`, each issue as Zod reports it **minus `pattern`**: Zod 4 attaches a failed `.regex()` check's source there, which for a generated `field.date` / `field.time` / `field.timestamp` check is a ~300-character calendar regex (and an authored `validator.regex` pattern is the server's to keep). The generated temporal checks carry a short `message` naming the expected format instead (`"must be an ISO date (YYYY-MM-DD)"`) | @@ -683,9 +683,10 @@ pin `reject` in both lanes of every port, and `api-settings/unknown-fields-dropp the generated lane. 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 -(a filter on a secret answers whether a guess is right). To return a credential from a route, hand-write that +field, so your own code writes a hash or token and reads it back. A credential is also never on a filter or sort +allowlist, whatever `@filterable` or `@sortable` say on it (a filter on a secret answers whether a guess is right, +and its order leaks it): the allowlist is built without it, so a request that names it is refused as any other field +the allowlist does not hold (`400` `invalid_filter_field` or `invalid_sort`, naming the field). On a single-table (TPH) hierarchy the mark holds for the shared column: a column one subtype marks as a credential is on no allowlist of the base or of any subtype. To return a credential from a route, hand-write that route; the generated one will not. Generated forms and the api docs omit both kinds of field as well. A served report is covered too. A report column is derived from its `@of` field, and a derived column keeps diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 76c759c50b..33faff0d95 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -125,8 +125,8 @@ Five rows need a footnote: | `@maxLength` | int | Length for string types (drives `varchar(N)`). | | `@column` | string | Physical column name (overrides the project's `naming.columns` rule). | | `@default` | any | Default value (literal or canonical SQL default function). | -| `@filterable` | bool | Field appears in the generated server-side filter allowlist. | -| `@sortable` | bool | Field appears in the server-side sort allowlist (defaults to `@filterable`). | +| `@filterable` | bool | Field appears in the generated server-side filter allowlist, unless it is a credential (`view.password`); see [api-contract.md](api-contract.md). | +| `@sortable` | bool | Field appears in the server-side sort allowlist (defaults to `@filterable`), unless it is a credential. | ## Column naming — `@column` and the `naming` setting diff --git a/docs/features/metadata-driven-runtime.md b/docs/features/metadata-driven-runtime.md index 285e3564b3..1827566544 100644 --- a/docs/features/metadata-driven-runtime.md +++ b/docs/features/metadata-driven-runtime.md @@ -134,7 +134,7 @@ rule below has tests in `examples/dynamic-grid/test/`. | Constraint errors | A unique or foreign-key failure is a `409` or `400` that names no table or column. | `write-contract.test.ts` | | Model reload | Reloads run one at a time. A schema change is applied by the migration engine's transactional applier, so one that fails part-way changes nothing and the model that was being served stays in place. | `reload-safety.test.ts` | -Three defects outside the example turned up while building this: +Two defects outside the example turned up while building this: - `DELETE` on a missing row through the `ObjectManager` route mount in `@metaobjectsdev/runtime-ts/fastify` answered `500`. Fixed in the package (it answers @@ -142,9 +142,6 @@ Three defects outside the example turned up while building this: - An `offset` with no `limit` was a SQL syntax error on SQLite and MySQL in both the Kysely and the Drizzle driver, so a list with no `api.pagination` answered `500` to `?offset=5`. Fixed in the drivers. -- The reference route generator's filter allowlist does not leave out a credential that a - model marks `@filterable`. This mount does. The generators were out of scope here, so - that one is reported and not changed. ## Measurement diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 353aaf5c07..f5cb0e1050 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -387,7 +387,7 @@ calls it copies the adapter's source too: | `meta eject …` | Copies into `codegen/generators/` | Also copies into `codegen/runtime/` (verbatim from `@metaobjectsdev/runtime-ts/src`) | |---|---|---| -| `routes` | `routes.ts` — the whole route composition (CRUD, read-only projections, M:N traversal, TPH per-subtype sets), not a call into the engine | `drizzle-fastify/*` (mounts, filter parser, list params, M:N and read-only mounts, error handler), `route-errors.ts`, `constraint-errors.ts`, `timestamp-wire.ts` | +| `routes` | `routes.ts` — the whole route composition (CRUD, read-only projections, M:N traversal, TPH per-subtype sets), not a call into the engine | `drizzle-fastify/*` (mounts, filter parser, list params, M:N and read-only mounts, error handler), `route-errors.ts`, `constraint-errors.ts`, `timestamp-wire.ts`, `decimal-wire.ts`, `duration-wire.ts`, `wire-format.ts`, `sql-dialect.ts`, `canonical-key.ts`, `errors.ts` | | `routes-hono` | `routes-hono.ts`, likewise self-contained | `hono/*`, plus the shared parser, allowlist, envelope and timestamp files it reaches | | `entity` | `entity.ts` | `drizzle-fastify/filter-allowlist.ts` — the `FilterAllowlist` / `SortAllowlist` types the entity module's allowlists are typed by | diff --git a/examples/advanced-modeling/codegen/generators/entity.ts b/examples/advanced-modeling/codegen/generators/entity.ts index 6d3c2234c6..926da1c687 100644 --- a/examples/advanced-modeling/codegen/generators/entity.ts +++ b/examples/advanced-modeling/codegen/generators/entity.ts @@ -145,7 +145,7 @@ function renderEntity(entity: MetaObject, ctx: RenderContext, opts?: RenderEntit renderZodValidators(entity, ctx), renderEntityConstants(entity, ctx.apiPrefix, namesConstArg(constantsNames)), ...(allowlists ? [renderFilterAllowlist(entity, undefined, ctx), renderSortAllowlist(entity, undefined, ctx)] : []), - renderFilterType(entity), + renderFilterType(entity, undefined, ctx.loadedRoot), ...(tphBlock !== null ? [tphBlock] : []), ]; diff --git a/examples/advanced-modeling/codegen/runtime/canonical-key.ts b/examples/advanced-modeling/codegen/runtime/canonical-key.ts new file mode 100644 index 0000000000..1b32e7c4e8 --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/canonical-key.ts @@ -0,0 +1,64 @@ +/** + * Canonical numeric key text. + * + * A numeric primary key or id arrives as text (an HTTP path parameter, a `ref` string). `Number()` + * reads far more than a number: `0x1`, `1e0`, `0b1`, ` 1 `, `+1`, `1.` and the empty string all + * come back as a number, so two different texts name one row, and a text that is no key at all + * names row 0. A key is read only from its one canonical spelling: + * + * - an integer key: an optional `-`, then digits with no leading zero (`0` alone is fine); + * - a decimal or floating-point key: the same, optionally followed by `.` and at least one digit. + * + * No exponent, no hex, no sign other than `-`, no whitespace, and no negative zero. The checks walk + * the characters; there is no pattern to keep in step with anything. + */ + +function isAsciiDigit(c: string): boolean { + return c >= "0" && c <= "9"; +} + +/** True when every character of `digits` is an ASCII digit and there is at least one. */ +function allDigits(digits: string): boolean { + if (digits === "") return false; + for (const c of digits) if (!isAsciiDigit(c)) return false; + return true; +} + +/** True when `unsigned` is digits with no leading zero (`0` alone is allowed). */ +function isCanonicalWhole(unsigned: string): boolean { + return allDigits(unsigned) && (unsigned.length === 1 || unsigned[0] !== "0"); +} + +function hasIntegerShape(text: string): boolean { + const negative = text.startsWith("-"); + const unsigned = negative ? text.slice(1) : text; + return isCanonicalWhole(unsigned) && !(negative && unsigned === "0"); +} + +/** + * True when `text` is an optional `-` and canonical whole digits, is not negative zero, and reads + * back as exactly one JS number (a safe integer): two canonical texts never name one key. + */ +export function isCanonicalInteger(text: string): boolean { + return hasIntegerShape(text) && Number.isSafeInteger(Number(text)); +} + +/** + * True when `text` is a canonical integer (a safe integer when it has no fraction), or one + * followed by `.` and at least one digit that reads back as a finite number. + */ +export function isCanonicalDecimal(text: string): boolean { + if (!text.includes(".")) return isCanonicalInteger(text); + return hasDecimalShape(text) && Number.isFinite(Number(text)); +} + +function hasDecimalShape(text: string): boolean { + const negative = text.startsWith("-"); + const unsigned = negative ? text.slice(1) : text; + const dot = unsigned.indexOf("."); + const whole = unsigned.slice(0, dot); + const fraction = unsigned.slice(dot + 1); + if (!isCanonicalWhole(whole) || !allDigits(fraction)) return false; + // Negative zero in any spelling (`-0.0`) is not a canonical key. + return !(negative && whole === "0" && [...fraction].every((c) => c === "0")); +} diff --git a/examples/advanced-modeling/codegen/runtime/constraint-errors.ts b/examples/advanced-modeling/codegen/runtime/constraint-errors.ts index d14834f7f1..a91577a165 100644 --- a/examples/advanced-modeling/codegen/runtime/constraint-errors.ts +++ b/examples/advanced-modeling/codegen/runtime/constraint-errors.ts @@ -27,6 +27,7 @@ * to match. An unrecognised error is still a 500 — but a 500 whose body says nothing about * the query, with the real error left to the server log where it belongs. */ +import { InvalidKeyError } from "./errors.js"; /** The constraint kinds worth telling a client apart. */ export type ConstraintKind = "foreign_key" | "unique" | "check" | "not_null"; @@ -107,6 +108,9 @@ export async function withConstraintMapping( } catch (err) { const failure = classifyConstraintError(err); if (failure !== undefined) return onFailure(failure); + // A key text that is no key carries no database detail, and the route's error handler + // answers it 400 `invalid_id`; redacting it to a 500 would hide a caller's own mistake. + if (err instanceof InvalidKeyError) throw err; // Not a constraint problem — the operator needs the detail, the caller must not have it. logError(err); throw new RedactedDatabaseError(); diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts index b2827b936c..93e97cffde 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -298,8 +298,10 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; if (useRawSql) { + const idLiteral = rawIdLiteral(id); + if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${rawIdLiteral(id)} LIMIT 1`)) as any[]; + const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; const row = rows[0] ? camelizeRow(rows[0]) : undefined; return row ?? reply.code(404).send({ error: "not_found" }); } diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/route-error-handler.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/route-error-handler.ts index ab240dc5c2..35dd5280e9 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/route-error-handler.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/route-error-handler.ts @@ -12,6 +12,7 @@ * * What it answers: * - a body Fastify's JSON parser refused → `400 { "error": "invalid_json" }`; + * - a key text ObjectManager refused as no key of the PK's type → `400 { "error": "invalid_id" }`; * - any other deliberate 4xx (an auth hook's 401, schema validation, 413, 415) → rethrown, * so the enclosing scope's handler — the adopter's, or Fastify's default — answers it * exactly as it did before the mount existed; @@ -31,6 +32,10 @@ import { isMalformedJsonBodyError, logUnexpectedError, } from "../route-errors.js"; +import { InvalidKeyError } from "../errors.js"; + +/** Wire code for an id that is not the canonical spelling of a key of the PK's type. */ +const ERROR_CODE_INVALID_ID = "invalid_id"; export function contractRouteErrorHandler( error: unknown, @@ -40,6 +45,11 @@ export function contractRouteErrorHandler( if (isMalformedJsonBodyError(error)) { return reply.code(HTTP_STATUS_BAD_REQUEST).send(INVALID_JSON_BODY); } + // ObjectManager refused a key text that is no key (`0x1`, `1e0`): the id the mounts that read + // a column already answer `invalid_id` for. + if (error instanceof InvalidKeyError) { + return reply.code(HTTP_STATUS_BAD_REQUEST).send({ error: ERROR_CODE_INVALID_ID }); + } // Throwing from a route-level handler hands the error to the enclosing scope's handler. if (isDeliberateClientError(error)) throw error; logUnexpectedError(error); diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/util.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/util.ts index d6aaea4bbb..9ba75c52cf 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/util.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/util.ts @@ -4,6 +4,7 @@ import { FIELD_SUBTYPE_UUID } from "@metaobjectsdev/metadata"; import { matchesFormat } from "./filter-value-format.js"; +import { isCanonicalDecimal } from "../canonical-key.js"; /** * Coerce a path-param id to number when numeric, else keep the string key. @@ -16,8 +17,8 @@ import { matchesFormat } from "./filter-value-format.js"; * with no declared columns (via `coerceIdForColumn`/`rawIdLiteral`). */ export function parseId(raw: string): number | string { - const n = Number(raw); - return Number.isFinite(n) && raw.trim() !== "" ? n : raw; + // Only the canonical spelling of a number is one: `0x1` and `1e0` stay text, never row 1. + return isCanonicalDecimal(raw) ? Number(raw) : raw; } /** @@ -36,8 +37,8 @@ export function parseId(raw: string): number | string { export function coerceIdForColumn(colRef: unknown, raw: string): number | string | undefined { const dataType = (colRef as { dataType?: string } | undefined)?.dataType; if (dataType === "number") { - const n = Number(raw); - return Number.isFinite(n) && raw.trim() !== "" ? n : undefined; + // Canonical decimal text only (see canonical-key.ts): `0x1` and `1e0` are not an id. + return isCanonicalDecimal(raw) ? Number(raw) : undefined; } // A Postgres uuid column rejects a malformed literal at execution time // ("invalid input syntax for type uuid"), which surfaced as a 500. The id's shape @@ -50,14 +51,18 @@ export function coerceIdForColumn(colRef: unknown, raw: string): number | string } /** - * SQL literal for an id on a raw-SQL view (no declared columns to inspect). Numeric ids - * stay unquoted; anything else is emitted as a quote-escaped string literal, so a uuid - * key is matched rather than coerced to NaN. SQLite applies column affinity on comparison, - * so both forms land on the right column type. + * SQL literal for an id on a raw-SQL view (no declared columns to inspect), or `undefined` + * when the text reads as a number but is not the canonical spelling of one (`01`, `1e0`, + * `0x1`). Numeric ids stay unquoted; anything else is emitted as a quote-escaped string + * literal, so a uuid key is matched rather than coerced to NaN. SQLite applies column + * affinity to a text literal compared with an integer column, so a quoted `'01'` or `'1e0'` + * would name row 1 again: with no column type to say the key is a string, such text is no id. */ -export function rawIdLiteral(raw: string): string { +export function rawIdLiteral(raw: string): string | undefined { const v = parseId(raw); - return typeof v === "number" ? String(v) : `'${raw.replace(/'/g, "''")}'`; + if (typeof v === "number") return String(v); + if (raw.trim() !== "" && !Number.isNaN(Number(raw))) return undefined; + return `'${raw.replace(/'/g, "''")}'`; } // Accepts "1" or boolean true (the qs serialization of withCount: 1 from buildFilterQs). diff --git a/examples/advanced-modeling/codegen/runtime/errors.ts b/examples/advanced-modeling/codegen/runtime/errors.ts new file mode 100644 index 0000000000..cbf93cedd2 --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/errors.ts @@ -0,0 +1,129 @@ +// All errors extend RuntimeError and JSON-serialize via toJSON() — admin UIs and MCP tools +// surface them as structured JSON, not Error.message strings. + +export interface ValidationFailure { + field: string; + rule: string; + message: string; + expected?: unknown; + received?: unknown; +} + +interface BaseOpts { + code?: string; + entity?: string; + cause?: unknown; +} + +export class RuntimeError extends Error { + readonly code: string; + readonly entity?: string; + override readonly cause?: unknown; + + constructor(message: string, opts: BaseOpts & { code: string }) { + super(message); + this.name = "RuntimeError"; + this.code = opts.code; + if (opts.entity !== undefined) this.entity = opts.entity; + if (opts.cause !== undefined) this.cause = opts.cause; + } + + toJSON(): Record { + const out: Record = { name: this.name, code: this.code, message: this.message }; + if (this.entity !== undefined) out.entity = this.entity; + return out; + } +} + +export class ValidationError extends RuntimeError { + readonly errors: ValidationFailure[]; + + constructor(message: string, opts: { entity?: string; errors: ValidationFailure[]; cause?: unknown }) { + super(message, { code: "validation_failed", ...(opts.entity !== undefined ? { entity: opts.entity } : {}), ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "ValidationError"; + this.errors = opts.errors; + } + + override toJSON(): Record { + return { ...super.toJSON(), errors: this.errors }; + } +} + +/** + * A key text that is not the canonical spelling of a key of the PK field's declared type (`0x1` + * or `1e0` for an integer key). The same `ValidationError` shape, so a caller that handles a + * failed value handles this too; the HTTP mounts answer it `400 {"error":"invalid_id"}`. + */ +export class InvalidKeyError extends ValidationError { + constructor(entity: string, field: string, expected: string) { + super(`Invalid key for ${entity}.${field}: expected ${expected}`, { + entity, + errors: [{ field, rule: "invalid_key", message: `expected ${expected}`, expected }], + }); + this.name = "InvalidKeyError"; + } +} + +export class NotFoundError extends RuntimeError { + readonly id: unknown; + + constructor(message: string, opts: { entity: string; id: unknown; cause?: unknown }) { + super(message, { code: "not_found", entity: opts.entity, ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "NotFoundError"; + this.id = opts.id; + } + + override toJSON(): Record { + return { ...super.toJSON(), id: this.id }; + } +} + +export class ConstraintViolationError extends RuntimeError { + readonly kind: "unique" | "foreign_key" | "not_null" | "check"; + readonly table: string; + readonly field?: string; + readonly detail?: string; + + constructor(message: string, opts: { + kind: "unique" | "foreign_key" | "not_null" | "check"; + table: string; + field?: string; + detail?: string; + cause?: unknown; + }) { + super(message, { code: "constraint_violation", ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "ConstraintViolationError"; + this.kind = opts.kind; + this.table = opts.table; + if (opts.field !== undefined) this.field = opts.field; + if (opts.detail !== undefined) this.detail = opts.detail; + } + + override toJSON(): Record { + const out: Record = { ...super.toJSON(), kind: this.kind, table: this.table }; + if (this.field !== undefined) out.field = this.field; + if (this.detail !== undefined) out.detail = this.detail; + return out; + } +} + +export class MetadataError extends RuntimeError { + constructor(message: string, opts: { entity?: string; cause?: unknown } = {}) { + super(message, { code: "metadata_error", ...(opts.entity !== undefined ? { entity: opts.entity } : {}), ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "MetadataError"; + } +} + +export class UnsafeNameError extends RuntimeError { + readonly value: string; + + constructor(message: string, opts: { value: string }) { + super(message, { code: "unsafe_name" }); + this.name = "UnsafeNameError"; + this.value = opts.value; + } + + override toJSON(): Record { + return { ...super.toJSON(), value: this.value }; + } +} diff --git a/examples/advanced-modeling/codegen/templates/entity-file.ts b/examples/advanced-modeling/codegen/templates/entity-file.ts index c5dddf6d1c..905384a229 100644 --- a/examples/advanced-modeling/codegen/templates/entity-file.ts +++ b/examples/advanced-modeling/codegen/templates/entity-file.ts @@ -228,7 +228,7 @@ ${docsPrefix}export type ${entity.name} = ${z}.infer c.attr(FIELD_ATTR_FILTERABLE) === true && c.name !== exclude); + .filter((c) => isFilterableField(c) && !credentials.has(c.name) && c.name !== exclude); } /** @@ -133,7 +135,7 @@ function filterableFields(entity: MetaObject, exclude?: string): MetaField[] { * branching is needed here. Absent `ctx`, or in the default mode, output is unchanged. */ export function renderFilterAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { - const fields = filterableFields(entity, exclude); + const fields = filterableFields(entity, exclude, ctx); if (fields.length === 0) { return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; @@ -169,7 +171,9 @@ export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: // @sortable: false explicitly opts out. // Uses shared isSortableField predicate — must stay in sync with renderFilterType. // `exclude` (FR-017): per-subtype TPH allowlists omit the discriminator. - const sortable = sortableFields(entity).filter((f) => f.name !== exclude); + // A credential is never sortable (isSortableField), nor a column a sibling subtype marks as one. + const credentials = credentialFieldNames(entity, ctx?.loadedRoot); + const sortable = flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude); if (sortable.length === 0) { return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; diff --git a/examples/advanced-modeling/codegen/templates/filter-shared.ts b/examples/advanced-modeling/codegen/templates/filter-shared.ts index c4de261bbc..9e6f5f2253 100644 --- a/examples/advanced-modeling/codegen/templates/filter-shared.ts +++ b/examples/advanced-modeling/codegen/templates/filter-shared.ts @@ -15,7 +15,8 @@ // runs the opposite way from the endpoint it queries. import { flatSurfaceFields } from "@metaobjectsdev/codegen-ts/engine"; -import { MetaField, MetaObject, type MetaData } from "@metaobjectsdev/metadata"; +import { hiddenFieldNames, isCredentialField, tphHierarchy } from "@metaobjectsdev/codegen-ts/engine"; +import { MetaField, MetaObject, type MetaData, type MetaRoot } from "@metaobjectsdev/metadata"; import { FIELD_ATTR_FILTERABLE, FIELD_ATTR_SORTABLE, @@ -28,27 +29,53 @@ import { * returns one of these two or says it has no answer. */ export type SortOrder = "asc" | "desc"; +/** + * Returns true if the given field is on the filter allowlist: it is marked `@filterable: true` + * and is not a credential. A filter on a secret is an oracle for it (`eq`, or `like` a prefix, + * one character at a time), so a credential (a field that declares a `view.password`) is never + * filterable, whatever the model marks. The allowlist is built from this predicate, so a + * request that names one is refused as any other field the allowlist does not hold. + */ +export function isFilterableField(field: MetaField): boolean { + return field.attr(FIELD_ATTR_FILTERABLE) === true && !isCredentialField(field); +} + /** * Returns true if the given field should be included in sort operations. * * Rules (in priority order): + * 0. a credential → never sortable (the order of a secret leaks it) * 1. @sortable: true → always sortable (even without @filterable) * 2. @sortable: false → never sortable (overrides @filterable) * 3. no @sortable → sortable iff @filterable === true */ export function isSortableField(field: MetaField): boolean { + if (isCredentialField(field)) return false; const sortableAttr = field.attr(FIELD_ATTR_SORTABLE); if (sortableAttr === true) return true; if (sortableAttr === false) return false; return field.attr(FIELD_ATTR_FILTERABLE) === true; } +/** + * The field names no allowlist of `entity` may hold because the column is a credential: a + * `view.password` on ANY declaration of a column that subtypes of one single-table (TPH) + * hierarchy share counts on every subtype that has it, the same rule the generated routes use to + * hide the column. `root` is the loaded model the hierarchy is read from; without it the entity + * stands alone. + */ +export function credentialFieldNames(entity: MetaObject, root: MetaRoot | undefined): ReadonlySet { + const hierarchy = root === undefined ? [entity] : tphHierarchy(entity, root); + return new Set(hiddenFieldNames(entity, hierarchy)); +} + /** * Returns all sortable field children of the given entity. */ -export function sortableFields(entity: MetaObject): MetaField[] { +export function sortableFields(entity: MetaObject, root?: MetaRoot): MetaField[] { // fields() returns effective fields, so inherited fields (from extends:/super:) are included in sort ops. - return flatSurfaceFields(entity).filter(isSortableField); + const credentials = credentialFieldNames(entity, root); + return flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name)); } /** diff --git a/examples/advanced-modeling/codegen/templates/filter-type.ts b/examples/advanced-modeling/codegen/templates/filter-type.ts index d3a06b53fd..d32ff351fd 100644 --- a/examples/advanced-modeling/codegen/templates/filter-type.ts +++ b/examples/advanced-modeling/codegen/templates/filter-type.ts @@ -4,9 +4,8 @@ import { flatSurfaceFields } from "@metaobjectsdev/codegen-ts/engine"; import { code, type Code } from "@metaobjectsdev/codegen-ts/engine"; -import { MetaField, MetaObject } from "@metaobjectsdev/metadata"; +import { MetaField, MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; import { - FIELD_ATTR_FILTERABLE, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, @@ -16,7 +15,7 @@ import { FIELD_SUBTYPE_ENUM, opsForField, } from "@metaobjectsdev/metadata"; -import { isSortableField } from "./filter-shared.js"; +import { credentialFieldNames, isFilterableField, isSortableField } from "./filter-shared.js"; import { entityTypeNames } from "./entity-type-names.js"; import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; @@ -80,11 +79,15 @@ function renderFieldUnion(field: MetaField): string { * per-subtype route path), keeping the client `Filter` type aligned with * the server's per-subtype allowlist. */ -export function renderFilterType(entity: MetaObject, exclude?: string): Code { +export function renderFilterType(entity: MetaObject, exclude?: string, root?: MetaRoot): Code { const filterName = entityTypeNames(entity).filter; // fields() returns effective fields, so inherited fields (from extends:/super:) are included in filter types. - const allFields = flatSurfaceFields(entity).filter((c) => c.name !== exclude); - const filterableFieldsList = allFields.filter((c) => c.attr(FIELD_ATTR_FILTERABLE) === true); + // A column a sibling subtype of the same table marks as a credential is no more filterable or + // sortable here than in the server allowlist (credentialFieldNames), or the client type would + // offer a filter the server answers 400. + const credentials = credentialFieldNames(entity, root); + const allFields = flatSurfaceFields(entity).filter((c) => c.name !== exclude && !credentials.has(c.name)); + const filterableFieldsList = allFields.filter(isFilterableField); // Sort union uses isSortableField — same predicate as renderSortAllowlist to prevent // client/server mismatches (@filterable: true + @sortable: false must be excluded from both). const sortFieldNames = allFields.filter(isSortableField).map((f) => `"${f.name}"`); diff --git a/examples/advanced-modeling/codegen/templates/projection-decl.ts b/examples/advanced-modeling/codegen/templates/projection-decl.ts index 57eed67274..4b409b4581 100644 --- a/examples/advanced-modeling/codegen/templates/projection-decl.ts +++ b/examples/advanced-modeling/codegen/templates/projection-decl.ts @@ -219,7 +219,7 @@ ${joinCode(constFieldLines, { on: "\n" })} ...(allowlists ? [renderFilterAllowlist(projection, undefined, ctx), renderSortAllowlist(projection, undefined, ctx)] : []), - renderFilterType(projection), + renderFilterType(projection, undefined, ctx?.loadedRoot), ]; const body = joinCode(sections, { on: "\n" }).toString(); diff --git a/examples/advanced-modeling/codegen/templates/value-object-file.ts b/examples/advanced-modeling/codegen/templates/value-object-file.ts index a7378360d0..6aa9680449 100644 --- a/examples/advanced-modeling/codegen/templates/value-object-file.ts +++ b/examples/advanced-modeling/codegen/templates/value-object-file.ts @@ -66,7 +66,7 @@ export function renderValueObjectFile(obj: MetaObject, apiPrefix = "", ctx?: Ren // FR-017 Tier 3: the per-subtype CLIENT filter type, discriminator-excluded — // kept in lockstep with the per-subtype allowlist above so a typed // `Filter` can't express a filter the server allowlist would 400. - const tphFilterType = tphSubtype ? renderFilterType(obj, discField) : null; + const tphFilterType = tphSubtype ? renderFilterType(obj, discField, ctx?.loadedRoot) : null; // A sourceless entity's wire contract: create + PATCH schemas, allowlists, filter type. // No constants object — it names a table and a route this object does not have. The // allowlists import runtime types, so a contract-only target (runtime: false) skips them. @@ -96,7 +96,7 @@ export function renderValueObjectFile(obj: MetaObject, apiPrefix = "", ctx?: Ren ...(tphSortAllowlist !== null ? [tphSortAllowlist] : []), ...(tphFilterType !== null ? [tphFilterType] : []), ...(sourcelessAllowlists ? [renderFilterAllowlist(obj, undefined, ctx), renderSortAllowlist(obj, undefined, ctx)] : []), - ...(sourceless ? [renderFilterType(obj)] : []), + ...(sourceless ? [renderFilterType(obj, undefined, ctx?.loadedRoot)] : []), ]; const body = joinCode(sections, { on: "\n" }).toString(); // ADR-0044/#228 — the hand-edit sidecar name follows this value object's EMITTED diff --git a/examples/showcase/codegen/generators/entity.ts b/examples/showcase/codegen/generators/entity.ts index 6d3c2234c6..926da1c687 100644 --- a/examples/showcase/codegen/generators/entity.ts +++ b/examples/showcase/codegen/generators/entity.ts @@ -145,7 +145,7 @@ function renderEntity(entity: MetaObject, ctx: RenderContext, opts?: RenderEntit renderZodValidators(entity, ctx), renderEntityConstants(entity, ctx.apiPrefix, namesConstArg(constantsNames)), ...(allowlists ? [renderFilterAllowlist(entity, undefined, ctx), renderSortAllowlist(entity, undefined, ctx)] : []), - renderFilterType(entity), + renderFilterType(entity, undefined, ctx.loadedRoot), ...(tphBlock !== null ? [tphBlock] : []), ]; diff --git a/examples/showcase/codegen/runtime/canonical-key.ts b/examples/showcase/codegen/runtime/canonical-key.ts new file mode 100644 index 0000000000..1b32e7c4e8 --- /dev/null +++ b/examples/showcase/codegen/runtime/canonical-key.ts @@ -0,0 +1,64 @@ +/** + * Canonical numeric key text. + * + * A numeric primary key or id arrives as text (an HTTP path parameter, a `ref` string). `Number()` + * reads far more than a number: `0x1`, `1e0`, `0b1`, ` 1 `, `+1`, `1.` and the empty string all + * come back as a number, so two different texts name one row, and a text that is no key at all + * names row 0. A key is read only from its one canonical spelling: + * + * - an integer key: an optional `-`, then digits with no leading zero (`0` alone is fine); + * - a decimal or floating-point key: the same, optionally followed by `.` and at least one digit. + * + * No exponent, no hex, no sign other than `-`, no whitespace, and no negative zero. The checks walk + * the characters; there is no pattern to keep in step with anything. + */ + +function isAsciiDigit(c: string): boolean { + return c >= "0" && c <= "9"; +} + +/** True when every character of `digits` is an ASCII digit and there is at least one. */ +function allDigits(digits: string): boolean { + if (digits === "") return false; + for (const c of digits) if (!isAsciiDigit(c)) return false; + return true; +} + +/** True when `unsigned` is digits with no leading zero (`0` alone is allowed). */ +function isCanonicalWhole(unsigned: string): boolean { + return allDigits(unsigned) && (unsigned.length === 1 || unsigned[0] !== "0"); +} + +function hasIntegerShape(text: string): boolean { + const negative = text.startsWith("-"); + const unsigned = negative ? text.slice(1) : text; + return isCanonicalWhole(unsigned) && !(negative && unsigned === "0"); +} + +/** + * True when `text` is an optional `-` and canonical whole digits, is not negative zero, and reads + * back as exactly one JS number (a safe integer): two canonical texts never name one key. + */ +export function isCanonicalInteger(text: string): boolean { + return hasIntegerShape(text) && Number.isSafeInteger(Number(text)); +} + +/** + * True when `text` is a canonical integer (a safe integer when it has no fraction), or one + * followed by `.` and at least one digit that reads back as a finite number. + */ +export function isCanonicalDecimal(text: string): boolean { + if (!text.includes(".")) return isCanonicalInteger(text); + return hasDecimalShape(text) && Number.isFinite(Number(text)); +} + +function hasDecimalShape(text: string): boolean { + const negative = text.startsWith("-"); + const unsigned = negative ? text.slice(1) : text; + const dot = unsigned.indexOf("."); + const whole = unsigned.slice(0, dot); + const fraction = unsigned.slice(dot + 1); + if (!isCanonicalWhole(whole) || !allDigits(fraction)) return false; + // Negative zero in any spelling (`-0.0`) is not a canonical key. + return !(negative && whole === "0" && [...fraction].every((c) => c === "0")); +} diff --git a/examples/showcase/codegen/runtime/constraint-errors.ts b/examples/showcase/codegen/runtime/constraint-errors.ts index d14834f7f1..a91577a165 100644 --- a/examples/showcase/codegen/runtime/constraint-errors.ts +++ b/examples/showcase/codegen/runtime/constraint-errors.ts @@ -27,6 +27,7 @@ * to match. An unrecognised error is still a 500 — but a 500 whose body says nothing about * the query, with the real error left to the server log where it belongs. */ +import { InvalidKeyError } from "./errors.js"; /** The constraint kinds worth telling a client apart. */ export type ConstraintKind = "foreign_key" | "unique" | "check" | "not_null"; @@ -107,6 +108,9 @@ export async function withConstraintMapping( } catch (err) { const failure = classifyConstraintError(err); if (failure !== undefined) return onFailure(failure); + // A key text that is no key carries no database detail, and the route's error handler + // answers it 400 `invalid_id`; redacting it to a 500 would hide a caller's own mistake. + if (err instanceof InvalidKeyError) throw err; // Not a constraint problem — the operator needs the detail, the caller must not have it. logError(err); throw new RedactedDatabaseError(); diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts index b2827b936c..93e97cffde 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -298,8 +298,10 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; if (useRawSql) { + const idLiteral = rawIdLiteral(id); + if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${rawIdLiteral(id)} LIMIT 1`)) as any[]; + const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; const row = rows[0] ? camelizeRow(rows[0]) : undefined; return row ?? reply.code(404).send({ error: "not_found" }); } diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/route-error-handler.ts b/examples/showcase/codegen/runtime/drizzle-fastify/route-error-handler.ts index ab240dc5c2..35dd5280e9 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/route-error-handler.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/route-error-handler.ts @@ -12,6 +12,7 @@ * * What it answers: * - a body Fastify's JSON parser refused → `400 { "error": "invalid_json" }`; + * - a key text ObjectManager refused as no key of the PK's type → `400 { "error": "invalid_id" }`; * - any other deliberate 4xx (an auth hook's 401, schema validation, 413, 415) → rethrown, * so the enclosing scope's handler — the adopter's, or Fastify's default — answers it * exactly as it did before the mount existed; @@ -31,6 +32,10 @@ import { isMalformedJsonBodyError, logUnexpectedError, } from "../route-errors.js"; +import { InvalidKeyError } from "../errors.js"; + +/** Wire code for an id that is not the canonical spelling of a key of the PK's type. */ +const ERROR_CODE_INVALID_ID = "invalid_id"; export function contractRouteErrorHandler( error: unknown, @@ -40,6 +45,11 @@ export function contractRouteErrorHandler( if (isMalformedJsonBodyError(error)) { return reply.code(HTTP_STATUS_BAD_REQUEST).send(INVALID_JSON_BODY); } + // ObjectManager refused a key text that is no key (`0x1`, `1e0`): the id the mounts that read + // a column already answer `invalid_id` for. + if (error instanceof InvalidKeyError) { + return reply.code(HTTP_STATUS_BAD_REQUEST).send({ error: ERROR_CODE_INVALID_ID }); + } // Throwing from a route-level handler hands the error to the enclosing scope's handler. if (isDeliberateClientError(error)) throw error; logUnexpectedError(error); diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/util.ts b/examples/showcase/codegen/runtime/drizzle-fastify/util.ts index d6aaea4bbb..9ba75c52cf 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/util.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/util.ts @@ -4,6 +4,7 @@ import { FIELD_SUBTYPE_UUID } from "@metaobjectsdev/metadata"; import { matchesFormat } from "./filter-value-format.js"; +import { isCanonicalDecimal } from "../canonical-key.js"; /** * Coerce a path-param id to number when numeric, else keep the string key. @@ -16,8 +17,8 @@ import { matchesFormat } from "./filter-value-format.js"; * with no declared columns (via `coerceIdForColumn`/`rawIdLiteral`). */ export function parseId(raw: string): number | string { - const n = Number(raw); - return Number.isFinite(n) && raw.trim() !== "" ? n : raw; + // Only the canonical spelling of a number is one: `0x1` and `1e0` stay text, never row 1. + return isCanonicalDecimal(raw) ? Number(raw) : raw; } /** @@ -36,8 +37,8 @@ export function parseId(raw: string): number | string { export function coerceIdForColumn(colRef: unknown, raw: string): number | string | undefined { const dataType = (colRef as { dataType?: string } | undefined)?.dataType; if (dataType === "number") { - const n = Number(raw); - return Number.isFinite(n) && raw.trim() !== "" ? n : undefined; + // Canonical decimal text only (see canonical-key.ts): `0x1` and `1e0` are not an id. + return isCanonicalDecimal(raw) ? Number(raw) : undefined; } // A Postgres uuid column rejects a malformed literal at execution time // ("invalid input syntax for type uuid"), which surfaced as a 500. The id's shape @@ -50,14 +51,18 @@ export function coerceIdForColumn(colRef: unknown, raw: string): number | string } /** - * SQL literal for an id on a raw-SQL view (no declared columns to inspect). Numeric ids - * stay unquoted; anything else is emitted as a quote-escaped string literal, so a uuid - * key is matched rather than coerced to NaN. SQLite applies column affinity on comparison, - * so both forms land on the right column type. + * SQL literal for an id on a raw-SQL view (no declared columns to inspect), or `undefined` + * when the text reads as a number but is not the canonical spelling of one (`01`, `1e0`, + * `0x1`). Numeric ids stay unquoted; anything else is emitted as a quote-escaped string + * literal, so a uuid key is matched rather than coerced to NaN. SQLite applies column + * affinity to a text literal compared with an integer column, so a quoted `'01'` or `'1e0'` + * would name row 1 again: with no column type to say the key is a string, such text is no id. */ -export function rawIdLiteral(raw: string): string { +export function rawIdLiteral(raw: string): string | undefined { const v = parseId(raw); - return typeof v === "number" ? String(v) : `'${raw.replace(/'/g, "''")}'`; + if (typeof v === "number") return String(v); + if (raw.trim() !== "" && !Number.isNaN(Number(raw))) return undefined; + return `'${raw.replace(/'/g, "''")}'`; } // Accepts "1" or boolean true (the qs serialization of withCount: 1 from buildFilterQs). diff --git a/examples/showcase/codegen/runtime/errors.ts b/examples/showcase/codegen/runtime/errors.ts new file mode 100644 index 0000000000..cbf93cedd2 --- /dev/null +++ b/examples/showcase/codegen/runtime/errors.ts @@ -0,0 +1,129 @@ +// All errors extend RuntimeError and JSON-serialize via toJSON() — admin UIs and MCP tools +// surface them as structured JSON, not Error.message strings. + +export interface ValidationFailure { + field: string; + rule: string; + message: string; + expected?: unknown; + received?: unknown; +} + +interface BaseOpts { + code?: string; + entity?: string; + cause?: unknown; +} + +export class RuntimeError extends Error { + readonly code: string; + readonly entity?: string; + override readonly cause?: unknown; + + constructor(message: string, opts: BaseOpts & { code: string }) { + super(message); + this.name = "RuntimeError"; + this.code = opts.code; + if (opts.entity !== undefined) this.entity = opts.entity; + if (opts.cause !== undefined) this.cause = opts.cause; + } + + toJSON(): Record { + const out: Record = { name: this.name, code: this.code, message: this.message }; + if (this.entity !== undefined) out.entity = this.entity; + return out; + } +} + +export class ValidationError extends RuntimeError { + readonly errors: ValidationFailure[]; + + constructor(message: string, opts: { entity?: string; errors: ValidationFailure[]; cause?: unknown }) { + super(message, { code: "validation_failed", ...(opts.entity !== undefined ? { entity: opts.entity } : {}), ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "ValidationError"; + this.errors = opts.errors; + } + + override toJSON(): Record { + return { ...super.toJSON(), errors: this.errors }; + } +} + +/** + * A key text that is not the canonical spelling of a key of the PK field's declared type (`0x1` + * or `1e0` for an integer key). The same `ValidationError` shape, so a caller that handles a + * failed value handles this too; the HTTP mounts answer it `400 {"error":"invalid_id"}`. + */ +export class InvalidKeyError extends ValidationError { + constructor(entity: string, field: string, expected: string) { + super(`Invalid key for ${entity}.${field}: expected ${expected}`, { + entity, + errors: [{ field, rule: "invalid_key", message: `expected ${expected}`, expected }], + }); + this.name = "InvalidKeyError"; + } +} + +export class NotFoundError extends RuntimeError { + readonly id: unknown; + + constructor(message: string, opts: { entity: string; id: unknown; cause?: unknown }) { + super(message, { code: "not_found", entity: opts.entity, ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "NotFoundError"; + this.id = opts.id; + } + + override toJSON(): Record { + return { ...super.toJSON(), id: this.id }; + } +} + +export class ConstraintViolationError extends RuntimeError { + readonly kind: "unique" | "foreign_key" | "not_null" | "check"; + readonly table: string; + readonly field?: string; + readonly detail?: string; + + constructor(message: string, opts: { + kind: "unique" | "foreign_key" | "not_null" | "check"; + table: string; + field?: string; + detail?: string; + cause?: unknown; + }) { + super(message, { code: "constraint_violation", ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "ConstraintViolationError"; + this.kind = opts.kind; + this.table = opts.table; + if (opts.field !== undefined) this.field = opts.field; + if (opts.detail !== undefined) this.detail = opts.detail; + } + + override toJSON(): Record { + const out: Record = { ...super.toJSON(), kind: this.kind, table: this.table }; + if (this.field !== undefined) out.field = this.field; + if (this.detail !== undefined) out.detail = this.detail; + return out; + } +} + +export class MetadataError extends RuntimeError { + constructor(message: string, opts: { entity?: string; cause?: unknown } = {}) { + super(message, { code: "metadata_error", ...(opts.entity !== undefined ? { entity: opts.entity } : {}), ...(opts.cause !== undefined ? { cause: opts.cause } : {}) }); + this.name = "MetadataError"; + } +} + +export class UnsafeNameError extends RuntimeError { + readonly value: string; + + constructor(message: string, opts: { value: string }) { + super(message, { code: "unsafe_name" }); + this.name = "UnsafeNameError"; + this.value = opts.value; + } + + override toJSON(): Record { + return { ...super.toJSON(), value: this.value }; + } +} diff --git a/examples/showcase/codegen/templates/entity-file.ts b/examples/showcase/codegen/templates/entity-file.ts index c5dddf6d1c..905384a229 100644 --- a/examples/showcase/codegen/templates/entity-file.ts +++ b/examples/showcase/codegen/templates/entity-file.ts @@ -228,7 +228,7 @@ ${docsPrefix}export type ${entity.name} = ${z}.infer c.attr(FIELD_ATTR_FILTERABLE) === true && c.name !== exclude); + .filter((c) => isFilterableField(c) && !credentials.has(c.name) && c.name !== exclude); } /** @@ -133,7 +135,7 @@ function filterableFields(entity: MetaObject, exclude?: string): MetaField[] { * branching is needed here. Absent `ctx`, or in the default mode, output is unchanged. */ export function renderFilterAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { - const fields = filterableFields(entity, exclude); + const fields = filterableFields(entity, exclude, ctx); if (fields.length === 0) { return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; @@ -169,7 +171,9 @@ export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: // @sortable: false explicitly opts out. // Uses shared isSortableField predicate — must stay in sync with renderFilterType. // `exclude` (FR-017): per-subtype TPH allowlists omit the discriminator. - const sortable = sortableFields(entity).filter((f) => f.name !== exclude); + // A credential is never sortable (isSortableField), nor a column a sibling subtype marks as one. + const credentials = credentialFieldNames(entity, ctx?.loadedRoot); + const sortable = flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude); if (sortable.length === 0) { return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; diff --git a/examples/showcase/codegen/templates/filter-shared.ts b/examples/showcase/codegen/templates/filter-shared.ts index c4de261bbc..9e6f5f2253 100644 --- a/examples/showcase/codegen/templates/filter-shared.ts +++ b/examples/showcase/codegen/templates/filter-shared.ts @@ -15,7 +15,8 @@ // runs the opposite way from the endpoint it queries. import { flatSurfaceFields } from "@metaobjectsdev/codegen-ts/engine"; -import { MetaField, MetaObject, type MetaData } from "@metaobjectsdev/metadata"; +import { hiddenFieldNames, isCredentialField, tphHierarchy } from "@metaobjectsdev/codegen-ts/engine"; +import { MetaField, MetaObject, type MetaData, type MetaRoot } from "@metaobjectsdev/metadata"; import { FIELD_ATTR_FILTERABLE, FIELD_ATTR_SORTABLE, @@ -28,27 +29,53 @@ import { * returns one of these two or says it has no answer. */ export type SortOrder = "asc" | "desc"; +/** + * Returns true if the given field is on the filter allowlist: it is marked `@filterable: true` + * and is not a credential. A filter on a secret is an oracle for it (`eq`, or `like` a prefix, + * one character at a time), so a credential (a field that declares a `view.password`) is never + * filterable, whatever the model marks. The allowlist is built from this predicate, so a + * request that names one is refused as any other field the allowlist does not hold. + */ +export function isFilterableField(field: MetaField): boolean { + return field.attr(FIELD_ATTR_FILTERABLE) === true && !isCredentialField(field); +} + /** * Returns true if the given field should be included in sort operations. * * Rules (in priority order): + * 0. a credential → never sortable (the order of a secret leaks it) * 1. @sortable: true → always sortable (even without @filterable) * 2. @sortable: false → never sortable (overrides @filterable) * 3. no @sortable → sortable iff @filterable === true */ export function isSortableField(field: MetaField): boolean { + if (isCredentialField(field)) return false; const sortableAttr = field.attr(FIELD_ATTR_SORTABLE); if (sortableAttr === true) return true; if (sortableAttr === false) return false; return field.attr(FIELD_ATTR_FILTERABLE) === true; } +/** + * The field names no allowlist of `entity` may hold because the column is a credential: a + * `view.password` on ANY declaration of a column that subtypes of one single-table (TPH) + * hierarchy share counts on every subtype that has it, the same rule the generated routes use to + * hide the column. `root` is the loaded model the hierarchy is read from; without it the entity + * stands alone. + */ +export function credentialFieldNames(entity: MetaObject, root: MetaRoot | undefined): ReadonlySet { + const hierarchy = root === undefined ? [entity] : tphHierarchy(entity, root); + return new Set(hiddenFieldNames(entity, hierarchy)); +} + /** * Returns all sortable field children of the given entity. */ -export function sortableFields(entity: MetaObject): MetaField[] { +export function sortableFields(entity: MetaObject, root?: MetaRoot): MetaField[] { // fields() returns effective fields, so inherited fields (from extends:/super:) are included in sort ops. - return flatSurfaceFields(entity).filter(isSortableField); + const credentials = credentialFieldNames(entity, root); + return flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name)); } /** diff --git a/examples/showcase/codegen/templates/filter-type.ts b/examples/showcase/codegen/templates/filter-type.ts index d3a06b53fd..d32ff351fd 100644 --- a/examples/showcase/codegen/templates/filter-type.ts +++ b/examples/showcase/codegen/templates/filter-type.ts @@ -4,9 +4,8 @@ import { flatSurfaceFields } from "@metaobjectsdev/codegen-ts/engine"; import { code, type Code } from "@metaobjectsdev/codegen-ts/engine"; -import { MetaField, MetaObject } from "@metaobjectsdev/metadata"; +import { MetaField, MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; import { - FIELD_ATTR_FILTERABLE, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, @@ -16,7 +15,7 @@ import { FIELD_SUBTYPE_ENUM, opsForField, } from "@metaobjectsdev/metadata"; -import { isSortableField } from "./filter-shared.js"; +import { credentialFieldNames, isFilterableField, isSortableField } from "./filter-shared.js"; import { entityTypeNames } from "./entity-type-names.js"; import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; @@ -80,11 +79,15 @@ function renderFieldUnion(field: MetaField): string { * per-subtype route path), keeping the client `Filter` type aligned with * the server's per-subtype allowlist. */ -export function renderFilterType(entity: MetaObject, exclude?: string): Code { +export function renderFilterType(entity: MetaObject, exclude?: string, root?: MetaRoot): Code { const filterName = entityTypeNames(entity).filter; // fields() returns effective fields, so inherited fields (from extends:/super:) are included in filter types. - const allFields = flatSurfaceFields(entity).filter((c) => c.name !== exclude); - const filterableFieldsList = allFields.filter((c) => c.attr(FIELD_ATTR_FILTERABLE) === true); + // A column a sibling subtype of the same table marks as a credential is no more filterable or + // sortable here than in the server allowlist (credentialFieldNames), or the client type would + // offer a filter the server answers 400. + const credentials = credentialFieldNames(entity, root); + const allFields = flatSurfaceFields(entity).filter((c) => c.name !== exclude && !credentials.has(c.name)); + const filterableFieldsList = allFields.filter(isFilterableField); // Sort union uses isSortableField — same predicate as renderSortAllowlist to prevent // client/server mismatches (@filterable: true + @sortable: false must be excluded from both). const sortFieldNames = allFields.filter(isSortableField).map((f) => `"${f.name}"`); diff --git a/examples/showcase/codegen/templates/projection-decl.ts b/examples/showcase/codegen/templates/projection-decl.ts index 57eed67274..4b409b4581 100644 --- a/examples/showcase/codegen/templates/projection-decl.ts +++ b/examples/showcase/codegen/templates/projection-decl.ts @@ -219,7 +219,7 @@ ${joinCode(constFieldLines, { on: "\n" })} ...(allowlists ? [renderFilterAllowlist(projection, undefined, ctx), renderSortAllowlist(projection, undefined, ctx)] : []), - renderFilterType(projection), + renderFilterType(projection, undefined, ctx?.loadedRoot), ]; const body = joinCode(sections, { on: "\n" }).toString(); diff --git a/examples/showcase/codegen/templates/value-object-file.ts b/examples/showcase/codegen/templates/value-object-file.ts index a7378360d0..6aa9680449 100644 --- a/examples/showcase/codegen/templates/value-object-file.ts +++ b/examples/showcase/codegen/templates/value-object-file.ts @@ -66,7 +66,7 @@ export function renderValueObjectFile(obj: MetaObject, apiPrefix = "", ctx?: Ren // FR-017 Tier 3: the per-subtype CLIENT filter type, discriminator-excluded — // kept in lockstep with the per-subtype allowlist above so a typed // `Filter` can't express a filter the server allowlist would 400. - const tphFilterType = tphSubtype ? renderFilterType(obj, discField) : null; + const tphFilterType = tphSubtype ? renderFilterType(obj, discField, ctx?.loadedRoot) : null; // A sourceless entity's wire contract: create + PATCH schemas, allowlists, filter type. // No constants object — it names a table and a route this object does not have. The // allowlists import runtime types, so a contract-only target (runtime: false) skips them. @@ -96,7 +96,7 @@ export function renderValueObjectFile(obj: MetaObject, apiPrefix = "", ctx?: Ren ...(tphSortAllowlist !== null ? [tphSortAllowlist] : []), ...(tphFilterType !== null ? [tphFilterType] : []), ...(sourcelessAllowlists ? [renderFilterAllowlist(obj, undefined, ctx), renderSortAllowlist(obj, undefined, ctx)] : []), - ...(sourceless ? [renderFilterType(obj)] : []), + ...(sourceless ? [renderFilterType(obj, undefined, ctx?.loadedRoot)] : []), ]; const body = joinCode(sections, { on: "\n" }).toString(); // ADR-0044/#228 — the hand-edit sidecar name follows this value object's EMITTED diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 5e46840049..7f1e5ce8af 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -57,7 +57,7 @@ fixtures/api-contract-conformance/ ``` Beside the 34 core scenarios above sit eleven **sub-corpora**, each a directory with its -own `meta.json`, `seed.json`, `scenarios/` and `README.md` (105 scenarios in all, 139 with the +own `meta.json`, `seed.json`, `scenarios/` and `README.md` (107 scenarios in all, 141 with the core): | Directory | Scenarios | Gates | Lanes | @@ -66,7 +66,7 @@ core): | `m2m/` | 9 | M:N traversal, and TPH x M:N together | both | | `jsonb/` | 6 | typed value-object columns, the numbers inside them, and an undeclared nested member dropped (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; a `readOnly` field is ignored the same way and still returned | generated only | +| `secret-fields/` | 4 | #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; a credential is on no filter or sort allowlist, so a filter or sort naming it is `400` (the `tph/` sub-directory checks this for a column one subtype of a single-table hierarchy marks as a credential) | 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 | diff --git a/fixtures/api-contract-conformance/secret-fields/README.md b/fixtures/api-contract-conformance/secret-fields/README.md index a7cc3b7f69..428e6b243d 100644 --- a/fixtures/api-contract-conformance/secret-fields/README.md +++ b/fixtures/api-contract-conformance/secret-fields/README.md @@ -10,7 +10,7 @@ The model is one `Account`: |-------------|-----------------------------|------------------------|-----------------------| | `name` | (nothing) | accepted | returned | | `tokenHash` | `@formExclude: true` | **ignored** | returned | -| `pinHash` | child `view.password` | **ignored** | **never returned** | +| `pinHash` | child `view.password`, `@filterable`, `@sortable` | **ignored** | **never returned**, never filterable or sortable | | `role` | `@mutability: readOnly` | **ignored** | returned | ## The contract @@ -31,6 +31,16 @@ The model is one `Account`: strategy, `SNAKE_CASE` and `KEBAB_CASE`. - **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`. +- **A credential is never filterable or sortable**, even when the model marks it `@filterable` or + `@sortable`: a filter on a secret is an oracle for it, and its order leaks it. The allowlists are built + without it, so a request that names it is refused with the same envelope as any other field they do not + hold (`invalid_filter_field`, `invalid_sort`). `pinHash` carries both marks in this model to prove it. +- **A credential on one subtype of a single-table (TPH) hierarchy is a credential for the whole + table.** The subtypes share one physical column, so a filter or sort on it is an oracle for the + secret whichever subtype is addressed. The allowlists of the base and of every subtype are built + without it, whichever subtype is declared first. `tph/` pins this: `approver` is a plain + `@filterable`, `@sortable` column on `CouponAuth` and a `view.password` on `PermitAuth`, and a + filter or sort naming it is a 400 on the base route and on both subtypes' routes. - **`@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 @@ -52,8 +62,15 @@ secret-fields/ ├── seed.json # two rows, both secrets set └── scenarios/ ├── read-omits-credential.yaml # GET by id and list: pinHash absent, tokenHash present + ├── filter-sort-refuses-credential.yaml # filter or sort on pinHash (marked @filterable, @sortable) is a 400 └── write-ignores-excluded.yaml # POST / PATCH / PUT / present-null leave tokenHash and the readOnly role alone +secret-fields/tph/ # the TPH sibling-credential case (the tph/ corpus's Auth hierarchy, one shared column marked) +├── meta.json # Auth + Bridge/Coupon/Permit; `approver` plain on CouponAuth, credential on PermitAuth +├── seed.json # the tph/ corpus's three rows +└── scenarios/ + └── tph-sibling-credential.yaml # filter or sort on approver is a 400 on the base, coupon and permit routes ``` -Generated lane only: what is under test is whether each port's GENERATOR emits routes that +`tph/` runs through each port's TPH generated-lane harness (the same one as the `tph/` corpus, pointed at +this model); every other scenario runs through the Account harness. Generated lane only: what is under test is whether each port's GENERATOR emits routes that honour the marks, which a hand-rolled reference server would satisfy by construction. diff --git a/fixtures/api-contract-conformance/secret-fields/meta.json b/fixtures/api-contract-conformance/secret-fields/meta.json index d000a949a6..19c9bff654 100644 --- a/fixtures/api-contract-conformance/secret-fields/meta.json +++ b/fixtures/api-contract-conformance/secret-fields/meta.json @@ -9,7 +9,7 @@ { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, { "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": "pinHash", "@maxLength": 100, "@filterable": true, "@sortable": true, "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/filter-sort-refuses-credential.yaml b/fixtures/api-contract-conformance/secret-fields/scenarios/filter-sort-refuses-credential.yaml new file mode 100644 index 0000000000..c5059bb250 --- /dev/null +++ b/fixtures/api-contract-conformance/secret-fields/scenarios/filter-sort-refuses-credential.yaml @@ -0,0 +1,53 @@ +name: filter-sort-refuses-credential +description: > + A credential (a field that declares `view.password`) is never on the filter or sort allowlist, + even when the model marks it `@filterable` and `@sortable`: a filter on a secret is an oracle for + it (`eq`, or `like` a prefix, one character at a time), and a sort leaks its order. `pinHash` + carries both marks here and the seeded rows hold distinct values, so a port whose allowlist took + the marks at their word would answer 200. Every port refuses an explicit request for it with the + same envelope as any other field the allowlist does not hold (`invalid_filter_field` and + `invalid_sort`, naming the field), and a field that is not a credential still filters. +requests: + - id: r1 + method: GET + path: /api/accounts?filter[pinHash][eq]=pin-hash-1 + expect: + status: 400 + body: + error: "invalid_filter_field" + field: "pinHash" + - id: r2 + method: GET + path: /api/accounts?filter[pinHash][like]=pin-hash-1%25 + expect: + status: 400 + body: + error: "invalid_filter_field" + field: "pinHash" + - id: r3 + method: GET + path: /api/accounts?sort=pinHash:asc + expect: + status: 400 + body: + error: "invalid_sort" + field: "pinHash" + - id: r4 + method: GET + path: /api/accounts?sort=pinHash:desc + expect: + status: 400 + body: + error: "invalid_sort" + field: "pinHash" + - id: r5 + method: GET + path: /api/accounts?filter[name][eq]=Ada%20Lovelace + expect: + status: 200 + body: + equals: + - id: 1 + name: "Ada Lovelace" + tokenHash: "token-hash-1" + role: "member" diff --git a/fixtures/api-contract-conformance/secret-fields/tph/meta.json b/fixtures/api-contract-conformance/secret-fields/tph/meta.json new file mode 100644 index 0000000000..eaa206c7e6 --- /dev/null +++ b/fixtures/api-contract-conformance/secret-fields/tph/meta.json @@ -0,0 +1,46 @@ +{ + "metadata.root": { + "package": "acme::auth", + "children": [ + { "object.entity": { + "name": "Auth", + "@discriminator": "type", + "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, + { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "issuedCurrency", "@maxLength": 3, "@mutability": "writeOnce" } }, + { "field.timestamp": { "name": "autoCreatedAt", "@autoSet": "onCreate" } }, + { "field.timestamp": { "name": "autoUpdatedAt", "@autoSet": "onUpdate" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } + ] + }}, + { "object.entity": { + "name": "BridgeAuth", + "extends": "Auth", + "@discriminatorValue": "Bridge", + "children": [ + { "field.int": { "name": "quantity", "@required": true, "@filterable": true, "@sortable": true } } + ] + }}, + { "object.entity": { + "name": "CouponAuth", + "extends": "Auth", + "@discriminatorValue": "Coupon", + "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } }, + { "field.string": { "name": "approver", "@maxLength": 80, "@filterable": true, "@sortable": true } } + ] + }}, + { "object.entity": { + "name": "PermitAuth", + "extends": "Auth", + "@discriminatorValue": "Permit", + "children": [ + { "field.string": { "name": "approver", "@maxLength": 80, "@filterable": true, "@sortable": true, "children": [ { "view.password": {} } ] } } + ] + }} + ] + } +} diff --git a/fixtures/api-contract-conformance/secret-fields/tph/scenarios/tph-sibling-credential.yaml b/fixtures/api-contract-conformance/secret-fields/tph/scenarios/tph-sibling-credential.yaml new file mode 100644 index 0000000000..7ccb8e33d6 --- /dev/null +++ b/fixtures/api-contract-conformance/secret-fields/tph/scenarios/tph-sibling-credential.yaml @@ -0,0 +1,74 @@ +name: tph-sibling-credential +description: > + A column that one subtype of a single-table (TPH) hierarchy marks as a credential is a + credential for the whole table. `approver` is declared by `CouponAuth` as a plain `@filterable` + and `@sortable` column and by `PermitAuth` as a `view.password`; the hierarchy shares one + `approver` column, so a filter or sort on it is an oracle for the secret whichever subtype is + addressed. Every allowlist built for the base and for both subtypes leaves it out, and a request + that names it is refused with the same envelope as any other field they do not hold + (`invalid_filter_field`, `invalid_sort`, naming the field) on the base route, on the plain + subtype's route and on the credential subtype's route. A column that is not a credential still + filters and sorts. +requests: + - id: r1 + method: GET + path: /api/auths?filter[approver][eq]=Dr.%20Smith + expect: + status: 400 + body: + error: "invalid_filter_field" + field: "approver" + - id: r2 + method: GET + path: /api/auths/coupon?filter[approver][eq]=Dr.%20Smith + expect: + status: 400 + body: + error: "invalid_filter_field" + field: "approver" + - id: r3 + method: GET + path: /api/auths/permit?filter[approver][like]=Dr%25 + expect: + status: 400 + body: + error: "invalid_filter_field" + field: "approver" + - id: r4 + method: GET + path: /api/auths?sort=approver:asc + expect: + status: 400 + body: + error: "invalid_sort" + field: "approver" + - id: r5 + method: GET + path: /api/auths/coupon?sort=approver:desc + expect: + status: 400 + body: + error: "invalid_sort" + field: "approver" + - id: r6 + method: GET + path: /api/auths/permit?sort=approver:asc + expect: + status: 400 + body: + error: "invalid_sort" + field: "approver" + - id: r7 + method: GET + path: /api/auths?filter[reference][eq]=REF-3 + expect: + status: 200 + body: + ids: [3] + - id: r8 + method: GET + path: /api/auths?sort=reference:desc + expect: + status: 200 + body: + ids: [3, 2, 1] diff --git a/fixtures/api-contract-conformance/secret-fields/tph/seed.json b/fixtures/api-contract-conformance/secret-fields/tph/seed.json new file mode 100644 index 0000000000..adf9bdc412 --- /dev/null +++ b/fixtures/api-contract-conformance/secret-fields/tph/seed.json @@ -0,0 +1,7 @@ +{ + "auths": [ + { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "couponAmount": null, "approver": null, "issuedCurrency": "USD", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 2, "type": "Coupon", "reference": "REF-2", "quantity": null, "couponAmount": "12.50", "approver": null, "issuedCurrency": "GBP", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 3, "type": "Permit", "reference": "REF-3", "quantity": null, "couponAmount": null, "approver": "Dr. Smith", "issuedCurrency": "EUR", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } + ] +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 7330aabfdf..132ec1aedf 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -18,7 +18,6 @@ public static class GizmoRoutes "Title", "Stamp", "Serial", - "PinHash", "TokenHash", "CreatedAt", "UpdatedAt", @@ -267,7 +266,6 @@ private static IOrderedQueryable ApplySortGizmo(IQueryable q, stri "Title" => desc ? q.OrderByDescending(x => EF.Property(x!, "Title") == null).ThenByDescending(x => EF.Property(x!, "Title")) : q.OrderBy(x => EF.Property(x!, "Title") == null).ThenBy(x => EF.Property(x!, "Title")), "Stamp" => desc ? q.OrderByDescending(x => EF.Property(x!, "Stamp") == null).ThenByDescending(x => EF.Property(x!, "Stamp")) : q.OrderBy(x => EF.Property(x!, "Stamp") == null).ThenBy(x => EF.Property(x!, "Stamp")), "Serial" => desc ? q.OrderByDescending(x => EF.Property(x!, "Serial") == null).ThenByDescending(x => EF.Property(x!, "Serial")) : q.OrderBy(x => EF.Property(x!, "Serial") == null).ThenBy(x => EF.Property(x!, "Serial")), - "PinHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "PinHash") == null).ThenByDescending(x => EF.Property(x!, "PinHash")) : q.OrderBy(x => EF.Property(x!, "PinHash") == null).ThenBy(x => EF.Property(x!, "PinHash")), "TokenHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "TokenHash") == null).ThenByDescending(x => EF.Property(x!, "TokenHash")) : q.OrderBy(x => EF.Property(x!, "TokenHash") == null).ThenBy(x => EF.Property(x!, "TokenHash")), "CreatedAt" => desc ? q.OrderByDescending(x => EF.Property(x!, "CreatedAt") == null).ThenByDescending(x => EF.Property(x!, "CreatedAt")) : q.OrderBy(x => EF.Property(x!, "CreatedAt") == null).ThenBy(x => EF.Property(x!, "CreatedAt")), "UpdatedAt" => desc ? q.OrderByDescending(x => EF.Property(x!, "UpdatedAt") == null).ThenByDescending(x => EF.Property(x!, "UpdatedAt")) : q.OrderBy(x => EF.Property(x!, "UpdatedAt") == null).ThenBy(x => EF.Property(x!, "UpdatedAt")), diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 7ba89aa8ee..be66505058 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -16,7 +16,6 @@ public static class VehicleRoutes { "Id", "Plate", - "VinHash", }; private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) @@ -39,7 +38,6 @@ public static class VehicleRoutes { "Id", "Plate", - "VinHash", "SeatCount", "RegNo", }; @@ -52,7 +50,6 @@ public static class VehicleRoutes { "Id", "Plate", - "VinHash", "PayloadKg", }; @@ -457,7 +454,6 @@ private static IOrderedQueryable ApplySort(IQueryable q, strin { "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), "Plate" => desc ? q.OrderByDescending(x => EF.Property(x!, "Plate") == null).ThenByDescending(x => EF.Property(x!, "Plate")) : q.OrderBy(x => EF.Property(x!, "Plate") == null).ThenBy(x => EF.Property(x!, "Plate")), - "VinHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "VinHash") == null).ThenByDescending(x => EF.Property(x!, "VinHash")) : q.OrderBy(x => EF.Property(x!, "VinHash") == null).ThenBy(x => EF.Property(x!, "VinHash")), _ => (IOrderedQueryable)q.OrderBy(x => 0), }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs index 7e48419a88..f06e5e8cef 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs @@ -137,4 +137,93 @@ public void A_model_with_neither_mark_is_unchanged() Assert.Contains("Results.Ok(rows)", src); Assert.Contains("Results.Ok(existing)", src); } + + // A credential marked @filterable and @sortable is still never on either allowlist: a filter + // on a secret is an oracle for it and a sort leaks its order. A normal field keeps both. + private const string FilterSortModel = """ + { "metadata.root": { "package": "acme::secrets", "children": [ + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@maxLength": 100, "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "pinHash", "@maxLength": 100, "@filterable": true, "@sortable": true, "children": [ { "view.password": {} } ] } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + [Fact] + public void A_credential_marked_filterable_and_sortable_is_on_neither_allowlist() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(FilterSortModel, id: "secrets.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 }, + }; + var filter = new FilterAllowlistGenerator().Generate(ctx) + .Single(f => System.IO.Path.GetFileName(f.Path) == "AccountFilterAllowlist.g.cs").Content; + Assert.Contains("\"name\"", filter); + Assert.DoesNotContain("pinHash", filter); + + var routes = new RoutesGenerator().Generate(ctx) + .Single(f => System.IO.Path.GetFileName(f.Path) == "AccountRoutes.g.cs").Content; + var start = routes.IndexOf("SortAllowlist", StringComparison.Ordinal); + var end = routes.IndexOf("MapAccountRoutes", StringComparison.Ordinal); + Assert.True(start >= 0 && end > start, routes); + var sort = routes[start..end]; + Assert.Contains("Name", sort); + Assert.DoesNotContain("PinHash", sort); + } + + private static string TphFilterableToken(string aTokenChildren, string bTokenChildren) => $$$""" + { "metadata.root": { "package": "acme::secrets", "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": "token", "@maxLength": 100, "@filterable": true, "@sortable": true{{{aTokenChildren}}} } }, + { "field.string": { "name": "label", "@maxLength": 100, "@filterable": true, "@sortable": true } } + ]}}, + { "object.entity": { "name": "BThing", "extends": "Thing", "@discriminatorValue": "B", "children": [ + { "field.string": { "name": "token", "@maxLength": 100, "@filterable": true, "@sortable": true{{{bTokenChildren}}} } } + ]}} + ]}} + """; + + [Theory] + [InlineData("", ", \"children\": [ { \"view.password\": {} } ]")] + [InlineData(", \"children\": [ { \"view.password\": {} } ]", "")] + public void A_column_any_sibling_subtype_hides_is_on_no_filter_or_sort_allowlist(string aChildren, string bChildren) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(TphFilterableToken(aChildren, bChildren), id: "secrets.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 }, + }; + var filters = new FilterAllowlistGenerator().Generate(ctx).ToList(); + foreach (var name in new[] { "ThingFilterAllowlist.g.cs", "AThingFilterAllowlist.g.cs", "BThingFilterAllowlist.g.cs" }) + { + var content = filters.Single(f => System.IO.Path.GetFileName(f.Path) == name).Content; + Assert.DoesNotContain("token", content); + } + Assert.Contains("\"label\"", filters.Single(f => System.IO.Path.GetFileName(f.Path) == "AThingFilterAllowlist.g.cs").Content); + + var routes = new RoutesGenerator().Generate(ctx) + .Single(f => System.IO.Path.GetFileName(f.Path) == "ThingRoutes.g.cs").Content; + var start = routes.IndexOf("SortAllowlist", StringComparison.Ordinal); + var end = routes.IndexOf("MapThingRoutes", StringComparison.Ordinal); + Assert.True(start >= 0 && end > start, routes); + var sort = routes[start..end]; + Assert.Contains("Label", sort); + Assert.DoesNotContain("Token", sort); + } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index edac5b1a99..9d6f079767 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -71,7 +71,10 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) { var cls = CSharpNaming.Pascal(entity.Name); var filterClass = CSharpNaming.FilterAllowlistName(entity); - var opsByField = ComputeFilterableOps(entity); + var hierarchyCredentials = TphPlanBuilder.HierarchyCredentialNames(entity, ctx.Root); + var opsByField = ComputeFilterableOps(entity) + .Where(kv => !hierarchyCredentials.Contains(kv.Key)) + .ToDictionary(kv => kv.Key, kv => kv.Value, System.StringComparer.Ordinal); // In its entity's namespace when package namespaces are on (as Names is), so mapping // the packages apart separates the allowlists too; claimed where it is emitted. var ns = ValueObjectNames.CompanionNamespace(entity, ctx.Config); @@ -149,6 +152,9 @@ protected virtual Dictionary> ComputeFilterableOps { if (field.SubType == FIELD_SUBTYPE_OBJECT) continue; if (!IsFilterable(field)) continue; + // A credential is never filterable: eq / like on a secret is an oracle for it. Left off + // the allowlist, an explicit request is refused as any unknown field is. + if (InstanceArtifacts.IsCredentialField(field)) continue; var ops = OpsForField(field); if (ops.Count == 0) continue; out_[field.Name] = ops; diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 7bd48d4ce8..419029b869 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -305,7 +305,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte .Where(f => (CSharpNaming.ScalarFor(f.SubType) is not null || (isReport && f.SubType == FIELD_SUBTYPE_ENUM)) && !f.ResolvedIsArray() - && !(isReport && IsCredentialField(f))) // a credential column would be a sort oracle + && !IsCredentialField(f)) // a credential column would be a sort oracle (any entity, not only a report) .ToList(); var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); @@ -627,8 +627,9 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t .Distinct(StringComparer.Ordinal).ToList(); // Sortable base scalar fields (the polymorphic list sorts on base columns). + var hierarchyCredentials = TphPlanBuilder.HierarchyCredentialNames(baseEntity, ctx.Root); var sortFieldNodes = baseEntity.Fields() - .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) + .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray() && !hierarchyCredentials.Contains(f.Name)) .ToList(); var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); @@ -665,7 +666,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t { var subClsName = CSharpNaming.Pascal(st.Entity.Name); var subSortFields = st.Entity.Fields() - .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) + .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray() && !hierarchyCredentials.Contains(f.Name)) .ToList(); AppendSortAllowlist(sb, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); @@ -824,8 +825,7 @@ private static List FrozenNavs(MetaObject entity, GenConfig config) => // #484 — a credential is a field that declares (or inherits, ADR-0039) a view.password child. // A credential is never returned by a generated route; it is also never written by one. - public static bool IsCredentialField(MetaField f) => - f.Views().Any(v => v.SubType == MetaObjects.Presentation.View.ViewConstants.VIEW_SUBTYPE_PASSWORD); + public static bool IsCredentialField(MetaField f) => InstanceArtifacts.IsCredentialField(f); // #484 — write-denied: the generated create / PATCH / PUT IGNORE the key (never a 400): the // effective @formExclude (resolving) or a credential. diff --git a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs index 01b7d4203a..d7f7c4610d 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs @@ -120,6 +120,22 @@ public static IReadOnlyList CollectSubtypeFields(MetaObject baseObj, return outFields; } + /// + /// The names of the columns any declaration in 's TPH hierarchy (the base + /// and every concrete subtype) marks as a credential (view.password). One table backs the + /// hierarchy, so a column a sibling subtype hides is no more filterable or sortable here. Empty + /// when the entity is in no hierarchy. + /// + public static HashSet HierarchyCredentialNames(MetaObject entity, MetaRoot root) + { + var names = new HashSet(StringComparer.Ordinal); + if (DiscriminatorRoot(entity) is not { } baseObj || For(baseObj, root) is not { } plan) return names; + foreach (var member in plan.Subtypes.Select(st => st.Entity).Prepend(baseObj)) + foreach (var f in member.Fields()) + if (InstanceArtifacts.IsCredentialField(f)) names.Add(f.Name); + return names; + } + // The concrete subtypes bound to this base via extends, in stable (name-sorted) order. private static List<(MetaObject Subtype, string Value)> CollectConcreteSubtypes(MetaObject baseObj, MetaRoot root) { diff --git a/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs b/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs index 5375d60a13..85caa83fbc 100644 --- a/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs +++ b/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs @@ -76,4 +76,12 @@ public static bool IsSourcelessEntity(MetaObject entity) => && entity.SubType != OBJECT_SUBTYPE_PROJECTION && entity.PrimaryIdentity() is not null && entity.Sources().Count == 0; + + /// + /// #484 — a credential is a field that declares (or inherits, ADR-0039) a view.password child. + /// It is never returned, written, filtered on or sorted by a generated route. A model question + /// shared by the routes and filter-allowlist generators. + /// + public static bool IsCredentialField(MetaField f) => + f.Views().Any(v => v.SubType == MetaObjects.Presentation.View.ViewConstants.VIEW_SUBTYPE_PASSWORD); } diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs index 53cedeefb9..323402f94f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs @@ -113,6 +113,9 @@ internal static class ApiContractCorpusPaths public static readonly string SecretFieldsScenariosDir = Path.Combine(SecretFieldsDir, "scenarios"); public static readonly string SecretFieldsSeedFile = Path.Combine(SecretFieldsDir, "seed.json"); public static readonly string SecretFieldsMetaJson = Path.Combine(SecretFieldsDir, "meta.json"); + public static readonly string SecretFieldsTphDir = Path.Combine(SecretFieldsDir, "tph"); + public static readonly string SecretFieldsTphScenariosDir = Path.Combine(SecretFieldsTphDir, "scenarios"); + public static readonly string SecretFieldsTphMetaJson = Path.Combine(SecretFieldsTphDir, "meta.json"); // api-settings subcorpus (api.pagination + api.unknownFields from its own config), generated lane only. public static readonly string ApiSettingsDir = Path.Combine(Corpus, "api-settings"); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsTphConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsTphConformanceTest.cs new file mode 100644 index 0000000000..00ffe4d058 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsTphConformanceTest.cs @@ -0,0 +1,72 @@ +// ApiContractSecretFieldsTphConformanceTest — #484: the C# GENERATED lane for a TPH sibling credential. +// +// A column one subtype of a single-table hierarchy marks as a credential (view.password) is a +// credential for the whole table: the allowlists of the base and of both subtypes leave it out, so +// a request naming it is refused with invalid_filter_field / invalid_sort. Drives the +// fixtures/api-contract-conformance/secret-fields/tph/ scenarios against the emitted AuthRoutes +// booted unmodified on Kestrel, through the TPH generated-server factory. +// +// Run on-demand (Docker required): +// dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj \ +// --filter "FullyQualifiedName~ApiContractSecretFieldsTph" + +using System.Text.Json.Nodes; +using MetaObjects.IntegrationTests.Runner; +using Xunit; + +namespace MetaObjects.IntegrationTests.Api; + +public sealed class ApiContractSecretFieldsTphConformanceTest +{ + [Theory] + [MemberData(nameof(Scenarios))] + public async Task Api_contract_secret_fields_tph_generated(string scenarioPath) + { + var scenario = ApiContractScenarioLoader.LoadScenario(scenarioPath); + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await TphGeneratedServerFactory.StartAsync( + pg, new TphHost(MetaJson: File.ReadAllText(ApiContractCorpusPaths.SecretFieldsTphMetaJson))); + await server.ApplySeedAsync(); + + using var client = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + foreach (var req in scenario.Requests) + { + var response = await client.SendAsync( + new HttpRequestMessage(new HttpMethod(req.Method), ApiContractWire.VerbatimUri(client, req.Path))); + string bodyText = await response.Content.ReadAsStringAsync(); + object? parsed = string.IsNullOrEmpty(bodyText) ? null : ToObject(JsonNode.Parse(bodyText)); + ApiContractAssertions.AssertResponse(scenario.Name, req, (int)response.StatusCode, parsed); + } + } + + public static IEnumerable Scenarios() => + Directory.EnumerateFiles(ApiContractCorpusPaths.SecretFieldsTphScenariosDir, "*.yaml", SearchOption.TopDirectoryOnly) + .OrderBy(p => p, StringComparer.Ordinal) + .Select(p => new object[] { p }); + + private static object? ToObject(JsonNode? node) + { + if (node is null) return null; + if (node is JsonObject obj) + { + var d = new Dictionary(StringComparer.Ordinal); + foreach (var kvp in obj) d[kvp.Key] = ToObject(kvp.Value); + return d; + } + if (node is JsonArray arr) + { + var l = new List(arr.Count); + foreach (var item in arr) l.Add(ToObject(item)); + return l; + } + if (node is JsonValue jv) + { + if (jv.TryGetValue(out var b)) return b; + if (jv.TryGetValue(out var lv)) return lv; + if (jv.TryGetValue(out var dv)) return dv; + if (jv.TryGetValue(out var sv)) return sv; + return jv.ToString(); + } + return null; + } +} diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt index 3edbc942ac..8b1415455e 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinFilterAllowlistGenerator.kt @@ -108,7 +108,10 @@ open class KotlinFilterAllowlistGenerator : MultiFileDirectGeneratorBase`. val opsByField = if (KotlinTphPlan.isTphBase(entity, loader)) { - computeFilterableOps(entity.metaFields + KotlinTphPlan.collectSubtypeFields(entity, loader)) + computeFilterableOps( + entity.metaFields + KotlinTphPlan.collectSubtypeFields(entity, loader), + KotlinTphPlan.hierarchyCredentialNames(entity, loader), + ) } else { computeFilterableOps(entity) } @@ -191,13 +194,26 @@ open class KotlinFilterAllowlistGenerator : MultiFileDirectGeneratorBase>): Map> { + fun computeFilterableOps(fields: Iterable>): Map> = + computeFilterableOps(fields, fields.filter { KotlinGenUtil.isCredentialField(it) }.map { it.name }.toSet()) + + /** + * [computeFilterableOps] with the credential names given: a TPH base passes the names any + * declaration in its hierarchy marks, since a shared column is declared once per subtype and the + * union keeps only the first declaration. Such a column is a credential whichever declaration + * comes first. + */ + fun computeFilterableOps(fields: Iterable>, credentials: Set): Map> { val out = linkedMapOf>() for (field in fields) { // field.object / field.map are jsonb columns with no scalar SQL column — // excluded from the filter allowlist (no filter dispatch). if (field is ObjectField || field is MapField) continue if (!isFilterable(field)) continue + // A credential (view.password) is never filterable, whatever @filterable says: a filter on it + // is an oracle for the secret. Left off the allowlist, a request for it is refused as any + // unknown field is. + if (field.name in credentials) continue val ops = opsForField(field) if (ops.isEmpty()) continue out.putIfAbsent(field.name, ops) // dedup base/subtype column names diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index 42015261f3..e8ff2c477e 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -446,8 +446,9 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase