@stonyx/rest-server 0.2.1-alpha.24 → 0.2.1-alpha.26

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 CHANGED
@@ -81,25 +81,28 @@ Configuration is read from `stonyx/config` under `restServer`:
81
81
  | `enableHealthCheck` | **Boolean** | `true` | Register `GET /health` endpoint (disable via `REST_HEALTH_CHECK_DISABLE=true`) |
82
82
  | `caseSensitiveRoutes` | **Boolean** | `true` | Match route paths case-sensitively. Disable via `REST_CASE_SENSITIVE_ROUTES=false`. See [Route Matching Strictness](#route-matching-strictness) — **disabling this re-opens a security hole**. |
83
83
  | `strictRoutes` | **Boolean** | `true` | Match route paths strictly, so a trailing slash does not match a route registered without one. Disable via `REST_STRICT_ROUTES=false`. See [Route Matching Strictness](#route-matching-strictness) — **disabling this re-opens a security hole**, and note `GET /health/` now 404s. |
84
- | `canonicalRoutes` | **Boolean** | `true` | Reject a request whose raw target is not the canonical path express matched, before your `auth` hook runs. Disable via `REST_CANONICAL_ROUTES=false`. See [Route Matching Strictness](#route-matching-strictness) — **disabling this re-opens a security hole**, and note `GET /route/` at a mount root and **every** absolute-form request target now 404. |
84
+ | `canonicalRoutes` | **Boolean** | `true` | Reject a request whose raw target is not the canonical path express matched, before your `auth` hook runs. Disable via `REST_CANONICAL_ROUTES=false`. See [Route Matching Strictness](#route-matching-strictness) — **disabling this re-opens a security hole**, and note `GET /route/` at a mount root and every absolute-form request target now 404 on the routes this module registers (see the scope limit under [Upgrading](#upgrading-behaviour-changes)). |
85
+ | `canonicalEncoding` | **Boolean** | `true` | Reject a request whose raw target percent-encodes an RFC 3986 §2.3 *unreserved* character (`A-Z a-z 0-9 - . _ ~`), before your `auth` hook runs. Disable via `REST_CANONICAL_ENCODING=false`. See [Route Matching Strictness](#route-matching-strictness) — **disabling this re-opens a security hole**, and note that a client over-encoding an unreserved character in a path now gets 404 (see [Upgrading](#upgrading-behaviour-changes)). |
85
86
  | `trustProxy` | **Boolean** | `false` | Trust reverse proxy headers (e.g. `X-Forwarded-Proto`). Enable via `REST_TRUST_PROXY=true` when running behind a load balancer such as AWS ALB/ELB to ensure correct protocol detection. |
86
87
  | `statusMap` | **Object** | `{}` | Optional mapping of HTTP status codes to custom messages |
87
88
 
88
89
  ### Route Matching Strictness
89
90
 
90
- Routes match **case-sensitively, strictly, and only at their canonical target
91
- by default**. Three controls, all on:
91
+ Routes match **case-sensitively, strictly, only at their canonical target, and
92
+ only at their canonical spelling by default**. Four controls, all on:
92
93
 
93
94
  | axis | control | example that no longer matches |
94
95
  |---|---|---|
95
96
  | casing | `case sensitive routing` (setting) | `GET /users/Success` -> does not reach `/success` |
96
97
  | trailing slash | `strict routing` (setting) | `GET /users/success/` -> does not reach `/success` |
97
98
  | canonical target | `canonicalRoutes` (per-request check) | `GET /users/` and `GET http://host/users` -> do not reach the mounted `/users` class |
99
+ | percent-encoding | `canonicalEncoding` (per-request check) | `GET /users/%73ecret` -> does not reach `/users/:id` with `id === "secret"` |
98
100
 
99
- The first two are express settings applied at both construction sites. The
100
- third is **not a setting** — no express setting can express itit is a
101
- per-request comparison of the raw request target against the path express
102
- matched, run ahead of your `auth` hook. See
101
+ The first two are express settings applied at both construction sites. The last
102
+ two are **not settings** — no express setting can express eitherthey are
103
+ per-request checks run ahead of your `auth` hook: one compares the raw request
104
+ target against the path express matched, the other rejects a raw target that
105
+ percent-encodes a character which never needs encoding. See
103
106
  [`src/route-matching.ts`](src/route-matching.ts).
104
107
 
105
108
  Read [What this does not do](#what-this-does-not-do) and
@@ -165,26 +168,101 @@ against `req.originalUrl` — the field express does not normalize:
165
168
  GET /admin 401 401 (hook fires, request blocked)
166
169
  GET /admin/ 200 404 (hook never fired; now a miss)
167
170
  GET http://host/admin 200 404 (absolute-form; hook never fired)
168
- GET http://host/admin/settings 200 404 (absolute-form, and every other route)
171
+ GET http://host/admin/settings 200 404 (absolute-form; every route from a request class)
169
172
  ```
170
173
 
171
174
  The second vector is the one to check first. [RFC 9112
172
175
  §3.2.2](https://www.rfc-editor.org/rfc/rfc9112#section-3.2.2) permits an
173
176
  **absolute-form** request target, express routes it, and it hands your hook the
174
177
  whole URI — `req.originalUrl === "http://host/admin"`. Unlike the mount-root
175
- slash, that affects **every route**, not one edge.
178
+ slash, that affects **every route mounted from a request class**, not one edge.
179
+ The qualifier is a registration-site limit, not a special case for one URL: the
180
+ check runs inside the handlers this module registers, so anything you register
181
+ directly on `RestServer.instance.api` is outside it. In this repo that is
182
+ `/health` alone, and `GET http://host/health` still returns 200 — measured.
176
183
 
177
184
  The target is compared **raw**. It is not parsed, normalized or resolved first:
178
185
  normalizing it would launder exactly the string your hook is exposed to and
179
186
  re-open the absolute-form vector by construction. Only the query string is
180
187
  removed before comparison, so `GET /admin?x=1` still reaches your hook — **strip
181
188
  the query yourself** if your hook compares `req.originalUrl` against a fixed
182
- path, or it will not match. Rejections are indistinguishable from a genuine miss
183
- by design; see [Upgrading](#upgrading-behaviour-changes).
189
+ path, or it will not match (see [Consumer
190
+ Contracts](#consumer-contracts)). Rejections are indistinguishable from a
191
+ genuine miss by design; see [Upgrading](#upgrading-behaviour-changes).
184
192
 
185
193
  Routes registered *with* a literal trailing slash are unaffected — their
186
- canonical target carries the slash. So are param routes, index-mounted route
187
- classes, and query strings on canonical paths.
194
+ canonical target carries the slash. So are index-mounted route classes and
195
+ query strings on canonical paths.
196
+
197
+ **Param routes: "unaffected" means "no regression".** `/resource/:id` keeps
198
+ matching exactly as it did. `canonicalRoutes` is structurally blind to how a
199
+ param value is *spelled* — express decodes only `req.params`, so `target` and
200
+ `canonical` are both the same encoded string and this comparison passes the
201
+ request through by construction. That axis has its own control, below.
202
+
203
+ #### The percent-encoding check (`canonicalEncoding`)
204
+
205
+ Express decodes **`req.params` and nothing else**. `req.path` and
206
+ `req.originalUrl` both stay percent-encoded, so an `auth` hook comparing either
207
+ of them against a fixed string was walked past by re-spelling the id:
208
+
209
+ ```
210
+ before after
211
+ GET /enc/secret 401 401 (hook fires, request blocked)
212
+ GET /enc/%73ecret 200 404 (hook never fired; handler got id "secret")
213
+ GET /enc/%73%65%63%72%65%74 200 404
214
+ GET /private/%66ailure 200 404 (guard missed; absorbed by a sibling /:id)
215
+ ```
216
+
217
+ `canonicalEncoding` closes it
218
+ ([#56](https://github.com/abofs/stonyx-rest-server/issues/56)). Before your
219
+ `auth` hook runs, the query-stripped raw target is rejected as a plain 404 if it
220
+ contains a percent-triplet whose octet is an
221
+ [RFC 3986 §2.3](https://www.rfc-editor.org/rfc/rfc3986#section-2.3)
222
+ **unreserved** character — `A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, `~`. Those are
223
+ exactly the characters a URI generator must **not** encode and a normalizer
224
+ **must** decode, so nothing a client is required to send is affected.
225
+
226
+ **This is not a list of spellings, it is a family.** For an id of *n* bytes
227
+ there are `∏(1 + vᵢ) − 1` non-canonical spellings, where a byte whose hex
228
+ carries a letter digit has two (`m`, `%6d`, `%6D`). Measured against unfixed
229
+ code: **63 of 63** spellings of `secret` returned 200, and **71 of 71** of
230
+ `admin`. Enumerating them in your own hook is not a remedy.
231
+
232
+ **Three things it deliberately does not reject:**
233
+
234
+ ```
235
+ GET /enc/sec%2fret -> 200 id "sec/ret" %2f is RESERVED — must stay encodable
236
+ GET /enc/a%2Bb -> 200 id "a+b" %2B is RESERVED
237
+ GET /enc/%2573ecret -> 200 id "%73ecret" express decodes exactly ONCE
238
+ GET /enc/x?name=%61 -> 200 id "x" the query string is stripped, not scanned
239
+ GET /enc/%zz -> 400 malformed escapes are the router's 400, unchanged
240
+ ```
241
+
242
+ If you were tempted to write `decodeURIComponent(req.path)` in your hook: the
243
+ first line is why not. The router **splits then decodes**, so `sec%2fret` is one
244
+ segment naming the id `sec/ret`; a hook that decodes then splits sees two
245
+ segments and denies a request the router routed somewhere else entirely. And a
246
+ hook that decodes *until stable* denies line three, which is a legitimately
247
+ distinct id.
248
+
249
+ **The residual, stated plainly: this does not give each id one spelling.**
250
+ Because reserved characters must stay encodable, two different raw targets can
251
+ still name the same record:
252
+
253
+ ```
254
+ GET /enc/a+b -> 200 id "a+b"
255
+ GET /enc/a%2Bb -> 200 id "a+b" <- two accepted spellings, one id
256
+ GET /enc/sec%2fret -> 200 id "sec/ret"
257
+ GET /enc/sec%2Fret -> 200 id "sec/ret" <- hex-digit case, same id again
258
+ ```
259
+
260
+ **So a hook comparing a raw path string is still unsound for any id containing a
261
+ reserved character, and `req.params` is the sound comparison.** `req.params` is
262
+ decoded by express and is populated *before* your `auth` hook runs, by design —
263
+ compare that, and none of this applies to you. This module cannot close the
264
+ residual for you without 404ing encodings clients are entitled to send; see
265
+ [Consumer Contracts](#consumer-contracts).
188
266
 
189
267
  #### What this does not do
190
268
 
@@ -215,16 +293,36 @@ another variant of the bug above.
215
293
 
216
294
  #### Upgrading: behaviour changes
217
295
 
218
- All three controls change which requests match, so all three are
296
+ All four controls change which requests match, so all four are
219
297
  consumer-visible.
220
298
 
299
+ **A client that over-encodes an unreserved character in a path now gets 404.**
300
+ `GET /public/url-params/%61/b/c` returns **404** where it previously returned
301
+ 200 — measured on this repo's own fixture. `%61` is `a`, and
302
+ [RFC 3986 §2.3](https://www.rfc-editor.org/rfc/rfc3986#section-2.3) says a
303
+ generator must not encode it, so no correct client emits this. Some do anyway:
304
+ over-eager `encodeURIComponent` on an id that never needed it, a URL builder
305
+ that percent-encodes everything, or a client library normalizing in the wrong
306
+ direction. Reserved characters are **unaffected** — `%2f`, `%2B`, `%25` and
307
+ every non-ASCII byte still route, and so does anything in the query string.
308
+ Remediation is `REST_CANONICAL_ENCODING=false`, or fix the client. Like the two
309
+ below, the rejection is **indistinguishable from a route that was never
310
+ registered**, and this module emits no request logging.
311
+
221
312
  **Clients or forward proxies sending absolute-form request targets now get 404
222
- on every route.** `GET http://host/admin HTTP/1.1` is a legal request target
223
- ([RFC 9112 §3.2.2](https://www.rfc-editor.org/rfc/rfc9112#section-3.2.2)) and
224
- express used to route it. It is now rejected, on **every** route — for a client
225
- that emits it, this is a total outage, not a partial one, and it is the largest
226
- blast radius in this change. Reverse proxies in normal use (nginx, HAProxy,
227
- AWS ALB) send origin-form and are unaffected; **forward** proxies and
313
+ on every route mounted from a request class.** `GET http://host/admin HTTP/1.1`
314
+ is a legal request target
315
+ ([RFC 9112 §3.2.2](https://www.rfc-editor.org/rfc/rfc9112#section-3.2.2)), and
316
+ express used to route it. It is now rejected on every route this module
317
+ registers for a client that emits it, this is a total outage, not a partial
318
+ one, and it is the largest blast radius in this change. The one carve-out is a
319
+ **registration site**, not a route: the check lives in the handlers mounted from
320
+ your request classes, so anything registered directly on
321
+ `RestServer.instance.api` never reaches it. `GET /health` is the only such route
322
+ in this repo, and `GET http://host/health` still returns 200 — so do not use it
323
+ to confirm the new rejection is live, and do not assume an authorized route you
324
+ registered on `api` yourself is covered. Reverse proxies in normal use (nginx,
325
+ HAProxy, AWS ALB) send origin-form and are unaffected; **forward** proxies and
228
326
  hand-rolled HTTP clients are the exposure. Remediation is
229
327
  `REST_CANONICAL_ROUTES=false`, or fix the client.
230
328
 
@@ -263,16 +361,17 @@ no log line and no stack, so it looks like a deploy that dropped a route.
263
361
 
264
362
  #### Opting out
265
363
 
266
- Three separate flags, one per axis:
364
+ Four separate flags, one per axis:
267
365
 
268
366
  ```bash
269
367
  REST_CASE_SENSITIVE_ROUTES=false # restores case-insensitive matching (#47)
270
368
  REST_STRICT_ROUTES=false # restores trailing-slash tolerance (#50)
271
369
  REST_CANONICAL_ROUTES=false # restores non-canonical request targets (#54)
370
+ REST_CANONICAL_ENCODING=false # restores percent-encoded spellings (#56)
272
371
  ```
273
372
 
274
373
  or equivalently
275
- `restServer: { caseSensitiveRoutes: false, strictRoutes: false, canonicalRoutes: false }`.
374
+ `restServer: { caseSensitiveRoutes: false, strictRoutes: false, canonicalRoutes: false, canonicalEncoding: false }`.
276
375
 
277
376
  **They are deliberately separate keys, and none implies the others.** Slash
278
377
  tolerance is a legitimate need — a health-check URL you cannot change today is
@@ -289,12 +388,41 @@ slash *and* the absolute-form target — against any hook authorizing on
289
388
  `req.originalUrl`. It is env-only, so restoring service does not need a
290
389
  redeploy; use it to stop the bleeding, then fix the client and remove it.
291
390
 
391
+ **`REST_CANONICAL_ENCODING=false` re-opens the `#56` bypass, and it is the
392
+ widest of the four.** With it set, `GET /users/%73ecret` reaches your `/:id`
393
+ handler with `id === "secret"` while your hook compared `%73ecret` and did not
394
+ match — and it does that against a hook comparing `req.path` **or**
395
+ `req.originalUrl`, on every route class with a param segment. The other three
396
+ flags each re-open one field's worth of exposure; this one re-opens both. It is
397
+ also **independent** of `REST_CANONICAL_ROUTES`: if you have to set that one for
398
+ an absolute-form-emitting forward proxy, you keep this one on, which is exactly
399
+ why they are separate keys. If you must set it, the mitigation that costs you
400
+ nothing is to compare `req.params` in your hook rather than a raw path string —
401
+ `req.params` is decoded and was never exposed to this.
402
+
292
403
  **Each flag restores the corresponding vulnerability described above** — the
293
404
  URL-based authorization in your application becomes bypassable along that axis
294
405
  again. They exist as one-line remediations for an existing deployment, not as a
295
406
  configuration to run on. Set the flag to restore service, then fix the client
296
407
  and remove the flag.
297
408
 
409
+ ### Consumer Contracts
410
+
411
+ Three things this module deliberately does **not** do for you. Each is a state
412
+ the framework permits, only your own discipline prevents, and that produces **no
413
+ error and no log** when that discipline lapses — so they are collected here
414
+ rather than left implied by the sections above.
415
+
416
+ | you must | because | symptom if you don't |
417
+ |---|---|---|
418
+ | **Strip the query string** before comparing `req.originalUrl` to a fixed path in an `auth` hook | `canonicalRoutes` compares the query-*stripped* target — a query string is a legitimately variable part of a request target, and rejecting on it would 404 every `?`-carrying request | `GET /admin?x=1` reaches your guarded handler **unauthenticated**, 200, no error, no log. Measured identical before and after `canonicalRoutes` |
419
+ | **Compare `req.params`, not a raw path string** | express decodes only `req.params`; `req.path` and `req.originalUrl` both stay percent-encoded. `canonicalEncoding` (#56) rejects an over-encoded *unreserved* character, but **reserved** characters must stay encodable, so one decoded id still has more than one accepted spelling: `GET /orders/a+b` and `GET /orders/a%2Bb` both run the handler with `id === "a+b"`, and `sec%2fret` / `sec%2Fret` both give `sec/ret` | your hook compares one spelling, the request arrives in another, and the handler runs **unauthenticated** — 200, no error, no log. Comparing `req.params.id` instead is immune by construction, and it is populated before `auth()` runs |
420
+ | **Compare param values with the same casing you look them up with** | param *values* are never case-normalized, and record ids are legitimately case-sensitive | `GET /orders/SECRET` runs the handler with `id === "SECRET"` while your hook compared `secret`. Note that lower-casing the value is **not** the fix: it false-denies a genuinely distinct `SECRET` record and, measured in a sibling module, false-allowed an encoded spelling at the same time |
421
+ | **Return `undefined` from `auth()` to mean "authorized"** — never `0` | any integer return is sent as the HTTP status | returning `0` sends a `0` status rather than allowing the request |
422
+
423
+ `test/sample/requests/admin.ts` in this repo is the worked example of a
424
+ correctly-written `originalUrl` hook for the first row.
425
+
298
426
  ### Running Behind a Load Balancer
299
427
 
300
428
  When your application runs behind a reverse proxy or load balancer (e.g. AWS ALB/ELB), the load balancer terminates SSL and forwards requests to your server over HTTP internally. This means Express sees `http` as the protocol even though the original client request used `https`.
@@ -1,4 +1,5 @@
1
1
  const {
2
+ REST_CANONICAL_ENCODING,
2
3
  REST_CANONICAL_ROUTES,
3
4
  REST_CASE_SENSITIVE_ROUTES,
4
5
  REST_CORS_ORIGIN,
@@ -23,13 +24,20 @@ const config = {
23
24
  // stubs `caseSensitiveRoutes` to `undefined` and src/route-matching.ts reads
24
25
  // `!== false`, so AC6 guards the source's read and not this default.
25
26
  // Measured: pin `caseSensitiveRoutes: true` in test/config/environment.ts AND
26
- // invert this line, and the suite reports 28 pass / 0 fail. A naive pin makes
27
+ // invert this line, and the suite reports 34 pass / 0 fail. A naive pin makes
27
28
  // an insecure published default completely invisible to a green suite --
28
29
  // quieter and weaker, which is the outcome pinning was supposed to prevent.
30
+ // Inverting this line ALONE, unpinned, reports 31 pass / 3 fail (#47's AC3,
31
+ // AC4 and AC5; AC6 green).
29
32
  //
30
33
  // The cost of leaving it unpinned is that the suite is ambient-sensitive here
31
- // (`REST_CASE_SENSITIVE_ROUTES=false pnpm test` => 25 pass / 3 fail), but it
32
- // fails LOUDLY, so there is no false green. Closing #43 for this key needs
34
+ // (`REST_CASE_SENSITIVE_ROUTES=false pnpm test` => 31 pass / 3 fail), but it
35
+ // fails LOUDLY, so there is no false green.
36
+ //
37
+ // Every count in this block was re-measured against the 34-test suite at
38
+ // #54's head. PASS totals here move whenever a test is ADDED anywhere in the
39
+ // repo -- the FAIL counts are the load-bearing half. Re-measure, do not
40
+ // adjust by arithmetic, when this block next looks stale. Closing #43 for this key needs
33
41
  // the subprocess-based env isolation this repo does not yet have; any fix
34
42
  // must keep a live assertion on this default.
35
43
  caseSensitiveRoutes: REST_CASE_SENSITIVE_ROUTES !== 'false',
@@ -47,19 +55,21 @@ const config = {
47
55
  // DELIBERATELY NOT PINNED in test/config/environment.ts -- do not "fix" this
48
56
  // as part of abofs/stonyx-rest-server#43. Same trap as the key above, and now
49
57
  // measured for both: pin `strictRoutes: true` in test/config/environment.ts
50
- // AND invert this line to `=== 'true'`, and the suite reports 31 pass /
58
+ // AND invert this line to `=== 'true'`, and the suite reports 34 pass /
51
59
  // 0 fail. A naive pin makes an insecure published default completely
52
60
  // invisible to a green suite.
53
61
  //
54
- // Unpinned, inverting this line alone turns #50's AC1 and AC2 red (29/2).
62
+ // Unpinned, inverting this line alone turns #50's AC1 and AC2 red (32/2).
55
63
  // AC3 stays GREEN under that mutation, because AC3 sets `strictRoutes` on the
56
64
  // config object directly and so guards src/route-matching.ts's READ rather
57
65
  // than this default -- the two assertions cover different halves and neither
58
66
  // subsumes the other.
59
67
  //
60
68
  // The cost is that the suite is ambient-sensitive here
61
- // (`REST_STRICT_ROUTES=false pnpm test` => 29 pass / 2 fail), but it fails
62
- // LOUDLY, so there is no false green. Closing #43 for either key needs
69
+ // (`REST_STRICT_ROUTES=false pnpm test` => 32 pass / 2 fail), but it fails
70
+ // LOUDLY, so there is no false green. All counts in this block re-measured
71
+ // against the 34-test suite at #54's head; the FAIL count is the load-bearing
72
+ // half, since PASS totals move whenever a test is added anywhere. Closing #43 for either key needs
63
73
  // subprocess-based env isolation this repo does not have; any fix must keep a
64
74
  // live assertion on this default.
65
75
  strictRoutes: REST_STRICT_ROUTES !== 'false',
@@ -75,8 +85,13 @@ const config = {
75
85
  // 1. `GET /route/` at a mounted route class's ROOT now returns 404.
76
86
  // 2. Clients or forward proxies emitting an ABSOLUTE-FORM request target
77
87
  // (`GET http://host/admin HTTP/1.1`, RFC 9112 3.2.2) now receive 404 on
78
- // EVERY route. This is the larger blast radius: for such a client it is
79
- // a total outage, not a partial one. Reverse proxies in normal use
88
+ // every route registered through Request.registerCalls(). That is a
89
+ // REGISTRATION-SITE limit, not a carve-out for one URL: /health is
90
+ // registered directly on the parent app (src/main.ts) and still answers
91
+ // 200 to an absolute-form target -- and so would any route a consumer
92
+ // registers on the public RestServer.instance.api itself. This is the
93
+ // larger blast radius: for such a client it is a total outage, not a
94
+ // partial one. Reverse proxies in normal use
80
95
  // (nginx, HAProxy, ALB) send origin-form and are unaffected.
81
96
  // This module emits no request log, so both look like a dropped route.
82
97
  //
@@ -105,8 +120,10 @@ const config = {
105
120
  // guards src/route-matching.ts's READ rather than this default -- the two
106
121
  // assertions cover different halves and neither subsumes the other.
107
122
  // Conversely, weakening the READ to `=== true` reports 33 pass / 1 fail with
108
- // AC2 as the only failure and AC1 fully green. Both measurements are on the
109
- // #54 branch head.
123
+ // AC2 as the only failure and AC1 fully green. All four counts in this block
124
+ // were re-measured on the #54 branch head after the AC1.11/AC1.12 assertions
125
+ // were added; the suite is 34 tests, and the FAIL count is the load-bearing
126
+ // half.
110
127
  //
111
128
  // The cost is that the suite is ambient-sensitive here
112
129
  // (`REST_CANONICAL_ROUTES=false pnpm test` => 32 pass / 2 fail), but it fails
@@ -115,6 +132,74 @@ const config = {
115
132
  // keep a live assertion on this default.
116
133
  canonicalRoutes: REST_CANONICAL_ROUTES !== 'false',
117
134
 
135
+ // Secure by default, same polarity and same reasoning as the three keys
136
+ // above: a request whose RAW target percent-encodes an RFC 3986 2.3
137
+ // UNRESERVED character (ALPHA / DIGIT / "-" / "." / "_" / "~") is rejected
138
+ // with a plain 404 before the consumer's `auth` hook runs
139
+ // (abofs/stonyx-rest-server#56). Like canonicalRoutes this is NOT an express
140
+ // setting -- it is a per-request check in src/route-matching.ts
141
+ // (`shouldRejectEncoding`), called from the handler closure in
142
+ // src/request.ts.
143
+ //
144
+ // What it closes: express decodes `req.params` and NOTHING else, so a
145
+ // consumer hook comparing `req.path` OR `req.originalUrl` was walked past by
146
+ // re-spelling an id -- `GET /enc/secret` -> 401 while
147
+ // `GET /enc/%73ecret` -> 200 with the guarded handler running
148
+ // unauthenticated and `req.params.id === 'secret'`. The spelling family is
149
+ // PROD(1 + v_i) - 1 per id, measured at 63 spellings for `secret` and 71 for
150
+ // `admin`, ALL of them 200 before this key existed. It is EXCLUSIVE to route
151
+ // classes carrying a `:param` segment; literal routes and mount segments
152
+ // match raw and were never reachable this way.
153
+ //
154
+ // BEHAVIOUR CHANGE for consumers upgrading, on a FOURTH axis:
155
+ // Any client that over-encodes an unreserved character in a path now gets
156
+ // 404. Measured on this repo's own fixture:
157
+ // `GET /public/url-params/%61/b/c` -> 404 (was 200). Over-encoding an
158
+ // unreserved character is never required by RFC 3986 -- a normaliser MUST
159
+ // decode these (6.2.2.2) -- so the blast radius is smaller than #54's,
160
+ // whose absolute-form vector hits a real deployment shape. It is still a
161
+ // breaking change and it is documented as one in the README.
162
+ //
163
+ // Opt out with REST_CANONICAL_ENCODING=false only as a temporary remediation
164
+ // -- it RE-OPENS the bypass. SEPARATE key from REST_CANONICAL_ROUTES on
165
+ // purpose, and this one is not a symmetry argument but a measurement: with
166
+ // the rule gated on `canonicalRoutes` instead of its own key,
167
+ // `REST_CANONICAL_ROUTES=false` returns `GET /enc/%73ecret` to 200 -- and
168
+ // that flag is exactly what a consumer behind an absolute-form-emitting
169
+ // forward proxy must set to stay up. Folding the two would hand precisely
170
+ // those consumers the encoding bypass as the price. Killed by
171
+ // test/unit/request-test.ts AC5.
172
+ //
173
+ // DELIBERATELY NOT PINNED in test/config/environment.ts -- do not "fix" this
174
+ // as part of abofs/stonyx-rest-server#43. Both halves RE-MEASURED for this
175
+ // key rather than inferred from the three above, against the 41-test suite
176
+ // at #56's head:
177
+ // (a) invert this line to `=== 'true'` ALONE, unpinned:
178
+ // 36 pass / 5 fail -- #56's integration AC1 and AC2, unit AC5 and AC6,
179
+ // and [Unit] Config AC7. It fails LOUDLY, so there is no false green.
180
+ // (b) pin `canonicalEncoding: true` in test/config/environment.ts AND
181
+ // invert this line: 40 pass / 1 fail, and the ONE failure is
182
+ // [Unit] Config AC7 -- every behavioural assertion goes green because
183
+ // the pin supplies the secure value the suite then observes. Measured
184
+ // again with test/unit/config-test.ts removed: 40 pass / 0 fail, a
185
+ // fully green suite shipping an insecure default. That is the trap, and
186
+ // AC7 is the only thing standing between this key and it.
187
+ //
188
+ // Conversely, weakening the READ in src/route-matching.ts to `=== true`
189
+ // reports 40 pass / 1 fail with unit AC6 as the only failure and every
190
+ // integration assertion green -- the two guard different halves and neither
191
+ // subsumes the other. Closing #43 for any of the four keys needs the
192
+ // subprocess-based env isolation this repo does not have; any fix must keep a
193
+ // live assertion on this default.
194
+ //
195
+ // FOUR security-relevant keys now, all defaulting on, all disable-able, none
196
+ // pinned. Per docs/framework/testing.md the pinned set has to be evaluated as
197
+ // a SET rather than key by key; [Unit] Config AC7 asserts all four together
198
+ // for that reason. Whoever takes #43 inherits four keys and this paragraph as
199
+ // the reason they are unpinned, rather than finding four and assuming
200
+ // neglect.
201
+ canonicalEncoding: REST_CANONICAL_ENCODING !== 'false',
202
+
118
203
  enableHealthCheck: REST_HEALTH_CHECK_DISABLE !== 'true',
119
204
  origin: REST_CORS_ORIGIN ?? '*',
120
205
  methods: REST_CORS_METHODS ?? 'GET,POST,PATCH,PUT,DELETE',
@@ -1 +1 @@
1
- {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../src/request.ts"],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,KAAK,EAAE,YAAY,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AACtG,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,KAAK,MAAM,GAAG,SAAS,CAAC;AAC3F,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,GAAG,cAAc,EAAE,CAAC,CAAC,CAAC;AAE9F,MAAM,CAAC,OAAO,OAAO,OAAO;IAC1B,MAAM,CAAC,SAAS,SAAmB;IAEnC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,cAAc,GAAG,YAAY;IASlD,MAAM,CAAC,kBAAkB,CAAC,GAAG,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAWrE,eAAe,EAAE,OAAO,CAAC;IACzB,QAAQ,EAAG,aAAa,CAAC;IACjB,IAAI,CAAC,EAAE,WAAW,CAAC;;IA4B3B,aAAa,IAAI,IAAI;CAsHtB"}
package/dist/request.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import express from 'express';
2
2
  import config from 'stonyx/config';
3
3
  import { makeArray } from '@stonyx/utils/object';
4
- import applyRouteMatching, { shouldRejectTarget } from './route-matching.js';
4
+ import applyRouteMatching, { shouldRejectEncoding, shouldRejectTarget } from './route-matching.js';
5
5
  const METHODS = new Set(['get', 'post', 'put', 'delete', 'patch']);
6
6
  export default class Request {
7
7
  static stateProp = '__stonyxState';
@@ -63,13 +63,24 @@ export default class Request {
63
63
  // bypasses against hooks that authorize on `req.originalUrl`: the
64
64
  // mount-root trailing slash and the absolute-form request target.
65
65
  //
66
- // Two properties of this line are load-bearing, and each has its own
67
- // red-able assertion:
66
+ // Three properties of this line are load-bearing. Each is named with
67
+ // the ONE assertion that turns red when it is removed -- assertion
68
+ // numbers in `test/integration/rest-server-test.ts` AC1, so the claim
69
+ // is checkable rather than a promise that coverage exists somewhere:
68
70
  //
69
- // 1. It runs BEFORE auth, and OUTSIDE `if (this.auth)`. Gating it on
70
- // the hook would leave `GET /public/` at 200 and make a security
71
- // control depend on an unrelated consumer choice.
72
- // 2. It rejects with `next('router')`, NOT sendStatusResponse() or
71
+ // 1. It runs OUTSIDE `if (this.auth)`. Gating it on the hook would
72
+ // leave `GET /public/` at 200 and make a security control depend
73
+ // on an unrelated consumer choice. Killed by AC1.6, which probes
74
+ // a route class with no hook.
75
+ // 2. It runs BEFORE that block, not merely outside it. This is a
76
+ // SEPARATE property from 1 and needs its own probe: AC1.6 is on
77
+ // a hookless class, so it stays green if this line is merely
78
+ // moved BELOW the block. Measured with it moved: the suite was
79
+ // 34 pass / 0 fail while `GET http://HOST/private/failure`
80
+ // answered 505 -- the consumer's hook status, which is the same
81
+ // oracle class as 3, and the hook itself ran on a request this
82
+ // module was about to reject. Killed by AC1.11.
83
+ // 3. It rejects with `next('router')`, NOT sendStatusResponse() or
73
84
  // res.sendStatus(404). Measured: sendStatus returns
74
85
  // `text/plain "Not Found"` while a genuine miss returns
75
86
  // `text/html <pre>Cannot GET ...</pre>` -- a working ORACLE
@@ -79,8 +90,39 @@ export default class Request {
79
90
  // Content-Type, same CSP header). Routing it through
80
91
  // sendStatusResponse() would additionally re-introduce the
81
92
  // oracle for any consumer who sets a 404 in `statusMap`.
93
+ // Killed by AC1.5.
94
+ //
95
+ // Properties 1 and 2 were previously stated here as a single item
96
+ // asserted to have "its own red-able assertion". It did not: only
97
+ // half of it was covered. Do not re-merge them.
82
98
  if (shouldRejectTarget(req))
83
99
  return next('router');
100
+ // abofs/stonyx-rest-server#56 -- reject a request whose RAW target
101
+ // spells an UNRESERVED character (RFC 3986 2.3) as a percent-triplet,
102
+ // closing the authorization bypass against a hook that compares
103
+ // `req.path` OR `req.originalUrl` on any route class with a `:param`
104
+ // segment. Express decodes only `req.params`, so both raw fields see
105
+ // `%73ecret` while the handler is given `secret`.
106
+ //
107
+ // A SEPARATE line and a SEPARATE predicate from #54's above, and it
108
+ // must stay that way. Extending shouldRejectTarget()'s comparison
109
+ // cannot reach this: `target === canonical` for EVERY one of these
110
+ // spellings, because both sides carry the same encoded string.
111
+ // Reading #54's key here is worse than useless -- measured, gating
112
+ // this rule on `canonicalRoutes` returns `GET /enc/%73ecret` to 200
113
+ // under `REST_CANONICAL_ROUTES=false`, which is exactly the flag an
114
+ // absolute-form-proxy consumer must set. Killed by
115
+ // `test/unit/request-test.ts` AC5.
116
+ //
117
+ // The same three load-bearing properties as the line above apply
118
+ // verbatim -- outside `if (this.auth)`, BEFORE it, and rejecting with
119
+ // `next('router')` rather than a sendStatus that answers `text/plain`
120
+ // and becomes an oracle. They are killed here by
121
+ // `test/integration/rest-server-test.ts` #56 AC1.4 (the shape
122
+ // deep-equal against a genuine miss) and AC1.5 (`/private/%66ailure`
123
+ // -> 404 rather than the hook's own status), on a class WITH a hook.
124
+ if (shouldRejectEncoding(req))
125
+ return next('router');
84
126
  // Run auth after route matching so request.params is populated
85
127
  if (this.auth) {
86
128
  const status = this.auth(req, getState(req));
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8G,MAAM,SAAS,CAAC;AACrI,OAAO,MAAM,MAAM,eAAe,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,kBAAkB,EAAE,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AAOnE,MAAM,CAAC,OAAO,OAAO,OAAO;IAC1B,MAAM,CAAC,SAAS,GAAG,eAAe,CAAC;IAEnC,MAAM,CAAC,QAAQ,CAAC,GAAmB;QACjC,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;QAC9B,MAAM,MAAM,GAAG,GAAyC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AAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;gCAAE,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;wBACrF,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;oBAC1B,CAAC;oBAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;wBAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;wBAAC,OAAO;oBAAC,CAAC;oBAC5D,IAAI,OAAO,QAAQ,KAAK,QAAQ;wBAAE,OAAO,kBAAkB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;oBAEtE,GAAG,CAAC,IAAI,CAAC,QAAmC,CAAC,CAAC;gBAChD,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC"}
@@ -77,13 +77,14 @@ import type { Express, Request as ExpressRequest } from 'express';
77
77
  * guarded handler running unauthenticated. `GET /public/` now returns 404, and
78
78
  * the integration AC asserts exactly that.
79
79
  *
80
- * Both guards are `!== false` for the same reason: these flags default to the
80
+ * All four guards in this file are `!== false` for the same reason: these flags
81
+ * default to the
81
82
  * truthy direction, so a truthy check fails OPEN for a consumer whose shipped
82
- * config predates the key. Both are also asserted at the unit tier for BOTH
83
+ * config predates the key. All are also asserted at the unit tier for BOTH
83
84
  * failure shapes -- key present-and-`undefined` and key absent as an own
84
- * property -- in `test/unit/request-test.ts` (#47's AC6, #50's AC3). The
85
- * integration tier cannot see either: with the shipped default `true`, a
86
- * fail-open guard leaves every integration assertion green.
85
+ * property -- in `test/unit/request-test.ts` (#47's AC6, #50's AC3, #54's AC2,
86
+ * #56's AC6). The integration tier cannot see any of them: with the shipped
87
+ * default `true`, a fail-open guard leaves every integration assertion green.
87
88
  */
88
89
  export default function applyRouteMatching(api: Express): void;
89
90
  /**
@@ -122,9 +123,11 @@ export default function applyRouteMatching(api: Express): void;
122
123
  * hazard here, so do not carry that constraint across.
123
124
  *
124
125
  * The caller must reject with `next('router')`, NOT `res.sendStatus(404)`, and
125
- * must run this whether or not `this.auth` is set -- see src/request.ts.
126
+ * must run this BEFORE `this.auth` as well as outside `if (this.auth)` -- those
127
+ * are two separate properties with two separate assertions (AC1.11 and AC1.6);
128
+ * see src/request.ts.
126
129
  *
127
- * Guard polarity is `!== false`, matching both siblings, for the same measured
130
+ * Guard polarity is `!== false`, matching its three siblings, for the same measured
128
131
  * reason: the secure value is the TRUTHY one, so a plain truthy check fails
129
132
  * OPEN for any consumer whose shipped `restServer` block predates the key --
130
133
  * the state every existing consumer is in, and reachable in practice because
@@ -140,4 +143,80 @@ export default function applyRouteMatching(api: Express): void;
140
143
  * key present-and-`undefined` and key absent as an own property.
141
144
  */
142
145
  export declare function shouldRejectTarget(req: ExpressRequest): boolean;
146
+ /**
147
+ * Decides whether a request must be rejected because its RAW request target
148
+ * spells an unreserved character as a percent-triplet
149
+ * (abofs/stonyx-rest-server#56).
150
+ *
151
+ * Closes a live authorization bypass on any route class carrying a `:param`
152
+ * segment. Express decodes `req.params` and NOTHING else -- `req.path` and
153
+ * `req.originalUrl` both stay percent-encoded -- so a consumer hook comparing
154
+ * either of those raw fields was walked past by re-spelling the id:
155
+ *
156
+ * GET /enc/secret -> 401 (hook fires)
157
+ * GET /enc/%73ecret -> 200 guarded handler, unauthenticated, id "secret"
158
+ *
159
+ * Both hook shapes are affected and neither is safer than the other; there is
160
+ * no spelling that defeats one and not the same-id comparison in the other.
161
+ * A third shape is worse still: a LITERAL guarded route co-registered with a
162
+ * sibling `/:id` (this repo's own `test/sample/requests/private.ts`) has the
163
+ * encoded spelling miss the literal layer and be ABSORBED by the param route,
164
+ * so the guard is walked past without the guarded handler ever running --
165
+ * measured `GET /private/failure` -> 505 vs `GET /private/%66ailure` -> 200.
166
+ *
167
+ * THE RULE IS AN UNRESERVED-OCTET SCAN, NOT A DECODE-AND-COMPARE. Two wrong
168
+ * implementations were built and measured, and each breaks a legitimate
169
+ * request:
170
+ *
171
+ * 1. `decodeURIComponent(target) !== target` -- rejects `/enc/sec%2fret`
172
+ * (404), which names the DISTINCT id `sec/ret`. The router SPLITS then
173
+ * DECODES; a whole-target decode decodes then splits, and the two
174
+ * disagree about `%2f` by construction. Killed by AC3.
175
+ * 2. decode until stable -- rejects `/enc/%2573ecret` (404), which names the
176
+ * legitimate id `%73ecret`. Express decodes EXACTLY ONCE, so `%2561` is
177
+ * not a bypass and a loop invents a false deny. Killed by AC4.
178
+ *
179
+ * WHY THIS IS NOT PART OF `shouldRejectTarget()` (#54), and why extending that
180
+ * comparison cannot work: for `GET /enc/%73ecret`, `originalUrl` is
181
+ * `/enc/%73ecret`, `baseUrl` is `/enc` and `path` is `/%73ecret`, so
182
+ * `target === canonical` -- both sides carry the SAME encoded string. The
183
+ * comparison is structurally blind to this axis and no change to it can see it.
184
+ *
185
+ * WHY IT IS A FOURTH KEY AND NOT A REUSE OF `canonicalRoutes`. Measured with
186
+ * the rule implemented correctly but gated on #54's key:
187
+ * `REST_CANONICAL_ROUTES=false` returns `GET /enc/%73ecret` to 200. That flag
188
+ * is exactly what a consumer behind an absolute-form-emitting forward proxy
189
+ * must set, so folding the two would hand precisely those consumers the
190
+ * encoding bypass as the price of staying up. Same argument the block above
191
+ * makes for why #50 is not a rename of #47. Pinned by
192
+ * `test/unit/request-test.ts` AC5, which also asserts -- in that same state --
193
+ * that #54's own vector IS re-opened, so an implementation that simply ignores
194
+ * `canonicalRoutes` cannot pass it vacuously.
195
+ *
196
+ * TIMING CONTRACT: identical to `shouldRejectTarget()` and NOT to the two
197
+ * settings above. Read per request, inside the handler closure in
198
+ * `Request.registerCalls()`; there is no lazy-materialisation hazard, so do not
199
+ * move it into `applyRouteMatching()`. The caller must reject with
200
+ * `next('router')`, and must run this BEFORE `this.auth` as well as outside
201
+ * `if (this.auth)` -- see src/request.ts.
202
+ *
203
+ * Guard polarity is `!== false`, matching all three siblings, for the same
204
+ * measured reason: the secure value is the TRUTHY one, so `=== true` fails OPEN
205
+ * for any consumer whose shipped `restServer` block predates the key. The
206
+ * integration tier CANNOT see that mutation -- with the shipped default `true`
207
+ * every integration assertion stays green -- so it is `test/unit/request-test.ts`
208
+ * AC6 that kills it, probing the key present-and-`undefined` and absent as an
209
+ * own property separately.
210
+ *
211
+ * WHAT THIS DOES NOT CLOSE, stated here rather than left implied. It cannot
212
+ * give each decoded id exactly one accepted spelling, because reserved
213
+ * characters must remain encodable: `/enc/a+b` and `/enc/a%2Bb` both name the
214
+ * id `a+b`, and `/enc/sec%2fret` and `/enc/sec%2Fret` both name `sec/ret`. So a
215
+ * hook comparing a raw path string REMAINS UNSOUND for any id containing a
216
+ * reserved character, and `req.params` -- which express decodes, and which is
217
+ * populated before `auth()` runs -- is the sound idiom. That residual is the
218
+ * consumer's comparison to own; the module cannot close it without 404ing
219
+ * encodings clients are required to emit.
220
+ */
221
+ export declare function shouldRejectEncoding(req: ExpressRequest): boolean;
143
222
  //# sourceMappingURL=route-matching.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-matching.d.ts","sourceRoot":"","sources":["../src/route-matching.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,SAAS,CAAC;AAGlE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqFG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAG7D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAe/D"}
1
+ {"version":3,"file":"route-matching.d.ts","sourceRoot":"","sources":["../src/route-matching.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,SAAS,CAAC;AAGlE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsFG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAG7D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAuB/D;AA2BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAkBjE"}
@@ -77,13 +77,14 @@ import config from 'stonyx/config';
77
77
  * guarded handler running unauthenticated. `GET /public/` now returns 404, and
78
78
  * the integration AC asserts exactly that.
79
79
  *
80
- * Both guards are `!== false` for the same reason: these flags default to the
80
+ * All four guards in this file are `!== false` for the same reason: these flags
81
+ * default to the
81
82
  * truthy direction, so a truthy check fails OPEN for a consumer whose shipped
82
- * config predates the key. Both are also asserted at the unit tier for BOTH
83
+ * config predates the key. All are also asserted at the unit tier for BOTH
83
84
  * failure shapes -- key present-and-`undefined` and key absent as an own
84
- * property -- in `test/unit/request-test.ts` (#47's AC6, #50's AC3). The
85
- * integration tier cannot see either: with the shipped default `true`, a
86
- * fail-open guard leaves every integration assertion green.
85
+ * property -- in `test/unit/request-test.ts` (#47's AC6, #50's AC3, #54's AC2,
86
+ * #56's AC6). The integration tier cannot see any of them: with the shipped
87
+ * default `true`, a fail-open guard leaves every integration assertion green.
87
88
  */
88
89
  export default function applyRouteMatching(api) {
89
90
  if (config.restServer?.caseSensitiveRoutes !== false)
@@ -127,9 +128,11 @@ export default function applyRouteMatching(api) {
127
128
  * hazard here, so do not carry that constraint across.
128
129
  *
129
130
  * The caller must reject with `next('router')`, NOT `res.sendStatus(404)`, and
130
- * must run this whether or not `this.auth` is set -- see src/request.ts.
131
+ * must run this BEFORE `this.auth` as well as outside `if (this.auth)` -- those
132
+ * are two separate properties with two separate assertions (AC1.11 and AC1.6);
133
+ * see src/request.ts.
131
134
  *
132
- * Guard polarity is `!== false`, matching both siblings, for the same measured
135
+ * Guard polarity is `!== false`, matching its three siblings, for the same measured
133
136
  * reason: the secure value is the TRUTHY one, so a plain truthy check fails
134
137
  * OPEN for any consumer whose shipped `restServer` block predates the key --
135
138
  * the state every existing consumer is in, and reachable in practice because
@@ -155,7 +158,131 @@ export function shouldRejectTarget(req) {
155
158
  const target = req.originalUrl.split('?')[0];
156
159
  // At a mount root express reports `req.path === '/'` while the canonical
157
160
  // target is the bare mount segment, so the two are not simply concatenated.
161
+ //
162
+ // `&& req.baseUrl` is load-bearing and is NOT a redundant truthiness guard.
163
+ // A route class named `index` mounts at '/' (src/main.ts `mountRoute()`),
164
+ // and that is the one mount shape where `req.baseUrl` is ''. Without the
165
+ // conjunct, `GET /` compares the raw target '/' against a canonical of '' and
166
+ // the APPLICATION ROOT is rejected. Measured before it had a guard: shipped
167
+ // `GET /` -> 200, conjunct dropped -> 404, suite 34 pass / 0 fail BOTH ways.
168
+ // Killed now by AC1.12, against `test/sample/requests/index.ts`.
158
169
  const canonical = req.path === '/' && req.baseUrl ? req.baseUrl : req.baseUrl + req.path;
159
170
  return target !== canonical;
160
171
  }
172
+ // RFC 3986 §2.3 UNRESERVED = ALPHA / DIGIT / "-" / "." / "_" / "~".
173
+ //
174
+ // These are the characters a URI generator MUST NOT percent-encode and that a
175
+ // normaliser MUST decode (§6.2.2.2), so an encoded one carries no information
176
+ // a client is ever required to send. Everything else -- every RESERVED
177
+ // character and every non-ASCII octet -- stays encodable, which is the whole
178
+ // reason this is an allowlist of octets rather than a ban on triplets. See
179
+ // `shouldRejectEncoding()` below.
180
+ const UNRESERVED_OCTET = /^[A-Za-z0-9\-._~]$/;
181
+ // A percent-triplet: `%` followed by exactly two hex digits, either case.
182
+ //
183
+ // A `%` can never be part of ANOTHER triplet's hex digits, because `%` is not a
184
+ // hex digit -- so scanning left to right without skipping cannot produce an
185
+ // overlapping false match. `%2561` therefore yields exactly one candidate
186
+ // (`%25`), which is the property AC4 pins.
187
+ //
188
+ // Malformed and over-long escapes (`%zz`, `%`, `%6`, `%c1%a1`, `%e0%81%a1`) are
189
+ // deliberately NOT this function's business: `router@2.2.0`'s `decodeParam`
190
+ // (lib/layer.js:225) answers 400 for them before any handler or hook runs.
191
+ // Verified here rather than imported -- measured 400 both before and after this
192
+ // change. None of those octets is unreserved, and the first three are not valid
193
+ // triplets at all, so the rule does not touch them either way.
194
+ const PERCENT_TRIPLET = /%([0-9A-Fa-f]{2})/g;
195
+ /**
196
+ * Decides whether a request must be rejected because its RAW request target
197
+ * spells an unreserved character as a percent-triplet
198
+ * (abofs/stonyx-rest-server#56).
199
+ *
200
+ * Closes a live authorization bypass on any route class carrying a `:param`
201
+ * segment. Express decodes `req.params` and NOTHING else -- `req.path` and
202
+ * `req.originalUrl` both stay percent-encoded -- so a consumer hook comparing
203
+ * either of those raw fields was walked past by re-spelling the id:
204
+ *
205
+ * GET /enc/secret -> 401 (hook fires)
206
+ * GET /enc/%73ecret -> 200 guarded handler, unauthenticated, id "secret"
207
+ *
208
+ * Both hook shapes are affected and neither is safer than the other; there is
209
+ * no spelling that defeats one and not the same-id comparison in the other.
210
+ * A third shape is worse still: a LITERAL guarded route co-registered with a
211
+ * sibling `/:id` (this repo's own `test/sample/requests/private.ts`) has the
212
+ * encoded spelling miss the literal layer and be ABSORBED by the param route,
213
+ * so the guard is walked past without the guarded handler ever running --
214
+ * measured `GET /private/failure` -> 505 vs `GET /private/%66ailure` -> 200.
215
+ *
216
+ * THE RULE IS AN UNRESERVED-OCTET SCAN, NOT A DECODE-AND-COMPARE. Two wrong
217
+ * implementations were built and measured, and each breaks a legitimate
218
+ * request:
219
+ *
220
+ * 1. `decodeURIComponent(target) !== target` -- rejects `/enc/sec%2fret`
221
+ * (404), which names the DISTINCT id `sec/ret`. The router SPLITS then
222
+ * DECODES; a whole-target decode decodes then splits, and the two
223
+ * disagree about `%2f` by construction. Killed by AC3.
224
+ * 2. decode until stable -- rejects `/enc/%2573ecret` (404), which names the
225
+ * legitimate id `%73ecret`. Express decodes EXACTLY ONCE, so `%2561` is
226
+ * not a bypass and a loop invents a false deny. Killed by AC4.
227
+ *
228
+ * WHY THIS IS NOT PART OF `shouldRejectTarget()` (#54), and why extending that
229
+ * comparison cannot work: for `GET /enc/%73ecret`, `originalUrl` is
230
+ * `/enc/%73ecret`, `baseUrl` is `/enc` and `path` is `/%73ecret`, so
231
+ * `target === canonical` -- both sides carry the SAME encoded string. The
232
+ * comparison is structurally blind to this axis and no change to it can see it.
233
+ *
234
+ * WHY IT IS A FOURTH KEY AND NOT A REUSE OF `canonicalRoutes`. Measured with
235
+ * the rule implemented correctly but gated on #54's key:
236
+ * `REST_CANONICAL_ROUTES=false` returns `GET /enc/%73ecret` to 200. That flag
237
+ * is exactly what a consumer behind an absolute-form-emitting forward proxy
238
+ * must set, so folding the two would hand precisely those consumers the
239
+ * encoding bypass as the price of staying up. Same argument the block above
240
+ * makes for why #50 is not a rename of #47. Pinned by
241
+ * `test/unit/request-test.ts` AC5, which also asserts -- in that same state --
242
+ * that #54's own vector IS re-opened, so an implementation that simply ignores
243
+ * `canonicalRoutes` cannot pass it vacuously.
244
+ *
245
+ * TIMING CONTRACT: identical to `shouldRejectTarget()` and NOT to the two
246
+ * settings above. Read per request, inside the handler closure in
247
+ * `Request.registerCalls()`; there is no lazy-materialisation hazard, so do not
248
+ * move it into `applyRouteMatching()`. The caller must reject with
249
+ * `next('router')`, and must run this BEFORE `this.auth` as well as outside
250
+ * `if (this.auth)` -- see src/request.ts.
251
+ *
252
+ * Guard polarity is `!== false`, matching all three siblings, for the same
253
+ * measured reason: the secure value is the TRUTHY one, so `=== true` fails OPEN
254
+ * for any consumer whose shipped `restServer` block predates the key. The
255
+ * integration tier CANNOT see that mutation -- with the shipped default `true`
256
+ * every integration assertion stays green -- so it is `test/unit/request-test.ts`
257
+ * AC6 that kills it, probing the key present-and-`undefined` and absent as an
258
+ * own property separately.
259
+ *
260
+ * WHAT THIS DOES NOT CLOSE, stated here rather than left implied. It cannot
261
+ * give each decoded id exactly one accepted spelling, because reserved
262
+ * characters must remain encodable: `/enc/a+b` and `/enc/a%2Bb` both name the
263
+ * id `a+b`, and `/enc/sec%2fret` and `/enc/sec%2Fret` both name `sec/ret`. So a
264
+ * hook comparing a raw path string REMAINS UNSOUND for any id containing a
265
+ * reserved character, and `req.params` -- which express decodes, and which is
266
+ * populated before `auth()` runs -- is the sound idiom. That residual is the
267
+ * consumer's comparison to own; the module cannot close it without 404ing
268
+ * encodings clients are required to emit.
269
+ */
270
+ export function shouldRejectEncoding(req) {
271
+ // `!== false`, not `=== false` and not a truthy check: the polarity is the
272
+ // load-bearing part and it should read identically to the three guards above.
273
+ const enforced = config.restServer?.canonicalEncoding !== false;
274
+ if (!enforced)
275
+ return false;
276
+ // Raw, unparsed, and only the query string removed -- by string split, for
277
+ // the same reason #54 gives: parsing would launder the exact string the
278
+ // consumer's hook is exposed to. The query is stripped because a query string
279
+ // is a legitimately variable part of a request target and may carry any
280
+ // encoding at all; `?name=%61` is a normal request and must not 404.
281
+ const target = req.originalUrl.split('?')[0];
282
+ for (const [, hex] of target.matchAll(PERCENT_TRIPLET)) {
283
+ if (UNRESERVED_OCTET.test(String.fromCharCode(parseInt(hex, 16))))
284
+ return true;
285
+ }
286
+ return false;
287
+ }
161
288
  //# sourceMappingURL=route-matching.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-matching.js","sourceRoot":"","sources":["../src/route-matching.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,eAAe,CAAC;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAChF,4EAA4E;AAC5E,0EAA0E;AAC1E,2CAA2C;AAC3C,EAAE;AACF,gFAAgF;AAChF,4EAA4E;AAC5E,2EAA2E;AAC3E,gFAAgF;AAChF,gFAAgF;AAChF,+DAA+D;AAC/D,MAAM,eAAe,GAAG,oBAAoB,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AACH,MAAM,UAAU,oBAAoB,CAAC,GAAmB;IACtD,2EAA2E;IAC3E,8EAA8E;IAC9E,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,EAAE,iBAAiB,KAAK,KAAK,CAAC;IAChE,IAAI,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5B,2EAA2E;IAC3E,wEAAwE;IACxE,8EAA8E;IAC9E,wEAAwE;IACxE,qEAAqE;IACrE,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAE7C,KAAK,MAAM,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC;QACvD,IAAI,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAI,EAAE,EAAE,CAAC,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;IAClF,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.2.1-alpha.24",
7
+ "version": "0.2.1-alpha.26",
8
8
  "description": "Rest Server Module for Stonyx Framework",
9
9
  "repository": {
10
10
  "type": "git",