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