@antelopejs/dms-api 0.3.0 → 0.4.1
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 +88 -148
- package/dist/db/models/api_settings.model.d.ts +1 -0
- package/dist/db/models/request_log.model.d.ts +1 -0
- package/dist/db/models/routes.model.d.ts +1 -0
- package/dist/db/models/routes_statistics.model.d.ts +1 -0
- package/frontend-vue/app/components/blocks/HealthHero.vue +11 -5
- package/frontend-vue/app/components/blocks/LiveTraffic.vue +3 -2
- package/frontend-vue/app/components/blocks/RequestDetail.vue +35 -33
- package/frontend-vue/app/components/blocks/RetentionInput.vue +51 -20
- package/frontend-vue/app/components/blocks/RouteTester.vue +86 -28
- package/frontend-vue/app/components/blocks/RouteTree.vue +9 -9
- package/frontend-vue/app/components/blocks/ScopeChip.vue +11 -7
- package/frontend-vue/app/composables/useClientValue.ts +18 -0
- package/frontend-vue/app/composables/useRouteDetail.ts +22 -106
- package/frontend-vue/app/utils/http.ts +10 -0
- package/frontend-vue/app/utils/testerRequest.ts +9 -7
- package/frontend-vue/dms.server.ts +9 -0
- package/frontend-vue/package.json +1 -1
- package/frontend-vue/server/tester.ts +266 -0
- package/frontend-vue/tests/clientValue.test.ts +64 -0
- package/frontend-vue/tests/dmsServer.test.ts +44 -0
- package/frontend-vue/tests/testerRequest.test.ts +1 -1
- package/frontend-vue/tests/testerRoute.test.ts +299 -0
- package/package.json +29 -13
- package/skills/dms-api/SKILL.md +31 -0
- package/frontend-vue/app/composables/useApiResource.ts +0 -92
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import type { DmsServerEvent, DmsSession } from '#dms/server'
|
|
2
|
+
|
|
3
|
+
// The API tester's server half: forwards one call the owner composes to the
|
|
4
|
+
// backend, with the session's credential when asked, and returns the answer
|
|
5
|
+
// without the session's tokens. Owner-only: the session must belong to the
|
|
6
|
+
// instance owner, which the backend confirms on every call.
|
|
7
|
+
|
|
8
|
+
const RESPONSE_LIMIT = 64 * 1024
|
|
9
|
+
const REQUEST_TIMEOUT_MS = 30_000
|
|
10
|
+
const METHODS = new Set([
|
|
11
|
+
'GET',
|
|
12
|
+
'HEAD',
|
|
13
|
+
'POST',
|
|
14
|
+
'PUT',
|
|
15
|
+
'PATCH',
|
|
16
|
+
'DELETE',
|
|
17
|
+
'OPTIONS',
|
|
18
|
+
])
|
|
19
|
+
const BLOCKED_HEADERS = new Set([
|
|
20
|
+
'host',
|
|
21
|
+
'cookie',
|
|
22
|
+
'cookie2',
|
|
23
|
+
'set-cookie',
|
|
24
|
+
'set-cookie2',
|
|
25
|
+
'connection',
|
|
26
|
+
'keep-alive',
|
|
27
|
+
'proxy-authenticate',
|
|
28
|
+
'proxy-authorization',
|
|
29
|
+
'te',
|
|
30
|
+
'trailer',
|
|
31
|
+
'transfer-encoding',
|
|
32
|
+
'upgrade',
|
|
33
|
+
'content-length',
|
|
34
|
+
'expect',
|
|
35
|
+
'forwarded',
|
|
36
|
+
'origin',
|
|
37
|
+
'referer',
|
|
38
|
+
'via',
|
|
39
|
+
'authorization',
|
|
40
|
+
])
|
|
41
|
+
const CONTROL_HEADER =
|
|
42
|
+
/^(?:sec-|proxy-|x-forwarded-|x-dms-|x-inertia|x-http-method|x-method-override|x-original-|x-rewrite-)/i
|
|
43
|
+
// URL paths must reject literal control characters before forwarding.
|
|
44
|
+
const UNSAFE_PATH = /[\\#\u0000- \u007f]/
|
|
45
|
+
// Decoded path segments need the same boundary after every decoding pass.
|
|
46
|
+
const UNSAFE_DECODED_SEGMENT = /[\\/#\u0000- \u007f]/
|
|
47
|
+
|
|
48
|
+
interface TesterInput {
|
|
49
|
+
path?: unknown
|
|
50
|
+
method?: unknown
|
|
51
|
+
headers?: unknown
|
|
52
|
+
body?: unknown
|
|
53
|
+
useSession?: unknown
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface ValidInput {
|
|
57
|
+
method: string
|
|
58
|
+
headers: Record<string, string>
|
|
59
|
+
body?: string
|
|
60
|
+
useSession: boolean
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
class InvalidInput extends Error {
|
|
64
|
+
readonly status = 400
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function invalidInput(): never {
|
|
68
|
+
throw new InvalidInput('Invalid tester request')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function validatePathSegment(segment: string) {
|
|
72
|
+
let decoded = segment
|
|
73
|
+
for (;;) {
|
|
74
|
+
if (['.', '..'].includes(decoded) || UNSAFE_DECODED_SEGMENT.test(decoded))
|
|
75
|
+
invalidInput()
|
|
76
|
+
let next: string
|
|
77
|
+
try {
|
|
78
|
+
next = decodeURIComponent(decoded)
|
|
79
|
+
} catch {
|
|
80
|
+
invalidInput()
|
|
81
|
+
}
|
|
82
|
+
if (next === decoded) break
|
|
83
|
+
decoded = next
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function targetUrl(event: DmsServerEvent, path: unknown): URL {
|
|
88
|
+
if (
|
|
89
|
+
typeof path !== 'string' ||
|
|
90
|
+
!path.startsWith('/') ||
|
|
91
|
+
path.startsWith('//') ||
|
|
92
|
+
UNSAFE_PATH.test(path)
|
|
93
|
+
)
|
|
94
|
+
invalidInput()
|
|
95
|
+
path.split('?', 1)[0].split('/').forEach(validatePathSegment)
|
|
96
|
+
const target = event.backendUrl(path)
|
|
97
|
+
if (target.hash) invalidInput()
|
|
98
|
+
return target
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function filteredHeaders(input: HeadersInit, allowAuthorization = false) {
|
|
102
|
+
const source = new Headers(input)
|
|
103
|
+
const connection = new Set(
|
|
104
|
+
(source.get('connection') ?? '')
|
|
105
|
+
.toLowerCase()
|
|
106
|
+
.split(',')
|
|
107
|
+
.map((name) => name.trim()),
|
|
108
|
+
)
|
|
109
|
+
return new Headers(
|
|
110
|
+
[...source].filter(
|
|
111
|
+
([name]) =>
|
|
112
|
+
!connection.has(name) &&
|
|
113
|
+
!CONTROL_HEADER.test(name) &&
|
|
114
|
+
(!BLOCKED_HEADERS.has(name) ||
|
|
115
|
+
(allowAuthorization && name === 'authorization')),
|
|
116
|
+
),
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function validateInput(event: DmsServerEvent, input: TesterInput) {
|
|
121
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
122
|
+
invalidInput()
|
|
123
|
+
if (
|
|
124
|
+
typeof input.method !== 'string' ||
|
|
125
|
+
!METHODS.has(input.method) ||
|
|
126
|
+
typeof input.useSession !== 'boolean'
|
|
127
|
+
)
|
|
128
|
+
invalidInput()
|
|
129
|
+
const headers = input.headers
|
|
130
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers))
|
|
131
|
+
invalidInput()
|
|
132
|
+
if (Object.values(headers).some((value) => typeof value !== 'string'))
|
|
133
|
+
invalidInput()
|
|
134
|
+
if (
|
|
135
|
+
input.body !== undefined &&
|
|
136
|
+
(typeof input.body !== 'string' || ['GET', 'HEAD'].includes(input.method))
|
|
137
|
+
)
|
|
138
|
+
invalidInput()
|
|
139
|
+
try {
|
|
140
|
+
new Headers(headers as Record<string, string>)
|
|
141
|
+
} catch {
|
|
142
|
+
invalidInput()
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
target: targetUrl(event, input.path),
|
|
146
|
+
input: input as ValidInput,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function limitedText(response: Response): Promise<string> {
|
|
151
|
+
if (!response.body) return ''
|
|
152
|
+
const reader = response.body.getReader()
|
|
153
|
+
const chunks: Uint8Array[] = []
|
|
154
|
+
let size = 0
|
|
155
|
+
for (;;) {
|
|
156
|
+
const { done, value } = await reader.read()
|
|
157
|
+
if (done) break
|
|
158
|
+
size += value.length
|
|
159
|
+
if (size > RESPONSE_LIMIT) {
|
|
160
|
+
await reader.cancel()
|
|
161
|
+
throw new Error('Backend response too large')
|
|
162
|
+
}
|
|
163
|
+
chunks.push(value)
|
|
164
|
+
}
|
|
165
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function isOwner(
|
|
169
|
+
event: DmsServerEvent,
|
|
170
|
+
session: DmsSession,
|
|
171
|
+
signal: AbortSignal,
|
|
172
|
+
) {
|
|
173
|
+
const response = await fetch(event.backendUrl('/api/auth/me'), {
|
|
174
|
+
headers: {
|
|
175
|
+
authorization: `Bearer ${session.accessToken}`,
|
|
176
|
+
'x-antelopejs-namespace': 'default',
|
|
177
|
+
},
|
|
178
|
+
redirect: 'manual',
|
|
179
|
+
signal,
|
|
180
|
+
})
|
|
181
|
+
const text = await limitedText(response)
|
|
182
|
+
if (!response.ok) return false
|
|
183
|
+
return JSON.parse(text)?.owner === true
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function redact(value: string, session: DmsSession): string {
|
|
187
|
+
const secrets = [session.accessToken, session.refreshToken].filter(
|
|
188
|
+
(secret): secret is string => typeof secret === 'string' && !!secret.length,
|
|
189
|
+
)
|
|
190
|
+
return secrets.reduce((result, secret) => {
|
|
191
|
+
const variants = [
|
|
192
|
+
secret,
|
|
193
|
+
encodeURIComponent(secret),
|
|
194
|
+
JSON.stringify(secret).slice(1, -1),
|
|
195
|
+
]
|
|
196
|
+
return variants.reduce(
|
|
197
|
+
(text, variant) => text.replaceAll(variant, '[REDACTED]'),
|
|
198
|
+
result,
|
|
199
|
+
)
|
|
200
|
+
}, value)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function forward(
|
|
204
|
+
input: ValidInput,
|
|
205
|
+
target: URL,
|
|
206
|
+
session: DmsSession,
|
|
207
|
+
signal: AbortSignal,
|
|
208
|
+
) {
|
|
209
|
+
const headers = filteredHeaders(input.headers, true)
|
|
210
|
+
if (input.useSession && !headers.has('authorization')) {
|
|
211
|
+
headers.set('authorization', `Bearer ${session.accessToken}`)
|
|
212
|
+
if (!headers.has('x-antelopejs-namespace'))
|
|
213
|
+
headers.set('x-antelopejs-namespace', 'default')
|
|
214
|
+
}
|
|
215
|
+
const upstream = await fetch(target, {
|
|
216
|
+
method: input.method,
|
|
217
|
+
headers,
|
|
218
|
+
redirect: 'manual',
|
|
219
|
+
signal,
|
|
220
|
+
body: input.body,
|
|
221
|
+
})
|
|
222
|
+
const responseHeaders = Object.fromEntries(
|
|
223
|
+
[...filteredHeaders(upstream.headers)].map(([name, value]) => [
|
|
224
|
+
redact(name, session),
|
|
225
|
+
redact(value, session),
|
|
226
|
+
]),
|
|
227
|
+
)
|
|
228
|
+
return {
|
|
229
|
+
status: upstream.status,
|
|
230
|
+
headers: responseHeaders,
|
|
231
|
+
body: redact(await limitedText(upstream), session),
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function failure(status: number, error: string): Response {
|
|
236
|
+
return Response.json({ error }, { status })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function inputFailureStatus(error: unknown): number | undefined {
|
|
240
|
+
const status = (error as { status?: unknown } | undefined)?.status
|
|
241
|
+
return status === 400 || status === 413 ? status : undefined
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* `POST /api/_dms-api/tester`: forwards an owner's tester call without
|
|
246
|
+
* returning the session's credentials.
|
|
247
|
+
*/
|
|
248
|
+
export async function testerRoute(event: DmsServerEvent): Promise<Response> {
|
|
249
|
+
try {
|
|
250
|
+
const session = event.session.read()
|
|
251
|
+
if (!session?.accessToken) return failure(401, 'Not authenticated')
|
|
252
|
+
const { input, target } = validateInput(
|
|
253
|
+
event,
|
|
254
|
+
await event.readJson<TesterInput>(),
|
|
255
|
+
)
|
|
256
|
+
const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
257
|
+
if (!(await isOwner(event, session, signal)))
|
|
258
|
+
return failure(403, 'Forbidden')
|
|
259
|
+
return Response.json(await forward(input, target, session, signal))
|
|
260
|
+
} catch (error) {
|
|
261
|
+
const status = inputFailureStatus(error)
|
|
262
|
+
return status
|
|
263
|
+
? failure(status, 'Invalid tester request')
|
|
264
|
+
: failure(502, 'DMS tester request failed')
|
|
265
|
+
}
|
|
266
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { createRenderer, createSSRApp, defineComponent, h, nextTick } from 'vue'
|
|
3
|
+
import { renderToString } from 'vue/server-renderer'
|
|
4
|
+
import { useClientValue } from '../app/composables/useClientValue'
|
|
5
|
+
|
|
6
|
+
// A value the server and the browser may write differently (a weekday
|
|
7
|
+
// written by two ICU versions: "Thursday, 15 October" in Node, "Thursday 15
|
|
8
|
+
// October" in a recent Chrome) must not reach the server's HTML, or the
|
|
9
|
+
// hydration of every page showing it reports a mismatch.
|
|
10
|
+
|
|
11
|
+
const Tooltip = (read: () => string) =>
|
|
12
|
+
defineComponent({
|
|
13
|
+
setup() {
|
|
14
|
+
const title = useClientValue(read)
|
|
15
|
+
return () => h('time', { title: title.value }, 'for 3 min')
|
|
16
|
+
},
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
interface TestNode {
|
|
20
|
+
tag: string
|
|
21
|
+
props: Record<string, unknown>
|
|
22
|
+
children: TestNode[]
|
|
23
|
+
text?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// A renderer without a DOM: enough to mount a component in Node.
|
|
27
|
+
const { createApp } = createRenderer<TestNode, TestNode>({
|
|
28
|
+
createElement: (tag) => ({ tag, props: {}, children: [] }),
|
|
29
|
+
createText: (text) => ({ tag: '#text', props: {}, children: [], text }),
|
|
30
|
+
createComment: (text) => ({ tag: '#comment', props: {}, children: [], text }),
|
|
31
|
+
setText: (node, text) => {
|
|
32
|
+
node.text = text
|
|
33
|
+
},
|
|
34
|
+
setElementText: (node, text) => {
|
|
35
|
+
node.children = [{ tag: '#text', props: {}, children: [], text }]
|
|
36
|
+
},
|
|
37
|
+
insert: (child, parent) => {
|
|
38
|
+
parent.children.push(child)
|
|
39
|
+
},
|
|
40
|
+
remove: () => {},
|
|
41
|
+
parentNode: () => null,
|
|
42
|
+
nextSibling: () => null,
|
|
43
|
+
patchProp: (node, key, _previous, next) => {
|
|
44
|
+
node.props[key] = next
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
describe('useClientValue', () => {
|
|
49
|
+
it('leaves the value out of the server render', async () => {
|
|
50
|
+
const read = vi.fn(() => 'Thursday, 15 October 2026 at 19:58')
|
|
51
|
+
const html = await renderToString(createSSRApp(Tooltip(read)))
|
|
52
|
+
expect(html).toBe('<time>for 3 min</time>')
|
|
53
|
+
expect(read).not.toHaveBeenCalled()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('gives the value once the browser has mounted the component', async () => {
|
|
57
|
+
const root: TestNode = { tag: 'root', props: {}, children: [] }
|
|
58
|
+
createApp(Tooltip(() => 'Thursday 15 October 2026 at 19:58')).mount(root)
|
|
59
|
+
await nextTick()
|
|
60
|
+
expect(root.children[0]?.props.title).toBe(
|
|
61
|
+
'Thursday 15 October 2026 at 19:58',
|
|
62
|
+
)
|
|
63
|
+
})
|
|
64
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { testerRoute } from '../server/tester'
|
|
3
|
+
|
|
4
|
+
// The frontend server (dms-frontend 0.6) serves no tester route of its own:
|
|
5
|
+
// the module's `dms.server.ts` is the only one to declare it.
|
|
6
|
+
|
|
7
|
+
vi.mock('#dms/server', () => ({
|
|
8
|
+
defineDmsServer: (setup: unknown) => setup,
|
|
9
|
+
}))
|
|
10
|
+
|
|
11
|
+
interface Registration {
|
|
12
|
+
method: unknown
|
|
13
|
+
path: string
|
|
14
|
+
handler: unknown
|
|
15
|
+
options: unknown
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function registrations(): Promise<Registration[]> {
|
|
19
|
+
const { default: setup } = await import('../dms.server')
|
|
20
|
+
const routes: Registration[] = []
|
|
21
|
+
const server = {
|
|
22
|
+
registerRoute: (
|
|
23
|
+
method: unknown,
|
|
24
|
+
path: string,
|
|
25
|
+
handler: unknown,
|
|
26
|
+
options?: unknown,
|
|
27
|
+
) => routes.push({ method, path, handler, options }),
|
|
28
|
+
}
|
|
29
|
+
;(setup as unknown as (server: unknown) => void)(server)
|
|
30
|
+
return routes
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('dms.server.ts', () => {
|
|
34
|
+
it("serves the tester's POST under the module's own namespace, and nothing else", async () => {
|
|
35
|
+
expect(await registrations()).toEqual([
|
|
36
|
+
{
|
|
37
|
+
method: 'POST',
|
|
38
|
+
path: '/api/_dms-api/tester',
|
|
39
|
+
handler: testerRoute,
|
|
40
|
+
options: undefined,
|
|
41
|
+
},
|
|
42
|
+
])
|
|
43
|
+
})
|
|
44
|
+
})
|
|
@@ -53,7 +53,7 @@ describe('sending through the proxy', () => {
|
|
|
53
53
|
)
|
|
54
54
|
expect(result).toEqual(reply)
|
|
55
55
|
const [url, init] = fetch.mock.calls[0]
|
|
56
|
-
expect(url).toBe('/api/_dms/tester')
|
|
56
|
+
expect(url).toBe('/api/_dms-api/tester')
|
|
57
57
|
expect(init).toMatchObject({
|
|
58
58
|
method: 'POST',
|
|
59
59
|
headers: { 'content-type': 'application/json' },
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { once } from 'node:events'
|
|
2
|
+
import {
|
|
3
|
+
createServer,
|
|
4
|
+
type IncomingHttpHeaders,
|
|
5
|
+
type IncomingMessage,
|
|
6
|
+
type Server,
|
|
7
|
+
type ServerResponse,
|
|
8
|
+
} from 'node:http'
|
|
9
|
+
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
|
|
10
|
+
import type { DmsServerEvent } from '#dms/server'
|
|
11
|
+
import { testerRoute } from '../server/tester'
|
|
12
|
+
|
|
13
|
+
// The route's own checks, on the event the frontend server hands it. The
|
|
14
|
+
// server's (same-origin, the 64 KiB body limit, the session cookie) are its
|
|
15
|
+
// own and tested there.
|
|
16
|
+
|
|
17
|
+
const ACCESS_TOKEN = 'private/owner"access?token'
|
|
18
|
+
const REFRESH_TOKEN = 'private\\refresh"token'
|
|
19
|
+
const BODY_LIMIT = 64 * 1024
|
|
20
|
+
|
|
21
|
+
interface Call {
|
|
22
|
+
path: string
|
|
23
|
+
method: string
|
|
24
|
+
headers: IncomingHttpHeaders
|
|
25
|
+
body: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const calls: Call[] = []
|
|
29
|
+
let backend = ''
|
|
30
|
+
let server: Server
|
|
31
|
+
let owner: unknown = true
|
|
32
|
+
let ownerStatus = 200
|
|
33
|
+
|
|
34
|
+
async function fixture(request: IncomingMessage, response: ServerResponse) {
|
|
35
|
+
const chunks: Buffer[] = []
|
|
36
|
+
for await (const chunk of request) chunks.push(chunk as Buffer)
|
|
37
|
+
calls.push({
|
|
38
|
+
path: request.url ?? '',
|
|
39
|
+
method: request.method ?? '',
|
|
40
|
+
headers: request.headers,
|
|
41
|
+
body: Buffer.concat(chunks).toString(),
|
|
42
|
+
})
|
|
43
|
+
if (request.url === '/api/auth/me') {
|
|
44
|
+
response.writeHead(ownerStatus, { location: '/unexpected-owner-redirect' })
|
|
45
|
+
return response.end(JSON.stringify({ owner }))
|
|
46
|
+
}
|
|
47
|
+
if (request.url === '/api/network-error') return request.socket.destroy()
|
|
48
|
+
if (request.url === '/api/large')
|
|
49
|
+
return response.end('a'.repeat(BODY_LIMIT + 1))
|
|
50
|
+
if (request.url === '/api/redirect') {
|
|
51
|
+
response.writeHead(302, {
|
|
52
|
+
location: 'https://dms.example/unexpected-redirect',
|
|
53
|
+
'set-cookie': 'upstream=secret',
|
|
54
|
+
})
|
|
55
|
+
return response.end('redirect response')
|
|
56
|
+
}
|
|
57
|
+
response.writeHead(422, {
|
|
58
|
+
'x-result': 'fixture',
|
|
59
|
+
'set-cookie': 'upstream=secret',
|
|
60
|
+
'x-reflected': ACCESS_TOKEN,
|
|
61
|
+
'x-reflected-uri': encodeURIComponent(ACCESS_TOKEN),
|
|
62
|
+
'x-reflected-json': JSON.stringify(REFRESH_TOKEN).slice(1, -1),
|
|
63
|
+
connection: 'x-hop',
|
|
64
|
+
'x-hop': 'hidden',
|
|
65
|
+
})
|
|
66
|
+
response.end(
|
|
67
|
+
[
|
|
68
|
+
request.method,
|
|
69
|
+
request.url,
|
|
70
|
+
Buffer.concat(chunks),
|
|
71
|
+
ACCESS_TOKEN,
|
|
72
|
+
REFRESH_TOKEN,
|
|
73
|
+
encodeURIComponent(ACCESS_TOKEN),
|
|
74
|
+
JSON.stringify(REFRESH_TOKEN).slice(1, -1),
|
|
75
|
+
].join(':'),
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The URL the frontend server's `backendUrl` gives: always on its origin. */
|
|
80
|
+
function backendUrl(path: string): URL {
|
|
81
|
+
const { pathname, search, hash } = new URL(path, 'http://frontend.local')
|
|
82
|
+
const url = new URL(backend)
|
|
83
|
+
url.pathname = pathname
|
|
84
|
+
url.search = search
|
|
85
|
+
url.hash = hash
|
|
86
|
+
return url
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const signedIn = { accessToken: ACCESS_TOKEN, refreshToken: REFRESH_TOKEN }
|
|
90
|
+
|
|
91
|
+
async function invoke(
|
|
92
|
+
input: Record<string, unknown> = {},
|
|
93
|
+
session: unknown = signedIn,
|
|
94
|
+
readJson?: () => Promise<unknown>,
|
|
95
|
+
) {
|
|
96
|
+
const event = {
|
|
97
|
+
session: { read: () => session },
|
|
98
|
+
readJson:
|
|
99
|
+
readJson ??
|
|
100
|
+
(async () => ({
|
|
101
|
+
path: '/api/echo',
|
|
102
|
+
method: 'GET',
|
|
103
|
+
headers: {},
|
|
104
|
+
useSession: true,
|
|
105
|
+
...input,
|
|
106
|
+
})),
|
|
107
|
+
backendUrl,
|
|
108
|
+
} as unknown as DmsServerEvent
|
|
109
|
+
const response = await testerRoute(event)
|
|
110
|
+
return { response, data: await response.json() }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
beforeAll(async () => {
|
|
114
|
+
server = createServer((request, response) => void fixture(request, response))
|
|
115
|
+
server.listen(0, '127.0.0.1')
|
|
116
|
+
await once(server, 'listening')
|
|
117
|
+
const address = server.address()
|
|
118
|
+
if (!address || typeof address !== 'object') throw new Error('no address')
|
|
119
|
+
backend = `http://127.0.0.1:${address.port}`
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
afterAll(async () => {
|
|
123
|
+
server.closeAllConnections()
|
|
124
|
+
await new Promise((settle) => server.close(settle))
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
beforeEach(() => {
|
|
128
|
+
calls.length = 0
|
|
129
|
+
owner = true
|
|
130
|
+
ownerStatus = 200
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
describe('the tester route', () => {
|
|
134
|
+
it('injects the session only when enabled and redacts reflected credentials', async () => {
|
|
135
|
+
const { response, data } = await invoke()
|
|
136
|
+
expect(response.status).toBe(200)
|
|
137
|
+
expect(calls[0].headers.authorization).toBe(`Bearer ${ACCESS_TOKEN}`)
|
|
138
|
+
expect(calls[1].headers.authorization).toBe(`Bearer ${ACCESS_TOKEN}`)
|
|
139
|
+
expect(calls[1].headers['x-antelopejs-namespace']).toBe('default')
|
|
140
|
+
expect(data.status).toBe(422)
|
|
141
|
+
expect(data.body).toBe(
|
|
142
|
+
'GET:/api/echo::[REDACTED]:[REDACTED]:[REDACTED]:[REDACTED]',
|
|
143
|
+
)
|
|
144
|
+
expect(data.headers['x-result']).toBe('fixture')
|
|
145
|
+
expect(data.headers['x-reflected']).toBe('[REDACTED]')
|
|
146
|
+
expect(data.headers['x-reflected-uri']).toBe('[REDACTED]')
|
|
147
|
+
expect(data.headers['x-reflected-json']).toBe('[REDACTED]')
|
|
148
|
+
expect(data.headers['set-cookie']).toBeUndefined()
|
|
149
|
+
expect(data.headers['x-hop']).toBeUndefined()
|
|
150
|
+
expect(response.headers.get('set-cookie')).toBeNull()
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
it('still checks the owner with the session when forwarding anonymously', async () => {
|
|
154
|
+
const { response } = await invoke({ useSession: false })
|
|
155
|
+
expect(response.status).toBe(200)
|
|
156
|
+
expect(calls[0].headers.authorization).toBe(`Bearer ${ACCESS_TOKEN}`)
|
|
157
|
+
expect(calls[1].headers.authorization).toBeUndefined()
|
|
158
|
+
expect(calls[1].headers['x-antelopejs-namespace']).toBeUndefined()
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
it('lets a manual authorization, even empty, override the session', async () => {
|
|
162
|
+
for (const useSession of [true, false]) {
|
|
163
|
+
for (const authorization of ['Bearer manual', '']) {
|
|
164
|
+
calls.length = 0
|
|
165
|
+
await invoke({
|
|
166
|
+
useSession,
|
|
167
|
+
headers: {
|
|
168
|
+
AuThOrIzAtIoN: authorization,
|
|
169
|
+
'X-Antelopejs-Namespace': 'custom',
|
|
170
|
+
},
|
|
171
|
+
})
|
|
172
|
+
expect(calls[1].headers.authorization).toBe(authorization)
|
|
173
|
+
expect(calls[1].headers['x-antelopejs-namespace']).toBe('custom')
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
it('refuses a missing session, a non-owner and a revoked one', async () => {
|
|
179
|
+
expect((await invoke({}, null)).response.status).toBe(401)
|
|
180
|
+
expect(calls).toHaveLength(0)
|
|
181
|
+
for (const value of [false, 'true', 1, null]) {
|
|
182
|
+
owner = value
|
|
183
|
+
expect((await invoke({ useSession: false })).response.status).toBe(403)
|
|
184
|
+
}
|
|
185
|
+
owner = true
|
|
186
|
+
ownerStatus = 401
|
|
187
|
+
expect((await invoke()).response.status).toBe(403)
|
|
188
|
+
ownerStatus = 302
|
|
189
|
+
expect((await invoke()).response.status).toBe(403)
|
|
190
|
+
expect(calls.every((call) => call.path === '/api/auth/me')).toBe(true)
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
it('refuses malicious paths before any backend call', async () => {
|
|
194
|
+
for (const path of [
|
|
195
|
+
'https://attacker.invalid/api',
|
|
196
|
+
'//attacker.invalid',
|
|
197
|
+
'/\\attacker',
|
|
198
|
+
'/api#fragment',
|
|
199
|
+
'/api/../escape',
|
|
200
|
+
'/api/%2e%2e/escape',
|
|
201
|
+
'/%252f%252fattacker',
|
|
202
|
+
'/api/%255cescape',
|
|
203
|
+
'/api/%00',
|
|
204
|
+
'/api/\n',
|
|
205
|
+
'/api/%zz',
|
|
206
|
+
'api/echo',
|
|
207
|
+
'/api/%23fragment',
|
|
208
|
+
])
|
|
209
|
+
expect((await invoke({ path })).response.status, path).toBe(400)
|
|
210
|
+
expect(calls).toHaveLength(0)
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
it('forwards any backend path with its query, method and body', async () => {
|
|
214
|
+
for (const path of [
|
|
215
|
+
'/settings',
|
|
216
|
+
'/dms/page',
|
|
217
|
+
'/custom/action?next=https%3A%2F%2Fexample.org%2F%23section%25done',
|
|
218
|
+
]) {
|
|
219
|
+
const { response } = await invoke({
|
|
220
|
+
path,
|
|
221
|
+
method: 'PATCH',
|
|
222
|
+
body: 'asymmetric body',
|
|
223
|
+
headers: { 'Content-Type': 'text/plain' },
|
|
224
|
+
})
|
|
225
|
+
expect(response.status).toBe(200)
|
|
226
|
+
expect(calls.at(-1)).toMatchObject({
|
|
227
|
+
path,
|
|
228
|
+
method: 'PATCH',
|
|
229
|
+
body: 'asymmetric body',
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
it('strips transport, cookie, control and connection-nominated headers', async () => {
|
|
235
|
+
const headers = {
|
|
236
|
+
hOsT: 'attacker.invalid',
|
|
237
|
+
CoOkIe: 'secret=value',
|
|
238
|
+
CoNnEcTiOn: 'X-Nominated',
|
|
239
|
+
'X-Nominated': 'hidden',
|
|
240
|
+
'Proxy-Authorization': 'private',
|
|
241
|
+
'X-Forwarded-Host': 'attacker.invalid',
|
|
242
|
+
'X-Dms-Service-Token': 'privileged',
|
|
243
|
+
'Sec-Fetch-Site': 'same-origin',
|
|
244
|
+
'X-Http-Method-Override': 'DELETE',
|
|
245
|
+
'X-Custom': 'retained',
|
|
246
|
+
}
|
|
247
|
+
expect((await invoke({ headers, useSession: false })).response.status).toBe(
|
|
248
|
+
200,
|
|
249
|
+
)
|
|
250
|
+
const forwarded = calls.at(-1)!.headers
|
|
251
|
+
expect(forwarded.host).toBe(new URL(backend).host)
|
|
252
|
+
expect(forwarded['x-custom']).toBe('retained')
|
|
253
|
+
for (const name of Object.keys(headers)
|
|
254
|
+
.map((name) => name.toLowerCase())
|
|
255
|
+
.filter((name) => !['host', 'connection', 'x-custom'].includes(name)))
|
|
256
|
+
expect(forwarded[name], name).toBeUndefined()
|
|
257
|
+
})
|
|
258
|
+
|
|
259
|
+
it('returns a redirect as it is, without following it', async () => {
|
|
260
|
+
const { data } = await invoke({ path: '/api/redirect' })
|
|
261
|
+
expect(data).toMatchObject({
|
|
262
|
+
status: 302,
|
|
263
|
+
headers: { location: 'https://dms.example/unexpected-redirect' },
|
|
264
|
+
body: 'redirect response',
|
|
265
|
+
})
|
|
266
|
+
expect(data.headers['set-cookie']).toBeUndefined()
|
|
267
|
+
expect(calls).toHaveLength(2)
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
it('answers a body past the server limit with 413, and network trouble with a generic 502', async () => {
|
|
271
|
+
const tooLarge = Object.assign(new Error('Request body too large'), {
|
|
272
|
+
status: 413,
|
|
273
|
+
})
|
|
274
|
+
const { response } = await invoke({}, signedIn, () =>
|
|
275
|
+
Promise.reject(tooLarge),
|
|
276
|
+
)
|
|
277
|
+
expect(response.status).toBe(413)
|
|
278
|
+
expect(calls).toHaveLength(0)
|
|
279
|
+
for (const path of ['/api/large', '/api/network-error']) {
|
|
280
|
+
const { response, data } = await invoke({ path })
|
|
281
|
+
expect(response.status).toBe(502)
|
|
282
|
+
expect(data).toEqual({ error: 'DMS tester request failed' })
|
|
283
|
+
}
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
it('validates the method, the header values and the body before any backend call', async () => {
|
|
287
|
+
for (const input of [
|
|
288
|
+
{ method: 'CONNECT' },
|
|
289
|
+
{ useSession: 'false' },
|
|
290
|
+
{ headers: [] },
|
|
291
|
+
{ headers: { x: 1 } },
|
|
292
|
+
{ headers: { x: 'bad\r\nheader' } },
|
|
293
|
+
{ body: 'GET body' },
|
|
294
|
+
{ method: 'POST', body: {} },
|
|
295
|
+
])
|
|
296
|
+
expect((await invoke(input)).response.status).toBe(400)
|
|
297
|
+
expect(calls).toHaveLength(0)
|
|
298
|
+
})
|
|
299
|
+
})
|