Skip to content

feat: a table with a composite primary key gets routes that address one row, and Python and Go accept the import settings - #268

Merged
cultron merged 8 commits into
mainfrom
feat/composite-key-routes
Nov 27, 2026
Merged

cultron merged 8 commits into
mainfrom
feat/composite-key-routes

Conversation

@cultron

@cultron cultron commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes #250. Part of #242. Needs @apso/crud and @apso/crud-typeorm 1.2.0 (apsoai/apso-packages), which must be published first.

What changes

A composite primary key gets routes that address one row, in TypeScript, Python and Go. A row is read, updated, replaced and deleted at one path segment per key column, in key order: /RateLimits/:bucket/:window_start. Key order is the primary fields in the order the schema lists them, then the foreign keys of the primary relationships, which is the order of the table's primary key. A single key keeps /:id. The MCP tools take one argument per key column, and apso test smoke creates, reads and deletes these rows. Since 0.58.1 a TypeScript service had list and create routes only for such a table, and Python and Go declared /:id routes that could not work.

Python and Go accept the three import settings. "primaryKeyType": "bigserial", "primaryKeyDefault": null and enumName were TypeScript only; the other two generators stopped with an error. A bigint id is sent and returned as a string in all three languages, and Python and Go read a number or a string.

The scope guard finds a row by the entity's own key (TypeScript). It looked a row up by a column called id. A tenant-scoped entity with its own key column (a slug key) answered 403 for every read, update and delete of one row. The create check compared only the key columns the body sent, so a key that existed in another tenant answered 409. It now compares the whole key, with the tenant column read from the caller.

A scoped create keeps a key the caller sends (TypeScript, with the packages). A signed-in user could not create a row of a scoped entity whose key they send; the insert failed with a NOT NULL error. That create now works and can only add a row.

Review

An independent review of the TypeScript and package change found a critical hole in my first version and I fixed it before this PR: a body that named a key column through its relation object ({"slug":"t","kind":{"id":1}}) passed the key check, and the save then updated the row the object names, including another tenant's. The guard and the package now read that object as the column before the key is checked. The same review found that the check missed soft-deleted rows, that the guard and the controller could disagree on the key, and that a composite-key controller on an older @apso/crud served /:id and acted on the wrong row. All four are fixed; a composite-key controller now fails to build and to start on the older package.

A second independent review covered those fixes and the Python and Go change. It confirmed the fixes under new body shapes and found no tenant-isolation problem in Python or Go. It found one more TypeScript problem, which I fixed: a boolean or enum key field was generated as a plain column, so TypeORM's key was narrower than the table's, and one tenant's DELETE by key also removed another tenant's row that shared the other key columns. Those fields, and float, now get a primary column, and a json or array field cannot be part of a key. It also found that Python's PUT required every key column in the body and that a Python MCP argument of .. was read as a path segment; both are fixed.

How I checked it

  • The full CLI test suite: 957 passed, 24 skipped, lint 0 errors.
  • TypeScript: a generated service on Postgres 16 with the 1.2.0 packages from tarballs. Read, PATCH, PUT and DELETE by both key segments; a scoped composite key that includes the tenant column; a scoped slug key; two tenants creating one key at once for 40 rounds (one wins every round and the stored row is the winner's); the OpenAPI paths; the MCP tool. The reviewer's attack script gets 409 on every relation-object create and the other tenant's rows are unchanged.
  • apso test smoke passes on the same schema in TypeScript, Python and Go, composite keys included. apso test access passes on the TypeScript, Python and Go services, composite keys included.
  • Python and Go: 90 requests per language against Postgres 16, covering each setting and the composite routes, a tenant-scoped composite key, and a bigint id above 2^53 sent as a string and as a number.

Known limits

Follow-up commit: the open items

  • Python and Go answer 409 for a duplicate key or unique value, where they answered 500 (Go's body carried the database message).
  • Python refuses an integer or bigint path segment outside its column's range with 422, where it answered 500.
  • A relationship declared from both sides keeps primary.
  • apso test access covers composite-key entities. On the reviewer's ten-entity schema R7 runs 688 cases with nothing skipped, and the suite passes on TypeScript, Python and Go services.
  • A tenant-scoped create is insert-only in the save's own transaction for every scope shape, including an entity scoped through a parent row (@CrudAuth insertOnly). In the reviewer's script, 40 rounds of two tenants racing for one nested-scope key all answered 201 and 409.
  • A timestamp key (no time zone) is found by the value the API returns when the server is not on UTC. Checked with the service on America/Chicago time against Postgres 16, including tenant isolation on a scoped timestamp key.

…ne row

A row is read, updated, replaced and deleted at one path segment per key
column, in key order: /RateLimits/:bucket/:window_start. The MCP tools and
the smoke test follow. Needs @apso/crud and @apso/crud-typeorm 1.2.0.

The scope guard finds the row a route names by the entity's own key. It
used a column called id, so a tenant-scoped entity with its own key column
answered 403 for every read, update and delete of one row. Its create check
compared only the key columns the body sent, so a key that existed in
another tenant answered 409; it now compares the whole key, with the tenant
column read from the caller.
…mposite key routes in Python and Go

The Python and Go generators refused three settings `apso import` writes and
declared /{id} routes that could not work for a composite key. They now
generate all four the way the shared DDL writer builds the tables.

- primaryKeyType "bigserial": the id is BIGINT with a sequence, and so is a
  foreign key onto it. Both are JSON strings on the wire, as in TypeScript.
  Python maps them with a BigIntString column type (models/types.py); Go uses
  int64 with the ",string" JSON tag.
- primaryKeyDefault null on a uuid id: no database default, and the create
  body carries the id.
- enumName: the model names the Postgres enum type the field names, and two
  fields may share one.
- An entity with its own key (several primary fields, primary ManyToOne
  relationships, or one primary field not named id) gets one path segment per
  key column, in the DDL's key order, for get, update, replace and delete.
  Each segment is parsed to its column's type. A row is matched on the whole
  key in the same query as the tenant scope. MCP tools take one argument per
  key column. An update never writes a key column.

"primary" on a relationship is no longer refused for Python and Go.
"joinColumnName" and "foreignKeyName" still are.

The schema parity test (APSO_PYGO_PARITY_URL) now also runs
test/fixtures/ddl/pygo-keys.apsorc for both languages.
…s a string in the Python API document

Go read a bigserial id, and a foreign key onto one, with the ",string" JSON
tag, which refuses a JSON number. TypeScript and Python read both forms.

- Go: models.BigInt (models/bigint.go) replaces int64 with ",string" for the
  id and for a foreign key onto it, in the model and the DTOs. It is sent as
  a JSON string, read from a string of digits or a whole number with every
  digit kept, and read and written as BIGINT through Scan and Value. The MCP
  and swagger types stay string.
- Python: a foreign key onto a bigserial id is declared as a string of digits
  in request bodies (BigIntKey in the schema file), as responses already
  declare it. A JSON number is still read.

The Go build test now runs `go test` on the keys fixture's DTOs: number and
string forms, a value above 2^53, and values that are not whole numbers.
… composite key needs @apso/crud 1.2.0

Review findings: a body that named a key column through its relation
object passed the create check and could write over another tenant's row;
the check missed soft-deleted rows; the guard and the controller could
disagree on the key when a relationship is declared from both sides; and
a composite-key controller on an older @apso/crud served /:id and acted on
the wrong row. It now fails to build and to start there.
…on's replace and MCP paths take a composite key

Second review findings: a boolean or enum key field was a plain @column,
so TypeORM's key was narrower than the table's and a delete by key also
removed another tenant's row that shared the other columns. Those fields,
and float, now get @PrimaryColumn; json and array fields cannot be part of
a key. Python's PUT needed every key column in the body, and an MCP tool
argument of '..' was resolved as a path segment.

@cultron cultron left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good: I read the description and the diff (38 files) and found nothing that must change in the code.

  • The scope guard now finds a row by the entity's real key from ScopeConfig.key, and a partial key on a route counts as no key, so it can't fall back to a looser lookup.
  • On create, a relation object sent for a key column is turned into its column before the key check, and an object value is refused, so the key that gets checked is the key that gets saved. The whole-key duplicate check now includes soft-deleted rows.
  • When auth is on, a key column that is the tenant column always takes the caller's tenant value, never the body's.
  • A composite-key controller on an older @apso/crud fails to build and to start instead of serving /:id. addMissingDeps(..., raise) lifts a template that still declares ^1.1.0.
  • Python and Go build their one-row routes from the same DDL key order (keyColumns), so the route, the model and the table agree.

Hold before merging: @apso/crud and @apso/crud-typeorm 1.2.0 are not on npm yet (npm shows crud 1.1.0 and crud-typeorm 1.1.2 as latest). apsoai/apso-packages#91 is still open. Every push to main here publishes, so this should merge only after 1.2.0 is out. CI on this head was still running when I reviewed (build, auth-smoke and break-each-rule in all three languages, build-and-publish). The credential scans passed.

- Python and Go answer 409 for a duplicate key or unique value, not 500
  with the database message.
- A text key column cannot hold '/' in Python and Go: their routers match
  the decoded path, so such a row could be stored and never addressed.
- Python refuses an integer or bigint path segment outside its column's
  range with 422 instead of failing in the database with 500.
- A relationship declared from both sides keeps 'primary'.
- apso test access covers composite-key entities: a row is addressed by
  its key path, and each tenant's key differs.
…and a timestamp key is found on a server not on UTC

Generated controllers set CrudAuth insertOnly for a tenant-scoped caller
(needs @apso/crud-core 1.2.0), so an entity scoped through a parent row no
longer relies on the guard's separate key check. The scope guard looks a
timestamp key up as the driver wrote it.
…copy of the scoped-create rule

reference-check and related-rows-check matched the guard's old readable()
call. body-id now also turns off @apso/crud-typeorm 1.2.0's insert-only
check in the generated services, since the package holds the same rule;
without that the suite stays green and the removal reads as not caught.

@cultron cultron left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes needed: re-review of 00d364a and 7ee9c77. The new commits look right (409 for duplicate keys in Python/Go, no '/' in a text key, range checks, insertOnly for tenant-scoped creates, timestamp keys looked up as the driver wrote them), and auth-smoke (typescript) now passes since @apso/crud 1.2.0 is out. But break-each-rule (typescript) fails at this head (it also failed at a407d1c): three R8 mutations report DID NOT APPLY, so the suite no longer proves those checks are covered.

Cause: scripts/access-mutations.mjs still matches the old guard code. readable() now takes four arguments and the key-collision check compares against metadata.primaryColumns.length, so these patterns find nothing:

  • reference-check: readable(targetRoute, id, targetScope) -> now readable(targetRoute, referenced, id, targetScope)
  • related-rows-check: second pattern readable(targetRoute, id, targetScope) -> now readable(targetRoute, primary, id, targetScope)
  • body-id: if (column.isGenerated || request.method !== "POST") {\s*delete item[column.propertyName]; -> now delete item[property];, and if (Object.keys(chosen).length > 0) { -> now ... === metadata.primaryColumns.length) {

Update those patterns (and confirm each removal is then caught) before merging. Still holding for the publish order: merge only once you're ready for 0.59.0 to go out.

if (!join.isVirtual) id = item[join.propertyName];
if (id == null || scopeFields.includes(join.propertyName) || !limited(targetScope)) continue;
if (typeof id === 'object' || !(await readable(targetRoute, id, targetScope))) throw denied();
if (typeof id === 'object' || !(await readable(targetRoute, referenced, id, targetScope))) throw denied();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This signature change breaks the reference-check mutation in scripts/access-mutations.mjs (its regex expects readable(targetRoute, id, targetScope)), so break-each-rule (typescript) reports DID NOT APPLY and fails. Update the pattern to the new four-argument call.

const id = row !== null && typeof row === 'object' ? row[primary] : row;
if (id == null || typeof id === 'object') throw denied();
if (!(await readable(targetRoute, id, targetScope))) throw denied();
if (!(await readable(targetRoute, primary, id, targetScope))) throw denied();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same for related-rows-check: its second pattern expects readable(targetRoute, id, targetScope) and no longer matches this line.

if (Object.keys(chosen).length > 0) {
// A whole key the client chooses: a create must not write over the row
// that has it. Part of a key names no row, so the save can only insert.
if (metadata.primaryColumns.length > 0 && Object.keys(chosen).length === metadata.primaryColumns.length) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

body-id mutation looks for if (Object.keys(chosen).length > 0) { and for delete item[column.propertyName]; after the isGenerated check (now delete item[property]; at L477). Neither matches, so that mutation does not apply either.

@cultron
cultron merged commit 07a6755 into main Nov 27, 2026
10 checks passed
cultron added a commit to apsoai/skills that referenced this pull request Nov 27, 2026
apsoai/cli#268: an entity keyed on more than one column gets routes for
every key column in key order (/RateLimits/:bucket/:window_start), and
bigserial, primaryKeyDefault null, enumName and a primary relationship
now generate in Python and Go too. The schema guide drops "TypeScript
only" from those keys and shows a composite-key route. Plugin 0.8.8.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Importer fidelity: language key, collision fix renames a column, arrays become text, composite keys, silent drops

1 participant