@contember/engine-common 2.2.0-alpha.2 → 2.2.0-alpha.20
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/dist/development/index.cjs +7 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +8 -1
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/egress/EgressGuard.cjs +170 -0
- package/dist/development/src/egress/EgressGuard.cjs.map +1 -0
- package/dist/development/src/egress/EgressGuard.js +170 -0
- package/dist/development/src/egress/EgressGuard.js.map +1 -0
- package/dist/development/src/egress/EgressPolicy.cjs +110 -0
- package/dist/development/src/egress/EgressPolicy.cjs.map +1 -0
- package/dist/development/src/egress/EgressPolicy.js +110 -0
- package/dist/development/src/egress/EgressPolicy.js.map +1 -0
- package/dist/development/src/egress/createEgressGuard.cjs +7 -0
- package/dist/development/src/egress/createEgressGuard.cjs.map +1 -0
- package/dist/development/src/egress/createEgressGuard.js +7 -0
- package/dist/development/src/egress/createEgressGuard.js.map +1 -0
- package/dist/development/src/runnable/Supervisor.cjs +27 -4
- package/dist/development/src/runnable/Supervisor.cjs.map +1 -1
- package/dist/development/src/runnable/Supervisor.js +27 -4
- package/dist/development/src/runnable/Supervisor.js.map +1 -1
- package/dist/production/index.cjs +7 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +8 -1
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/egress/EgressGuard.cjs +170 -0
- package/dist/production/src/egress/EgressGuard.cjs.map +1 -0
- package/dist/production/src/egress/EgressGuard.js +170 -0
- package/dist/production/src/egress/EgressGuard.js.map +1 -0
- package/dist/production/src/egress/EgressPolicy.cjs +110 -0
- package/dist/production/src/egress/EgressPolicy.cjs.map +1 -0
- package/dist/production/src/egress/EgressPolicy.js +110 -0
- package/dist/production/src/egress/EgressPolicy.js.map +1 -0
- package/dist/production/src/egress/createEgressGuard.cjs +7 -0
- package/dist/production/src/egress/createEgressGuard.cjs.map +1 -0
- package/dist/production/src/egress/createEgressGuard.js +7 -0
- package/dist/production/src/egress/createEgressGuard.js.map +1 -0
- package/dist/production/src/runnable/Supervisor.cjs +27 -4
- package/dist/production/src/runnable/Supervisor.cjs.map +1 -1
- package/dist/production/src/runnable/Supervisor.js +27 -4
- package/dist/production/src/runnable/Supervisor.js.map +1 -1
- package/dist/types/MigrationVersionHelper.d.ts.map +1 -1
- package/dist/types/egress/EgressGuard.d.ts +37 -0
- package/dist/types/egress/EgressGuard.d.ts.map +1 -0
- package/dist/types/egress/EgressPolicy.d.ts +25 -0
- package/dist/types/egress/EgressPolicy.d.ts.map +1 -0
- package/dist/types/egress/createEgressGuard.d.ts +9 -0
- package/dist/types/egress/createEgressGuard.d.ts.map +1 -0
- package/dist/types/egress/index.d.ts +4 -0
- package/dist/types/egress/index.d.ts.map +1 -0
- package/dist/types/eventEmitter/events.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/runnable/Supervisor.d.ts +2 -0
- package/dist/types/runnable/Supervisor.d.ts.map +1 -1
- package/dist/types/runnable/utils.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/PromiseMap.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/egress/EgressGuard.ts +197 -0
- package/src/egress/EgressPolicy.ts +129 -0
- package/src/egress/createEgressGuard.ts +14 -0
- package/src/egress/index.ts +3 -0
- package/src/index.ts +1 -0
- package/src/runnable/Supervisor.ts +30 -6
- package/tests/cases/egress/egressGuard.test.ts +147 -0
- package/tests/cases/egress/egressPolicy.test.ts +78 -0
- package/tests/cases/supervisor.test.ts +195 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { lookup as dnsLookup, LookupAddress } from 'node:dns'
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import https from 'node:https'
|
|
4
|
+
import { LookupFunction } from 'node:net'
|
|
5
|
+
import { EgressError, EgressPolicy } from './EgressPolicy.js'
|
|
6
|
+
|
|
7
|
+
export interface EgressRequestInit {
|
|
8
|
+
readonly method?: string
|
|
9
|
+
readonly headers?: HeadersInit
|
|
10
|
+
readonly body?: string
|
|
11
|
+
readonly signal?: AbortSignal
|
|
12
|
+
/** As in `fetch`: `follow` (the default) re-checks every hop against the policy. */
|
|
13
|
+
readonly redirect?: 'follow' | 'manual' | 'error'
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type EgressFetch = (url: string, init: EgressRequestInit) => Promise<Response>
|
|
17
|
+
|
|
18
|
+
export interface EgressHttpOptions {
|
|
19
|
+
readonly agent: http.Agent
|
|
20
|
+
readonly lookup: LookupFunction
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
|
|
24
|
+
const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])
|
|
25
|
+
const MAX_REDIRECTS = 20
|
|
26
|
+
const REQUEST_BODY_HEADERS = ['content-encoding', 'content-language', 'content-location', 'content-type']
|
|
27
|
+
const CREDENTIAL_HEADERS = ['authorization', 'proxy-authorization', 'cookie']
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Outgoing HTTP to URLs chosen by tenants (webhooks, identity providers), under an {@link EgressPolicy}. Built over
|
|
31
|
+
* `node:http(s)` with dedicated agents and a per-request `lookup` that checks every resolved address before connecting:
|
|
32
|
+
* the global agent reuses keep-alive sockets, Bun ignores an agent's `lookup`, and `fetch` takes no `lookup` at all.
|
|
33
|
+
*/
|
|
34
|
+
export class EgressGuard {
|
|
35
|
+
private readonly lookup: LookupFunction
|
|
36
|
+
private readonly httpsAgent: https.Agent
|
|
37
|
+
private readonly httpAgent: http.Agent
|
|
38
|
+
|
|
39
|
+
constructor(private readonly policy: EgressPolicy) {
|
|
40
|
+
this.lookup = (hostname, options, callback) => {
|
|
41
|
+
dnsLookup(hostname, { family: options.family ?? 0, hints: options.hints, all: true }, (err, addresses: LookupAddress[]) => {
|
|
42
|
+
if (err) {
|
|
43
|
+
callback(err, [])
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
if (addresses.length === 0) {
|
|
48
|
+
throw new EgressError(`${hostname} did not resolve`)
|
|
49
|
+
}
|
|
50
|
+
for (const address of addresses) {
|
|
51
|
+
this.policy.checkAddress(hostname, address.address)
|
|
52
|
+
}
|
|
53
|
+
} catch (e) {
|
|
54
|
+
callback(e instanceof Error ? e : new Error(String(e)), [])
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
if (options.all) {
|
|
58
|
+
callback(null, addresses)
|
|
59
|
+
} else {
|
|
60
|
+
callback(null, addresses[0].address, addresses[0].family)
|
|
61
|
+
}
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
this.httpsAgent = new https.Agent({ keepAlive: false, lookup: this.lookup })
|
|
65
|
+
this.httpAgent = new http.Agent({ keepAlive: false, lookup: this.lookup })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Options for a client that issues its own `node:http(s)` requests; throws when the URL itself is not allowed. */
|
|
69
|
+
public httpOptions(url: URL): EgressHttpOptions {
|
|
70
|
+
this.policy.checkUrl(url)
|
|
71
|
+
return {
|
|
72
|
+
agent: url.protocol === 'https:' ? this.httpsAgent : this.httpAgent,
|
|
73
|
+
lookup: this.lookup,
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A `fetch` subset that buffers the response body. Redirects follow `fetch` semantics, each hop re-checked. */
|
|
78
|
+
public readonly fetch: EgressFetch = async (input, init) => {
|
|
79
|
+
let url = this.parseUrl(input)
|
|
80
|
+
let method = (init.method ?? 'GET').toUpperCase()
|
|
81
|
+
let body = init.body
|
|
82
|
+
const headers = new Headers(init.headers)
|
|
83
|
+
for (let redirects = 0;; redirects++) {
|
|
84
|
+
const response = await this.request(url, method, headers, body, init.signal)
|
|
85
|
+
const location = response.headers.get('location')
|
|
86
|
+
if (!REDIRECT_STATUSES.has(response.status) || location === null || init.redirect === 'manual') {
|
|
87
|
+
return response
|
|
88
|
+
}
|
|
89
|
+
if (init.redirect === 'error') {
|
|
90
|
+
throw new EgressError(`${url.origin} responded with a redirect`)
|
|
91
|
+
}
|
|
92
|
+
if (redirects >= MAX_REDIRECTS) {
|
|
93
|
+
throw new EgressError(`Too many redirects from ${url.origin}`)
|
|
94
|
+
}
|
|
95
|
+
const next = this.parseUrl(location, url)
|
|
96
|
+
if (
|
|
97
|
+
((response.status === 301 || response.status === 302) && method === 'POST')
|
|
98
|
+
|| (response.status === 303 && method !== 'GET' && method !== 'HEAD')
|
|
99
|
+
) {
|
|
100
|
+
method = 'GET'
|
|
101
|
+
body = undefined
|
|
102
|
+
for (const name of REQUEST_BODY_HEADERS) {
|
|
103
|
+
headers.delete(name)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (next.origin !== url.origin) {
|
|
107
|
+
for (const name of CREDENTIAL_HEADERS) {
|
|
108
|
+
headers.delete(name)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
url = next
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
public dispose(): void {
|
|
116
|
+
this.httpsAgent.destroy()
|
|
117
|
+
this.httpAgent.destroy()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private parseUrl(value: string, base?: URL): URL {
|
|
121
|
+
let url: URL
|
|
122
|
+
try {
|
|
123
|
+
url = new URL(value, base)
|
|
124
|
+
} catch {
|
|
125
|
+
throw new EgressError('Invalid URL')
|
|
126
|
+
}
|
|
127
|
+
this.policy.checkUrl(url)
|
|
128
|
+
return url
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private request(url: URL, method: string, headers: Headers, body: string | undefined, signal: AbortSignal | undefined): Promise<Response> {
|
|
132
|
+
return new Promise((resolve, reject) => {
|
|
133
|
+
if (signal?.aborted) {
|
|
134
|
+
reject(signal.reason)
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
const outgoingHeaders: Record<string, string> = Object.fromEntries(headers.entries())
|
|
138
|
+
if (body !== undefined) {
|
|
139
|
+
outgoingHeaders['content-length'] = String(Buffer.byteLength(body))
|
|
140
|
+
}
|
|
141
|
+
const isHttps = url.protocol === 'https:'
|
|
142
|
+
let settled = false
|
|
143
|
+
const onAbort = () => fail(signal?.reason)
|
|
144
|
+
const fail = (error: unknown) => {
|
|
145
|
+
if (settled) {
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
settled = true
|
|
149
|
+
signal?.removeEventListener('abort', onAbort)
|
|
150
|
+
req.destroy()
|
|
151
|
+
reject(error)
|
|
152
|
+
}
|
|
153
|
+
const req = (isHttps ? https : http).request(url, {
|
|
154
|
+
method,
|
|
155
|
+
headers: outgoingHeaders,
|
|
156
|
+
agent: isHttps ? this.httpsAgent : this.httpAgent,
|
|
157
|
+
lookup: this.lookup,
|
|
158
|
+
}, res => {
|
|
159
|
+
const chunks: Buffer[] = []
|
|
160
|
+
res.on('data', (chunk: Buffer) => chunks.push(chunk))
|
|
161
|
+
res.on('error', fail)
|
|
162
|
+
res.on('end', () => {
|
|
163
|
+
if (settled) {
|
|
164
|
+
return
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const response = this.createResponse(res, Buffer.concat(chunks))
|
|
168
|
+
settled = true
|
|
169
|
+
signal?.removeEventListener('abort', onAbort)
|
|
170
|
+
resolve(response)
|
|
171
|
+
} catch (e) {
|
|
172
|
+
fail(e)
|
|
173
|
+
}
|
|
174
|
+
})
|
|
175
|
+
})
|
|
176
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
177
|
+
req.on('error', fail)
|
|
178
|
+
req.end(body)
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private createResponse(res: http.IncomingMessage, body: Buffer): Response {
|
|
183
|
+
const status = res.statusCode ?? 0
|
|
184
|
+
if (status < 200 || status > 599) {
|
|
185
|
+
throw new EgressError(`Unexpected HTTP status ${status}`)
|
|
186
|
+
}
|
|
187
|
+
const headers = new Headers()
|
|
188
|
+
for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
|
|
189
|
+
headers.append(res.rawHeaders[i], res.rawHeaders[i + 1])
|
|
190
|
+
}
|
|
191
|
+
return new Response(NULL_BODY_STATUSES.has(status) ? null : new Uint8Array(body), {
|
|
192
|
+
status,
|
|
193
|
+
statusText: res.statusMessage ?? '',
|
|
194
|
+
headers,
|
|
195
|
+
})
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { BlockList, isIP, isIPv4 } from 'node:net'
|
|
2
|
+
|
|
3
|
+
// IPv4 special-purpose ranges (IANA): unspecified, private, CGNAT, loopback, link-local, protocol assignments,
|
|
4
|
+
// documentation, 6to4 relay, benchmarking, multicast, reserved and broadcast.
|
|
5
|
+
const SPECIAL_PURPOSE_IPV4: readonly [string, number][] = [
|
|
6
|
+
['0.0.0.0', 8],
|
|
7
|
+
['10.0.0.0', 8],
|
|
8
|
+
['100.64.0.0', 10],
|
|
9
|
+
['127.0.0.0', 8],
|
|
10
|
+
['169.254.0.0', 16],
|
|
11
|
+
['172.16.0.0', 12],
|
|
12
|
+
['192.0.0.0', 24],
|
|
13
|
+
['192.0.2.0', 24],
|
|
14
|
+
['192.88.99.0', 24],
|
|
15
|
+
['192.168.0.0', 16],
|
|
16
|
+
['198.18.0.0', 15],
|
|
17
|
+
['198.51.100.0', 24],
|
|
18
|
+
['203.0.113.0', 24],
|
|
19
|
+
['224.0.0.0', 4],
|
|
20
|
+
['240.0.0.0', 4],
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
// Only global unicast (2000::/3) is reachable; within it, protocol assignments (incl. Teredo), documentation and
|
|
24
|
+
// 6to4 (which embeds an arbitrary IPv4 address) are refused too. Everything outside 2000::/3 — unspecified, loopback,
|
|
25
|
+
// IPv4-mapped, NAT64, unique-local, link-local, multicast — never passes.
|
|
26
|
+
const GLOBAL_UNICAST_IPV6: readonly [string, number] = ['2000::', 3]
|
|
27
|
+
const SPECIAL_PURPOSE_IPV6: readonly [string, number][] = [
|
|
28
|
+
['2001::', 23],
|
|
29
|
+
['2001:db8::', 32],
|
|
30
|
+
['2002::', 16],
|
|
31
|
+
['3fff::', 20],
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
const normalizeHost = (host: string): string => host.toLowerCase().replace(/^\[(.*)]$/, '$1').replace(/\.$/, '')
|
|
35
|
+
|
|
36
|
+
const ipFamily = (address: string): 'ipv4' | 'ipv6' | null => {
|
|
37
|
+
const version = isIP(address)
|
|
38
|
+
return version === 4 ? 'ipv4' : version === 6 ? 'ipv6' : null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class EgressError extends Error {}
|
|
42
|
+
|
|
43
|
+
export interface EgressPolicyConfig {
|
|
44
|
+
/** Allows `http://` URLs; otherwise only `https://` is fetched. */
|
|
45
|
+
readonly allowHttp: boolean
|
|
46
|
+
/** Host names, addresses and CIDR ranges exempt from the non-public address check. */
|
|
47
|
+
readonly allowlist: readonly string[]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Which URLs the engine may fetch on behalf of a tenant: `https://` only (unless `allowHttp`), never a special-purpose
|
|
52
|
+
* address unless allow-listed. Checked per connection (on the resolved address), so DNS rebinding cannot bypass it.
|
|
53
|
+
*/
|
|
54
|
+
export class EgressPolicy {
|
|
55
|
+
private readonly specialPurpose = new BlockList()
|
|
56
|
+
private readonly globalUnicastIpv6 = new BlockList()
|
|
57
|
+
private readonly allowedNetworks = new BlockList()
|
|
58
|
+
private readonly allowedHosts: ReadonlySet<string>
|
|
59
|
+
private readonly allowHttp: boolean
|
|
60
|
+
|
|
61
|
+
constructor(config: EgressPolicyConfig) {
|
|
62
|
+
for (const [network, prefix] of SPECIAL_PURPOSE_IPV4) {
|
|
63
|
+
this.specialPurpose.addSubnet(network, prefix, 'ipv4')
|
|
64
|
+
}
|
|
65
|
+
for (const [network, prefix] of SPECIAL_PURPOSE_IPV6) {
|
|
66
|
+
this.specialPurpose.addSubnet(network, prefix, 'ipv6')
|
|
67
|
+
}
|
|
68
|
+
this.globalUnicastIpv6.addSubnet(GLOBAL_UNICAST_IPV6[0], GLOBAL_UNICAST_IPV6[1], 'ipv6')
|
|
69
|
+
|
|
70
|
+
const allowedHosts = new Set<string>()
|
|
71
|
+
for (const entry of config.allowlist) {
|
|
72
|
+
const [network, prefixText, ...rest] = entry.trim().split('/')
|
|
73
|
+
const family = ipFamily(network)
|
|
74
|
+
if (family === null) {
|
|
75
|
+
if (prefixText !== undefined || network === '') {
|
|
76
|
+
throw new EgressError(`Invalid egress allowlist entry ${entry}`)
|
|
77
|
+
}
|
|
78
|
+
allowedHosts.add(normalizeHost(network))
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
const maxPrefix = family === 'ipv4' ? 32 : 128
|
|
82
|
+
if (rest.length > 0 || (prefixText !== undefined && !/^\d{1,3}$/.test(prefixText))) {
|
|
83
|
+
throw new EgressError(`Invalid egress allowlist entry ${entry}`)
|
|
84
|
+
}
|
|
85
|
+
const prefix = prefixText === undefined ? maxPrefix : Number(prefixText)
|
|
86
|
+
if (prefix > maxPrefix) {
|
|
87
|
+
throw new EgressError(`Invalid egress allowlist entry ${entry}`)
|
|
88
|
+
}
|
|
89
|
+
this.allowedNetworks.addSubnet(network, prefix, family)
|
|
90
|
+
}
|
|
91
|
+
this.allowedHosts = allowedHosts
|
|
92
|
+
this.allowHttp = config.allowHttp
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Throws unless the URL may be fetched; an IP-literal host is checked here because no lookup will run for it. */
|
|
96
|
+
public checkUrl(url: URL): void {
|
|
97
|
+
const host = normalizeHost(url.hostname)
|
|
98
|
+
if (url.username !== '' || url.password !== '') {
|
|
99
|
+
throw new EgressError('Outgoing request URLs must not carry credentials')
|
|
100
|
+
}
|
|
101
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && this.allowHttp)) {
|
|
102
|
+
throw new EgressError(`Only https:// URLs are allowed, got ${url.protocol}//${host}`)
|
|
103
|
+
}
|
|
104
|
+
if (ipFamily(host) !== null) {
|
|
105
|
+
this.checkAddress(host, host)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Throws unless a connection to `address`, resolved from `host`, is allowed. */
|
|
110
|
+
public checkAddress(host: string, address: string): void {
|
|
111
|
+
const normalizedHost = normalizeHost(host)
|
|
112
|
+
if (this.allowedHosts.has(normalizedHost)) {
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
const family = ipFamily(address)
|
|
116
|
+
if (family === null) {
|
|
117
|
+
throw new EgressError(`Invalid address ${address} for ${normalizedHost}`)
|
|
118
|
+
}
|
|
119
|
+
if (this.allowedNetworks.check(address, family)) {
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
const isPublic = isIPv4(address)
|
|
123
|
+
? !this.specialPurpose.check(address, 'ipv4')
|
|
124
|
+
: this.globalUnicastIpv6.check(address, 'ipv6') && !this.specialPurpose.check(address, 'ipv6')
|
|
125
|
+
if (!isPublic) {
|
|
126
|
+
throw new EgressError(`${normalizedHost} resolves to the non-public address ${address}`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { EgressGuard } from './EgressGuard.js'
|
|
2
|
+
import { EgressPolicy } from './EgressPolicy.js'
|
|
3
|
+
|
|
4
|
+
export interface EgressConfig {
|
|
5
|
+
/** Opt-in: unset, outgoing requests to tenant-chosen URLs are not restricted. */
|
|
6
|
+
readonly guard?: boolean
|
|
7
|
+
readonly allowHttp?: boolean
|
|
8
|
+
readonly allowlist?: readonly string[]
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const createEgressGuard = (config: EgressConfig | undefined): EgressGuard | null =>
|
|
12
|
+
config?.guard === true
|
|
13
|
+
? new EgressGuard(new EgressPolicy({ allowHttp: config.allowHttp ?? false, allowlist: config.allowlist ?? [] }))
|
|
14
|
+
: null
|
package/src/index.ts
CHANGED
|
@@ -7,6 +7,8 @@ export type SupervisorOptions = {
|
|
|
7
7
|
minBackoff?: number
|
|
8
8
|
maxBackoff?: number
|
|
9
9
|
exponentiationBase?: number
|
|
10
|
+
/** Uptime (ms, default 60 000) after which a run counts as stable and the backoff resets; a run that crashes sooner counts as a failed restart. */
|
|
11
|
+
stableAfter?: number
|
|
10
12
|
}
|
|
11
13
|
|
|
12
14
|
export class Supervisor implements Runnable {
|
|
@@ -22,29 +24,51 @@ export class Supervisor implements Runnable {
|
|
|
22
24
|
const abortController = new AbortController()
|
|
23
25
|
let innerRunning: Running | undefined
|
|
24
26
|
let wasHealthy = false
|
|
27
|
+
let startedAt: number | undefined
|
|
28
|
+
const endRun = () => {
|
|
29
|
+
if (startedAt !== undefined && Date.now() - startedAt >= (this.options.stableAfter ?? 60_000)) {
|
|
30
|
+
restartCount = 0
|
|
31
|
+
}
|
|
32
|
+
startedAt = undefined
|
|
33
|
+
}
|
|
25
34
|
|
|
26
35
|
await new Promise<void>(async (resolve, reject) => {
|
|
27
36
|
while (!abortController.signal.aborted) {
|
|
37
|
+
let runEnded = false
|
|
28
38
|
try {
|
|
29
39
|
await new Promise<void>(async (resolveRunning, rejectRunning) => {
|
|
30
40
|
try {
|
|
31
41
|
innerRunning = await this.runnable.run({
|
|
32
|
-
onClose:
|
|
33
|
-
|
|
42
|
+
onClose: () => {
|
|
43
|
+
runEnded = true
|
|
44
|
+
resolveRunning()
|
|
45
|
+
},
|
|
46
|
+
onError: e => {
|
|
47
|
+
runEnded = true
|
|
48
|
+
rejectRunning(e)
|
|
49
|
+
},
|
|
34
50
|
logger: logger.child({ runningId: Math.random().toString().substring(2) }),
|
|
35
51
|
})
|
|
36
|
-
|
|
52
|
+
// a run that ended before run() returned was already handled as a crash; recording it as started would count the backoff as uptime
|
|
53
|
+
if (!runEnded) {
|
|
54
|
+
if (!wasHealthy) {
|
|
55
|
+
restartCount = 0
|
|
56
|
+
}
|
|
57
|
+
startedAt = Date.now()
|
|
58
|
+
}
|
|
37
59
|
resolve()
|
|
38
60
|
wasHealthy = true
|
|
39
61
|
} catch (e) {
|
|
40
62
|
rejectRunning(e)
|
|
41
63
|
}
|
|
42
64
|
})
|
|
65
|
+
endRun()
|
|
43
66
|
} catch (e) {
|
|
44
67
|
innerRunning = undefined
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
68
|
+
endRun()
|
|
69
|
+
restartCount++
|
|
70
|
+
const restartLimit = wasHealthy ? this.options.max : (this.options.startupMax ?? 10)
|
|
71
|
+
const shouldRestart = restartLimit === undefined || restartCount <= restartLimit
|
|
48
72
|
if (shouldRestart) {
|
|
49
73
|
const timeoutMs = Math.ceil(Math.min(
|
|
50
74
|
Math.pow(this.options.exponentiationBase ?? 2, restartCount - 1) * (this.options.minBackoff ?? 1_000),
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import { EgressGuard, EgressPolicy } from '../../../src/index.js'
|
|
4
|
+
|
|
5
|
+
type RecordedRequest = { method: string; url: string; headers: http.IncomingHttpHeaders; body: string }
|
|
6
|
+
|
|
7
|
+
const startServer = async (handler: (req: http.IncomingMessage, res: http.ServerResponse) => void) => {
|
|
8
|
+
const requests: RecordedRequest[] = []
|
|
9
|
+
const server = http.createServer((req, res) => {
|
|
10
|
+
let body = ''
|
|
11
|
+
req.on('data', chunk => (body += chunk))
|
|
12
|
+
req.on('end', () => {
|
|
13
|
+
requests.push({ method: req.method ?? '', url: req.url ?? '', headers: req.headers, body })
|
|
14
|
+
handler(req, res)
|
|
15
|
+
})
|
|
16
|
+
})
|
|
17
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
|
|
18
|
+
const address = server.address()
|
|
19
|
+
if (address === null || typeof address === 'string') {
|
|
20
|
+
throw new Error('expected a TCP address')
|
|
21
|
+
}
|
|
22
|
+
return { server, port: address.port, requests }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const guardWith = (allowlist: string[]) => new EgressGuard(new EgressPolicy({ allowHttp: true, allowlist }))
|
|
26
|
+
|
|
27
|
+
describe('EgressGuard.fetch', () => {
|
|
28
|
+
let target: Awaited<ReturnType<typeof startServer>>
|
|
29
|
+
let redirector: Awaited<ReturnType<typeof startServer>>
|
|
30
|
+
|
|
31
|
+
beforeAll(async () => {
|
|
32
|
+
target = await startServer((req, res) => {
|
|
33
|
+
res.writeHead(201, 'Created', { 'content-type': 'application/json', 'x-test': 'yes' })
|
|
34
|
+
res.end(JSON.stringify({ ok: true }))
|
|
35
|
+
})
|
|
36
|
+
redirector = await startServer((req, res) => {
|
|
37
|
+
const status = Number(new URL(req.url ?? '/', 'http://x').searchParams.get('status') ?? 307)
|
|
38
|
+
res.writeHead(status, { location: `http://127.0.0.1:${target.port}/landed` })
|
|
39
|
+
res.end()
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
afterAll(() => {
|
|
44
|
+
target.server.close()
|
|
45
|
+
redirector.server.close()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test('a host name that resolves to a non-public address is refused before connecting', async () => {
|
|
49
|
+
const before = target.requests.length
|
|
50
|
+
const guard = guardWith([])
|
|
51
|
+
await expect(guard.fetch(`http://localhost:${target.port}/hook`, { method: 'POST', body: '{}' })).rejects.toThrow('non-public address')
|
|
52
|
+
expect(target.requests.length).toBe(before)
|
|
53
|
+
guard.dispose()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
test('http is refused unless allowed', async () => {
|
|
57
|
+
const guard = new EgressGuard(new EgressPolicy({ allowHttp: false, allowlist: ['localhost'] }))
|
|
58
|
+
await expect(guard.fetch(`http://localhost:${target.port}/hook`, {})).rejects.toThrow('Only https:// URLs are allowed')
|
|
59
|
+
guard.dispose()
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('an allow-listed local host is reached and its response returned', async () => {
|
|
63
|
+
const guard = guardWith(['localhost'])
|
|
64
|
+
const response = await guard.fetch(`http://localhost:${target.port}/hook`, {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: { 'content-type': 'application/json', 'x-token': 'secret' },
|
|
67
|
+
body: '{"a":1}',
|
|
68
|
+
})
|
|
69
|
+
expect(response.status).toBe(201)
|
|
70
|
+
expect(response.statusText).toBe('Created')
|
|
71
|
+
expect(response.headers.get('x-test')).toBe('yes')
|
|
72
|
+
expect(await response.json()).toEqual({ ok: true })
|
|
73
|
+
const received = target.requests.at(-1)
|
|
74
|
+
expect(received?.method).toBe('POST')
|
|
75
|
+
expect(received?.body).toBe('{"a":1}')
|
|
76
|
+
expect(received?.headers['x-token']).toBe('secret')
|
|
77
|
+
guard.dispose()
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
test('a redirect to a non-public address is refused', async () => {
|
|
81
|
+
const before = target.requests.length
|
|
82
|
+
const guard = guardWith(['localhost'])
|
|
83
|
+
await expect(guard.fetch(`http://localhost:${redirector.port}/`, { method: 'POST', body: '{}' })).rejects.toThrow('non-public address')
|
|
84
|
+
expect(target.requests.length).toBe(before)
|
|
85
|
+
guard.dispose()
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('an allowed redirect keeps a 307 POST and drops credentials across origins', async () => {
|
|
89
|
+
const guard = guardWith(['localhost', '127.0.0.1'])
|
|
90
|
+
const response = await guard.fetch(`http://localhost:${redirector.port}/?status=307`, {
|
|
91
|
+
method: 'POST',
|
|
92
|
+
headers: { 'authorization': 'Bearer secret', 'x-other': 'kept' },
|
|
93
|
+
body: '{"a":1}',
|
|
94
|
+
})
|
|
95
|
+
expect(response.status).toBe(201)
|
|
96
|
+
const received = target.requests.at(-1)
|
|
97
|
+
expect(received?.url).toBe('/landed')
|
|
98
|
+
expect(received?.method).toBe('POST')
|
|
99
|
+
expect(received?.body).toBe('{"a":1}')
|
|
100
|
+
expect(received?.headers.authorization).toBeUndefined()
|
|
101
|
+
expect(received?.headers['x-other']).toBe('kept')
|
|
102
|
+
guard.dispose()
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('a 302 after a POST continues as a GET without a body', async () => {
|
|
106
|
+
const guard = guardWith(['localhost', '127.0.0.1'])
|
|
107
|
+
await guard.fetch(`http://localhost:${redirector.port}/?status=302`, {
|
|
108
|
+
method: 'POST',
|
|
109
|
+
headers: { 'content-type': 'application/json' },
|
|
110
|
+
body: '{}',
|
|
111
|
+
})
|
|
112
|
+
const received = target.requests.at(-1)
|
|
113
|
+
expect(received?.method).toBe('GET')
|
|
114
|
+
expect(received?.body).toBe('')
|
|
115
|
+
expect(received?.headers['content-type']).toBeUndefined()
|
|
116
|
+
guard.dispose()
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test('a manual redirect is returned as is', async () => {
|
|
120
|
+
const guard = guardWith(['localhost'])
|
|
121
|
+
const response = await guard.fetch(`http://localhost:${redirector.port}/`, { redirect: 'manual' })
|
|
122
|
+
expect(response.status).toBe(307)
|
|
123
|
+
guard.dispose()
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
test('an aborted request rejects with the abort reason', async () => {
|
|
127
|
+
const hanging = await startServer(() => {})
|
|
128
|
+
const guard = guardWith(['localhost'])
|
|
129
|
+
const controller = new AbortController()
|
|
130
|
+
const pending = guard.fetch(`http://localhost:${hanging.port}/`, { signal: controller.signal })
|
|
131
|
+
setTimeout(() => controller.abort(new Error('timed out')), 50)
|
|
132
|
+
await expect(pending).rejects.toThrow('timed out')
|
|
133
|
+
guard.dispose()
|
|
134
|
+
hanging.server.closeAllConnections()
|
|
135
|
+
hanging.server.close()
|
|
136
|
+
})
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
describe('EgressGuard.httpOptions', () => {
|
|
140
|
+
test('refuses a disallowed URL before a client issues the request', () => {
|
|
141
|
+
const guard = new EgressGuard(new EgressPolicy({ allowHttp: false, allowlist: [] }))
|
|
142
|
+
expect(() => guard.httpOptions(new URL('http://example.com/'))).toThrow('Only https:// URLs are allowed')
|
|
143
|
+
expect(() => guard.httpOptions(new URL('https://169.254.169.254/'))).toThrow('non-public address')
|
|
144
|
+
expect(guard.httpOptions(new URL('https://example.com/')).lookup).toBeFunction()
|
|
145
|
+
guard.dispose()
|
|
146
|
+
})
|
|
147
|
+
})
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { createEgressGuard, EgressError, EgressPolicy } from '../../../src/index.js'
|
|
3
|
+
|
|
4
|
+
const strict = new EgressPolicy({ allowHttp: false, allowlist: [] })
|
|
5
|
+
|
|
6
|
+
describe('EgressPolicy addresses', () => {
|
|
7
|
+
test.each([
|
|
8
|
+
'0.0.0.0',
|
|
9
|
+
'10.1.2.3',
|
|
10
|
+
'100.64.0.1',
|
|
11
|
+
'127.0.0.1',
|
|
12
|
+
'169.254.169.254',
|
|
13
|
+
'172.16.0.1',
|
|
14
|
+
'192.168.1.1',
|
|
15
|
+
'224.0.0.1',
|
|
16
|
+
'255.255.255.255',
|
|
17
|
+
'::',
|
|
18
|
+
'::1',
|
|
19
|
+
'::ffff:127.0.0.1',
|
|
20
|
+
'::ffff:169.254.169.254',
|
|
21
|
+
'64:ff9b::7f00:1',
|
|
22
|
+
'fc00::1',
|
|
23
|
+
'fd12:3456::1',
|
|
24
|
+
'fe80::1',
|
|
25
|
+
'ff02::1',
|
|
26
|
+
'2001:db8::1',
|
|
27
|
+
'2002:7f00:1::1',
|
|
28
|
+
])('refuses %s', address => {
|
|
29
|
+
expect(() => strict.checkAddress('example.com', address)).toThrow(EgressError)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
test.each(['93.184.215.14', '1.1.1.1', '2606:4700:4700::1111'])('allows public %s', address => {
|
|
33
|
+
expect(() => strict.checkAddress('example.com', address)).not.toThrow()
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test('an allow-listed network or host passes the address check', () => {
|
|
37
|
+
const policy = new EgressPolicy({ allowHttp: false, allowlist: ['10.0.0.0/8', 'internal.example', '::1'] })
|
|
38
|
+
expect(() => policy.checkAddress('hooks.example.com', '10.20.30.40')).not.toThrow()
|
|
39
|
+
expect(() => policy.checkAddress('Internal.Example.', '192.168.0.1')).not.toThrow()
|
|
40
|
+
expect(() => policy.checkAddress('hooks.example.com', '::1')).not.toThrow()
|
|
41
|
+
expect(() => policy.checkAddress('hooks.example.com', '192.168.0.1')).toThrow(EgressError)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
test.each(['10.0.0.0/33', '10.0.0.0/8/1', 'host/8', '', '::1/x'])('rejects the invalid allowlist entry %p', entry => {
|
|
45
|
+
expect(() => new EgressPolicy({ allowHttp: false, allowlist: [entry] })).toThrow(EgressError)
|
|
46
|
+
})
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
describe('EgressPolicy URLs', () => {
|
|
50
|
+
test('only https unless http is allowed', () => {
|
|
51
|
+
expect(() => strict.checkUrl(new URL('https://example.com/hook'))).not.toThrow()
|
|
52
|
+
expect(() => strict.checkUrl(new URL('http://example.com/hook'))).toThrow('Only https:// URLs are allowed')
|
|
53
|
+
expect(() => strict.checkUrl(new URL('ftp://example.com/hook'))).toThrow(EgressError)
|
|
54
|
+
const withHttp = new EgressPolicy({ allowHttp: true, allowlist: [] })
|
|
55
|
+
expect(() => withHttp.checkUrl(new URL('http://example.com/hook'))).not.toThrow()
|
|
56
|
+
expect(() => withHttp.checkUrl(new URL('ftp://example.com/hook'))).toThrow(EgressError)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('an IP-literal host is checked without a lookup', () => {
|
|
60
|
+
expect(() => strict.checkUrl(new URL('https://127.0.0.1/'))).toThrow('non-public address')
|
|
61
|
+
expect(() => strict.checkUrl(new URL('https://[::1]/'))).toThrow('non-public address')
|
|
62
|
+
expect(() => strict.checkUrl(new URL('https://[::ffff:a9fe:a9fe]/'))).toThrow('non-public address')
|
|
63
|
+
expect(() => strict.checkUrl(new URL('https://1.1.1.1/'))).not.toThrow()
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
test('URLs with credentials are refused', () => {
|
|
67
|
+
expect(() => strict.checkUrl(new URL('https://user:pass@example.com/'))).toThrow(EgressError)
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
describe('createEgressGuard', () => {
|
|
72
|
+
test('the guard is opt-in', () => {
|
|
73
|
+
expect(createEgressGuard(undefined)).toBeNull()
|
|
74
|
+
expect(createEgressGuard({})).toBeNull()
|
|
75
|
+
expect(createEgressGuard({ guard: false, allowHttp: true })).toBeNull()
|
|
76
|
+
expect(createEgressGuard({ guard: true })).not.toBeNull()
|
|
77
|
+
})
|
|
78
|
+
})
|