@johnhenry/browsermesh-ingress 0.1.0 → 0.2.0
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 +155 -9
- package/package.json +3 -3
- package/src/headers.mjs +48 -1
- package/src/index.mjs +2 -2
- package/src/ingress.mjs +111 -43
- package/src/provider.mjs +73 -14
- package/src/wire.mjs +15 -0
package/README.md
CHANGED
|
@@ -62,13 +62,14 @@ const { port, close } = await listenNode(ingress, { port: 8080, host: '127.0.0.1
|
|
|
62
62
|
```
|
|
63
63
|
|
|
64
64
|
`createMeshIngress({ node | service, resolve, authorize?, deny?, limits?, methods?, forwardHeaders?, exposeHeaders?,
|
|
65
|
-
forwardClientAddress?, verifyResponse?, rpc?, onAudit?, clock? })` returns
|
|
66
|
-
stats(), close() }`.
|
|
67
|
-
|
|
68
|
-
- `resolve(request) -> Promise<{ peer, path?, headers?, response? } | null>`: `peer` is the pod id the
|
|
69
|
-
to; `path` replaces the request's path (the query is kept); `headers` are added to what the provider
|
|
70
|
-
`response` is `{ contentSecurityPolicy, cacheControl, allowSetCookie }` to opt this mapping out of
|
|
71
|
-
(`nosniff` is not optional). `null` is a 404.
|
|
65
|
+
forwardClientAddress?, verifyResponse?, signRequest?, retry?, rpc?, onAudit?, clock? })` returns
|
|
66
|
+
`{ handle(request, { clientAddress }), stats(), close() }`.
|
|
67
|
+
|
|
68
|
+
- `resolve(request, { attempt, tried }) -> Promise<{ peer, path?, headers?, response? } | null>`: `peer` is the pod id the
|
|
69
|
+
answer is pinned to; `path` replaces the request's path (the query is kept); `headers` are added to what the provider
|
|
70
|
+
is sent; `response` is `{ contentSecurityPolicy, cacheControl, allowSetCookie, addHeaders }` to opt this mapping out of
|
|
71
|
+
the response policy or to add headers you author (`nosniff` is not optional). `null` is a 404. The second argument is
|
|
72
|
+
`{ attempt: 0, tried: [] }` unless `retry` is set (see Retry).
|
|
72
73
|
- `authorize(request, target) -> boolean`: anything but `true` is a 403. `deny(request) -> Response | true | null`: a
|
|
73
74
|
Response is sent as it is, `true` is a 451.
|
|
74
75
|
- `limits`: see Defaults. `verifyResponse({ peer, bytes, sig, request })`: signed responses (below).
|
|
@@ -95,6 +96,45 @@ node.registry.grantCapabilities(ingressPodId, ['protocol:http:open']) // the r
|
|
|
95
96
|
`signal` aborts when the client goes away or the deadline passes. `request.url` is `http://<the client's host><path>`.
|
|
96
97
|
A request body is read whole (bounded) before the handler runs, so it works in every browser; response bodies stream.
|
|
97
98
|
|
|
99
|
+
**`allowFrom` is required, and is a list or a function.** A list names the ingress pod ids served. A function
|
|
100
|
+
`(podId, context) => boolean | Promise<boolean>` (`context` is `{ peer, protocol, version }`) is for an ingress whose pod
|
|
101
|
+
identity is new each session and so cannot be listed: it is asked on open and again for every request, and only `true`
|
|
102
|
+
serves (anything else, a throw or a rejection refuses; the handler never runs). Omitting `allowFrom` is still an error.
|
|
103
|
+
**With a function, your own check carries the weight**: the registry grant and the pod id alone no longer say which ingress
|
|
104
|
+
this is, so decide by another proof, for example a signed request (`verifyRequest`, below).
|
|
105
|
+
|
|
106
|
+
### Signed requests (optional)
|
|
107
|
+
|
|
108
|
+
`serveHttpOnMesh(..., { verifyRequest: async (request, { peer, sig, bytes, rid, nonce }) => boolean })` runs before the
|
|
109
|
+
handler, on a clone of the request (the body is still the handler's to read), and can refuse: only `true` lets the request
|
|
110
|
+
through, and a refusal is a 502 `provider-refused-request` for the client. The ingress-side counterpart is
|
|
111
|
+
`createMeshIngress({ signRequest: async (bytes, { peer }) => signature })`, symmetrical to `sign` / `verifyResponse`.
|
|
112
|
+
The signed bytes (`signedRequestBytes()`) are the request's id and a fresh nonce, host, method and target, the headers as
|
|
113
|
+
sent, the client address when forwarded, and the SHA-256 of the body, marked as a request so they never double as a
|
|
114
|
+
response's. `bytes` is rebuilt by the provider from what arrived, so any change in transit fails the check. A provider that
|
|
115
|
+
wants signed requests only must itself refuse a request with no `sig` (the hook is called with `sig` undefined). A
|
|
116
|
+
`signRequest` that throws or returns no text is a 500 `sign-error` and nothing is sent. The package chooses no
|
|
117
|
+
cryptography; a provider that does not know `sig` ignores it, so an older provider simply does not verify.
|
|
118
|
+
|
|
119
|
+
### Declining a request
|
|
120
|
+
|
|
121
|
+
A handler that cannot answer, and has done no work for the request, returns `declineRequest()` (exported) instead of a
|
|
122
|
+
response. The ingress surfaces it as the named failure `provider-declined` (502); it is **never** sent to the client as the
|
|
123
|
+
provider's own response. A handler that merely returns a 421 is giving an ordinary answer, which passes through. On the
|
|
124
|
+
wire a decline is `{ status: 421, headers: [], body: false, declined: true }`; an older ingress that does not know
|
|
125
|
+
`declined` shows its client a plain, empty 421.
|
|
126
|
+
|
|
127
|
+
### Retry (optional)
|
|
128
|
+
|
|
129
|
+
`createMeshIngress({ retry: { attempts: 2, on: ['provider-unreachable', 'provider-pin-mismatch', 'provider-declined'] } })`
|
|
130
|
+
(off by default; `on` defaults to all three, nothing else can be named). After one of those failures, which all happen
|
|
131
|
+
before a provider did any work, `resolve` is called again with `{ attempt, tried }`, the pod ids already tried, so it can
|
|
132
|
+
pick another; a mapping that returns `null` or a pod already tried ends the retries with the original failure. At most
|
|
133
|
+
`attempts` (1 to 5) more times, under the same single deadline. Every attempt is authorised (`authorize`), rate-limited and
|
|
134
|
+
audited on its own (the audit record has `attempt`, and `retried: true` for one that was handed on); `stats().retries`
|
|
135
|
+
counts them. Never after a provider started answering (its own error, a bad signature, a refused request, a stalled body)
|
|
136
|
+
and, for `POST` and `PATCH`, only with `retry.nonIdempotent: true`.
|
|
137
|
+
|
|
98
138
|
`fromSiteHandler(createSiteRequestHandler(siteConfig))` serves a serverless site (`browsermesh-apps`) over `http`
|
|
99
139
|
without rewriting it (wrap, not replace: the legacy service keeps working over mesh-rpc).
|
|
100
140
|
|
|
@@ -106,6 +146,112 @@ the source) are the request's id and a fresh nonce, host, method and target, the
|
|
|
106
146
|
them and the SHA-256 of the body; the provider buffers a signed response. A response with no signature, or one the hook
|
|
107
147
|
does not accept, is a 502 (`response-unsigned`, `response-signature-invalid`). The package chooses no cryptography.
|
|
108
148
|
|
|
149
|
+
## Headers, by default and on purpose
|
|
150
|
+
|
|
151
|
+
What crosses, with no option set (a test pins both lists to the code):
|
|
152
|
+
|
|
153
|
+
<!-- headers-table:begin -->
|
|
154
|
+
| Direction | Passed by default | Never, whatever you set |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| Request, client to provider | `accept`, `accept-language`, `content-type`, `if-match`, `if-modified-since`, `if-none-match`, `if-unmodified-since`, `range` | `host`, `connection`, `keep-alive`, `proxy-*`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `content-length`, `expect`, `forwarded`, `x-real-ip`, `via`, `x-forwarded-*`, `x-original-url`, `x-rewrite-url` |
|
|
157
|
+
| Response, provider to client | `content-type`, `content-length`, `content-language`, `content-disposition`, `content-range`, `accept-ranges`, `etag`, `last-modified`, `location` (a path on this origin only), `vary`, `retry-after`, `allow` | `content-encoding` other than `identity` (a 502), and everything not listed, including `set-cookie`, CORS, HSTS, `refresh`, `link` |
|
|
158
|
+
<!-- headers-table:end -->
|
|
159
|
+
|
|
160
|
+
`Authorization`, `Cookie` and every other request header are **not** forwarded unless you name them; CORS and every other
|
|
161
|
+
response header are **not** exposed unless you name them. Do it deliberately, per ingress:
|
|
162
|
+
|
|
163
|
+
```js
|
|
164
|
+
createMeshIngress({
|
|
165
|
+
service, resolve,
|
|
166
|
+
forwardHeaders: ['authorization', 'cookie'], // the provider now sees them: it must be a pod you trust with them
|
|
167
|
+
exposeHeaders: ['access-control-allow-origin', 'access-control-allow-credentials', 'x-request-id'],
|
|
168
|
+
})
|
|
169
|
+
// or, for one mapping and values you author yourself (no line breaks, 16 at most, never the forced headers):
|
|
170
|
+
resolve: () => ({ peer, response: { addHeaders: { 'access-control-allow-origin': 'https://app.example' } } })
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`forwardHeaders` and `exposeHeaders` apply to every mapping and let through whatever the provider or client sent;
|
|
174
|
+
`response.addHeaders` sets values you wrote for one mapping and replaces what the provider sent under that name. Names on
|
|
175
|
+
the never list stay refused. Forwarding `authorization` or `cookie` to a provider you do not fully trust hands it the
|
|
176
|
+
client's credentials; exposing `set-cookie` needs `allowSetCookie: true` in the mapping.
|
|
177
|
+
|
|
178
|
+
## Every failure the ingress produces
|
|
179
|
+
|
|
180
|
+
Each is a response with this status and an `x-browsermesh-ingress-reason` header carrying the reason (also in the audit
|
|
181
|
+
record and `stats().reasons`). A test pins this table to the code: a status and reason added or removed in the source
|
|
182
|
+
fails it until the table says so.
|
|
183
|
+
|
|
184
|
+
<!-- failures-table:begin -->
|
|
185
|
+
| Status | Reason | Failure mode |
|
|
186
|
+
| --- | --- | --- |
|
|
187
|
+
| 400 | `bad-framing` | `Transfer-Encoding` with `Content-Length`, a bad `Content-Length`, a body that is not the declared length |
|
|
188
|
+
| 400 | `bad-header-value` | a request header with a control character |
|
|
189
|
+
| 400 | `bad-headers` | a header the listener could not parse |
|
|
190
|
+
| 400 | `bad-host` | a `Host` that is not a plain hostname, or a URL with credentials |
|
|
191
|
+
| 400 | `bad-request` | a request the listener could not read |
|
|
192
|
+
| 400 | `bad-request-head` | (provider side) a malformed request head |
|
|
193
|
+
| 400 | `bad-stream` | a body stream that is not one this end expects |
|
|
194
|
+
| 400 | `bad-target` | a request target that is not an origin-form path |
|
|
195
|
+
| 400 | `body-on-get` | a body on `GET` or `HEAD` |
|
|
196
|
+
| 403 | `forbidden` | `authorize` said no (or, provider side, `allowFrom`) |
|
|
197
|
+
| 404 | `no-mapping` | `resolve` returned `null` |
|
|
198
|
+
| 405 | `method-not-allowed` | a method not in `methods` (with `Allow`) |
|
|
199
|
+
| 408 | `body-timeout` | the client's body stalled |
|
|
200
|
+
| 413 | `body-too-large` | the request body is over the cap |
|
|
201
|
+
| 414 | `target-too-long` | the target is over 2048 characters |
|
|
202
|
+
| 426 | `upgrade-unsupported` | a WebSocket or other upgrade |
|
|
203
|
+
| 429 | `client-inflight` | too many requests from this client in flight (with `Retry-After`) |
|
|
204
|
+
| 429 | `client-rate` | too many requests from this client in the window (with `Retry-After`) |
|
|
205
|
+
| 431 | `headers-too-large` | too many or too large request headers |
|
|
206
|
+
| 451 | `denied` | `deny` returned `true` |
|
|
207
|
+
| 499 | `client-aborted` | the client went away |
|
|
208
|
+
| 500 | `bad-mapping` | `resolve` named a bad pod id, path, header or response policy |
|
|
209
|
+
| 500 | `deny-error` | `deny` threw |
|
|
210
|
+
| 500 | `internal-error` | an unexpected failure inside the ingress |
|
|
211
|
+
| 500 | `resolve-error` | `resolve` threw |
|
|
212
|
+
| 500 | `sign-error` | `signRequest` threw or returned no text |
|
|
213
|
+
| 502 | `bad-content-encoding` | the provider sent a content coding that is not `identity` |
|
|
214
|
+
| 502 | `bad-response-head` | the provider's answer is not a well-formed head |
|
|
215
|
+
| 502 | `bad-response-length` | the body is not the length the provider declared |
|
|
216
|
+
| 502 | `bad-response-status` | a status outside 200-599 |
|
|
217
|
+
| 502 | `provider-closed` | the channel to the provider closed mid-request |
|
|
218
|
+
| 502 | `provider-declined` | the provider declined the request (`declineRequest()`), retryable |
|
|
219
|
+
| 502 | `provider-error` | the provider's handler failed (an internal error on its side) |
|
|
220
|
+
| 502 | `provider-failed` | the provider failed to answer |
|
|
221
|
+
| 502 | `provider-no-http` | the provider does not serve the `http` protocol |
|
|
222
|
+
| 502 | `provider-not-authorized` | the provider has not granted this ingress the protocol, or no longer does |
|
|
223
|
+
| 502 | `provider-pin-mismatch` | the channel is bound to another pod than the mapping names, retryable |
|
|
224
|
+
| 502 | `provider-redirect-refused` | a `Location` that is not a path on this origin |
|
|
225
|
+
| 502 | `provider-refused-body` | the provider would not take the request body |
|
|
226
|
+
| 502 | `provider-refused-request` | the provider's `verifyRequest` refused the request |
|
|
227
|
+
| 502 | `provider-unreachable` | no direct link to the provider (routed delivery is not supported), retryable |
|
|
228
|
+
| 502 | `provider-version` | no version of the protocol in common |
|
|
229
|
+
| 502 | `response-signature-invalid` | `verifyResponse` did not accept the signature |
|
|
230
|
+
| 502 | `response-too-large` | the response is over the cap |
|
|
231
|
+
| 502 | `response-unsigned` | `verifyResponse` is set and the response has no signature |
|
|
232
|
+
| 503 | `busy` | (provider side) too many bodies or requests waiting |
|
|
233
|
+
| 503 | `closing` | the ingress is shutting down |
|
|
234
|
+
| 503 | `overloaded` | the ingress is at its global in-flight cap (with `Retry-After`) |
|
|
235
|
+
| 503 | `provider-inflight` | this provider is at its in-flight cap (with `Retry-After`) |
|
|
236
|
+
| 503 | `provider-rate` | this provider is over its rate (with `Retry-After`) |
|
|
237
|
+
| 504 | `provider-idle` | the provider announced a body and did not send it, or stalled |
|
|
238
|
+
| 504 | `provider-timeout` | the whole request ran past `timeoutMs`, or the provider did not answer the open |
|
|
239
|
+
<!-- failures-table:end -->
|
|
240
|
+
|
|
241
|
+
A provider's own answer, including its own 4xx and 5xx and a plain 421, passes through with the policy headers applied.
|
|
242
|
+
|
|
243
|
+
## What carries it, and what it does not do
|
|
244
|
+
|
|
245
|
+
- The `http` protocol channel needs only **a byte duplex with a peer identity**: the channel is a protocol on the existing
|
|
246
|
+
mesh link, so it rides whatever link the mesh has to the pod, a direct WebRTC channel, a WebSocket, or a relayed link,
|
|
247
|
+
as long as each message arrives from the peer the link says it is.
|
|
248
|
+
- **On a link whose peer identity is only asserted by a third party** (a relay that vouches for who is on the other end,
|
|
249
|
+
rather than a key both ends checked), the pod id the ingress and the provider see is only as good as that third party. There
|
|
250
|
+
the signed-response (`sign` / `verifyResponse`) and signed-request (`signRequest` / `verifyRequest`) hooks should be
|
|
251
|
+
mandatory in your application: set all four, and refuse an unsigned answer or request.
|
|
252
|
+
- **There is no multi-hop delivery**: the ingress asks the one pod a mapping names over a link it has; a pod it has no
|
|
253
|
+
direct link to is a 502 `provider-unreachable`. `retry` picks another named pod; it does not route.
|
|
254
|
+
|
|
109
255
|
## Defaults (each has a test)
|
|
110
256
|
|
|
111
257
|
| Rule | Default |
|
|
@@ -124,7 +270,7 @@ does not accept, is a 502 (`response-unsigned`, `response-signature-invalid`). T
|
|
|
124
270
|
| Framing | `Transfer-Encoding` with `Content-Length`, a bad or repeated `Content-Length`, a body on GET/HEAD: 400 |
|
|
125
271
|
| Upgrade | 426: WebSocket is not bridged |
|
|
126
272
|
| Response headers | allow-list; `Set-Cookie`, `Content-Encoding`, HSTS, `Refresh`, CORS and unknown headers dropped |
|
|
127
|
-
| Forced | `Content-Security-Policy: default-src 'none'; sandbox
|
|
273
|
+
| Forced | `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox` (a response is never framed; `contentSecurityPolicy` in the mapping replaces or removes it), `X-Content-Type-Options: nosniff`, `Cache-Control: no-store`, `Vary` |
|
|
128
274
|
| Redirects | never followed; a `Location` that is not a path on this origin is a 502 |
|
|
129
275
|
| Audit | pod, host, method, status, reason, bytes, duration; never query strings, paths or bodies |
|
|
130
276
|
|
|
@@ -157,7 +303,7 @@ protocol service to.
|
|
|
157
303
|
## Wire
|
|
158
304
|
|
|
159
305
|
Protocol `http` v1 on a protocol channel: one channel request `fetch { rid, nonce, method, target, host, headers, body,
|
|
160
|
-
client? } -> { status, headers, body, sig? }`; bodies are protocol streams (`{ rid, kind: 'request' }` ingress to
|
|
306
|
+
client?, sig? } -> { status, headers, body, sig?, declined? }`; bodies are protocol streams (`{ rid, kind: 'request' }` ingress to
|
|
161
307
|
provider, `{ rid, kind: 'response' }` opened by the provider before it answers). No new framing; a peer without the
|
|
162
308
|
protocol answers the open with `unknown-protocol` and is sent nothing else. Design: [`docs/design/http-ingress.md`](../../docs/design/http-ingress.md);
|
|
163
309
|
threat model: [`docs/security.md`](../../docs/security.md#http-ingress).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-ingress",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Real HTTP in, a mesh peer answers: a bounded request forwarder from an HTTP listener to the one BrowserMesh pod a mapping names, over a protocol channel",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -47,10 +47,10 @@
|
|
|
47
47
|
"@johnhenry/browsermesh-discovery": "^0.4.0",
|
|
48
48
|
"@johnhenry/browsermesh-pod": "^0.5.0",
|
|
49
49
|
"@johnhenry/browsermesh-primitives": "^0.6.1",
|
|
50
|
-
"@johnhenry/browsermesh-transport": "^0.
|
|
50
|
+
"@johnhenry/browsermesh-transport": "^0.11.0",
|
|
51
51
|
"node-datachannel": "^0.33.4"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
|
-
"@johnhenry/browsermesh-apps": "^0.21.
|
|
54
|
+
"@johnhenry/browsermesh-apps": "^0.21.2"
|
|
55
55
|
}
|
|
56
56
|
}
|
package/src/headers.mjs
CHANGED
|
@@ -31,7 +31,8 @@ export const DEFAULT_PASS_RESPONSE_HEADERS = Object.freeze([
|
|
|
31
31
|
'etag', 'last-modified', 'location', 'vary', 'retry-after', 'allow',
|
|
32
32
|
])
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
// `frame-ancestors 'none'`: a response the ingress serves is never something a page frames, unless the mapping says so.
|
|
35
|
+
export const DEFAULT_CSP = "default-src 'none'; frame-ancestors 'none'; sandbox"
|
|
35
36
|
|
|
36
37
|
/** Statuses that carry no body. */
|
|
37
38
|
export const NO_BODY_STATUS = new Set([204, 205, 304])
|
|
@@ -153,6 +154,44 @@ export function checkClientRequestShape(headers, method, { maxCount, maxBytes })
|
|
|
153
154
|
return { contentLength: cl === null ? null : Number(cl.trim()), chunked: te !== null }
|
|
154
155
|
}
|
|
155
156
|
|
|
157
|
+
const HOP_BY_HOP_RESPONSE = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade'])
|
|
158
|
+
const FRAMING_RESPONSE = new Set(['content-length', 'content-encoding'])
|
|
159
|
+
export const MAX_ADD_HEADERS = 16
|
|
160
|
+
export const MAX_ADD_HEADER_VALUE = 1024
|
|
161
|
+
export const MAX_ADD_HEADERS_BYTES = 4096
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The headers an operator adds to a mapping's responses (`response.addHeaders`), checked: at most 16 of at most 1024 bytes
|
|
165
|
+
* of text each (4 KiB in all), names that are tokens, values with no control character (so no line break), no hop-by-hop or
|
|
166
|
+
* framing header, and none of the forced headers unless that header's own opt-out is set (`contentSecurityPolicy: false`,
|
|
167
|
+
* `cacheControl: false`; `x-content-type-options` has none; `set-cookie` needs `allowSetCookie`). A bad one is a bad mapping.
|
|
168
|
+
* @param {object} response - the mapping's `response` policy
|
|
169
|
+
* @returns {Array<[string, string]>} lower-cased names
|
|
170
|
+
*/
|
|
171
|
+
export function checkAddHeaders(response = {}) {
|
|
172
|
+
const add = response.addHeaders
|
|
173
|
+
if (add === undefined) return []
|
|
174
|
+
const bad = () => new IngressError(500, 'bad-mapping', 'A mapping named a response header that may not be added.')
|
|
175
|
+
if (!add || typeof add !== 'object' || Array.isArray(add)) throw bad()
|
|
176
|
+
const entries = Object.entries(add)
|
|
177
|
+
if (entries.length > MAX_ADD_HEADERS) throw bad()
|
|
178
|
+
const out = []
|
|
179
|
+
let bytes = 0
|
|
180
|
+
for (const [rawName, value] of entries) {
|
|
181
|
+
const name = rawName.toLowerCase()
|
|
182
|
+
if (!isToken(name) || typeof value !== 'string' || !isValue(value) || byteLength(value) > MAX_ADD_HEADER_VALUE) throw bad()
|
|
183
|
+
if (HOP_BY_HOP_RESPONSE.has(name) || name.startsWith('proxy-') || FRAMING_RESPONSE.has(name)) throw bad()
|
|
184
|
+
if (name === 'content-security-policy' && response.contentSecurityPolicy !== false) throw bad()
|
|
185
|
+
if (name === 'cache-control' && response.cacheControl !== false) throw bad()
|
|
186
|
+
if (name === 'x-content-type-options') throw bad()
|
|
187
|
+
if (name === 'set-cookie' && response.allowSetCookie !== true) throw bad()
|
|
188
|
+
bytes += byteLength(name) + byteLength(value) + 4
|
|
189
|
+
if (bytes > MAX_ADD_HEADERS_BYTES) throw bad()
|
|
190
|
+
out.push([name, value])
|
|
191
|
+
}
|
|
192
|
+
return out
|
|
193
|
+
}
|
|
194
|
+
|
|
156
195
|
/** Is this a Location the ingress may pass on? Only an absolute path on the same origin; never another origin or scheme. */
|
|
157
196
|
export function safeLocation(value) {
|
|
158
197
|
return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') && !/[\\\u0000-\u001f\u007f]/.test(value)
|
|
@@ -169,6 +208,8 @@ export function responseHeadersForClient(list, { response = {}, forward = [], ex
|
|
|
169
208
|
if (response.allowSetCookie === true) pass.add('set-cookie')
|
|
170
209
|
const out = new Headers()
|
|
171
210
|
const vary = new Set(varyNames(forward))
|
|
211
|
+
const added = checkAddHeaders(response)
|
|
212
|
+
for (const [name, value] of added) if (name === 'vary') for (const v of value.split(',')) if (v.trim()) vary.add(v.trim().toLowerCase())
|
|
172
213
|
for (const [name, value] of list) {
|
|
173
214
|
const lower = name.toLowerCase()
|
|
174
215
|
if (lower === 'content-encoding') {
|
|
@@ -185,6 +226,12 @@ export function responseHeadersForClient(list, { response = {}, forward = [], ex
|
|
|
185
226
|
if (vary.has('*')) out.set('vary', '*')
|
|
186
227
|
else if (vary.size) out.set('vary', [...vary].join(', '))
|
|
187
228
|
applyForcedHeaders(out, response)
|
|
229
|
+
// The operator's own headers last: they replace what the provider set under the same name.
|
|
230
|
+
for (const [name, value] of added) {
|
|
231
|
+
if (name === 'vary') continue // merged above
|
|
232
|
+
if (name === 'set-cookie') out.append(name, value)
|
|
233
|
+
else out.set(name, value)
|
|
234
|
+
}
|
|
188
235
|
return out
|
|
189
236
|
}
|
|
190
237
|
|
package/src/index.mjs
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* This entry imports no `node:` module (a test asserts it).
|
|
9
9
|
*/
|
|
10
10
|
export { createMeshIngress } from './ingress.mjs'
|
|
11
|
-
export { serveHttpOnMesh, fromSiteHandler, PROVIDER_LIMIT_DEFAULTS } from './provider.mjs'
|
|
11
|
+
export { serveHttpOnMesh, fromSiteHandler, declineRequest, PROVIDER_LIMIT_DEFAULTS } from './provider.mjs'
|
|
12
12
|
export { INGRESS_LIMIT_DEFAULTS, parseBytes, parseDuration } from './limits.mjs'
|
|
13
13
|
export { IngressError, REASON_HEADER } from './errors.mjs'
|
|
14
14
|
export { DEFAULT_CSP, DEFAULT_FORWARD_REQUEST_HEADERS, DEFAULT_PASS_RESPONSE_HEADERS } from './headers.mjs'
|
|
15
|
-
export { HTTP_PROTOCOL, HTTP_VERSIONS, signedBytes } from './wire.mjs'
|
|
15
|
+
export { HTTP_PROTOCOL, HTTP_VERSIONS, signedBytes, signedRequestBytes } from './wire.mjs'
|
package/src/ingress.mjs
CHANGED
|
@@ -10,12 +10,12 @@ import { attachService } from '@johnhenry/browsermesh-apps/mesh-service'
|
|
|
10
10
|
import { createMeshProtocolService } from '@johnhenry/browsermesh-apps/protocol-channel'
|
|
11
11
|
import { IngressError, REASON_HEADER } from './errors.mjs'
|
|
12
12
|
import {
|
|
13
|
-
NO_BODY_STATUS, applyForcedHeaders, checkClientRequestShape, checkHost, checkMappedPath, checkTarget, isPodId,
|
|
13
|
+
NO_BODY_STATUS, applyForcedHeaders, checkAddHeaders, checkClientRequestShape, checkHost, checkMappedPath, checkTarget, isPodId,
|
|
14
14
|
requestHeadersForProvider, responseHeadersForClient,
|
|
15
15
|
} from './headers.mjs'
|
|
16
16
|
import { createInflight, createRateLimiter, resolveLimits } from './limits.mjs'
|
|
17
17
|
import {
|
|
18
|
-
FETCH_METHOD, HTTP_PROTOCOL, HTTP_VERSIONS, KIND_RESPONSE, KIND_REQUEST, WIRE_METHODS, signedBytes, sha256Hex, validateResponseHead,
|
|
18
|
+
FETCH_METHOD, HTTP_PROTOCOL, HTTP_VERSIONS, KIND_RESPONSE, KIND_REQUEST, WIRE_METHODS, signedBytes, signedRequestBytes, sha256Hex, validateResponseHead,
|
|
19
19
|
validateStreamMeta,
|
|
20
20
|
} from './wire.mjs'
|
|
21
21
|
|
|
@@ -38,14 +38,38 @@ function within(promise, ms, make) {
|
|
|
38
38
|
|
|
39
39
|
const reasonOf = (e) => (e instanceof IngressError ? e.reason : e?.name === 'AbortError' ? 'client-aborted' : 'error')
|
|
40
40
|
|
|
41
|
+
/** The failures in which the provider did no work, so a retry cannot repeat anything it did. Nothing else is ever retried. */
|
|
42
|
+
export const RETRYABLE_REASONS = Object.freeze(['provider-unreachable', 'provider-pin-mismatch', 'provider-declined'])
|
|
43
|
+
const MAX_RETRY_ATTEMPTS = 5
|
|
44
|
+
const IDEMPOTENT = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'])
|
|
45
|
+
|
|
46
|
+
function resolveRetry(retry) {
|
|
47
|
+
if (retry === undefined) return null
|
|
48
|
+
if (!retry || typeof retry !== 'object' || Array.isArray(retry)) throw new TypeError('createMeshIngress: retry must be { attempts, on?, nonIdempotent? }')
|
|
49
|
+
const { attempts, on = RETRYABLE_REASONS, nonIdempotent = false } = retry
|
|
50
|
+
if (!Number.isInteger(attempts) || attempts < 1 || attempts > MAX_RETRY_ATTEMPTS) throw new TypeError(`createMeshIngress: retry.attempts must be an integer from 1 to ${MAX_RETRY_ATTEMPTS}`)
|
|
51
|
+
if (!Array.isArray(on) || !on.length || !on.every((r) => RETRYABLE_REASONS.includes(r))) throw new TypeError(`createMeshIngress: retry.on must be a non-empty list of ${RETRYABLE_REASONS.join(', ')}`)
|
|
52
|
+
if (typeof nonIdempotent !== 'boolean') throw new TypeError('createMeshIngress: retry.nonIdempotent must be a boolean')
|
|
53
|
+
return { attempts, on: new Set(on), nonIdempotent }
|
|
54
|
+
}
|
|
55
|
+
|
|
41
56
|
/**
|
|
42
57
|
* @param {object} opts
|
|
43
58
|
* @param {object} [opts.service] - a mesh service with the protocol channel: `attachService(node, undefined, createMeshProtocolService())`, or its `.api`
|
|
44
59
|
* @param {object} [opts.node] - alternatively a mesh node: this attaches a protocol service to it (do not also attach one yourself) and `close()` detaches it
|
|
45
|
-
* @param {(request: Request) => Promise<{ peer: string, path?: string, headers?: Record<string,string>, response?: object }|null>} opts.resolve
|
|
60
|
+
* @param {(request: Request, attempt: { attempt: number, tried: string[] }) => Promise<{ peer: string, path?: string, headers?: Record<string,string>, response?: object }|null>} opts.resolve
|
|
46
61
|
* Which pod answers. `null` is a 404. `peer` is the pod id the answer is pinned to; `path` replaces the request's path;
|
|
47
|
-
* `headers` are added to what the provider is sent; `response` is `{ contentSecurityPolicy, cacheControl, allowSetCookie
|
|
48
|
-
* to opt this mapping out of the response policy
|
|
62
|
+
* `headers` are added to what the provider is sent; `response` is `{ contentSecurityPolicy, cacheControl, allowSetCookie,
|
|
63
|
+
* addHeaders }` to opt this mapping out of the response policy, or to add headers the operator authors (`addHeaders`: at
|
|
64
|
+
* most 16 names to values; no line breaks, hop-by-hop or framing headers; the forced headers only where their own opt-out is set).
|
|
65
|
+
* The second argument is `{ attempt: 0, tried: [] }` the first time; with `retry` it is asked again with the pod ids already tried.
|
|
66
|
+
* @param {{ attempts: number, on?: string[], nonIdempotent?: boolean }} [opts.retry]
|
|
67
|
+
* Off by default. After a failure in which the provider did no work (`on`: any of `provider-unreachable`,
|
|
68
|
+
* `provider-pin-mismatch`, `provider-declined`; all three by default), `resolve` is called again, up to `attempts` (1 to 5) more
|
|
69
|
+
* times, with the pods already tried; each attempt is authorised and audited on its own. Never after a provider started answering;
|
|
70
|
+
* POST and PATCH only with `nonIdempotent: true`.
|
|
71
|
+
* @param {(bytes: Uint8Array, info: { peer: string }) => (string|Promise<string>)} [opts.signRequest]
|
|
72
|
+
* Sign each request for the provider's `verifyRequest` (the request counterpart of `verifyResponse`). The package picks no cryptography.
|
|
49
73
|
* @param {(request: Request, target: object) => (boolean|Promise<boolean>)} [opts.authorize] - falsy: 403
|
|
50
74
|
* @param {(request: Request) => (Response|boolean|null|Promise<Response|boolean|null>)} [opts.deny] - a Response is sent as it is; `true` is a 451
|
|
51
75
|
* @param {object} [opts.limits] - see `INGRESS_LIMIT_DEFAULTS`
|
|
@@ -61,11 +85,12 @@ const reasonOf = (e) => (e instanceof IngressError ? e.reason : e?.name === 'Abo
|
|
|
61
85
|
*/
|
|
62
86
|
export function createMeshIngress({
|
|
63
87
|
service, node, resolve, authorize, deny, limits: limitOptions, methods = ['GET', 'HEAD'], forwardHeaders = [], exposeHeaders = [],
|
|
64
|
-
forwardClientAddress = false, verifyResponse, rpc, onAudit, clock, protocol = HTTP_PROTOCOL,
|
|
88
|
+
forwardClientAddress = false, verifyResponse, signRequest, retry, rpc, onAudit, clock, protocol = HTTP_PROTOCOL,
|
|
65
89
|
} = {}) {
|
|
66
90
|
if (typeof resolve !== 'function') throw new TypeError('createMeshIngress: resolve(request) is required: nothing is served without a mapping')
|
|
67
91
|
if (!service && !node) throw new TypeError('createMeshIngress: a mesh service (or a node to attach one to) is required')
|
|
68
|
-
for (const [name, fn] of Object.entries({ authorize, deny, verifyResponse, onAudit })) if (fn !== undefined && typeof fn !== 'function') throw new TypeError(`createMeshIngress: ${name} must be a function`)
|
|
92
|
+
for (const [name, fn] of Object.entries({ authorize, deny, verifyResponse, signRequest, onAudit })) if (fn !== undefined && typeof fn !== 'function') throw new TypeError(`createMeshIngress: ${name} must be a function`)
|
|
93
|
+
const retrying = resolveRetry(retry)
|
|
69
94
|
if (rpc !== undefined && typeof rpc?.request !== 'function') throw new TypeError('createMeshIngress: rpc must be a mesh-rpc api with request()')
|
|
70
95
|
const allowedMethods = new Set(methods.map((m) => String(m).toUpperCase()))
|
|
71
96
|
for (const m of allowedMethods) if (!WIRE_METHODS.has(m)) throw new TypeError(`createMeshIngress: method ${m} is never served (allowed: ${[...WIRE_METHODS].join(', ')})`)
|
|
@@ -86,7 +111,7 @@ export function createMeshIngress({
|
|
|
86
111
|
const LEGACY_MEMORY_MS = 60_000
|
|
87
112
|
const active = new Set() // abort controllers of requests in flight
|
|
88
113
|
let closed = false
|
|
89
|
-
const counters = { requests: 0, served: 0, refused: 0, failed: 0, requestBytes: 0, responseBytes: 0, fallbacks: 0, reasons: {} }
|
|
114
|
+
const counters = { requests: 0, served: 0, refused: 0, failed: 0, requestBytes: 0, responseBytes: 0, fallbacks: 0, retries: 0, reasons: {} }
|
|
90
115
|
const count = (reason) => { counters.reasons[reason] = (counters.reasons[reason] ?? 0) + 1 }
|
|
91
116
|
|
|
92
117
|
// ------------------------------------------------------------ HTTP responses the ingress makes itself
|
|
@@ -195,8 +220,14 @@ export function createMeshIngress({
|
|
|
195
220
|
|
|
196
221
|
async function handle(request, info = {}) {
|
|
197
222
|
const startedAt = now()
|
|
198
|
-
const record = { peer: null, host: null, method: request?.method ?? null, status: 0, reason: undefined, requestBytes: 0, responseBytes: 0, durationMs: 0 }
|
|
223
|
+
const record = { peer: null, host: null, method: request?.method ?? null, status: 0, reason: undefined, requestBytes: 0, responseBytes: 0, durationMs: 0, attempt: 0 }
|
|
199
224
|
let audited = false
|
|
225
|
+
// An attempt that was handed on (see `retry`): audited as it happened, then the request goes on.
|
|
226
|
+
const auditAttempt = (rec, e) => {
|
|
227
|
+
counters.retries += 1
|
|
228
|
+
count(e.reason)
|
|
229
|
+
if (onAudit) { try { onAudit({ ...rec, status: e.status, reason: e.reason, retried: true, durationMs: Math.max(0, now() - startedAt) }) } catch { /* an audit sink never breaks a request */ } }
|
|
230
|
+
}
|
|
200
231
|
const audit = (status, reason) => {
|
|
201
232
|
if (audited) return
|
|
202
233
|
audited = true
|
|
@@ -252,39 +283,64 @@ export function createMeshIngress({
|
|
|
252
283
|
if (verdict) throw new IngressError(451, 'denied', 'Unavailable for legal reasons.')
|
|
253
284
|
}
|
|
254
285
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
286
|
+
// One attempt per pass. Without `retry` there is exactly one. With it, a failure in which the provider did no work
|
|
287
|
+
// (it was unreachable, it was the wrong pod, it declined) asks `resolve` again, with the pods already tried; every
|
|
288
|
+
// attempt is mapped, authorised, rate-limited and audited on its own, and all of them share the one deadline.
|
|
289
|
+
const tried = []
|
|
290
|
+
let attempt = 0
|
|
291
|
+
let lastFailure = null
|
|
292
|
+
let bodyBytes = null
|
|
293
|
+
let theirs = null
|
|
294
|
+
for (;;) {
|
|
295
|
+
let mapping
|
|
296
|
+
try { mapping = await resolve(request, { attempt, tried: [...tried] }) } catch { throw new IngressError(500, 'resolve-error', 'The mapping failed.') }
|
|
297
|
+
if (!mapping) throw lastFailure ?? new IngressError(404, 'no-mapping', 'Nothing is served at this address.')
|
|
298
|
+
if (!isPodId(mapping.peer)) throw new IngressError(500, 'bad-mapping', 'A mapping named something that is not a pod id.')
|
|
299
|
+
const peer = mapping.peer
|
|
300
|
+
if (tried.includes(peer)) throw lastFailure // a pod already tried is not asked twice
|
|
301
|
+
record.peer = peer
|
|
302
|
+
record.attempt = attempt
|
|
303
|
+
const path = mapping.path === undefined ? undefined : checkMappedPath(mapping.path)
|
|
304
|
+
const outTarget = path === undefined ? target : checkTarget(path + url.search, limits.maxTargetLength)
|
|
305
|
+
const outHeaders = requestHeadersForProvider(request.headers, { forward: forwardHeaders, extra: mapping.headers })
|
|
306
|
+
const policy = mapping.response && typeof mapping.response === 'object' ? mapping.response : {}
|
|
307
|
+
checkAddHeaders(policy) // a bad operator header is a bad mapping, found before any provider is asked
|
|
275
308
|
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
309
|
+
if (authorize) {
|
|
310
|
+
let ok = false
|
|
311
|
+
try { ok = (await authorize(request, mapping)) === true } catch { ok = false }
|
|
312
|
+
if (!ok) throw new IngressError(403, 'forbidden', 'This request is not authorised.')
|
|
313
|
+
}
|
|
314
|
+
const pr = providerRate.take(peer)
|
|
315
|
+
if (!pr.ok) throw new IngressError(503, 'provider-rate', 'This provider is receiving too many requests.', { headers: { 'retry-after': String(Math.ceil(pr.retryAfterMs / 1000)) } })
|
|
316
|
+
theirs?.() // the pod this attempt replaces
|
|
317
|
+
theirs = inflight.enter(`p:${peer}`, limits.maxInflightPerProvider)
|
|
318
|
+
if (!theirs) throw new IngressError(503, 'provider-inflight', 'This provider is busy.', { headers: { 'retry-after': '1' } })
|
|
319
|
+
releases.push(theirs)
|
|
279
320
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
321
|
+
if (attempt === 0) {
|
|
322
|
+
// The whole request is bounded from here: the client's body, the provider's head and its body.
|
|
323
|
+
deadline = unref(setTimeout(() => ac.abort(new IngressError(504, 'provider-timeout', 'The provider did not answer in time.')), limits.timeoutMs))
|
|
324
|
+
request.signal?.addEventListener('abort', () => ac.abort(new IngressError(499, 'client-aborted', 'The client went away.')), { once: true })
|
|
325
|
+
bodyBytes = await readBody(request, shape.contentLength, limits.maxRequestBodyBytes)
|
|
326
|
+
record.requestBytes = bodyBytes.byteLength
|
|
327
|
+
}
|
|
328
|
+
const forward = { method, target: outTarget, host, headers: outHeaders, body: bodyBytes, client: forwardClientAddress ? client.slice(0, 64) : undefined, peer }
|
|
329
|
+
try {
|
|
330
|
+
// A streamed response keeps the deadline and the slots until its body ends; a buffered one is finished here.
|
|
331
|
+
const response = await forwardToProvider(forward, policy, ac, record, (status, reason) => { clearTimeout(deadline); audit(status, reason); done() })
|
|
332
|
+
if (response.finished) { clearTimeout(deadline); audit(response.status, undefined); done() }
|
|
333
|
+
return response.response
|
|
334
|
+
} catch (e) {
|
|
335
|
+
const retryable = retrying && e instanceof IngressError && retrying.on.has(e.reason) && attempt < retrying.attempts && !ac.signal.aborted
|
|
336
|
+
&& (retrying.nonIdempotent || IDEMPOTENT.has(method))
|
|
337
|
+
if (!retryable) throw e
|
|
338
|
+
auditAttempt(record, e)
|
|
339
|
+
lastFailure = e
|
|
340
|
+
tried.push(peer)
|
|
341
|
+
attempt += 1
|
|
342
|
+
}
|
|
343
|
+
}
|
|
288
344
|
} catch (e) {
|
|
289
345
|
clearTimeout(deadline)
|
|
290
346
|
if (process.env.DEBUG_INGRESS && !(e instanceof IngressError && e.status < 500)) console.error('DEBUG-INGRESS', e)
|
|
@@ -314,10 +370,19 @@ export function createMeshIngress({
|
|
|
314
370
|
}
|
|
315
371
|
if (ac.signal.aborted) throw ac.signal.reason
|
|
316
372
|
const rid = state.nextRid++
|
|
317
|
-
const entry = { reader: null, readerReady: deferred(), fail: (e) => ac.abort(e) }
|
|
318
|
-
state.pending.set(rid, entry)
|
|
319
373
|
const nonce = randomHex(16)
|
|
320
374
|
const hasBody = forward.body.byteLength > 0
|
|
375
|
+
// A signed request: the provider's `verifyRequest` is given exactly these bytes, rebuilt from what arrives.
|
|
376
|
+
let sig
|
|
377
|
+
if (signRequest) {
|
|
378
|
+
try {
|
|
379
|
+
const bytes = signedRequestBytes({ rid, nonce, host: forward.host, method: forward.method, target: forward.target, headers: forward.headers, client: forward.client, digest: await sha256Hex(forward.body) })
|
|
380
|
+
sig = await signRequest(bytes, { peer })
|
|
381
|
+
} catch { sig = undefined }
|
|
382
|
+
if (typeof sig !== 'string' || !sig || sig.length > 2048) throw new IngressError(500, 'sign-error', 'The ingress could not sign the request.')
|
|
383
|
+
}
|
|
384
|
+
const entry = { reader: null, readerReady: deferred(), fail: (e) => ac.abort(e) }
|
|
385
|
+
state.pending.set(rid, entry)
|
|
321
386
|
const cleanup = () => state.pending.delete(rid)
|
|
322
387
|
const cancelReader = (why) => { entry.reader?.cancel(why).catch(() => {}); entry.readerReady.promise.then((r) => r.cancel(why).catch(() => {}), () => {}) }
|
|
323
388
|
const onAbort = () => cancelReader('request ended')
|
|
@@ -327,11 +392,13 @@ export function createMeshIngress({
|
|
|
327
392
|
try {
|
|
328
393
|
const fetchP = state.channel.request(FETCH_METHOD, {
|
|
329
394
|
rid, nonce, method: forward.method, target: forward.target, host: forward.host,
|
|
330
|
-
headers: forward.headers, body: hasBody, ...(forward.client ? { client: forward.client } : {}),
|
|
395
|
+
headers: forward.headers, body: hasBody, ...(forward.client ? { client: forward.client } : {}), ...(sig ? { sig } : {}),
|
|
331
396
|
}, { signal: ac.signal, timeoutMs: limits.timeoutMs })
|
|
332
397
|
// The body travels as a stream. A provider may answer before it has read all of it: the head decides.
|
|
333
398
|
if (hasBody) state.streams.sendBody(forward.body, { rid, kind: KIND_REQUEST }, { signal: ac.signal, timeoutMs: limits.openTimeoutMs }).catch(() => {})
|
|
334
399
|
head = validateResponseHead(await fetchP, limits)
|
|
400
|
+
// "Not me, try another": never the provider's own answer, and nothing of it reaches the client.
|
|
401
|
+
if (head.declined === true) throw new IngressError(502, 'provider-declined', 'The provider declined this request.')
|
|
335
402
|
} catch (e) {
|
|
336
403
|
cleanup()
|
|
337
404
|
ac.signal.removeEventListener('abort', onAbort)
|
|
@@ -340,6 +407,7 @@ export function createMeshIngress({
|
|
|
340
407
|
if (e instanceof IngressError) throw e
|
|
341
408
|
if (e?.reason === 'timeout') throw new IngressError(504, 'provider-timeout', 'The provider did not answer in time.')
|
|
342
409
|
if (e?.reason === 'not-authorized') throw new IngressError(502, 'provider-not-authorized', 'The provider no longer accepts this ingress.')
|
|
410
|
+
if (e?.reason === 'request-unverified') throw new IngressError(502, 'provider-refused-request', 'The provider did not accept the request\'s signature.')
|
|
343
411
|
if (e?.reason === 'too-large' || e?.reason === 'stream-too-large') throw new IngressError(502, 'provider-refused-body', 'The provider would not take the request body.')
|
|
344
412
|
throw new IngressError(502, e?.code === -32603 ? 'provider-error' : 'provider-failed', 'The provider failed to answer.')
|
|
345
413
|
}
|
package/src/provider.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { ChannelErrorCode, MeshChannelError } from '@johnhenry/browsermesh-apps/
|
|
|
10
10
|
import { IngressError } from './errors.mjs'
|
|
11
11
|
import { NO_BODY_STATUS, isPodId } from './headers.mjs'
|
|
12
12
|
import {
|
|
13
|
-
FETCH_METHOD, HTTP_PROTOCOL, HTTP_VERSIONS, KIND_REQUEST, KIND_RESPONSE, sha256Hex, signedBytes, validateRequestHead, validateStreamMeta,
|
|
13
|
+
FETCH_METHOD, HTTP_PROTOCOL, HTTP_VERSIONS, KIND_REQUEST, KIND_RESPONSE, sha256Hex, signedBytes, signedRequestBytes, validateRequestHead, validateStreamMeta,
|
|
14
14
|
} from './wire.mjs'
|
|
15
15
|
|
|
16
16
|
export const PROVIDER_LIMIT_DEFAULTS = Object.freeze({
|
|
@@ -40,40 +40,63 @@ function deferred() {
|
|
|
40
40
|
* @param {object} service - a mesh service with the protocol channel (`attachService(node, undefined, createMeshProtocolService())`, or its `.api`)
|
|
41
41
|
* @param {Function|{ fetch: Function }} handler - `(request, { peer, signal, client }) => Response | Promise<Response>`
|
|
42
42
|
* @param {object} opts
|
|
43
|
-
* @param {string[]|((
|
|
43
|
+
* @param {string[]|((podId: string, context: { peer: string, protocol: string, version: number }) => (boolean|Promise<boolean>))} opts.allowFrom
|
|
44
|
+
* The ingress pods served; required, nothing is served to any other. A list names pod ids. A function is asked with the
|
|
45
|
+
* channel's verified pod id and a context, on open and again for every request; only `true` serves (anything else, a throw
|
|
46
|
+
* or a rejection refuses). With a function the provider's own check carries the weight (for an ingress whose pod id is new
|
|
47
|
+
* each session: verify a signed request with `verifyRequest`).
|
|
48
|
+
* @param {(request: Request, context: { peer: string, sig: string|undefined, bytes: Uint8Array, rid: number, nonce: string }) => (boolean|Promise<boolean>)} [opts.verifyRequest]
|
|
49
|
+
* Runs before the handler, on a clone of the request (its body is still the handler's to read). Only `true` lets the request
|
|
50
|
+
* through; `false`, anything else or a throw refuses it and the handler never runs. `sig` is what the ingress's `signRequest`
|
|
51
|
+
* made (absent when it signed nothing) and `bytes` is exactly what it signed, rebuilt from what arrived.
|
|
44
52
|
* @param {object} [opts.limits] - see `PROVIDER_LIMIT_DEFAULTS`
|
|
45
53
|
* @param {(bytes: Uint8Array, info: { peer: string }) => (string|Promise<string>)} [opts.sign] - sign the response: the provider buffers it so the signature covers the body
|
|
46
54
|
* @param {string} [opts.protocol='http']
|
|
47
55
|
* @returns {{ stop(): void, stats(): object }}
|
|
48
56
|
*/
|
|
49
|
-
export function serveHttpOnMesh(service, handler, { allowFrom, limits: limitOptions, sign, protocol = HTTP_PROTOCOL, onLog } = {}) {
|
|
57
|
+
export function serveHttpOnMesh(service, handler, { allowFrom, limits: limitOptions, sign, verifyRequest, protocol = HTTP_PROTOCOL, onLog } = {}) {
|
|
50
58
|
const api = service && typeof service === 'object' ? (service.api ?? service) : null
|
|
51
59
|
if (typeof api?.serveProtocol !== 'function') throw new TypeError('serveHttpOnMesh: the first argument is a mesh service with serveProtocol (createMeshProtocolService)')
|
|
52
60
|
const fn = typeof handler === 'function' ? handler : typeof handler?.fetch === 'function' ? (req, ctx) => handler.fetch(req, ctx) : null
|
|
53
61
|
if (!fn) throw new TypeError('serveHttpOnMesh: handler must be a function or { fetch }')
|
|
54
62
|
if (sign !== undefined && typeof sign !== 'function') throw new TypeError('serveHttpOnMesh: sign must be a function')
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
63
|
+
if (verifyRequest !== undefined && typeof verifyRequest !== 'function') throw new TypeError('serveHttpOnMesh: verifyRequest must be a function')
|
|
64
|
+
/** @type {(peer: string, context: object) => (boolean|Promise<boolean>)} Never throws; true or false, or a promise of one. */
|
|
65
|
+
let decide
|
|
66
|
+
if (Array.isArray(allowFrom) && allowFrom.length && allowFrom.every(isPodId)) { const set = new Set(allowFrom); decide = (p) => set.has(p) }
|
|
67
|
+
else if (typeof allowFrom === 'function') {
|
|
68
|
+
decide = (p, context) => {
|
|
69
|
+
let verdict
|
|
70
|
+
try { verdict = allowFrom(p, context) } catch { return false }
|
|
71
|
+
return verdict && typeof verdict.then === 'function' ? Promise.resolve(verdict).then((v) => v === true, () => false) : verdict === true
|
|
72
|
+
}
|
|
73
|
+
} else throw new TypeError('serveHttpOnMesh: allowFrom (a non-empty list of ingress pod ids, or a function) is required: nothing is served to a pod that is not named')
|
|
59
74
|
const limits = { ...PROVIDER_LIMIT_DEFAULTS, ...limitOptions }
|
|
60
75
|
for (const [k, v] of Object.entries(limits)) if (!Number.isSafeInteger(v) || v <= 0) throw new TypeError(`serveHttpOnMesh: limits.${k} must be a positive integer`)
|
|
61
76
|
const log = onLog || (() => {})
|
|
62
77
|
|
|
63
78
|
const channels = new Set()
|
|
64
|
-
const counters = { channels: 0, requests: 0, refused: 0, errors: 0, requestBytes: 0, responseBytes: 0, inflight: 0 }
|
|
79
|
+
const counters = { channels: 0, requests: 0, refused: 0, declined: 0, errors: 0, requestBytes: 0, responseBytes: 0, inflight: 0 }
|
|
65
80
|
|
|
66
|
-
function accept(channel, { peer }) {
|
|
67
|
-
|
|
81
|
+
function accept(channel, { peer, version }) {
|
|
82
|
+
const context = { peer, protocol, version }
|
|
83
|
+
// `open` is the verdict at the open: true, false, or null while an async `allowFrom` is still deciding. Nothing is
|
|
84
|
+
// served on a channel whose verdict is not true: every request asks again (below) and a body that arrives meanwhile
|
|
85
|
+
// is only held, bounded, until a request claims it.
|
|
86
|
+
const first = decide(peer, context)
|
|
87
|
+
let open = typeof first === 'boolean' ? first : null
|
|
88
|
+
const refuse = () => { open = false; counters.refused += 1; channels.delete(channel); channel.close('not an ingress this pod serves') }
|
|
89
|
+
if (open === false) { counters.refused += 1; channel.close('not an ingress this pod serves'); return }
|
|
68
90
|
counters.channels += 1
|
|
69
91
|
channels.add(channel)
|
|
92
|
+
if (open === null) first.then((ok) => { if (ok) open = true; else refuse() })
|
|
70
93
|
// One cap per layer, for both directions: the larger of the two. The request body's own cap is enforced where it is read.
|
|
71
94
|
const streams = createStreamLayer(channel, { maxStreams: limits.maxInflight * 2, maxStreamBytes: Math.max(limits.maxRequestBodyBytes, limits.maxResponseBytes) })
|
|
72
95
|
const bodies = new Map() // rid -> { reader } | { waiter }
|
|
73
96
|
let inflight = 0
|
|
74
97
|
|
|
75
98
|
streams.onStream((reader, { meta }) => {
|
|
76
|
-
if (
|
|
99
|
+
if (open === false) throw new IngressError(403, 'forbidden', 'not served')
|
|
77
100
|
validateStreamMeta(meta, KIND_REQUEST)
|
|
78
101
|
if (bodies.size >= limits.maxInflight * 2) throw new IngressError(503, 'busy', 'too many bodies waiting')
|
|
79
102
|
const have = bodies.get(meta.rid)
|
|
@@ -97,7 +120,14 @@ export function serveHttpOnMesh(service, handler, { allowFrom, limits: limitOpti
|
|
|
97
120
|
}
|
|
98
121
|
|
|
99
122
|
channel.onRequest(FETCH_METHOD, async (params, ctx) => {
|
|
100
|
-
if (
|
|
123
|
+
if (open === false) { counters.refused += 1; throw new MeshChannelError(ChannelErrorCode.UNAUTHORIZED, 'not-authorized', 'not served') }
|
|
124
|
+
// Asked again for every request, so a function that stops saying yes stops the next request, and a decision still
|
|
125
|
+
// pending at the open is settled before any work (a list is a plain lookup).
|
|
126
|
+
if ((await decide(peer, context)) !== true) {
|
|
127
|
+
if (open !== false) refuse()
|
|
128
|
+
else counters.refused += 1
|
|
129
|
+
throw new MeshChannelError(ChannelErrorCode.UNAUTHORIZED, 'not-authorized', 'not served')
|
|
130
|
+
}
|
|
101
131
|
if (inflight >= limits.maxInflight) throw new MeshChannelError(ChannelErrorCode.BUSY, 'busy', 'too many requests in flight')
|
|
102
132
|
let head
|
|
103
133
|
try { head = validateRequestHead(params, limits) } catch (e) { counters.errors += 1; throw asChannelError(e) }
|
|
@@ -118,8 +148,22 @@ export function serveHttpOnMesh(service, handler, { allowFrom, limits: limitOpti
|
|
|
118
148
|
counters.inflight -= 1
|
|
119
149
|
}
|
|
120
150
|
try {
|
|
121
|
-
const request = await buildRequest(head, ac, claimBody, limits.maxRequestBodyBytes, counters)
|
|
151
|
+
const { request, body: bodyBytes } = await buildRequest(head, ac, claimBody, limits.maxRequestBodyBytes, counters)
|
|
152
|
+
if (verifyRequest) {
|
|
153
|
+
const bytes = signedRequestBytes({
|
|
154
|
+
rid: head.rid, nonce: head.nonce, host: head.host, method: head.method, target: head.target, headers: head.headers, client: head.client,
|
|
155
|
+
digest: await sha256Hex(bodyBytes ?? new Uint8Array(0)),
|
|
156
|
+
})
|
|
157
|
+
let ok = false
|
|
158
|
+
try { ok = (await verifyRequest(request.clone(), { peer, sig: head.sig, bytes, rid: head.rid, nonce: head.nonce })) === true } catch { ok = false }
|
|
159
|
+
if (!ok) { counters.refused += 1; throw new MeshChannelError(ChannelErrorCode.UNAUTHORIZED, 'request-unverified', 'the request was not accepted') }
|
|
160
|
+
}
|
|
122
161
|
const response = await fn(request, { peer, signal: ac.signal, client: head.client })
|
|
162
|
+
if (response && typeof response === 'object' && DECLINED.has(response)) {
|
|
163
|
+
// "Not me, try another": nothing of the response is sent, and no body was produced.
|
|
164
|
+
counters.declined += 1
|
|
165
|
+
return { status: 421, headers: [], body: false, declined: true }
|
|
166
|
+
}
|
|
123
167
|
if (!response || typeof response !== 'object' || !Number.isInteger(response.status) || !response.headers || typeof response.headers.entries !== 'function') {
|
|
124
168
|
throw new MeshChannelError(ChannelErrorCode.INTERNAL, 'bad-handler-result', 'the handler did not return a Response')
|
|
125
169
|
}
|
|
@@ -186,7 +230,22 @@ async function buildRequest(head, ac, claimBody, maxBytes, counters) {
|
|
|
186
230
|
}
|
|
187
231
|
counters.requestBytes += body.byteLength
|
|
188
232
|
}
|
|
189
|
-
return new Request(`http://${head.host}${head.target}`, { method: head.method, headers, body, signal: ac.signal, redirect: 'manual' })
|
|
233
|
+
return { request: new Request(`http://${head.host}${head.target}`, { method: head.method, headers, body, signal: ac.signal, redirect: 'manual' }), body }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const DECLINED = new WeakSet()
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* A handler's way to say "not me, try another": return this instead of a response when this pod cannot answer the
|
|
240
|
+
* request and has done no work for it. The ingress surfaces it as the named failure `provider-declined` (never as this
|
|
241
|
+
* pod's own response) and, if it was given a `retry` option, resolves the request again with this pod's id in `tried`.
|
|
242
|
+
* Only the object this returns declines: a response that merely has status 421 is an ordinary answer.
|
|
243
|
+
* @returns {Response}
|
|
244
|
+
*/
|
|
245
|
+
export function declineRequest() {
|
|
246
|
+
const response = new Response(null, { status: 421 })
|
|
247
|
+
DECLINED.add(response)
|
|
248
|
+
return response
|
|
190
249
|
}
|
|
191
250
|
|
|
192
251
|
async function collect(stream, max, signal) {
|
package/src/wire.mjs
CHANGED
|
@@ -32,6 +32,7 @@ export function validateRequestHead(head, { maxHeaderCount, maxHeaderBytes, maxT
|
|
|
32
32
|
if (typeof body !== 'boolean') throw new IngressError(400, 'bad-request-head', 'The body flag is not a boolean.')
|
|
33
33
|
if (head.client !== undefined && (typeof head.client !== 'string' || head.client.length > 64)) throw new IngressError(400, 'bad-request-head', 'The client field is not a short string.')
|
|
34
34
|
if (typeof head.nonce !== 'string' || !/^[0-9a-f]{16,64}$/.test(head.nonce)) throw new IngressError(400, 'bad-request-head', 'The nonce is not 16 to 64 hex characters.')
|
|
35
|
+
if (head.sig !== undefined && (typeof head.sig !== 'string' || head.sig.length > 2048)) throw new IngressError(400, 'bad-request-head', 'The signature is not a short string.')
|
|
35
36
|
return head
|
|
36
37
|
}
|
|
37
38
|
|
|
@@ -43,6 +44,9 @@ export function validateResponseHead(head, { maxHeaderCount, maxHeaderBytes }) {
|
|
|
43
44
|
checkHeaderList(headers, { maxCount: maxHeaderCount, maxBytes: maxHeaderBytes, status: 502, reason: 'bad-response-head' })
|
|
44
45
|
if (typeof body !== 'boolean') throw new IngressError(502, 'bad-response-head', 'The body flag is not a boolean.')
|
|
45
46
|
if (head.sig !== undefined && (typeof head.sig !== 'string' || head.sig.length > 2048)) throw new IngressError(502, 'bad-response-head', 'The signature is not a short string.')
|
|
47
|
+
// A provider that declines ("not me, try another") says so with `declined: true` and nothing else: status 421, no headers, no body.
|
|
48
|
+
if (head.declined !== undefined && typeof head.declined !== 'boolean') throw new IngressError(502, 'bad-response-head', 'The declined flag is not a boolean.')
|
|
49
|
+
if (head.declined === true && (status !== 421 || head.headers.length || body || head.sig !== undefined)) throw new IngressError(502, 'bad-response-head', 'A declined answer carries no headers, body or signature.')
|
|
46
50
|
return head
|
|
47
51
|
}
|
|
48
52
|
|
|
@@ -68,3 +72,14 @@ export function signedBytes({ rid, nonce, host, method, target, status, headers,
|
|
|
68
72
|
for (const [name] of headers) if (!isToken(name)) throw new TypeError('bad header name')
|
|
69
73
|
return new TextEncoder().encode(JSON.stringify({ v: 1, rid, nonce, host, method, target, status, headers, digest }))
|
|
70
74
|
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* What a request signature covers (`signRequest` on the ingress, `verifyRequest` on the provider): the request's id and a
|
|
78
|
+
* fresh nonce (so a signature cannot be replayed for another request), the host, method and target, the header list as sent,
|
|
79
|
+
* and the SHA-256 of the body. `dir: 'request'` keeps it apart from a response's bytes.
|
|
80
|
+
* @returns {Uint8Array}
|
|
81
|
+
*/
|
|
82
|
+
export function signedRequestBytes({ rid, nonce, host, method, target, headers, client, digest }) {
|
|
83
|
+
for (const [name] of headers) if (!isToken(name)) throw new TypeError('bad header name')
|
|
84
|
+
return new TextEncoder().encode(JSON.stringify({ v: 1, dir: 'request', rid, nonce, host, method, target, headers, client, digest }))
|
|
85
|
+
}
|