From 0e2a819cec6cd3c6a41f3635e817640bf94361fd Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 21:11:28 -0500 Subject: [PATCH 01/10] fix: exclude credential fields from filter and sort allowlists; read numeric keys only from canonical decimal text A field that declares a view.password is now left out of the generated filter and sort allowlists in every port, so a client cannot probe a credential by filtering or sorting on it; an explicit request answers the existing invalid_filter_field / invalid_sort 400. Covered by one shared api-contract scenario and a test per port. The TypeScript, Java and Python ObjectManagers now read a numeric primary key from text only in canonical decimal form (no 0x1, 1e0, +1, whitespace, leading zero or negative zero), with each runtime's existing bad-key error. Also corrects the grid-proof line count in the CHANGELOG. --- CHANGELOG.md | 32 +++- docs/CONFORMANCE.md | 10 +- docs/features/api-contract.md | 9 +- .../codegen/generators/entity.ts | 2 +- .../codegen/runtime/constraint-errors.ts | 4 + .../drizzle-fastify/mount-read-only.ts | 4 +- .../drizzle-fastify/route-error-handler.ts | 10 ++ .../codegen/runtime/drizzle-fastify/util.ts | 25 +-- .../codegen/templates/filter-allowlist.ts | 16 +- .../codegen/templates/filter-shared.ts | 33 +++- .../codegen/templates/filter-type.ts | 15 +- .../codegen/templates/projection-decl.ts | 2 +- .../codegen/templates/value-object-file.ts | 4 +- .../showcase/codegen/generators/entity.ts | 2 +- .../codegen/runtime/constraint-errors.ts | 4 + .../drizzle-fastify/mount-read-only.ts | 4 +- .../drizzle-fastify/route-error-handler.ts | 10 ++ .../codegen/runtime/drizzle-fastify/util.ts | 25 +-- .../codegen/templates/filter-allowlist.ts | 16 +- .../codegen/templates/filter-shared.ts | 33 +++- .../showcase/codegen/templates/filter-type.ts | 15 +- .../codegen/templates/projection-decl.ts | 2 +- .../codegen/templates/value-object-file.ts | 4 +- .../secret-fields/README.md | 7 +- .../secret-fields/meta.json | 2 +- .../filter-sort-refuses-credential.yaml | 53 +++++++ .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 2 - .../pre-rc22-propname/VehicleRoutes.g.cs | 4 - .../SecretFieldsCodegenTests.cs | 40 +++++ .../Generators/FilterAllowlistGenerator.cs | 3 + .../Generators/RoutesGenerator.cs | 9 +- .../MetaObjects.Codegen/InstanceArtifacts.cs | 8 + .../kotlin/KotlinFilterAllowlistGenerator.kt | 4 + .../kotlin/KotlinSpringControllerGenerator.kt | 7 +- .../kotlin/KotlinSecretFieldsTest.kt | 25 +++ .../spring/SpringControllerGenerator.java | 3 + .../SpringFilterAllowlistGenerator.java | 4 + .../spring/SpringSecretFieldsCodegenTest.java | 28 +++- .../InMemoryAccountRepositorySource.java | 16 +- .../manager/db/ObjectManagerDB.java | 8 +- .../metaobjects/manager/db/codec/KeyText.java | 110 +++++++++++++ .../manager/db/PrimaryKeyRefTextTest.java | 78 ++++++++++ .../manager/db/codec/NumericKeyTextTest.java | 105 +++++++++++++ .../generators/filter_allowlist_generator.py | 10 +- .../codegen/generators/router_generator.py | 19 +-- .../src/metaobjects/runtime/object_manager.py | 57 ++++++- .../codegen/test_router_secret_fields.py | 30 ++++ .../test_object_manager_numeric_key_text.py | 71 +++++++++ .../packages/codegen-ts/src/api-surface.ts | 6 +- .../codegen-ts/src/contract/build-openapi.ts | 26 ++-- .../src/generators/agent-ui-page.ts | 8 +- .../codegen-ts/src/reference/entity.ts | 2 +- .../src/templates/filter-allowlist.ts | 16 +- .../codegen-ts/src/templates/filter-shared.ts | 33 +++- .../codegen-ts/src/templates/filter-type.ts | 15 +- .../src/templates/projection-decl.ts | 2 +- .../src/templates/value-object-file.ts | 4 +- .../test/filter-allowlist-credential.test.ts | 115 ++++++++++++++ .../packages/runtime-ts/src/canonical-key.ts | 50 ++++++ .../runtime-ts/src/constraint-errors.ts | 4 + .../src/drizzle-fastify/mount-read-only.ts | 4 +- .../drizzle-fastify/route-error-handler.ts | 10 ++ .../runtime-ts/src/drizzle-fastify/util.ts | 25 +-- .../packages/runtime-ts/src/errors.ts | 15 ++ .../runtime-ts/src/hono/mount-read-only.ts | 4 +- .../packages/runtime-ts/src/index.ts | 1 + .../packages/runtime-ts/src/object-manager.ts | 26 ++-- .../test/object-manager-canonical-key.test.ts | 146 ++++++++++++++++++ .../test-generators/src/generators/entity.ts | 2 +- .../src/templates/filter-allowlist.ts | 16 +- .../src/templates/filter-shared.ts | 33 +++- .../src/templates/filter-type.ts | 15 +- .../src/templates/projection-decl.ts | 2 +- .../src/templates/value-object-file.ts | 4 +- 74 files changed, 1382 insertions(+), 186 deletions(-) create mode 100644 fixtures/api-contract-conformance/secret-fields/scenarios/filter-sort-refuses-credential.yaml create mode 100644 server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/KeyText.java create mode 100644 server/java/omdb/src/test/java/com/metaobjects/manager/db/PrimaryKeyRefTextTest.java create mode 100644 server/java/omdb/src/test/java/com/metaobjects/manager/db/codec/NumericKeyTextTest.java create mode 100644 server/python/tests/runtime/test_object_manager_numeric_key_text.py create mode 100644 server/typescript/packages/codegen-ts/test/filter-allowlist-credential.test.ts create mode 100644 server/typescript/packages/runtime-ts/src/canonical-key.ts create mode 100644 server/typescript/packages/runtime-ts/test/object-manager-canonical-key.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1359436c0b..7c370063d9 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,36 @@ 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 TypeScript a column a sibling subtype of the same single table marks as one + counts too, as it does for hiding the column from responses; the other ports decide per entity, as they do + for 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. + +- **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. 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..80eec61f79 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/) | 140 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 3 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/` (140) -All 139 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port +All 140 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/` (3, #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), `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 140 + 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..d88a89dce3 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 | | 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). 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/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/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..db44d2e4a2 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.isFinite(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/templates/filter-allowlist.ts b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts index eb5392b047..5d1527373a 100644 --- a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts +++ b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts @@ -2,7 +2,6 @@ import { flatSurfaceFields } from "@metaobjectsdev/codegen-ts/engine"; import { code, type Code } from "@metaobjectsdev/codegen-ts/engine"; import { MetaField, MetaObject } from "@metaobjectsdev/metadata"; import { - FIELD_ATTR_FILTERABLE, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, @@ -20,7 +19,7 @@ import { opsForField, } from "@metaobjectsdev/metadata"; import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; -import { sortableFields, declaredSortDefaultOrder } from "./filter-shared.js"; +import { credentialFieldNames, isFilterableField, isSortableField, declaredSortDefaultOrder } from "./filter-shared.js"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { httpRuntimeSpecifier } from "@metaobjectsdev/codegen-ts/engine"; import { DEFAULT_OUTPUT_LAYOUT } from "@metaobjectsdev/codegen-ts/engine"; @@ -114,10 +113,13 @@ function valueShape(f: MetaField): string { return ""; } -function filterableFields(entity: MetaObject, exclude?: string): MetaField[] { +function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: RenderContext | undefined): MetaField[] { // fields() returns effective fields, so inherited fields (from extends:/super:) are included in allowlists. + // A credential is never filterable, whatever @filterable says (isFilterableField); a column a + // sibling subtype of the same table marks as a credential is not either (credentialFieldNames). + const credentials = credentialFieldNames(entity, ctx?.loadedRoot); return flatSurfaceFields(entity) - .filter((c) => 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/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..db44d2e4a2 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.isFinite(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/templates/filter-allowlist.ts b/examples/showcase/codegen/templates/filter-allowlist.ts index eb5392b047..5d1527373a 100644 --- a/examples/showcase/codegen/templates/filter-allowlist.ts +++ b/examples/showcase/codegen/templates/filter-allowlist.ts @@ -2,7 +2,6 @@ import { flatSurfaceFields } from "@metaobjectsdev/codegen-ts/engine"; import { code, type Code } from "@metaobjectsdev/codegen-ts/engine"; import { MetaField, MetaObject } from "@metaobjectsdev/metadata"; import { - FIELD_ATTR_FILTERABLE, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, @@ -20,7 +19,7 @@ import { opsForField, } from "@metaobjectsdev/metadata"; import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; -import { sortableFields, declaredSortDefaultOrder } from "./filter-shared.js"; +import { credentialFieldNames, isFilterableField, isSortableField, declaredSortDefaultOrder } from "./filter-shared.js"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { httpRuntimeSpecifier } from "@metaobjectsdev/codegen-ts/engine"; import { DEFAULT_OUTPUT_LAYOUT } from "@metaobjectsdev/codegen-ts/engine"; @@ -114,10 +113,13 @@ function valueShape(f: MetaField): string { return ""; } -function filterableFields(entity: MetaObject, exclude?: string): MetaField[] { +function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: RenderContext | undefined): MetaField[] { // fields() returns effective fields, so inherited fields (from extends:/super:) are included in allowlists. + // A credential is never filterable, whatever @filterable says (isFilterableField); a column a + // sibling subtype of the same table marks as a credential is not either (credentialFieldNames). + const credentials = credentialFieldNames(entity, ctx?.loadedRoot); return flatSurfaceFields(entity) - .filter((c) => 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/secret-fields/README.md b/fixtures/api-contract-conformance/secret-fields/README.md index a7cc3b7f69..2217bfcb83 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,10 @@ 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. - **`@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,6 +56,7 @@ 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 ``` 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/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..f9deb43634 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs @@ -137,4 +137,44 @@ 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); + } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index edac5b1a99..a8b87d2e17 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -149,6 +149,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..d17dd2f6c9 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(); @@ -628,7 +628,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // Sortable base scalar fields (the polymorphic list sorts on base columns). 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() && !IsCredentialField(f)) .ToList(); var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); @@ -665,7 +665,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() && !IsCredentialField(f)) .ToList(); AppendSortAllowlist(sb, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); @@ -824,8 +824,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/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/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..e6b6614239 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 @@ -198,6 +198,10 @@ open class KotlinFilterAllowlistGenerator : MultiFileDirectGeneratorBase