@stonyx/orm 0.3.2-alpha.89 → 0.3.2-alpha.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1454
- package/dist/hooks.d.ts +1 -15
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -8
- package/dist/main.d.ts +0 -116
- package/dist/main.js +0 -119
- package/dist/manage-record.js +9 -234
- package/dist/orm-request.d.ts +3 -284
- package/dist/orm-request.js +68 -1336
- package/dist/record.d.ts +0 -16
- package/dist/record.js +3 -149
- package/dist/setup-rest-server.js +5 -51
- package/dist/standalone-db.js +5 -17
- package/dist/types/orm-types.d.ts +0 -249
- package/dist/utils.d.ts +0 -44
- package/dist/utils.js +0 -47
- package/package.json +4 -4
- package/src/hooks.ts +1 -15
- package/src/index.ts +0 -10
- package/src/main.ts +0 -123
- package/src/manage-record.ts +9 -253
- package/src/orm-request.ts +71 -1362
- package/src/record.ts +3 -176
- package/src/setup-rest-server.ts +6 -59
- package/src/standalone-db.ts +6 -17
- package/src/types/orm-types.ts +1 -256
- package/src/types/stonyx-rest-server.d.ts +1 -14
- package/src/utils.ts +0 -50
- package/dist/access-verdict.d.ts +0 -85
- package/dist/access-verdict.js +0 -284
- package/src/access-verdict.ts +0 -312
package/dist/orm-request.js
CHANGED
|
@@ -1,293 +1,10 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* REST request handling and access enforcement for @stonyx/orm.
|
|
3
|
-
*
|
|
4
|
-
* ---------------------------------------------------------------------------
|
|
5
|
-
* THE `access()` CONTRACT: `access(request, { model, operation })`
|
|
6
|
-
* ---------------------------------------------------------------------------
|
|
7
|
-
* `auth()` calls your predicate with TWO arguments. The second is the access
|
|
8
|
-
* CONTEXT -- the structural facts about the request, which the framework
|
|
9
|
-
* already holds and which you should read INSTEAD of parsing anything:
|
|
10
|
-
*
|
|
11
|
-
* context.model The model this route was mounted for, as a model name:
|
|
12
|
-
* kebab-case, exactly as declared under
|
|
13
|
-
* `config.orm.paths.model` and keyed in the store --
|
|
14
|
-
* `'owner'`, `'animal'`, `'phone-number'`. NOT the
|
|
15
|
-
* pluralised, dasherized, mount-prefixed ROUTE name. It is
|
|
16
|
-
* read from the OrmRequest instance, fixed at mount time,
|
|
17
|
-
* and no request can influence it.
|
|
18
|
-
*
|
|
19
|
-
* context.operation The operation being authorised. Exactly one of the four
|
|
20
|
-
* verbs `'read'`, `'create'`, `'update'`, `'delete'` --
|
|
21
|
-
* no second vocabulary ON THIS PATH, and never an HTTP
|
|
22
|
-
* method name like `'GET'`. These are the same four
|
|
23
|
-
* strings the permission-array return shape is written in
|
|
24
|
-
* (`['read', 'create']`), because both come from the one
|
|
25
|
-
* `methodAccessMap` below.
|
|
26
|
-
*
|
|
27
|
-
* NOT the hook vocabulary. `HookContext.operation`
|
|
28
|
-
* (`src/hooks.ts`, documented under "Hook Context Object"
|
|
29
|
-
* in the README) carries `'list' | 'get' | 'create' |
|
|
30
|
-
* 'update' | 'delete'` on an identically-named key of an
|
|
31
|
-
* identically-shaped context object, and the access
|
|
32
|
-
* vocabulary collapses `list` and `get` into `'read'`. For
|
|
33
|
-
* one `GET /animals/1` a hook sees `'get'` and `access()`
|
|
34
|
-
* sees `'read'`, so a predicate cannot tell a collection
|
|
35
|
-
* read from a record read. `AccessOperation` makes
|
|
36
|
-
* `operation === 'get'` a compile error for a TypeScript
|
|
37
|
-
* consumer, because a predicate that stops matching falls
|
|
38
|
-
* through to the permission array -- the misreading is
|
|
39
|
-
* fail-open shaped.
|
|
40
|
-
*
|
|
41
|
-
* `undefined` when the dispatched method has no entry in
|
|
42
|
-
* that map. Express delivers `HEAD` to the `GET` handler,
|
|
43
|
-
* so this is reachable. It is left undefined rather than
|
|
44
|
-
* defaulted on purpose -- a fabricated `'read'` would turn
|
|
45
|
-
* an unclassified request into an authorised one. Treat
|
|
46
|
-
* `undefined` as "not classified" and deny.
|
|
47
|
-
*
|
|
48
|
-
* So a consumer writes `if (model === 'owner' && operation === 'read')`. There
|
|
49
|
-
* is no string to parse, no variant to miss, and no way to fail open through a
|
|
50
|
-
* URL shape nobody anticipated.
|
|
51
|
-
*
|
|
52
|
-
* WHAT THE CONTEXT DOES NOT TELL YOU: WHICH SURFACE. It names the model and
|
|
53
|
-
* the verb, not the route. Measured over the live router, six surfaces produce
|
|
54
|
-
* one identical context:
|
|
55
|
-
*
|
|
56
|
-
* GET /owners { model: 'owner', operation: 'read' }
|
|
57
|
-
* GET /owners/gina { model: 'owner', operation: 'read' }
|
|
58
|
-
* GET /owners/gina/pets { model: 'owner', operation: 'read' }
|
|
59
|
-
* GET /owners/gina/relationships/pets { model: 'owner', operation: 'read' }
|
|
60
|
-
* GET /owners/archived { model: 'owner', operation: 'read' }
|
|
61
|
-
* GET /owners/gina?include=pets { model: 'owner', operation: 'read' }
|
|
62
|
-
*
|
|
63
|
-
* So a rule that depends on the SUB-PATH still needs `request.path` -- which is
|
|
64
|
-
* mount-relative and query-free, and is the one read of argument one the
|
|
65
|
-
* warning below sanctions. This repo's own fixture has such a rule: its
|
|
66
|
-
* `/archived` deny cannot be expressed from the context alone, and a predicate
|
|
67
|
-
* migrated to context-only would silently drop it, turning a deny into an
|
|
68
|
-
* allow.
|
|
69
|
-
*
|
|
70
|
-
* THE RELATED-RESOURCE HALF OF THAT SENTENCE IS NOW OUT OF DATE AND IS
|
|
71
|
-
* CORRECTED HERE RATHER THAN DELETED. Both relationship route families resolve
|
|
72
|
-
* the RELATED model's own access class and ask it
|
|
73
|
-
* `{ model: <related>, operation: 'read', recordId: null }`
|
|
74
|
-
* (abofs/stonyx-orm#232), so those surfaces no longer serve another model's
|
|
75
|
-
* records under `model: 'owner'` unexamined. What the context still gives no
|
|
76
|
-
* signal of is WHICH related record is being asked about -- `recordId` is
|
|
77
|
-
* `null` there and `request.params` names a record of a different model. See
|
|
78
|
-
* `AccessContext.recordId` in ./types/orm-types.ts for the full statement of
|
|
79
|
-
* that limit.
|
|
80
|
-
*
|
|
81
|
-
* AND THE `?include=` HALF IS NOW OUT OF DATE TOO, CORRECTED THE SAME WAY. It
|
|
82
|
-
* read: "`?include=` is still unfiltered and is abofs/stonyx-orm#233 / #235."
|
|
83
|
-
* Both have landed. #235 filters what a record already in `included` may NAME,
|
|
84
|
-
* and #233 filters MEMBERSHIP at the traversal's push site -- see
|
|
85
|
-
* `traverseIncludePath` below. The ask is the same shape as the
|
|
86
|
-
* related-resource one and carries the same limit: `recordId` is `null`, so a
|
|
87
|
-
* deny expressible only as a request-scoped `return false` -- which is how the
|
|
88
|
-
* shipped sample spells `/archived` -- still cannot fire on this path. That
|
|
89
|
-
* residual is abofs/stonyx-orm#243's, not #233's, and it is measured
|
|
90
|
-
* byte-identical on `dev`.
|
|
91
|
-
*
|
|
92
|
-
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237, AND KEPT FOR THE
|
|
93
|
-
* CONSTRAINT IT STATES RATHER THAN AS A DESCRIPTION OF THE CODE. The context
|
|
94
|
-
* now also carries `recordId` -- the DECODED route-parameter id, see
|
|
95
|
-
* `AccessContext.recordId` in ./types/orm-types.ts -- so the fixture's
|
|
96
|
-
* `/archived` deny IS expressible from the context alone, and the shipped
|
|
97
|
-
* sample no longer reads `request.path` at all. Retiring this wording WITH the
|
|
98
|
-
* measurement that retires it, rather than by deletion, is
|
|
99
|
-
* abofs/stonyx-orm#238.
|
|
100
|
-
*
|
|
101
|
-
* `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
|
|
102
|
-
* matching but BEFORE any handler executes (`@stonyx/rest-server`
|
|
103
|
-
* `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
|
|
104
|
-
* record would force a pre-fetch on every request, a second store hit and an
|
|
105
|
-
* ordering change in the middle of an authorization path. It is also
|
|
106
|
-
* unnecessary: the FUNCTION return shape already is the per-record hook. Return
|
|
107
|
-
* `(record) => boolean` and the handlers apply it to every record the request
|
|
108
|
-
* touches. Auth-time and record-time are separate decision points.
|
|
109
|
-
*
|
|
110
|
-
* THE SECOND ARGUMENT IS ADDITIVE. JavaScript ignores extra arguments, so an
|
|
111
|
-
* existing `access(request)` predicate keeps working exactly as before. The
|
|
112
|
-
* warning immediately below is therefore still live: `request` is still
|
|
113
|
-
* argument ONE, and reading it is still how predicates fail open.
|
|
114
|
-
*
|
|
115
|
-
* To reach ANOTHER model's predicate -- e.g. to check an animal while servicing
|
|
116
|
-
* an owners route -- use the boot-time registry:
|
|
117
|
-
*
|
|
118
|
-
* const predicate = Orm.instance.getAccess('animal');
|
|
119
|
-
* if (!predicate) return deny;
|
|
120
|
-
* const verdict = predicate(request, { model: 'animal', operation: 'read' });
|
|
121
|
-
*
|
|
122
|
-
* `undefined` means NO PREDICATE COULD BE RESOLVED for that name -- which
|
|
123
|
-
* includes the case where the model has an access class that failed to load,
|
|
124
|
-
* because `setup-rest-server.ts` catches a load failure, warns, and publishes
|
|
125
|
-
* whatever partial map it had. It does NOT mean the model is unrestricted.
|
|
126
|
-
* Treat it as DENY, the same way `operation === undefined` is treated above.
|
|
127
|
-
*
|
|
128
|
-
* PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not make
|
|
129
|
-
* the answer model-correct on its own -- the resolved predicate has to READ it.
|
|
130
|
-
* Measured against an ARITY-1 predicate, on a request express dispatched to
|
|
131
|
-
* `GET /owners/angela`, asked about ANIMALS:
|
|
132
|
-
*
|
|
133
|
-
* getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
|
|
134
|
-
* -> record => record.id !== 'angela' && record.id !== 'restricted'
|
|
135
|
-
*
|
|
136
|
-
* That is the OWNERS filter, and it returns `true` for animal 21 -- the record
|
|
137
|
-
* hidden on every animal surface. Under a mount that predicate recognises
|
|
138
|
-
* neither way it is worse: it falls through to
|
|
139
|
-
* `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
|
|
140
|
-
* context was supplied and the answer is not the animal answer, and it is wrong
|
|
141
|
-
* in the GRANTING direction, because that predicate is arity-1 and identifies
|
|
142
|
-
* its collection from the request. (Asserted on a live dispatch by AC9 in
|
|
143
|
-
* test/integration/orm-test.ts, against a deliberately arity-1 predicate.)
|
|
144
|
-
*
|
|
145
|
-
* This repo's own sample access class has since been MIGRATED to read the
|
|
146
|
-
* context (abofs/stonyx-orm#222), so `getAccess('animal')` here now answers
|
|
147
|
-
* with the animal filter. That is not true of a consumer tree: an arity-1
|
|
148
|
-
* predicate keeps working -- the second argument is additive -- and the caller
|
|
149
|
-
* has no supported way to tell which kind it got. The boot-time arity warning
|
|
150
|
-
* that surfaces one is abofs/stonyx-orm#221.
|
|
151
|
-
* So: pass the context, and do not treat a resolved predicate's answer as
|
|
152
|
-
* model-specific until that predicate has been migrated to read the context.
|
|
153
|
-
*
|
|
154
|
-
* ---------------------------------------------------------------------------
|
|
155
|
-
* DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
|
|
156
|
-
* ---------------------------------------------------------------------------
|
|
157
|
-
* You do not have to. `auth()` below hands your predicate the ACCESS CONTEXT as
|
|
158
|
-
* argument two, and `context.model` already names the collection -- see the
|
|
159
|
-
* contract section above. Argument ONE is still the raw transport artifact, and
|
|
160
|
-
* everything from here to the end of this banner is the record of what happened
|
|
161
|
-
* when predicates worked the collection out from it. IT IS HISTORY, NOT
|
|
162
|
-
* GUIDANCE: do not write any of it into a new predicate. Every attempt to
|
|
163
|
-
* identify the collection by parsing the request target has failed OPEN. Five
|
|
164
|
-
* distinct variants of the same three-line example have now been found, each
|
|
165
|
-
* after the previous was fixed, by five different people:
|
|
166
|
-
*
|
|
167
|
-
* 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
|
|
168
|
-
* prefix match against it is ALWAYS false.
|
|
169
|
-
* 2. `request.originalUrl` carries the query string, so an anchored equality
|
|
170
|
-
* check misses `/owners?filter[age]=30`.
|
|
171
|
-
* 3. The router is a bare `express()` (`caseSensitive: false`) while a
|
|
172
|
-
* hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
|
|
173
|
-
* past it. Router-side: abofs/stonyx-rest-server#47.
|
|
174
|
-
* 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
|
|
175
|
-
* nothing -- environment-specifically, which is worse.
|
|
176
|
-
* 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
|
|
177
|
-
* `parseurl(req).pathname`, but `originalUrl` is the raw target, so
|
|
178
|
-
* `GET http://anything.example/owners/angela` reaches the handler with
|
|
179
|
-
* `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
|
|
180
|
-
* prefix match is false, `access()` falls through to whatever it returns
|
|
181
|
-
* last, and the record comes back in full. It walks past a hard
|
|
182
|
-
* `return false` deny the same way.
|
|
183
|
-
*
|
|
184
|
-
* The fix is not a sixth rule, and it is not a better string to match. It is to
|
|
185
|
-
* stop identifying the collection at all: read `context.model`. That is a claim
|
|
186
|
-
* about IDENTIFYING THE COLLECTION, not about the sample as a whole -- the
|
|
187
|
-
* `/archived` SUB-PATH rule is still a string match, and abofs/stonyx-orm#228 is
|
|
188
|
-
* a sixth spelling that gets past it.
|
|
189
|
-
*
|
|
190
|
-
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: the `/archived` rule is
|
|
191
|
-
* no longer a string match against the request target -- it compares the
|
|
192
|
-
* decoded `recordId` the framework supplies -- and abofs/stonyx-orm#228 is
|
|
193
|
-
* CLOSED. Retirement of this wording: abofs/stonyx-orm#238.
|
|
194
|
-
*
|
|
195
|
-
* An intermediate revision of the sample read `request.baseUrl` -- the mount
|
|
196
|
-
* Express ACTUALLY MATCHED. That closed all five variants (no query string,
|
|
197
|
-
* not mount-relative, unaffected by absolute-form, already carrying the
|
|
198
|
-
* configured `ORM_REST_ROUTE` prefix), but it was a transport artifact
|
|
199
|
-
* standing in for a structural fact and the sample no longer does it.
|
|
200
|
-
* `context.model` IS the structural fact, so variants 1, 2, 4 and 5 are
|
|
201
|
-
* unconstructible against a migrated predicate rather than handled.
|
|
202
|
-
*
|
|
203
|
-
* VARIANT 3 SURVIVES, and is deliberately not in that list. It is the general
|
|
204
|
-
* shape "a hand-written matcher normalises differently from the router", and a
|
|
205
|
-
* migrated predicate still runs one string comparison for any SUB-PATH rule --
|
|
206
|
-
* in the shipped sample, the `/archived` deny. That comparison folds case but
|
|
207
|
-
* does not decode, so `GET /owners/%61rchived` steps past it. See the
|
|
208
|
-
* normalisation paragraph below and abofs/stonyx-orm#228.
|
|
209
|
-
*
|
|
210
|
-
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237. Variant 3 lived in that
|
|
211
|
-
* one string comparison, and the comparison is gone: the sample compares the
|
|
212
|
-
* decoded `recordId`. Left standing rather than edited because the same
|
|
213
|
-
* "variant 3 survives" wording sits at four sites -- this header, README.md
|
|
214
|
-
* twice, and test/sample/access/global-access.ts -- three of which SHIP, so
|
|
215
|
-
* retiring one of four leaves the shipped copies contradicting each other.
|
|
216
|
-
* Retiring all four WITH their measurement is abofs/stonyx-orm#238.
|
|
217
|
-
*
|
|
218
|
-
* ONE READ OF ARGUMENT ONE SURVIVES, AND IT MUST: `request.path`. It is
|
|
219
|
-
* mount-relative and query-free, and it is for rules that distinguish SUB-PATHS
|
|
220
|
-
* beneath the mount. The context names which model and which verb, NOT which
|
|
221
|
-
* route, so the sample's `/archived` deny cannot be expressed from the context
|
|
222
|
-
* alone and a context-ONLY rewrite would silently turn that deny into an allow.
|
|
223
|
-
*
|
|
224
|
-
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: NO read of argument one
|
|
225
|
-
* survives in the shipped sample. `recordId` names WHICH RECORD the route was
|
|
226
|
-
* addressed to, so the `/archived` deny is expressible from the context alone
|
|
227
|
-
* -- and it still must not be dropped; expressible is not optional. Retirement
|
|
228
|
-
* of this wording: abofs/stonyx-orm#238.
|
|
229
|
-
*
|
|
230
|
-
* NORMALISE THE WAY THE ROUTER DOES, AND CASE-FOLDING ALONE IS NOT THAT. The
|
|
231
|
-
* sample lower-cases before comparing, because a matcher stricter than the
|
|
232
|
-
* case-insensitive router can be stepped around. That closes the case gap only.
|
|
233
|
-
* Express sets `request.path` from the RAW, UNDECODED pathname while the router
|
|
234
|
-
* DECODES `:id`, so `GET /owners/%61rchived` reaches a `path === '/archived'`
|
|
235
|
-
* comparison as `/%61rchived` and walks past the deny. That gap is live in the
|
|
236
|
-
* sample and is tracked as abofs/stonyx-orm#228; the `.toLowerCase()` is not a
|
|
237
|
-
* complete normalisation recipe. Compare record ids at their real case.
|
|
238
|
-
*
|
|
239
|
-
* DO NOT FOLLOW THE PARAGRAPH ABOVE. SUPERSEDED 2026-09-01 BY
|
|
240
|
-
* abofs/stonyx-orm#236/#237, and flagged here rather than merely dated because
|
|
241
|
-
* it is an INSTRUCTION, not a stale observation. `.toLowerCase()` on the access
|
|
242
|
-
* path was measured WRONG IN BOTH DIRECTIONS AT ONCE: with a distinct owner
|
|
243
|
-
* seeded at `ARCHIVED`, `GET /owners/ARCHIVED` was a false DENY on the wrong
|
|
244
|
-
* record and `GET /owners/%41RCHIVED` a false ALLOW on that same record. A
|
|
245
|
-
* record id is a VALUE, not a literal route segment, and express's
|
|
246
|
-
* `case sensitive routing` governs literal segments only. Compare
|
|
247
|
-
* `context.recordId` AS IT ARRIVES: do not case-fold it, do not decode it, do
|
|
248
|
-
* not derive it from `request.path`. `AccessContext.recordId` in
|
|
249
|
-
* ./types/orm-types.ts is the contract and says "Do NOT case-fold it"; the same
|
|
250
|
-
* published tarball ships both files, and THIS paragraph is the one that is
|
|
251
|
-
* wrong. Retiring it WITH its measurement is abofs/stonyx-orm#238.
|
|
252
|
-
*
|
|
253
|
-
* `?? ''` is not a defence. It converts an absent request target into an empty
|
|
254
|
-
* string, which matches no collection, which falls through to the permission
|
|
255
|
-
* array -- a total grant. An input you cannot identify must DENY, and that
|
|
256
|
-
* applies to BOTH arguments: since #202 the guard and the read can sit on
|
|
257
|
-
* different objects, and a guard on argument two does not protect a read of
|
|
258
|
-
* argument one. The sample returns `false` for an absent `model` AND for an
|
|
259
|
-
* absent or non-string `request.path`, rather than falling through either way.
|
|
260
|
-
*
|
|
261
|
-
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237 as to WHAT is guarded --
|
|
262
|
-
* the principle is unchanged. The sample no longer reads `request.path`, so it
|
|
263
|
-
* returns `false` for an absent `model` AND for an absent `recordId`
|
|
264
|
-
* (`undefined`, the one spelling `auth()` never produces). Retirement of this
|
|
265
|
-
* wording: abofs/stonyx-orm#238.
|
|
266
|
-
*
|
|
267
|
-
* THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
|
|
268
|
-
* the operation and the record. Prefer the array shape (`['read']`) or `false`
|
|
269
|
-
* until #202 lands; the function shape is what requires any matching at all.
|
|
270
|
-
*
|
|
271
|
-
* The enforcement gates in this file (GATE 0/1/2, the create rollback, the
|
|
272
|
-
* per-handler `isDenied` re-checks) are correct independently of that -- they
|
|
273
|
-
* enforce whatever predicate you return. The stopgap is the part where YOU have
|
|
274
|
-
* to work out which predicate to return.
|
|
275
|
-
*
|
|
276
|
-
* AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
|
|
277
|
-
* It is evaluated against the record the route is ADDRESSED TO, on that model
|
|
278
|
-
* only. A write to a DIFFERENT collection can still re-parent a hidden record
|
|
279
|
-
* and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
|
|
280
|
-
* See `### Known limitations` in README.
|
|
281
|
-
*/
|
|
282
1
|
import { Request } from '@stonyx/rest-server';
|
|
283
2
|
import Orm, { store, createRecord, updateRecord } from '@stonyx/orm';
|
|
284
3
|
import { camelCaseToKebabCase } from '@stonyx/utils/string';
|
|
285
4
|
import { getPluralName } from './plural-registry.js';
|
|
286
5
|
import { getBeforeHooks, getAfterHooks } from './hooks.js';
|
|
287
6
|
import config from 'stonyx/config';
|
|
288
|
-
import
|
|
289
|
-
import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
|
|
290
|
-
import { interpretAccess, createLinkageFilter } from './access-verdict.js';
|
|
7
|
+
import { isOrmRecord } from './utils.js';
|
|
291
8
|
const methodAccessMap = {
|
|
292
9
|
GET: 'read',
|
|
293
10
|
POST: 'create',
|
|
@@ -331,120 +48,16 @@ function getBaseUrl(request) {
|
|
|
331
48
|
const host = request.get('host');
|
|
332
49
|
return `${protocol}://${host}`;
|
|
333
50
|
}
|
|
334
|
-
/**
|
|
335
|
-
* The ONE coercion from a caller-supplied id to the key the store holds it
|
|
336
|
-
* under. Every id-bearing surface in this file goes through it, and none has a
|
|
337
|
-
* copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
|
|
338
|
-
* post-create `context.record` lookup in `_withHooks`.
|
|
339
|
-
*
|
|
340
|
-
* WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
|
|
341
|
-
* each had their own arithmetic, and they disagreed: `parseInt(id)` versus
|
|
342
|
-
* `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
|
|
343
|
-
*
|
|
344
|
-
* GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
|
|
345
|
-
* POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
|
|
346
|
-
* -> a MISS, so the duplicate check was skipped and
|
|
347
|
-
* createRecord OVERWROTE 9105 in place, answering 200
|
|
348
|
-
*
|
|
349
|
-
* -- a narrower form of the raw-versus-normalised divergence that the body-id
|
|
350
|
-
* normalisation was added to close, reintroduced by the fix for it. Two
|
|
351
|
-
* coercions that must agree cannot be kept in agreement by review; they have to
|
|
352
|
-
* be one function. Pinned by assertion 43.
|
|
353
|
-
*
|
|
354
|
-
* The third copy was found later and in a quieter place: `_withHooks` populated
|
|
355
|
-
* `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
|
|
356
|
-
* function's body, inlined verbatim, feeding `store.get`. It was equivalent on
|
|
357
|
-
* every input reachable there, which is exactly what the two that DID diverge
|
|
358
|
-
* looked like until someone tried a hex id.
|
|
359
|
-
*
|
|
360
|
-
* SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
|
|
361
|
-
* `id = attr('string')` a numeric-looking id is filed under the STRING key, so
|
|
362
|
-
* this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
|
|
363
|
-
* `context.record` is `undefined` for an after-`create` hook. Inherited -- the
|
|
364
|
-
* inlined copy computed the same thing -- and NOT fixed here, because picking
|
|
365
|
-
* the right coercion needs the model's declared id type, which is the same
|
|
366
|
-
* structural information abofs/stonyx-orm#202 is about. Filed as
|
|
367
|
-
* abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
|
|
368
|
-
* red rather than passing silently.
|
|
369
|
-
*
|
|
370
|
-
* `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
|
|
371
|
-
* It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
|
|
372
|
-
* also radix-less -- because that transform is what actually produces the store
|
|
373
|
-
* KEY a record is filed under. `getId` merely agrees with it. They differ from
|
|
374
|
-
* `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
|
|
375
|
-
* this function to `Number` would make the lookup key disagree with the landing
|
|
376
|
-
* key on those shapes.
|
|
377
|
-
*
|
|
378
|
-
* THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
|
|
379
|
-
* (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
|
|
380
|
-
* to authorization, it would silently reopen the hex divergence in the other
|
|
381
|
-
* direction, and this comment would still read as correct. Assertion 45 pins
|
|
382
|
-
* the transform's radix-less shape directly, so that edit turns a test red
|
|
383
|
-
* rather than shipping.
|
|
384
|
-
*
|
|
385
|
-
* The reason `parseInt` is safe here is the `isNaN` gate in front of it:
|
|
386
|
-
* `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
|
|
387
|
-
* DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
|
|
388
|
-
* rejects it as a string instead, so nothing is ever truncated. That gate, not
|
|
389
|
-
* the parser, is the load-bearing half -- assertion 43 pins it.
|
|
390
|
-
*/
|
|
391
|
-
function coerceId(id) {
|
|
392
|
-
if (isNaN(id))
|
|
393
|
-
return id;
|
|
394
|
-
return parseInt(id);
|
|
395
|
-
}
|
|
396
51
|
function getId(params) {
|
|
397
52
|
const id = params.id;
|
|
398
53
|
if (!id)
|
|
399
54
|
return '';
|
|
400
|
-
|
|
401
|
-
}
|
|
402
|
-
/**
|
|
403
|
-
* Normalise a caller-supplied BODY id to the key the store will hold it under.
|
|
404
|
-
*
|
|
405
|
-
* `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
|
|
406
|
-
* where the value is always a string and a falsy one means "no id". A JSON body
|
|
407
|
-
* id is neither -- it can arrive as a number, and `0` is a legitimate id that
|
|
408
|
-
* `getId()` would flatten to `''`.
|
|
409
|
-
*
|
|
410
|
-
* WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
|
|
411
|
-
* RAW body value while every other surface normalised through `getId()`. The
|
|
412
|
-
* store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
|
|
413
|
-
* the entry held under `21` and the duplicate check is skipped by typing the id
|
|
414
|
-
* as a string. On `dev` that silently overwrote the colliding record and
|
|
415
|
-
* answered 200; combined with the denied-create rollback added for #190 it
|
|
416
|
-
* became an unauthenticated DELETE of any id. Normalising here is half of that
|
|
417
|
-
* fix -- see the rollback in createHandler for the other half.
|
|
418
|
-
*
|
|
419
|
-
* It shares `coerceId` with `getId` so the two surfaces cannot drift apart
|
|
420
|
-
* again, and differs from `getId` in exactly ONE place, below.
|
|
421
|
-
*/
|
|
422
|
-
function normalizeBodyId(id) {
|
|
423
|
-
// Non-strings pass through untouched: a JSON body id can arrive as a number,
|
|
424
|
-
// and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
|
|
425
|
-
// and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
|
|
426
|
-
if (typeof id !== 'string')
|
|
427
|
-
return id;
|
|
428
|
-
// THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
|
|
429
|
-
// `getId` maps a falsy param to `''`, and `''` is the only string a body can
|
|
430
|
-
// carry that means "no id" -- `createRecord` treats it as absent and assigns a
|
|
431
|
-
// server id. Coercing it instead would make it address a real slot, because
|
|
432
|
-
// `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
|
|
433
|
-
// non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
|
|
434
|
-
// then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
|
|
435
|
-
// an unrelated record it never named. Pinned by assertion 44.
|
|
436
|
-
//
|
|
437
|
-
// Note what is deliberately NOT special-cased here any more: whitespace.
|
|
438
|
-
// `id.trim() === ''` used to short-circuit `' '` as well, which made the
|
|
439
|
-
// body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
|
|
440
|
-
// so `' '` addresses the NaN slot on every other route while the collision
|
|
441
|
-
// lookup missed it. Same class of bug as the hex divergence above.
|
|
442
|
-
if (id === '')
|
|
55
|
+
if (isNaN(id))
|
|
443
56
|
return id;
|
|
444
|
-
return
|
|
57
|
+
return parseInt(id);
|
|
445
58
|
}
|
|
446
59
|
function buildResponse(data, includeParam, recordOrRecords, options = {}) {
|
|
447
|
-
const { links, baseUrl
|
|
60
|
+
const { links, baseUrl } = options;
|
|
448
61
|
const response = { data };
|
|
449
62
|
// Add top-level links
|
|
450
63
|
if (links) {
|
|
@@ -455,108 +68,16 @@ function buildResponse(data, includeParam, recordOrRecords, options = {}) {
|
|
|
455
68
|
const includes = parseInclude(includeParam);
|
|
456
69
|
if (includes.length === 0)
|
|
457
70
|
return response;
|
|
458
|
-
|
|
459
|
-
// BOTH (abofs/stonyx-orm#233). It carries #234's per-type verdict cache and
|
|
460
|
-
// per-(type, id) decision cache, so the traversal below and the `toJSON`
|
|
461
|
-
// calls beneath it share one resolution of the consumer's `access()` per
|
|
462
|
-
// type for the whole response. Building a second filter here would double
|
|
463
|
-
// every predicate call and, worse, could answer the two questions
|
|
464
|
-
// differently about the same record.
|
|
465
|
-
const includedRecords = collectIncludedRecords(recordOrRecords, includes, linkage);
|
|
71
|
+
const includedRecords = collectIncludedRecords(recordOrRecords, includes);
|
|
466
72
|
if (includedRecords.length > 0) {
|
|
467
|
-
|
|
468
|
-
// line is one story's and the line above it is another's
|
|
469
|
-
// (abofs/stonyx-orm#235 and #233 respectively).
|
|
470
|
-
//
|
|
471
|
-
// - WHICH RESOURCES REACH THIS ARRAY is decided by
|
|
472
|
-
// `collectIncludedRecords` on the line above. That is MEMBERSHIP and
|
|
473
|
-
// it is #233's. As of #233 that call is given the SAME `linkage`
|
|
474
|
-
// filter, so a hidden owner is no longer a member: she is dropped at
|
|
475
|
-
// the push site and her subtree is never traversed. Pinned by
|
|
476
|
-
// `[DEFECT] #233 AC2` and `[DEFECT] #233 AC4`; the re-specification of
|
|
477
|
-
// `[GUARD] #235 X1`, which pinned the PRE-#233 answer here, is in that
|
|
478
|
-
// same test.
|
|
479
|
-
// - WHAT A RECORD ALREADY IN THIS ARRAY MAY NAME in its own
|
|
480
|
-
// `relationships.*.data` is LINKAGE -- the same question #234 answers
|
|
481
|
-
// for the primary document -- and that is what the `linkage` option
|
|
482
|
-
// below decides. Before it, `GET /animals/1?include=owner,owner.pets`
|
|
483
|
-
// filtered the primary document's `owner.data` to `null` and then
|
|
484
|
-
// handed back eight PERMITTED animals in `included` each naming
|
|
485
|
-
// `{"type":"owner","id":"angela"}` -- angela's whole `pets` set,
|
|
486
|
-
// `[1, 3, 7, 10, 11, 15, 17, 20]`. `included` itself is NINE
|
|
487
|
-
// resources there: those eight animals plus the hidden owner, whose
|
|
488
|
-
// membership is #233's and not an animal. Neither #233 nor #234
|
|
489
|
-
// closes that.
|
|
490
|
-
//
|
|
491
|
-
// THE FILTER IS THE CALLER'S, PASSED IN, NOT BUILT HERE. Both call sites
|
|
492
|
-
// already hold one for the primary document, and sharing it is what keeps
|
|
493
|
-
// the per-type verdict cache and the per-(type, id) decision cache alive
|
|
494
|
-
// across the primary document AND the sideload -- one verdict resolution
|
|
495
|
-
// per type for the whole response, pinned by `[GUARD] #235 C1`. Building a
|
|
496
|
-
// fresh filter here would resolve the consumer's `access()` once per
|
|
497
|
-
// included record instead.
|
|
498
|
-
//
|
|
499
|
-
// `linkage` IS OPTIONAL IN THE TYPE AND IS NOT OPTIONAL IN PRACTICE.
|
|
500
|
-
// Stating it precisely because the opposite claim stood here in an earlier
|
|
501
|
-
// draft of this change: BOTH of this function's callers supply a filter
|
|
502
|
-
// (`getCollectionHandler` and `getSingleHandler`, the only two), so the
|
|
503
|
-
// `undefined` branch has no live caller in this module today. It is
|
|
504
|
-
// optional so that omitting it degrades to the PRE-#234 document rather
|
|
505
|
-
// than to a denial -- `Record.toJSON` reads an ABSENT option as "no verdict
|
|
506
|
-
// was supplied" and emits linkage in full.
|
|
507
|
-
//
|
|
508
|
-
// WHAT IT MUST NEVER BE HANDED IS A NON-FUNCTION. `toJSON` does NOT read a
|
|
509
|
-
// non-function as absent: `Object.prototype.toString.call(linkage)` must be
|
|
510
|
-
// `'[object Function]'`, and anything else -- `null`, an `AsyncFunction`,
|
|
511
|
-
// and INCLUDING the primitive `true` -- DENIES every relationship on the
|
|
512
|
-
// document and logs once. `toJSON({ linkage: true })` emits `null` linkage.
|
|
513
|
-
// So do not "simplify" this to a boolean, and do not make it default to
|
|
514
|
-
// `true`: both spellings look like "allow everything" and mean the exact
|
|
515
|
-
// opposite (abofs/stonyx-orm#224).
|
|
516
|
-
response.included = includedRecords.map(record => record.toJSON?.({ baseUrl, linkage }));
|
|
73
|
+
response.included = includedRecords.map(record => record.toJSON?.({ baseUrl }));
|
|
517
74
|
}
|
|
518
75
|
return response;
|
|
519
76
|
}
|
|
520
77
|
/**
|
|
521
|
-
* Recursively traverse an include path and collect related records
|
|
522
|
-
*
|
|
523
|
-
* ---------------------------------------------------------------------------
|
|
524
|
-
* THE `linkage` FILTER DECIDES MEMBERSHIP HERE (abofs/stonyx-orm#233)
|
|
525
|
-
* ---------------------------------------------------------------------------
|
|
526
|
-
* A resource reaches `included` because some record NAMED it, and until #233
|
|
527
|
-
* being named was the whole test. That made `?include=` a restoration of every
|
|
528
|
-
* record the read surfaces withhold: `GET /owners/angela` is 404 and
|
|
529
|
-
* `GET /animals/1?include=owner` returned her document in full, attributes and
|
|
530
|
-
* all. Measured on dev @ 8dda5d6, over the live router.
|
|
531
|
-
*
|
|
532
|
-
* FILTERED AT THE PUSH SITE, AND THE SITE MATTERS. The obvious alternative --
|
|
533
|
-
* let the traversal run and filter `collectIncludedRecords`' RETURN value --
|
|
534
|
-
* closes the membership half and leaves the worse half open: dropping a parent
|
|
535
|
-
* AFTER traversing through it publishes that parent's exact child set. On this
|
|
536
|
-
* repo's own fixture `GET /animals/1?include=owner,owner.pets` names angela's
|
|
537
|
-
* eight animals `[1, 3, 7, 10, 11, 15, 17, 20]`, which IS her `pets` array,
|
|
538
|
-
* reconstructed from a resource the caller may not read. So a denied record is
|
|
539
|
-
* `continue`d before it is pushed to `included` AND before it is pushed to
|
|
540
|
-
* `nextRecords`, which is what prunes the subtree.
|
|
541
|
-
*
|
|
542
|
-
* A DENIED RECORD IS DELIBERATELY NOT ADDED TO `seen`. `seen` is the
|
|
543
|
-
* deduplicator for records that DID enter `included`; putting a denial in it
|
|
544
|
-
* would conflate "already emitted" with "withheld", and the `else if` branch
|
|
545
|
-
* below would then push a denied record into `nextRecords` for deeper
|
|
546
|
-
* traversal -- re-opening the prune this function just closed. Re-asking is
|
|
547
|
-
* free: #234's filter caches per `(type, id)`, so the second ask is a `Map`
|
|
548
|
-
* hit and not a call into the consumer's `access()`.
|
|
549
|
-
*
|
|
550
|
-
* ABSENT FILTER MEANS PRE-#233 BEHAVIOUR, NOT A DENIAL. `linkage` is optional
|
|
551
|
-
* for the same reason it is optional on `buildResponse` and on
|
|
552
|
-
* `Record.toJSON`: an absent option means "no verdict was supplied", and the
|
|
553
|
-
* honest degradation is the document that shipped before, not an empty one.
|
|
554
|
-
* Both of `buildResponse`'s callers -- `getCollectionHandler` and
|
|
555
|
-
* `getSingleHandler`, the only two -- supply it, which is pinned by
|
|
556
|
-
* `[GUARD] #233 AC8`. What must never arrive here is a non-function; the
|
|
557
|
-
* guard below is the fail-closed reading of one.
|
|
78
|
+
* Recursively traverse an include path and collect related records
|
|
558
79
|
*/
|
|
559
|
-
function traverseIncludePath(currentRecords, includePath, depth, seen, included
|
|
80
|
+
function traverseIncludePath(currentRecords, includePath, depth, seen, included) {
|
|
560
81
|
if (depth >= includePath.length)
|
|
561
82
|
return; // Reached end of path
|
|
562
83
|
const relationshipName = includePath[depth];
|
|
@@ -580,19 +101,6 @@ function traverseIncludePath(currentRecords, includePath, depth, seen, included,
|
|
|
580
101
|
continue;
|
|
581
102
|
const type = relatedRecord.__model.__name;
|
|
582
103
|
const id = relatedRecord.id;
|
|
583
|
-
// MEMBERSHIP AND PRUNE, abofs/stonyx-orm#233. `continue` skips BOTH
|
|
584
|
-
// pushes below -- the record does not enter `included` and it does not
|
|
585
|
-
// become a parent at the next depth.
|
|
586
|
-
//
|
|
587
|
-
// FAIL CLOSED ON A RECORD WHOSE TYPE CANNOT BE NAMED, the same reading
|
|
588
|
-
// #232's `isLinkable` uses on the relationship routes: `type` is the key
|
|
589
|
-
// the verdict is resolved under, so a missing or empty one means there
|
|
590
|
-
// is no predicate to ask and no way to ask it. Denying is the only safe
|
|
591
|
-
// answer, and it is only reachable while a filter is in force -- with no
|
|
592
|
-
// filter this whole check is skipped and the pre-#233 document is
|
|
593
|
-
// emitted unchanged.
|
|
594
|
-
if (linkage && !(typeof type === 'string' && type !== '' && linkage(type, relatedRecord)))
|
|
595
|
-
continue;
|
|
596
104
|
// Initialize Set for this type if needed
|
|
597
105
|
let seenIds = seen.get(type);
|
|
598
106
|
if (!seenIds) {
|
|
@@ -613,10 +121,10 @@ function traverseIncludePath(currentRecords, includePath, depth, seen, included,
|
|
|
613
121
|
}
|
|
614
122
|
// If there are more segments in the path, recursively process
|
|
615
123
|
if (depth < includePath.length - 1 && nextRecords.length > 0) {
|
|
616
|
-
traverseIncludePath(nextRecords, includePath, depth + 1, seen, included
|
|
124
|
+
traverseIncludePath(nextRecords, includePath, depth + 1, seen, included);
|
|
617
125
|
}
|
|
618
126
|
}
|
|
619
|
-
function collectIncludedRecords(data, includes
|
|
127
|
+
function collectIncludedRecords(data, includes) {
|
|
620
128
|
if (!includes || includes.length === 0)
|
|
621
129
|
return [];
|
|
622
130
|
if (!data)
|
|
@@ -627,7 +135,7 @@ function collectIncludedRecords(data, includes, linkage) {
|
|
|
627
135
|
const records = Array.isArray(data) ? data : [data];
|
|
628
136
|
// Process each include path
|
|
629
137
|
for (const includePath of includes) {
|
|
630
|
-
traverseIncludePath(records, includePath, 0, seen, included
|
|
138
|
+
traverseIncludePath(records, includePath, 0, seen, included);
|
|
631
139
|
}
|
|
632
140
|
return included;
|
|
633
141
|
}
|
|
@@ -679,39 +187,6 @@ function createFilterPredicate(filters) {
|
|
|
679
187
|
return String(current) === value;
|
|
680
188
|
});
|
|
681
189
|
}
|
|
682
|
-
/**
|
|
683
|
-
* A function-style `access` return is a per-record predicate, and it is only
|
|
684
|
-
* meaningful if every surface that can hand a record to a caller consults it.
|
|
685
|
-
* Before #190 exactly one of seven did.
|
|
686
|
-
*
|
|
687
|
-
* Enforcement is deliberately post-fetch. `access` returns an opaque JS
|
|
688
|
-
* predicate and `store.findAll(model, conditions)` accepts only an equality
|
|
689
|
-
* conditions object that the SQL drivers translate to a WHERE clause, so
|
|
690
|
-
* query-layer enforcement would require a breaking change to the published
|
|
691
|
-
* `access` contract. That belongs in #197, not in a security patch. Six of the
|
|
692
|
-
* seven surfaces fetch by primary key anyway, so this costs exactly one row.
|
|
693
|
-
*/
|
|
694
|
-
function isDenied(filter, record) {
|
|
695
|
-
if (typeof filter !== 'function')
|
|
696
|
-
return false;
|
|
697
|
-
// A predicate that throws is treated as a denial. Unguarded, a throw escapes
|
|
698
|
-
// to express's default handler, which answers 500 (with a stack trace outside
|
|
699
|
-
// NODE_ENV=production) while a missing id still answers 404 -- so a
|
|
700
|
-
// record-dependent throw re-separates "hidden" from "does not exist" and
|
|
701
|
-
// hands back the oracle this whole change exists to close.
|
|
702
|
-
try {
|
|
703
|
-
return !filter(record);
|
|
704
|
-
}
|
|
705
|
-
catch (error) {
|
|
706
|
-
// Denied, but not silently. A consumer predicate that throws on every
|
|
707
|
-
// record turns the whole collection into a 404 wall, and with no
|
|
708
|
-
// diagnostic that is indistinguishable from an empty database. `stonyx/log`
|
|
709
|
-
// is the module convention (see setup-rest-server.ts); optional-call
|
|
710
|
-
// because a consumer may not have configured the log types.
|
|
711
|
-
log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
|
|
712
|
-
return true;
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
190
|
export default class OrmRequest extends Request {
|
|
716
191
|
model;
|
|
717
192
|
access;
|
|
@@ -735,174 +210,37 @@ export default class OrmRequest extends Request {
|
|
|
735
210
|
if (queryFilterPredicate)
|
|
736
211
|
recordsToReturn = recordsToReturn.filter(queryFilterPredicate);
|
|
737
212
|
const baseUrl = getBaseUrl(request);
|
|
738
|
-
|
|
739
|
-
// verdict cache and the per-(type, id) decision cache, and both are
|
|
740
|
-
// worthless if it is rebuilt inside the map. Measured on this exact
|
|
741
|
-
// surface with no `include=`: 48 linkage entries collapse to 7 distinct
|
|
742
|
-
// (type, id) pairs.
|
|
743
|
-
const linkage = createLinkageFilter(request);
|
|
744
|
-
const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
|
|
213
|
+
const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
|
|
745
214
|
return buildResponse(data, request.query?.include, recordsToReturn, {
|
|
746
215
|
links: { self: `${baseUrl}/${pluralizedModel}` },
|
|
747
|
-
baseUrl
|
|
748
|
-
// THE SAME filter object the primary documents above were serialized
|
|
749
|
-
// with, deliberately: it carries the caches, and rebuilding one here
|
|
750
|
-
// would re-resolve every type (abofs/stonyx-orm#235).
|
|
751
|
-
linkage
|
|
216
|
+
baseUrl
|
|
752
217
|
});
|
|
753
218
|
};
|
|
754
|
-
const getSingleHandler = async (request
|
|
219
|
+
const getSingleHandler = async (request) => {
|
|
755
220
|
const record = await store.find(model, getId(request.params));
|
|
756
221
|
if (!record)
|
|
757
222
|
return 404;
|
|
758
|
-
// 404, never 403: the status for "exists but filtered out" must be
|
|
759
|
-
// identical to "does not exist", or the fix trades an authorization
|
|
760
|
-
// bypass for a narrower existence oracle.
|
|
761
|
-
if (isDenied(filter, record))
|
|
762
|
-
return 404;
|
|
763
223
|
const fieldsMap = parseFields(request.query);
|
|
764
224
|
const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
|
|
765
225
|
const baseUrl = getBaseUrl(request);
|
|
766
|
-
|
|
767
|
-
// `buildResponse` IS given the filter now (abofs/stonyx-orm#235), and it
|
|
768
|
-
// is the SAME object the primary document is serialized with -- one
|
|
769
|
-
// verdict per type for the whole response, sideload included.
|
|
770
|
-
//
|
|
771
|
-
// The boundary, so the next reader does not have to derive it: this
|
|
772
|
-
// closes what a record already in `included` may NAME. WHETHER a
|
|
773
|
-
// resource appears in `included` at all is MEMBERSHIP and it is
|
|
774
|
-
// abofs/stonyx-orm#233's. THAT IS NOW CLOSED TOO, and the same `linkage`
|
|
775
|
-
// object closes it: `buildResponse` hands this filter to
|
|
776
|
-
// `collectIncludedRecords`, which denies at the push site. Corrected
|
|
777
|
-
// rather than deleted -- this comment read "a hidden owner is still a
|
|
778
|
-
// member here", which is the sentence the identical copy in
|
|
779
|
-
// `buildResponse` carried and which #233 falsified in both places. They
|
|
780
|
-
// are still two questions and neither closes the other: a record can be
|
|
781
|
-
// a member while its own linkage is filtered.
|
|
782
|
-
return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
|
|
226
|
+
return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
|
|
783
227
|
links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
|
|
784
|
-
baseUrl
|
|
785
|
-
linkage
|
|
228
|
+
baseUrl
|
|
786
229
|
});
|
|
787
230
|
};
|
|
788
|
-
const createHandler = async (
|
|
789
|
-
// BOUND, not destructured (abofs/stonyx-orm#235). `HandlerFn` has always
|
|
790
|
-
// delivered the request as argument one; this handler simply discarded
|
|
791
|
-
// the binding, which is why its response document named ids every read
|
|
792
|
-
// surface withholds. `createLinkageFilter` needs the live request and
|
|
793
|
-
// there is no signature change involved in giving it one.
|
|
794
|
-
const { body, query } = request;
|
|
231
|
+
const createHandler = async ({ body, query }) => {
|
|
795
232
|
const { type, id, attributes, relationships: rels } = (body?.data || {});
|
|
796
233
|
if (!type)
|
|
797
234
|
return 400; // Bad request
|
|
798
235
|
const fieldsMap = parseFields(query);
|
|
799
236
|
const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
|
|
800
|
-
//
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
// records, so POST leaks existence through its STATUS. A previous revision
|
|
804
|
-
// filtered the collision status (403 when the colliding record is denied,
|
|
805
|
-
// 409 when it is visible) and that is NOT sufficient, because the status
|
|
806
|
-
// of a create is a third outcome. With a payload the caller is permitted
|
|
807
|
-
// to create -- the normative case for a per-tenant filter, and the case an
|
|
808
|
-
// attacker picks -- all three are distinguishable in ONE request per id:
|
|
809
|
-
//
|
|
810
|
-
// POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
|
|
811
|
-
// POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
|
|
812
|
-
// POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
|
|
813
|
-
//
|
|
814
|
-
// Filtering only the collision status narrows that to callers who cannot
|
|
815
|
-
// create a record they are allowed to see. It does not close it.
|
|
816
|
-
//
|
|
817
|
-
// It cannot be closed while a caller both chooses the id and learns
|
|
818
|
-
// whether the create succeeded: a successful create must answer
|
|
819
|
-
// differently from a refused one. So when a per-record filter is in force
|
|
820
|
-
// the caller does not get to choose the id at all. The refusal is
|
|
821
|
-
// UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
|
|
822
|
-
// lookup cost, can depend on whether that id exists. 403 -- the same
|
|
823
|
-
// status as a denied create -- so the two cannot be separated either.
|
|
824
|
-
//
|
|
825
|
-
// BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
|
|
826
|
-
// pinned by nothing:
|
|
827
|
-
//
|
|
828
|
-
// status -- assertion 22 sweeps payload x id x id-type, plus `null`.
|
|
829
|
-
// latency -- assertion 41 asserts NO `store.find` is issued on this
|
|
830
|
-
// path. Moving the refusal to after a lookup and returning
|
|
831
|
-
// the same 403 left the suite green while re-opening a
|
|
832
|
-
// hit-versus-miss timing difference on every id-bearing POST,
|
|
833
|
-
// which is what would turn #197 from a ~0.06ms post-fetch
|
|
834
|
-
// residual into a live timing oracle on create.
|
|
835
|
-
//
|
|
836
|
-
// AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
|
|
837
|
-
// the `id` member of the resource object, so it holds only while that is
|
|
838
|
-
// the ONLY way a caller id can reach `createRecord`. It was not: the
|
|
839
|
-
// relationships loop below re-admitted one under `key === "id"` and the
|
|
840
|
-
// gate never fired. Both strips -- `attributes.id` and `relationships.id`
|
|
841
|
-
// -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
|
|
842
|
-
// them. Adding a third channel without a strip re-opens the oracle.
|
|
843
|
-
//
|
|
844
|
-
// Scoped to function-style `access` because that is exactly the population
|
|
845
|
-
// the oracle exists for: with no per-record filter there are no hidden
|
|
846
|
-
// records, and 409 discloses nothing GET /:id does not already.
|
|
847
|
-
//
|
|
848
|
-
// RESIDUALS, stated rather than implied.
|
|
849
|
-
//
|
|
850
|
-
// - a caller can still learn that a collection HAS a per-record filter
|
|
851
|
-
// (403 rather than 409/200 for an id-bearing POST). That discloses a
|
|
852
|
-
// configuration fact, not a record.
|
|
853
|
-
// - this gate is about ids arriving on THIS model's create route. It
|
|
854
|
-
// says nothing about a write to ANOTHER collection: a `POST /owners`
|
|
855
|
-
// carrying `relationships: {pets: {data: {id: 21}}}` -- or
|
|
856
|
-
// `attributes: {pets: [21, 22]}`, which never enters the
|
|
857
|
-
// relationships loop at all -- re-parents hidden animal 21 onto an
|
|
858
|
-
// owner the caller may write, which changes the very field the
|
|
859
|
-
// animals predicate reads and DE-HIDES it. Blocking that needs animal
|
|
860
|
-
// 21 checked against the ANIMAL model's predicate while servicing an
|
|
861
|
-
// OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
|
|
862
|
-
// #207, blocked on #202 (`access` receives the model structurally)
|
|
863
|
-
// and #196 (setup-rest-server discards the model->predicate map at
|
|
864
|
-
// boot). NOT closed here, and no comment in this file may say it is.
|
|
865
|
-
//
|
|
866
|
-
// See README `### Known limitations`.
|
|
867
|
-
if (id !== undefined) {
|
|
868
|
-
if (typeof filter === 'function')
|
|
869
|
-
return 403; // Forbidden
|
|
870
|
-
// `normalizeBodyId`, not the raw value: a string-typed id misses the
|
|
871
|
-
// store's numeric key, which skipped this check entirely.
|
|
872
|
-
const existing = await store.find(model, normalizeBodyId(id));
|
|
873
|
-
if (existing)
|
|
874
|
-
return 409; // Conflict
|
|
875
|
-
}
|
|
237
|
+
// Check for duplicate ID
|
|
238
|
+
if (id !== undefined && await store.find(model, id))
|
|
239
|
+
return 409; // Conflict
|
|
876
240
|
const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
|
|
877
|
-
// Extract relationship IDs from JSON:API relationships object
|
|
878
|
-
//
|
|
879
|
-
// `key` comes VERBATIM from the request body, so `id` is stripped here for
|
|
880
|
-
// exactly the same reason it is stripped from `attributes` on the line
|
|
881
|
-
// above -- and it must be, or GATE 0 is walked around by moving one field:
|
|
882
|
-
//
|
|
883
|
-
// POST /animals {"id":21, ...} -> 403 GATE 0 fires
|
|
884
|
-
// POST /animals {"relationships":{"id":{"data":{"id":21}}},
|
|
885
|
-
// "attributes":{"owner":"gina"}} -> 200 BYPASS
|
|
886
|
-
//
|
|
887
|
-
// Top-level `id` stayed `undefined`, so GATE 0 never fired and the
|
|
888
|
-
// collision lookup never ran; `createRecord` took its last-entry-wins
|
|
889
|
-
// branch, overwrote hidden record 21 in place and reset its `owner` to a
|
|
890
|
-
// value the caller chose -- de-hiding it permanently. That is #190 itself,
|
|
891
|
-
// on the create surface. Pinned by assertion 39.
|
|
892
|
-
//
|
|
893
|
-
// The `id` member of the resource object is now the ONLY channel a caller
|
|
894
|
-
// id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
|
|
895
|
-
// GATE 0's guarantee checkable rather than merely asserted. It is not a
|
|
896
|
-
// statement about the record's reachability in general -- a relationship
|
|
897
|
-
// write on another collection reaches it without ever touching this
|
|
898
|
-
// handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
|
|
899
|
-
// loop verbatim; the general form -- the loop accepts any key, not just
|
|
900
|
-
// `id`, so a body key that is not a declared relationship is still
|
|
901
|
-
// mass-assigned -- is abofs/stonyx-orm#204.
|
|
241
|
+
// Extract relationship IDs from JSON:API relationships object
|
|
902
242
|
if (rels) {
|
|
903
243
|
for (const [key, value] of Object.entries(rels)) {
|
|
904
|
-
if (key === 'id')
|
|
905
|
-
continue;
|
|
906
244
|
const relData = value?.data;
|
|
907
245
|
if (relData && relData.id !== undefined) {
|
|
908
246
|
sanitizedAttributes[key] = relData.id;
|
|
@@ -910,163 +248,16 @@ export default class OrmRequest extends Request {
|
|
|
910
248
|
}
|
|
911
249
|
}
|
|
912
250
|
const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
|
|
913
|
-
|
|
914
|
-
// the predicate can run, and the rollback below must be able to prove the
|
|
915
|
-
// slot it removes is one THIS REQUEST created. Identity alone cannot
|
|
916
|
-
// prove it: when `assignRecordId` lands on an occupied id, `createRecord`
|
|
917
|
-
// mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
|
|
918
|
-
// is true for a record the request did not create. The map's size is the
|
|
919
|
-
// only O(1) signal that distinguishes an insert from an overwrite.
|
|
920
|
-
const slotsBefore = store.get(model)?.size ?? 0;
|
|
921
|
-
// THE ONE `createRecord` FAILURE THIS ROUTE ANSWERS RATHER THAN
|
|
922
|
-
// PROPAGATES, and it is narrow on purpose.
|
|
923
|
-
//
|
|
924
|
-
// `assignRecordId` throws when it cannot derive a free store key for a
|
|
925
|
-
// server-assigned id. Unguarded that rejection is auto-forwarded -- there
|
|
926
|
-
// is no catch here, none in @stonyx/rest-server's dispatcher
|
|
927
|
-
// (dist/request.js:41-70), and express 5 hands it to its default error
|
|
928
|
-
// handler, which serialises the STACK, with absolute install paths and the
|
|
929
|
-
// internal module graph, to an unauthenticated caller outside
|
|
930
|
-
// NODE_ENV=production. That is the hazard :553-558 already names in this
|
|
931
|
-
// file, and every sibling refusal in this handler returns an integer
|
|
932
|
-
// status instead. So this one returns 409, matching the client-duplicate
|
|
933
|
-
// refusal at :713: the caller asked for a record and the collection has no
|
|
934
|
-
// id to give it.
|
|
935
|
-
//
|
|
936
|
-
// MATCHED ON THE SHARED PREFIX, not on a literal, and NOT by catching
|
|
937
|
-
// everything: `createRecord` also throws for "ORM is not ready", a
|
|
938
|
-
// read-only view and an unregistered model store, and turning any of those
|
|
939
|
-
// into a 409 would report a configuration fault as a conflict. Anything
|
|
940
|
-
// else is re-thrown unchanged.
|
|
941
|
-
let created;
|
|
942
|
-
try {
|
|
943
|
-
created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
|
|
944
|
-
}
|
|
945
|
-
catch (error) {
|
|
946
|
-
if (!(error instanceof Error) || !error.message.startsWith(NO_FREE_ID_ERROR))
|
|
947
|
-
throw error;
|
|
948
|
-
// Not silently. A collection that can no longer assign an id is a
|
|
949
|
-
// configuration fault (a non-injective id transform), and a bare 409
|
|
950
|
-
// with no diagnostic is indistinguishable from an ordinary duplicate.
|
|
951
|
-
log.error?.(`[@stonyx/orm] ${error.message}`);
|
|
952
|
-
return 409; // Conflict
|
|
953
|
-
}
|
|
251
|
+
const created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
|
|
954
252
|
const record = isOrmRecord(created) ? created : null;
|
|
955
253
|
if (!record)
|
|
956
254
|
return 500;
|
|
957
|
-
|
|
958
|
-
// 403 here, NOT 404. The oracle argument does not apply to create: there
|
|
959
|
-
// is no pre-existing record whose existence could leak, the caller
|
|
960
|
-
// supplied the attributes, and 404 on a mounted collection route is
|
|
961
|
-
// indistinguishable from "model not mounted" -- a genuinely different
|
|
962
|
-
// failure a developer needs to diagnose.
|
|
963
|
-
//
|
|
964
|
-
// The rollback is not optional. createRecord writes to the store BEFORE
|
|
965
|
-
// the predicate can run, so returning 403 alone would leave the record
|
|
966
|
-
// behind: a worse bug than the bypass being fixed.
|
|
967
|
-
if (isDenied(filter, record)) {
|
|
968
|
-
// ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
|
|
969
|
-
// on its own is a write primitive keyed by a value the caller may have
|
|
970
|
-
// supplied: with the raw-id collision bypass above, a denied
|
|
971
|
-
// `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
|
|
972
|
-
// unauthenticated deletion primitive across the whole id space, created
|
|
973
|
-
// by adding a rollback to a lookup that could be skipped.
|
|
974
|
-
//
|
|
975
|
-
// Both conditions are required and neither implies the other:
|
|
976
|
-
// createdNewSlot -- the store grew, so this request inserted rather
|
|
977
|
-
// than overwrote. SURVIVOR AS OF #203, AND THAT IS
|
|
978
|
-
// WHAT THIS NOTE IS FOR. It used to be killable:
|
|
979
|
-
// `assignRecordId` returned last-INSERTED + 1, so a
|
|
980
|
-
// server-assigned id could land on an occupied slot,
|
|
981
|
-
// `createRecord` updated in place, and removing this
|
|
982
|
-
// half turned access-filter-enforcement-test.ts
|
|
983
|
-
// assertion 31 red. #203 closed that: the
|
|
984
|
-
// server-assigned path now walks past occupied keys,
|
|
985
|
-
// so no create reaching here can overwrite. Measured
|
|
986
|
-
// -- delete `createdNewSlot &&` below: `dev` gives
|
|
987
|
-
// 55 pass / 1 fail with assertion 31 RED, this tree
|
|
988
|
-
// gives 56 pass / 0 fail, GREEN.
|
|
989
|
-
// KEPT ANYWAY, AND NOT FOR THE OLD REASON. Without
|
|
990
|
-
// it a denied create becomes `store.remove` on a key
|
|
991
|
-
// the caller may have influenced, which :815-820
|
|
992
|
-
// records as having been an unauthenticated deletion
|
|
993
|
-
// primitive across the whole id space. BECOMES
|
|
994
|
-
// KILLABLE AGAIN the moment any caller-supplied id
|
|
995
|
-
// can reach `createRecord` from this handler --
|
|
996
|
-
// which is exactly what has-many.ts:65 and
|
|
997
|
-
// belongs-to.ts:45 already do for ANOTHER model's
|
|
998
|
-
// store (abofs/stonyx-orm#207), and what a third
|
|
999
|
-
// un-stripped id channel would do for this one
|
|
1000
|
-
// (#204). Do not delete it on the strength of #203
|
|
1001
|
-
// being closed; that is the reasoning :862-867 warns
|
|
1002
|
-
// about, one level up.
|
|
1003
|
-
// identity -- the slot still holds the object we just created,
|
|
1004
|
-
// so nothing between createRecord and here replaced
|
|
1005
|
-
// it. Deleting this half SURVIVES the suite, and it
|
|
1006
|
-
// is kept anyway. WHY IT IS REDUNDANT: there is no
|
|
1007
|
-
// `await` anywhere between `slotsBefore` and
|
|
1008
|
-
// `store.remove` -- the whole window is synchronous,
|
|
1009
|
-
// so it is atomic under Node's event loop; before-
|
|
1010
|
-
// `create` hooks run BEFORE the handler
|
|
1011
|
-
// (`_withHooks` runs its hook loop ahead of
|
|
1012
|
-
// `await handler(...)`), and a consumer predicate
|
|
1013
|
-
// inside `isDenied` runs AFTER `createdNewSlot` is
|
|
1014
|
-
// computed and cannot flip it. That is a property of
|
|
1015
|
-
// THIS function, not of GATE 0 -- an earlier note
|
|
1016
|
-
// credited GATE 0, which was both wrong (a caller id
|
|
1017
|
-
// reached createRecord through the relationships
|
|
1018
|
-
// loop, #204) and the wrong kind of reason: a guard
|
|
1019
|
-
// justified on code sixty lines upstream gets
|
|
1020
|
-
// silently re-armed when that code moves.
|
|
1021
|
-
// SO IT BECOMES REACHABLE IF AN `await` IS
|
|
1022
|
-
// INTRODUCED HERE, which is the change a future
|
|
1023
|
-
// editor would actually make. Stated here rather
|
|
1024
|
-
// than by reference: `docs/` is not in `files`, so
|
|
1025
|
-
// a pointer into it resolves to nothing for anyone
|
|
1026
|
-
// who installed this package. README carries the
|
|
1027
|
-
// consumer-facing half.
|
|
1028
|
-
if (createdNewSlot && store.get(model, record.id) === record) {
|
|
1029
|
-
store.remove(model, record.id, { _skipAutoPersist: true });
|
|
1030
|
-
}
|
|
1031
|
-
return 403;
|
|
1032
|
-
}
|
|
1033
|
-
// The filter is built HERE, per invocation, and never hoisted into the
|
|
1034
|
-
// OrmRequest constructor where the other per-mount values live: a verdict
|
|
1035
|
-
// cached across requests answers a second caller with the first caller's
|
|
1036
|
-
// authorization (src/access-verdict.ts says so at the constructor an
|
|
1037
|
-
// implementer would reach for).
|
|
1038
|
-
//
|
|
1039
|
-
// AND IT IS BUILT AFTER `createRecord`, AFTER THE ROLLBACK WINDOW AND
|
|
1040
|
-
// AFTER `isDenied`, so the record is in its final form at the call. The
|
|
1041
|
-
// filter is lazy per type and per (type, id), so it cannot observe a
|
|
1042
|
-
// pre-write state even if it were built earlier.
|
|
1043
|
-
//
|
|
1044
|
-
// `fields` is passed here and NOT in `updateHandler`: the two handlers
|
|
1045
|
-
// are asymmetric on purpose (`updateHandler` has no `fieldsMap` in
|
|
1046
|
-
// scope), and a single copy-pasted wiring would drop it from one of them.
|
|
1047
|
-
return { data: record.toJSON?.({ fields: modelFields, linkage: createLinkageFilter(request) }) };
|
|
255
|
+
return { data: record.toJSON?.({ fields: modelFields }) };
|
|
1048
256
|
};
|
|
1049
|
-
const updateHandler = async (
|
|
1050
|
-
// Bound rather than destructured, for the reason given in
|
|
1051
|
-
// `createHandler` above (abofs/stonyx-orm#235). `PATCH /animals/1`
|
|
1052
|
-
// returned 200 naming angela seconds after `GET /animals/1` returned
|
|
1053
|
-
// `owner.data: null` for the same record -- one HTTP verb apart.
|
|
1054
|
-
const { body, params } = request;
|
|
257
|
+
const updateHandler = async ({ body, params }) => {
|
|
1055
258
|
const found = await store.find(model, getId(params));
|
|
1056
259
|
if (!found || !isOrmRecord(found))
|
|
1057
260
|
return 404;
|
|
1058
|
-
// Checked BEFORE any attribute is applied. 404 rather than 403 for the
|
|
1059
|
-
// same reason as GET /:id -- 403 would disclose both that the record
|
|
1060
|
-
// exists and that this caller specifically is excluded.
|
|
1061
|
-
//
|
|
1062
|
-
// NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
|
|
1063
|
-
// verdict is computed BEFORE the before-hook loop runs, and a before-hook
|
|
1064
|
-
// is a published extension point that can change the answer -- by
|
|
1065
|
-
// mutating the record, or against a predicate that closes over
|
|
1066
|
-
// per-request state. This is the only re-evaluation after that window.
|
|
1067
|
-
// Pinned by assertion 32; deleting it turns a 404 into an applied update.
|
|
1068
|
-
if (isDenied(filter, found))
|
|
1069
|
-
return 404;
|
|
1070
261
|
const record = found;
|
|
1071
262
|
const { attributes, relationships: rels } = (body?.data || {});
|
|
1072
263
|
if (!attributes && !rels)
|
|
@@ -1086,19 +277,6 @@ export default class OrmRequest extends Request {
|
|
|
1086
277
|
if (rels) {
|
|
1087
278
|
const relUpdates = {};
|
|
1088
279
|
for (const [key, value] of Object.entries(rels)) {
|
|
1089
|
-
// The same missing key filter as createHandler's, and as the
|
|
1090
|
-
// attribute loop directly above -- which already had it, while this
|
|
1091
|
-
// loop did not. A PATCH carrying
|
|
1092
|
-
// `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
|
|
1093
|
-
// and RE-KEYED the record: the object held under store key 9102 then
|
|
1094
|
-
// reported id 9101, so a visible record claimed a hidden record's
|
|
1095
|
-
// identity on every surface that reads `record.id` rather than the map
|
|
1096
|
-
// key. Gated by GATE 1 on the addressed record, so it is store
|
|
1097
|
-
// corruption rather than a filter bypass -- but it is the same one-line
|
|
1098
|
-
// omission two handlers apart. Pinned by assertion 40; INHERITED from
|
|
1099
|
-
// `dev`; abofs/stonyx-orm#204.
|
|
1100
|
-
if (key === 'id')
|
|
1101
|
-
continue;
|
|
1102
280
|
const relData = value?.data;
|
|
1103
281
|
if (relData && relData.id !== undefined) {
|
|
1104
282
|
relUpdates[key] = relData.id;
|
|
@@ -1108,40 +286,10 @@ export default class OrmRequest extends Request {
|
|
|
1108
286
|
updateRecord(record, relUpdates, { _skipAutoPersist: true });
|
|
1109
287
|
}
|
|
1110
288
|
}
|
|
1111
|
-
|
|
1112
|
-
// `fieldsMap` in scope, and adding `baseUrl` would put `links` on a
|
|
1113
|
-
// document that has never carried them -- an unrelated behaviour change.
|
|
1114
|
-
// #224 AC6's "emits `data: []` WITH links" is a statement about the READ
|
|
1115
|
-
// surfaces; on these two handlers a filtered relationship and a
|
|
1116
|
-
// genuinely-empty one are both a bare `{ data }`, which is what makes
|
|
1117
|
-
// them indistinguishable here too.
|
|
1118
|
-
return { data: record.toJSON?.({ linkage: createLinkageFilter(request) }) };
|
|
289
|
+
return { data: record.toJSON?.() };
|
|
1119
290
|
};
|
|
1120
|
-
const deleteHandler =
|
|
1121
|
-
|
|
1122
|
-
// the record and once to remove it -- and a coercion evaluated repeatedly
|
|
1123
|
-
// is a coercion that can be edited in one place and not the other, which
|
|
1124
|
-
// is the defect `coerceId` exists to prevent.
|
|
1125
|
-
const recordId = getId(params);
|
|
1126
|
-
const record = await store.find(model, recordId);
|
|
1127
|
-
// BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
|
|
1128
|
-
// returned 204 before this change. It now returns 404, matching the
|
|
1129
|
-
// denied case below. This is deliberate and load-bearing -- if a denied
|
|
1130
|
-
// delete returned 404 while a missing one returned 204, the pair would be
|
|
1131
|
-
// a perfect existence oracle and the whole fix would be worthless.
|
|
1132
|
-
// Returning 204 for a denied delete was rejected instead: it falsely
|
|
1133
|
-
// reports success for a request that changed nothing.
|
|
1134
|
-
if (!record)
|
|
1135
|
-
return 404;
|
|
1136
|
-
// Re-evaluated after the before-hook loop, exactly as in updateHandler --
|
|
1137
|
-
// GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
|
|
1138
|
-
// turns a 404 into a destroyed record.
|
|
1139
|
-
if (isDenied(filter, record))
|
|
1140
|
-
return 404;
|
|
1141
|
-
// Removed by the id of the record actually fetched, not by re-deriving it
|
|
1142
|
-
// from the params a second time: the record the filter tested and the
|
|
1143
|
-
// record removed are then provably the same one.
|
|
1144
|
-
store.remove(model, record.id, { _skipAutoPersist: true });
|
|
291
|
+
const deleteHandler = ({ params }) => {
|
|
292
|
+
store.remove(model, getId(params), { _skipAutoPersist: true });
|
|
1145
293
|
return 204;
|
|
1146
294
|
};
|
|
1147
295
|
// Wrap handlers with hooks
|
|
@@ -1166,63 +314,9 @@ export default class OrmRequest extends Request {
|
|
|
1166
314
|
};
|
|
1167
315
|
}
|
|
1168
316
|
}
|
|
1169
|
-
// Wraps a handler with before/after hook execution
|
|
1170
|
-
//
|
|
1171
|
-
// ===========================================================================
|
|
1172
|
-
// TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
|
|
1173
|
-
//
|
|
1174
|
-
// The defect this function was fixed for is NOT "a delete persists past a
|
|
1175
|
-
// 404". It is that _withHooks has SEVERAL executors downstream of the
|
|
1176
|
-
// handler, and originally the handler's response gated none of them. Three
|
|
1177
|
-
// exist today:
|
|
1178
|
-
//
|
|
1179
|
-
// 1. sqlDb.persist -- issues real SQL against the backing store
|
|
1180
|
-
// 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
|
|
1181
|
-
// a cascade delete, a webhook, a search-index
|
|
1182
|
-
// purge. `context.recordId` and
|
|
1183
|
-
// `context.oldState` are populated for it.
|
|
1184
|
-
// 3. Orm.db.save() -- a full serialize-and-write of the store
|
|
1185
|
-
//
|
|
1186
|
-
// Gating them one at a time is how this keeps regressing, so the rule is:
|
|
1187
|
-
// compute denial ONCE at each point where it becomes knowable, and keep every
|
|
1188
|
-
// executor downstream of a gate. If you add a fourth executor to this
|
|
1189
|
-
// function, it goes below GATE 2 or it is a security bug.
|
|
1190
|
-
//
|
|
1191
|
-
// GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
|
|
1192
|
-
// run/are built BEFORE the handler can consult the filter. Without it a denied
|
|
1193
|
-
// DELETE still handed the hidden record's full contents to consumer code.
|
|
1194
|
-
// GATE 2 (post-handler) covers everything the handler's status can reach.
|
|
1195
|
-
// ===========================================================================
|
|
317
|
+
// Wraps a handler with before/after hook execution
|
|
1196
318
|
_withHooks(operation, handler) {
|
|
1197
319
|
return async (request, state) => {
|
|
1198
|
-
// `|| {}` so this function behaves like the relationship routes below,
|
|
1199
|
-
// which declare `state` with a `= {}` default. It is unkillable through
|
|
1200
|
-
// the rest-server dispatcher, which always passes `getState(req)`; it is
|
|
1201
|
-
// listed as such in the guards-redundant-by-construction table rather
|
|
1202
|
-
// than left silently unkillable, and it defends the WHOLE function (the
|
|
1203
|
-
// context, the snapshot and the handler call all read `callState`) rather
|
|
1204
|
-
// than one destructure that the next line would throw past anyway.
|
|
1205
|
-
const callState = (state || {});
|
|
1206
|
-
// ---------------------------------------------------------------------
|
|
1207
|
-
// THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
|
|
1208
|
-
// can run.
|
|
1209
|
-
//
|
|
1210
|
-
// `callState` is the object `auth()` planted the filter in, and it is
|
|
1211
|
-
// also handed to every before-hook as `context.state` -- a published,
|
|
1212
|
-
// WRITABLE extension point. So `state.filter` is an INPUT to the
|
|
1213
|
-
// authorization decision, not only an output channel, and re-reading it
|
|
1214
|
-
// after the hook loop lets a consumer hook disarm the filter:
|
|
1215
|
-
//
|
|
1216
|
-
// beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
|
|
1217
|
-
// -> GET /animals/21 turned 404 into 200
|
|
1218
|
-
// -> GET /animals turned 20 records into 22
|
|
1219
|
-
//
|
|
1220
|
-
// GATE 1 already used this snapshot, so writes held; the READ handlers
|
|
1221
|
-
// re-destructured `filter` from the live bag and did not. Everything
|
|
1222
|
-
// downstream now reads `filter` from here, and the handler is handed
|
|
1223
|
-
// `handlerState` below -- never `callState`.
|
|
1224
|
-
// ---------------------------------------------------------------------
|
|
1225
|
-
const { filter } = callState;
|
|
1226
320
|
// Build context object for hooks
|
|
1227
321
|
const context = {
|
|
1228
322
|
model: this.model,
|
|
@@ -1231,35 +325,11 @@ export default class OrmRequest extends Request {
|
|
|
1231
325
|
params: request.params,
|
|
1232
326
|
body: request.body,
|
|
1233
327
|
query: request.query,
|
|
1234
|
-
|
|
1235
|
-
// it by @stonyx/rest-server after the handler returns, so hooks must be
|
|
1236
|
-
// able to write to it. What must not happen is the authorization
|
|
1237
|
-
// decision reading it back, which is what the snapshot above prevents.
|
|
1238
|
-
state: callState,
|
|
328
|
+
state,
|
|
1239
329
|
};
|
|
1240
330
|
// Capture old state for operations that modify data
|
|
1241
331
|
if (operation === 'update' || operation === 'delete') {
|
|
1242
332
|
const existingRecord = await store.find(this.model, getId(request.params));
|
|
1243
|
-
// GATE 1 -- pre-handler. This record fetch already happened for
|
|
1244
|
-
// oldState, so the check is free.
|
|
1245
|
-
//
|
|
1246
|
-
// Returning here rather than letting updateHandler/deleteHandler
|
|
1247
|
-
// produce the same 404 is the point: everything between here and there
|
|
1248
|
-
// is an executor the caller is not authorized to reach.
|
|
1249
|
-
// - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
|
|
1250
|
-
// Building it and handing it to a before-hook discloses exactly what
|
|
1251
|
-
// the filter exists to hide.
|
|
1252
|
-
// - context.recordId is populated for delete BEFORE the handler runs,
|
|
1253
|
-
// which is the same shape as the sqlDb landmine one layer up:
|
|
1254
|
-
// `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
|
|
1255
|
-
// children behind a correct 404.
|
|
1256
|
-
// - a before-hook may return a value and short-circuit, which would
|
|
1257
|
-
// otherwise return a response without the filter ever executing.
|
|
1258
|
-
//
|
|
1259
|
-
// 404, not 403, for the same reason as getSingleHandler: the status for
|
|
1260
|
-
// "exists but filtered out" must equal "does not exist".
|
|
1261
|
-
if (existingRecord && isDenied(filter, existingRecord))
|
|
1262
|
-
return 404;
|
|
1263
333
|
if (existingRecord) {
|
|
1264
334
|
// Deep copy the record's data to preserve old state
|
|
1265
335
|
context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
|
|
@@ -1277,49 +347,14 @@ export default class OrmRequest extends Request {
|
|
|
1277
347
|
}
|
|
1278
348
|
}
|
|
1279
349
|
// Execute main handler
|
|
1280
|
-
|
|
1281
|
-
// assigned LAST so it wins over anything a before-hook wrote to
|
|
1282
|
-
// `callState.filter` -- including a `delete`, which the spread would
|
|
1283
|
-
// otherwise carry through as an absent key. Every other key a hook adds
|
|
1284
|
-
// is still visible to the handler; only the authorization input is
|
|
1285
|
-
// pinned.
|
|
1286
|
-
const handlerState = { ...callState, filter };
|
|
1287
|
-
const response = await handler(request, handlerState);
|
|
350
|
+
const response = await handler(request, state);
|
|
1288
351
|
// Set context.record for update BEFORE persist so SQL drivers can read it
|
|
1289
352
|
if (operation === 'update' && response?.data) {
|
|
1290
353
|
context.record = store.get(this.model, getId(request.params));
|
|
1291
354
|
}
|
|
1292
|
-
//
|
|
1293
|
-
// integer, and no executor below may run for one.
|
|
1294
|
-
//
|
|
1295
|
-
// `>= 400` deliberately covers every failure status, not just the
|
|
1296
|
-
// authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
|
|
1297
|
-
// are equally requests in which nothing happened, and a persist or a
|
|
1298
|
-
// cascade hook for one of them is just as wrong.
|
|
1299
|
-
// `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
|
|
1300
|
-
// unkillable TODAY: the only non-integer a handler in this file can
|
|
1301
|
-
// return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
|
|
1302
|
-
// coercion, so dropping it changes no reachable outcome. It is kept
|
|
1303
|
-
// because `>=` coerces rather than rejects, and the shapes it coerces
|
|
1304
|
-
// are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
|
|
1305
|
-
// returned an array would have every response read as a denial. Listed
|
|
1306
|
-
// as an equivalent mutant rather than left to read as coverage; it
|
|
1307
|
-
// becomes killable the moment a handler returns anything array-like or
|
|
1308
|
-
// numeric-string-like.
|
|
1309
|
-
const denied = Number.isInteger(response) && response >= 400;
|
|
1310
|
-
// EXECUTOR 1 -- SQL persistence, for all write operations.
|
|
1311
|
-
//
|
|
1312
|
-
// `response` is passed to sqlDb.persist below, but it is dropped at the
|
|
1313
|
-
// driver boundary: _persistDelete(modelName, context) never receives it
|
|
1314
|
-
// and guards only on context.recordId -- which _withHooks set above,
|
|
1315
|
-
// BEFORE the handler ran. Without this gate a correct 404 still issues
|
|
1316
|
-
// DELETE FROM ... WHERE id = ? on every SQL backend.
|
|
1317
|
-
//
|
|
1318
|
-
// No file-backed test can observe that, because Orm.instance.sqlDb is
|
|
1319
|
-
// null in file/directory mode. See the stubbed-sqlDb assertions in
|
|
1320
|
-
// test/unit/access-filter-enforcement-test.ts.
|
|
355
|
+
// Persist to SQL database for all write operations (create/update/delete)
|
|
1321
356
|
const sqlDb = Orm.instance.sqlDb;
|
|
1322
|
-
if (sqlDb && WRITE_OPERATIONS.has(operation)
|
|
357
|
+
if (sqlDb && WRITE_OPERATIONS.has(operation)) {
|
|
1323
358
|
await sqlDb.persist(operation, this.model, context, response);
|
|
1324
359
|
}
|
|
1325
360
|
// Add response and relevant records to context
|
|
@@ -1333,44 +368,19 @@ export default class OrmRequest extends Request {
|
|
|
1333
368
|
else if (operation === 'create' && response?.data && (response.data.id)) {
|
|
1334
369
|
// For create, get the record from store using the ID from the response
|
|
1335
370
|
const responseData = response.data;
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
// third coercion feeding a store lookup, sitting under a docblock that
|
|
1339
|
-
// said neither surface had a copy. Equivalent on every input that can
|
|
1340
|
-
// reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
|
|
1341
|
-
// `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
|
|
1342
|
-
// de-duplication rather than a behaviour change -- and that is the
|
|
1343
|
-
// point: the two that disagreed were equivalent on every input anyone
|
|
1344
|
-
// checked, too.
|
|
1345
|
-
context.record = store.get(this.model, normalizeBodyId(responseData.id));
|
|
371
|
+
const recordId = isNaN(responseData.id) ? responseData.id : parseInt(responseData.id);
|
|
372
|
+
context.record = store.get(this.model, recordId);
|
|
1346
373
|
}
|
|
1347
374
|
else if (operation === 'delete') {
|
|
1348
375
|
// For delete, the record may no longer exist, but we have oldState
|
|
1349
376
|
context.recordId = getId(request.params);
|
|
1350
377
|
}
|
|
1351
|
-
//
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
// a cascade delete, a webhook, a token revocation, a search-index purge.
|
|
1355
|
-
//
|
|
1356
|
-
// BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
|
|
1357
|
-
// failed. Previously `afterHook('delete', ...)` ran with a populated
|
|
1358
|
-
// context.recordId on a 404, so a consumer cascade destroyed children for
|
|
1359
|
-
// a request that deleted nothing. Firing a hook named "after<operation>"
|
|
1360
|
-
// for an operation that did not occur is a booby trap, and the denied case
|
|
1361
|
-
// is unreachable-before-#190 while the missing case is inherited debt --
|
|
1362
|
-
// both are closed by the same gate. `context.response` therefore only ever
|
|
1363
|
-
// carries a success status into a hook.
|
|
1364
|
-
if (!denied) {
|
|
1365
|
-
for (const hook of getAfterHooks(operation, this.model)) {
|
|
1366
|
-
await hook(context);
|
|
1367
|
-
}
|
|
378
|
+
// Run after hooks sequentially
|
|
379
|
+
for (const hook of getAfterHooks(operation, this.model)) {
|
|
380
|
+
await hook(context);
|
|
1368
381
|
}
|
|
1369
|
-
//
|
|
1370
|
-
|
|
1371
|
-
// store on every DELETE of any id, with no record touched: amplification
|
|
1372
|
-
// rather than corruption, but the same root cause and the same fix.
|
|
1373
|
-
if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
|
|
382
|
+
// Auto-save DB after write operations when configured
|
|
383
|
+
if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
|
|
1374
384
|
await Orm.db.save();
|
|
1375
385
|
}
|
|
1376
386
|
return response;
|
|
@@ -1382,119 +392,21 @@ export default class OrmRequest extends Request {
|
|
|
1382
392
|
// Dasherize the relationship name for URL paths (e.g., accessLinks -> access-links)
|
|
1383
393
|
const dasherizedName = camelCaseToKebabCase(relationshipName);
|
|
1384
394
|
// Related resource route: GET /:id/{relationship}
|
|
1385
|
-
|
|
1386
|
-
// These generated routes are not wrapped by _withHooks, which is why they
|
|
1387
|
-
// were the least obvious two of the seven unguarded surfaces in #190.
|
|
1388
|
-
// They are still dispatched by @stonyx/rest-server as
|
|
1389
|
-
// `handler(req, getState(req))`, so `state` -- and therefore the filter
|
|
1390
|
-
// planted by auth() -- has always been available here; it was simply
|
|
1391
|
-
// never declared or read.
|
|
1392
|
-
routes[`/:id/${dasherizedName}`] = async (request, { filter } = {}) => {
|
|
395
|
+
routes[`/:id/${dasherizedName}`] = async (request) => {
|
|
1393
396
|
const record = await store.find(model, getId(request.params));
|
|
1394
397
|
if (!record)
|
|
1395
398
|
return 404;
|
|
1396
|
-
// Filtering the PARENT: a caller who may not see the record may not see
|
|
1397
|
-
// what it is related to either.
|
|
1398
|
-
if (isDenied(filter, record))
|
|
1399
|
-
return 404;
|
|
1400
399
|
const relatedData = record.__relationships[relationshipName];
|
|
1401
400
|
const baseUrl = getBaseUrl(request);
|
|
1402
|
-
// ONE FILTER, TWO JOBS, AND abofs/stonyx-orm#232 IS THE SECOND ONE.
|
|
1403
|
-
//
|
|
1404
|
-
// As LINKAGE (#234) it decides which ids the emitted documents may NAME
|
|
1405
|
-
// in their own `relationships.*.data`. As MEMBERSHIP (this issue) it
|
|
1406
|
-
// decides whether the related record is served here AT ALL -- the
|
|
1407
|
-
// related resource is PRIMARY data on this route, so there is no
|
|
1408
|
-
// linkage-consistency question to answer separately.
|
|
1409
|
-
//
|
|
1410
|
-
// Until #232 this route filtered only the PARENT, so a record its own
|
|
1411
|
-
// model's predicate hides was served in full from another model's
|
|
1412
|
-
// route, at ZERO query parameters. Measured on dev @ 8dda5d6:
|
|
1413
|
-
//
|
|
1414
|
-
// GET /owners/angela -> 404
|
|
1415
|
-
// GET /animals/1/owner -> 200, owner:angela, full attributes
|
|
1416
|
-
// GET /traits/2/tag -> 200, a model NO access class
|
|
1417
|
-
// claims, on a collection that has
|
|
1418
|
-
// no mounted route at all
|
|
1419
|
-
//
|
|
1420
|
-
// ARGUMENT ONE IS THE LIVE REQUEST, NOT A DERIVED ONE. A fabricated
|
|
1421
|
-
// request addressing the RELATED resource was the original design and
|
|
1422
|
-
// it is dropped: #241 removed the shipped fixture's read of argument
|
|
1423
|
-
// one, so a fabricated value changes nothing it could observe.
|
|
1424
|
-
// `createLinkageFilter` is also a published public export
|
|
1425
|
-
// (src/index.ts) whose resolution granularity is per TYPE; supplying a
|
|
1426
|
-
// per-RECORD request would mean widening it, which takes a consumer
|
|
1427
|
-
// `access()` from ~2 calls to ~7 on a plain `GET /animals`. That is a
|
|
1428
|
-
// separate, consumer-visible story.
|
|
1429
|
-
//
|
|
1430
|
-
// GUARDED BY OWN-PROPERTY IDENTITY, NOT BY THE #234 AC13 PIN. That pin
|
|
1431
|
-
// (test/unit/linkage-verdict-test.ts, `strictEqual(seen[0].request,
|
|
1432
|
-
// READ_REQUEST)`) calls `createLinkageFilter` DIRECTLY, so it pins the
|
|
1433
|
-
// function's pass-through and constrains no call site -- an earlier
|
|
1434
|
-
// revision of this comment cited it for this decision and was wrong.
|
|
1435
|
-
// `Object.create(request)` here measured 1015 / 0 with nothing red.
|
|
1436
|
-
// test/integration/orm-test.ts, `#232 AC9`, now asserts that the object
|
|
1437
|
-
// the predicate is handed OWNS `params` (`Object.hasOwn`) and has
|
|
1438
|
-
// nothing request-shaped behind it on the prototype chain. A derived
|
|
1439
|
-
// request inherits `params` -- so it satisfies every value assertion
|
|
1440
|
-
// there -- and reds on those two. Measured: with the derived request in
|
|
1441
|
-
// place, 1014 / 1, and that one is this guard.
|
|
1442
|
-
//
|
|
1443
|
-
// THE RESIDUAL THAT FOLLOWS FROM THAT IS DISCLOSED, NOT PAPERED OVER.
|
|
1444
|
-
// `recordId` is `null` here and the request names a record of a
|
|
1445
|
-
// DIFFERENT model, so a consumer predicate can express a model-level or
|
|
1446
|
-
// a request-level deny for a related resource, but NOT a per-record
|
|
1447
|
-
// one. README.md and docs/usage-patterns.md say so; a ledger assertion
|
|
1448
|
-
// in test/unit/relationship-route-access-test.ts keeps them saying it.
|
|
1449
|
-
const linkage = createLinkageFilter(request);
|
|
1450
|
-
// FAIL CLOSED ON A RECORD WHOSE TYPE CANNOT BE NAMED. `isLinkable` is
|
|
1451
|
-
// keyed on the model name; without one there is no predicate to ask,
|
|
1452
|
-
// and an unidentifiable input must never be the permissive path.
|
|
1453
|
-
const isLinkable = (r) => {
|
|
1454
|
-
const type = r.__model?.__name;
|
|
1455
|
-
return typeof type === 'string' && type !== '' && linkage(type, r);
|
|
1456
|
-
};
|
|
1457
401
|
let data;
|
|
1458
402
|
if (info.isArray) {
|
|
1459
|
-
// hasMany - return array
|
|
1460
|
-
// Dropped, never errored: the result is byte-identical to a genuinely
|
|
1461
|
-
// empty relationship, so this route is not an existence oracle.
|
|
403
|
+
// hasMany - return array
|
|
1462
404
|
const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
|
|
1463
|
-
data = related.
|
|
405
|
+
data = related.map(r => r.toJSON?.({ baseUrl }));
|
|
1464
406
|
}
|
|
1465
407
|
else {
|
|
1466
|
-
// belongsTo - return single or null
|
|
1467
|
-
|
|
1468
|
-
// same reason the hasMany branch above drops rather than errors: this
|
|
1469
|
-
// route must not be an existence oracle for the RELATED record.
|
|
1470
|
-
//
|
|
1471
|
-
// THE OTHER SPELLING WAS 404 AND IT WAS MEASURED AS A DISCLOSURE.
|
|
1472
|
-
// Unauthenticated, zero query parameters, one request each, on `tag`
|
|
1473
|
-
// -- the model with no route mounted at all, which is exactly what
|
|
1474
|
-
// #240 AC5 exists to protect:
|
|
1475
|
-
//
|
|
1476
|
-
// GET /traits/1/tag [ABSENT] -> 200 application/json len 68
|
|
1477
|
-
// GET /traits/2/tag [DENIED] -> 404 text/plain len 9
|
|
1478
|
-
//
|
|
1479
|
-
// and `GET /traits/1` and `GET /traits/2` both report
|
|
1480
|
-
// `relationships.tag = {"data":null}` byte-identical modulo the id,
|
|
1481
|
-
// because #234 closed THAT oracle deliberately. A 404 here would let
|
|
1482
|
-
// a caller ask which of those two nulls was a denial. Under
|
|
1483
|
-
// `data: null` the pair closes completely: 200/200, same
|
|
1484
|
-
// content-type, same content-length, bodies identical modulo the
|
|
1485
|
-
// parent id the caller put in the URL. It opens nothing -- `links`
|
|
1486
|
-
// are entirely parent-derived, there is no `meta` and no counts.
|
|
1487
|
-
//
|
|
1488
|
-
// This is also what README.md's module-wide rule already demanded:
|
|
1489
|
-
// every status on a record route must be identical for filtered-out
|
|
1490
|
-
// and does-not-exist. The route now CONFORMS to that rule rather than
|
|
1491
|
-
// carving an exception out of it.
|
|
1492
|
-
if (!isOrmRecord(relatedData))
|
|
1493
|
-
data = null;
|
|
1494
|
-
else if (!isLinkable(relatedData))
|
|
1495
|
-
data = null;
|
|
1496
|
-
else
|
|
1497
|
-
data = relatedData.toJSON?.({ baseUrl, linkage });
|
|
408
|
+
// belongsTo - return single or null
|
|
409
|
+
data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
|
|
1498
410
|
}
|
|
1499
411
|
return {
|
|
1500
412
|
links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}/${dasherizedName}` },
|
|
@@ -1502,99 +414,23 @@ export default class OrmRequest extends Request {
|
|
|
1502
414
|
};
|
|
1503
415
|
};
|
|
1504
416
|
// Relationship linkage route: GET /:id/relationships/{relationship}
|
|
1505
|
-
|
|
1506
|
-
// NO `linkage` FILTER FROM abofs/stonyx-orm#235, AND THAT IS A SCOPE
|
|
1507
|
-
// BOUNDARY RATHER THAN AN OVERSIGHT -- abofs/stonyx-orm#232 OWNS THIS
|
|
1508
|
-
// ROUTE, and PR #247 is IN FLIGHT against it in this same sprint. If you
|
|
1509
|
-
// are reading this after #247 landed, the filtering below is #232's and
|
|
1510
|
-
// this note records why it was never #235's to add.
|
|
1511
|
-
//
|
|
1512
|
-
// The three sites #235 does own -- `buildResponse`'s `included`, and the
|
|
1513
|
-
// two write handlers, `POST /:models` and `PATCH /:models/:id` -- all
|
|
1514
|
-
// reach the filter through `record.toJSON()`, which is where the
|
|
1515
|
-
// `linkage` OPTION is applied.
|
|
1516
|
-
//
|
|
1517
|
-
// The related-resource branch above ALSO passes a `linkage` filter, and
|
|
1518
|
-
// it is NOT one of those three: it is abofs/stonyx-orm#234's code and
|
|
1519
|
-
// predates this change. `git diff 8dda5d6..HEAD -- src/orm-request.ts`
|
|
1520
|
-
// leaves that branch byte-unchanged.
|
|
1521
|
-
//
|
|
1522
|
-
// This branch builds its `{ type, id }` objects BY
|
|
1523
|
-
// HAND and never calls `toJSON` at all, so the `linkage` option cannot
|
|
1524
|
-
// reach it -- whatever this route filters, it has to filter itself, which
|
|
1525
|
-
// is precisely why doing so is a separate change with a separate owner.
|
|
1526
|
-
//
|
|
1527
|
-
// It is also a DIFFERENT QUESTION. Everywhere #235 touches, linkage is
|
|
1528
|
-
// metadata ABOUT a document. Here the linkage IS the primary data, so
|
|
1529
|
-
// dropping an entry is a MEMBERSHIP decision about what this route
|
|
1530
|
-
// serves -- the same class as abofs/stonyx-orm#233 and #196, not the
|
|
1531
|
-
// class #234/#235 close. That is why it is absent from #224 §2a's
|
|
1532
|
-
// seven-site inventory.
|
|
1533
|
-
//
|
|
1534
|
-
// MEASURED, so the next person does not re-derive it. Against this
|
|
1535
|
-
// branch's baseline of 1011/0, wiring `createLinkageFilter` into the
|
|
1536
|
-
// belongsTo branch below takes the suite to 1009/2, reddening
|
|
1537
|
-
// `[GUARD] #235 X2` and the
|
|
1538
|
-
// `GET /animals/:id/relationships/owner returns relationship linkage`
|
|
1539
|
-
// test -- the latter is #232's own reproduction, not a regression.
|
|
1540
|
-
//
|
|
1541
|
-
// THE BASELINE IS QUOTED WITH THE RESULT BECAUSE AN EARLIER REVISION OF
|
|
1542
|
-
// THIS COMMENT SAID 993/2 AND SHIPPED IT. This file lands in consumers'
|
|
1543
|
-
// `node_modules`, so a wrong number here is a wrong number in the
|
|
1544
|
-
// published package. 993+2 = 995 is the DEV baseline, carried over from
|
|
1545
|
-
// a branch on which `[GUARD] #235 X2` does not exist. A pass/fail pair
|
|
1546
|
-
// with no baseline beside it cannot be checked by reading, which is how
|
|
1547
|
-
// it survived three artifacts and a review; the qualitative claim was
|
|
1548
|
-
// right the whole time and only the count was wrong.
|
|
1549
|
-
//
|
|
1550
|
-
// `[GUARD] #235 X2` in test/integration/orm-test.ts pins the OWNERSHIP
|
|
1551
|
-
// BOUNDARY here rather than this route's current answer, so that it
|
|
1552
|
-
// survives #247 landing. Read its comment before changing it.
|
|
1553
|
-
routes[`/:id/relationships/${dasherizedName}`] = async (request, { filter } = {}) => {
|
|
417
|
+
routes[`/:id/relationships/${dasherizedName}`] = async (request) => {
|
|
1554
418
|
const record = await store.find(model, getId(request.params));
|
|
1555
419
|
if (!record)
|
|
1556
420
|
return 404;
|
|
1557
|
-
if (isDenied(filter, record))
|
|
1558
|
-
return 404;
|
|
1559
421
|
const relatedData = record.__relationships[relationshipName];
|
|
1560
422
|
const baseUrl = getBaseUrl(request);
|
|
1561
|
-
// THE ONE READ SURFACE THAT DOES NOT GO THROUGH `toJSON()`. It builds
|
|
1562
|
-
// `{ type, id }` BY HAND, which is why #234's linkage filter never
|
|
1563
|
-
// reached it and why this half belongs to abofs/stonyx-orm#232 rather
|
|
1564
|
-
// than to #234: on this route the linkage IS the primary data of an
|
|
1565
|
-
// opt-in request, so filtering it changes the route's MEMBERSHIP
|
|
1566
|
-
// semantics, not the ids named inside somebody else's document.
|
|
1567
|
-
//
|
|
1568
|
-
// DELIBERATELY NOT STATED AS A COUNT. README.md's Consumer Contracts
|
|
1569
|
-
// section enumerates the surfaces on which the framework resolves a
|
|
1570
|
-
// verdict and hands it to `toJSON()`, and that enumeration GROWS --
|
|
1571
|
-
// abofs/stonyx-orm#235 adds the two write handlers and the `included`
|
|
1572
|
-
// records. This route is not on that list under any count, because it
|
|
1573
|
-
// never calls `toJSON()`: whatever it filters, it filters here. A
|
|
1574
|
-
// number written into this comment would be false the next time that
|
|
1575
|
-
// list changes, and the README already carries the enumeration.
|
|
1576
|
-
//
|
|
1577
|
-
// Same filter, same argument-one decision, same residual as
|
|
1578
|
-
// `/:id/{relationship}` above -- read the block there.
|
|
1579
|
-
const linkage = createLinkageFilter(request);
|
|
1580
|
-
const isLinkable = (r) => {
|
|
1581
|
-
const type = r.__model?.__name;
|
|
1582
|
-
return typeof type === 'string' && type !== '' && linkage(type, r);
|
|
1583
|
-
};
|
|
1584
423
|
let data;
|
|
1585
424
|
if (info.isArray) {
|
|
1586
425
|
// hasMany - return array of linkage objects
|
|
1587
426
|
const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
|
|
1588
427
|
data = related
|
|
1589
428
|
.filter((r) => Boolean(r.__model))
|
|
1590
|
-
.filter(isLinkable)
|
|
1591
429
|
.map(r => ({ type: r.__model.__name, id: r.id }));
|
|
1592
430
|
}
|
|
1593
431
|
else {
|
|
1594
|
-
// belongsTo - return single linkage or null
|
|
1595
|
-
|
|
1596
|
-
// the measured oracle in the `/:id/{relationship}` block above.
|
|
1597
|
-
if (isOrmRecord(relatedData) && relatedData.__model && isLinkable(relatedData)) {
|
|
432
|
+
// belongsTo - return single linkage or null
|
|
433
|
+
if (isOrmRecord(relatedData) && relatedData.__model) {
|
|
1598
434
|
data = { type: relatedData.__model.__name, id: relatedData.id };
|
|
1599
435
|
}
|
|
1600
436
|
else {
|
|
@@ -1610,135 +446,31 @@ export default class OrmRequest extends Request {
|
|
|
1610
446
|
};
|
|
1611
447
|
};
|
|
1612
448
|
}
|
|
1613
|
-
// Catch-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
//
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
// `/:id/{relationship}` above.
|
|
1629
|
-
routes[`/:id/:relationship`] = async () => 404;
|
|
1630
|
-
routes[`/:id/relationships/:relationship`] = async () => 404;
|
|
449
|
+
// Catch-all for invalid relationship names on related resource route
|
|
450
|
+
routes[`/:id/:relationship`] = async (request) => {
|
|
451
|
+
const record = await store.find(model, getId(request.params));
|
|
452
|
+
if (!record)
|
|
453
|
+
return 404;
|
|
454
|
+
// If we reach here, relationship doesn't exist (valid ones were registered above)
|
|
455
|
+
return 404;
|
|
456
|
+
};
|
|
457
|
+
// Catch-all for invalid relationship names on relationship linkage route
|
|
458
|
+
routes[`/:id/relationships/:relationship`] = async (request) => {
|
|
459
|
+
const record = await store.find(model, getId(request.params));
|
|
460
|
+
if (!record)
|
|
461
|
+
return 404;
|
|
462
|
+
return 404;
|
|
463
|
+
};
|
|
1631
464
|
return routes;
|
|
1632
465
|
}
|
|
1633
466
|
auth(request, state) {
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
// failure mode is reachable by following the docs.
|
|
1639
|
-
// -------------------------------------------------------------------------
|
|
1640
|
-
// #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
|
|
1641
|
-
//
|
|
1642
|
-
// Both members are already in hand here. `model` is `this.model`, the name
|
|
1643
|
-
// setup-rest-server mounted this route for; `operation` is the SAME
|
|
1644
|
-
// `methodAccessMap` lookup the permission-array branch at the bottom of
|
|
1645
|
-
// this method performs, so the predicate form and the array form cannot
|
|
1646
|
-
// answer differently about the same request.
|
|
1647
|
-
//
|
|
1648
|
-
// NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
|
|
1649
|
-
// Deriving `model` here from `request.baseUrl` (or from the mounted route
|
|
1650
|
-
// name, or from `getPluralName(this.model)`) would move all five fail-open
|
|
1651
|
-
// variants listed in this file's header OUT of the consumer and INTO the
|
|
1652
|
-
// framework, where every consumer inherits them at once. `this.model` is
|
|
1653
|
-
// assigned once at mount time and no request can influence it.
|
|
1654
|
-
//
|
|
1655
|
-
// `operation` is left UNDEFINED for a method with no entry in
|
|
1656
|
-
// `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
|
|
1657
|
-
// GET handler, so an unmapped method really does reach this line; a
|
|
1658
|
-
// `?? 'read'` here would hand the consumer a fabricated authorisation fact
|
|
1659
|
-
// and turn an unclassified request into an authorised one. Undefined is
|
|
1660
|
-
// the honest answer.
|
|
1661
|
-
//
|
|
1662
|
-
// `record` is deliberately absent -- see `AccessContext` in
|
|
1663
|
-
// src/types/orm-types.ts. Nothing is fetched at this point and adding a
|
|
1664
|
-
// lookup here would put a store read in the middle of an authorization
|
|
1665
|
-
// path. The function return shape below IS the per-record hook.
|
|
1666
|
-
//
|
|
1667
|
-
// -------------------------------------------------------------------------
|
|
1668
|
-
// #236 -- `recordId`, the DECODED route-parameter id, for the same reason.
|
|
1669
|
-
//
|
|
1670
|
-
// WHICH RECORD is the third structural fact the framework already holds and
|
|
1671
|
-
// the consumer was left to re-derive, and re-deriving it failed OPEN. The
|
|
1672
|
-
// documented sample compared `request.path` -- the RAW, undecoded pathname
|
|
1673
|
-
// -- against a literal `/archived`, while the router DECODES `:id`. So
|
|
1674
|
-
// `GET /owners/%61rchived` walked past the deny and was dispatched as the
|
|
1675
|
-
// record `archived`: 200 with the record in full, and DELETE answered 204
|
|
1676
|
-
// with the record destroyed, unauthenticated. Four spellings measured, all
|
|
1677
|
-
// four through; 255 non-canonical spellings of that 8-character id decode
|
|
1678
|
-
// to the same key, so this was never a deny-list of one.
|
|
1679
|
-
//
|
|
1680
|
-
// TWO CONSUMER-SIDE NORMALISATIONS WERE MEASURED WRONG IN OPPOSITE
|
|
1681
|
-
// DIRECTIONS, which is the argument for doing it once, here.
|
|
1682
|
-
// `.toLowerCase()` case-folds a route-parameter VALUE on the axis that
|
|
1683
|
-
// governs literal SEGMENTS: with a distinct owner seeded at `ARCHIVED`,
|
|
1684
|
-
// `GET /owners/ARCHIVED` was a false DENY on the wrong record and
|
|
1685
|
-
// `GET /owners/%41RCHIVED` a false ALLOW on that same one.
|
|
1686
|
-
// `decodeURIComponent(request.path)` decodes THEN splits while the router
|
|
1687
|
-
// splits THEN decodes, so it over-denied `/owners/archived%2fx` -- 403 for
|
|
1688
|
-
// a genuinely distinct record. Failing closed there was luck, not design.
|
|
1689
|
-
//
|
|
1690
|
-
// `getId(request.params)` AND NOT `request.params.id`, for exactly the
|
|
1691
|
-
// reason `operation` is a `methodAccessMap` lookup: it is the SAME single
|
|
1692
|
-
// coercion the store lookup one layer down performs, so the predicate and
|
|
1693
|
-
// the dispatch cannot disagree about which record a request addresses.
|
|
1694
|
-
// The raw string would reintroduce that divergence on hex-shaped ids --
|
|
1695
|
-
// `GET /animals/0x2391` looks up record `9105`.
|
|
1696
|
-
//
|
|
1697
|
-
// NOTHING HERE PARSES THE REQUEST TARGET EITHER. `request.params` is what
|
|
1698
|
-
// the router matched, so a mount prefix, an absolute-form target, a query
|
|
1699
|
-
// string or a case-varied mount cannot move this value -- the same
|
|
1700
|
-
// guarantee `model` carries, by the same means.
|
|
1701
|
-
//
|
|
1702
|
-
// `null` and not `undefined` on a collection route, so the KEY IS ALWAYS
|
|
1703
|
-
// PRESENT -- the rule `operation`'s own docblock already establishes. A
|
|
1704
|
-
// context reaching a predicate WITHOUT the key therefore did not come from
|
|
1705
|
-
// here; it was hand-assembled by a caller resolving the predicate through
|
|
1706
|
-
// `Orm.instance.getAccess()`, and that absence stays deniable only because
|
|
1707
|
-
// `auth()` never produces it.
|
|
1708
|
-
// -------------------------------------------------------------------------
|
|
1709
|
-
const context = {
|
|
1710
|
-
model: this.model,
|
|
1711
|
-
operation: methodAccessMap[request.method],
|
|
1712
|
-
recordId: request.params && 'id' in request.params ? getId(request.params) : null,
|
|
1713
|
-
};
|
|
1714
|
-
let access;
|
|
1715
|
-
try {
|
|
1716
|
-
access = this.access(request, context);
|
|
1717
|
-
}
|
|
1718
|
-
catch (error) {
|
|
1719
|
-
// Same reasoning as `isDenied`: fail closed, but say so. An `access()`
|
|
1720
|
-
// that throws denies EVERY request to the collection, and a silent 403
|
|
1721
|
-
// wall is the hardest possible thing to diagnose from the outside.
|
|
1722
|
-
log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
|
|
1723
|
-
return 403; // Forbidden
|
|
1724
|
-
}
|
|
1725
|
-
// THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
|
|
1726
|
-
//
|
|
1727
|
-
// It used to be inline here, and it was the only copy, which was fine while
|
|
1728
|
-
// `auth()` was the only thing that had to ask. It is not any more: the
|
|
1729
|
-
// linkage path has to ask model X's predicate about model X's records while
|
|
1730
|
-
// servicing a request routed to model Y, and a second inline copy of these
|
|
1731
|
-
// six branches would be a second authorization vocabulary -- one that can
|
|
1732
|
-
// drift, and that reviewers would have to notice had drifted. The branch
|
|
1733
|
-
// order in `interpretAccess` is this block, moved, not rewritten.
|
|
1734
|
-
const verdict = interpretAccess(access, methodAccessMap[request.method]);
|
|
1735
|
-
if (!verdict.granted)
|
|
467
|
+
const access = this.access(request);
|
|
468
|
+
if (!access)
|
|
469
|
+
return 403;
|
|
470
|
+
if (Array.isArray(access) && !access.includes(methodAccessMap[request.method]))
|
|
1736
471
|
return 403;
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
// request and hands the same one to `auth()` and to the handler.
|
|
1740
|
-
if (verdict.filter)
|
|
1741
|
-
state.filter = verdict.filter;
|
|
472
|
+
if (typeof access === 'function')
|
|
473
|
+
state.filter = access;
|
|
1742
474
|
return undefined;
|
|
1743
475
|
}
|
|
1744
476
|
}
|