-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
184 lines (157 loc) · 7.9 KB
/
Copy pathtest.js
File metadata and controls
184 lines (157 loc) · 7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
const assert = require('assert')
const http = require('http')
const { test, before, after } = require('node:test')
const { createSwitchboardServer } = require('./dist/index')
let server
let port
function negotiationItem(id, { forAddress = 'recipient-address', fromAddress = 'sender-address', networkId = 'network-a' } = {}) {
return {
id,
for: forAddress,
from: fromAddress,
negotiation: {
type: 'offer',
address: fromAddress,
networkId,
connectionId: `connection-${id}`,
sdp: 'v=0\r\ns=valid\r\n',
timestamp: Date.now()
}
}
}
function switchboardRequest({ networkId = 'network-a', address = 'sender-address', negotiationItems = [], acknowledgedNegotiationIds = [] } = {}) {
return { networkId, address, negotiationItems, acknowledgedNegotiationIds }
}
function request({ method = 'POST', path = '/', body = '', headers = {}, chunks } = {}) {
return new Promise((resolve, reject) => {
const payload = typeof body === 'string' ? body : JSON.stringify(body)
const requestHeaders = { ...headers }
if (method === 'POST' && !requestHeaders['Content-Length']) {
requestHeaders['Content-Type'] = requestHeaders['Content-Type'] || 'application/json'
requestHeaders['Content-Length'] = Buffer.byteLength(payload)
}
const req = http.request({ port, path, method, headers: requestHeaders }, res => {
let response = ''
res.on('data', chunk => response += chunk)
res.on('end', () => resolve({
status: res.statusCode,
headers: res.headers,
body: response ? JSON.parse(response) : undefined
}))
})
req.on('error', reject)
if (chunks) chunks.forEach(chunk => req.write(chunk))
else req.write(payload)
req.end()
})
}
before(async () => {
server = createSwitchboardServer()
await new Promise(resolve => server.listen(0, resolve))
port = server.address().port
})
after(async () => {
await new Promise(resolve => server.close(resolve))
})
test('serves CORS preflight, health, and readiness endpoints', async () => {
let response = await request({ method: 'OPTIONS' })
assert.equal(response.status, 204)
assert.match(response.headers['access-control-allow-methods'], /GET/)
assert.ok(response.headers['x-request-id'])
for (const path of ['/health', '/ready']) {
response = await request({ method: 'GET', path })
assert.equal(response.status, 200)
assert.deepEqual(response.body, { status: 'ok' })
assert.ok(response.headers['x-request-id'])
}
const missing = await request({ method: 'GET', path: '/' })
assert.equal(missing.status, 404)
assert.deepEqual(missing.body, { error: 'not found' })
})
test('rejects unsupported methods and malformed request bodies', async () => {
let response = await request({ method: 'PUT' })
assert.equal(response.status, 405)
assert.deepEqual(response.body, { error: 'invalid request' })
response = await request({ body: '{' })
assert.equal(response.status, 400)
response = await request({ body: switchboardRequest({ negotiationItems: {} }) })
assert.equal(response.status, 400)
response = await request({ body: { networkId: 'network-a', address: 'sender-address', negotiationItems: [] } })
assert.equal(response.status, 400)
})
test('enforces streamed body limits', async () => {
const oversized = 'x'.repeat(1024 * 1024 + 1)
const response = await request({ body: oversized })
assert.equal(response.status, 413)
assert.deepEqual(response.body, { error: 'request too large' })
})
test('validates negotiation identity, identifiers, and acknowledgement IDs', async () => {
const item = negotiationItem('validation-item')
const invalidRequests = [
switchboardRequest({ negotiationItems: [{ ...item, id: '' }] }),
switchboardRequest({ negotiationItems: [{ ...item, from: 'forged-address' }] }),
switchboardRequest({ negotiationItems: [negotiationItem('wrong-network', { networkId: 'other-network' })] }),
switchboardRequest({ negotiationItems: [{ ...item, negotiation: { ...item.negotiation, address: 'forged-address' } }] }),
switchboardRequest({ negotiationItems: [{ ...item, negotiation: { ...item.negotiation, sdp: 'x'.repeat(65537) } }] }),
switchboardRequest({ acknowledgedNegotiationIds: [' invalid-id'] }),
switchboardRequest({ acknowledgedNegotiationIds: new Array(101).fill('id') })
]
for (const body of invalidRequests) {
const response = await request({ body })
assert.equal(response.status, 400)
assert.deepEqual(response.body, { error: 'invalid request' })
}
})
test('deduplicates IDs per network and only permits recipients to acknowledge', async () => {
const item = negotiationItem('same-id')
let response = await request({ body: switchboardRequest({ negotiationItems: [item] }) })
assert.equal(response.status, 200)
response = await request({ body: switchboardRequest({ negotiationItems: [item] }) })
assert.equal(response.status, 200)
response = await request({ body: switchboardRequest({ address: 'attacker-address', acknowledgedNegotiationIds: ['same-id'] }) })
assert.equal(response.status, 200)
response = await request({ body: switchboardRequest({ address: 'recipient-address' }) })
assert.equal(response.status, 200)
assert.deepEqual(response.body.negotiationItems.map(item => item.id), ['same-id'])
response = await request({ body: switchboardRequest({ address: 'recipient-address', acknowledgedNegotiationIds: ['same-id'] }) })
assert.equal(response.status, 200)
assert.deepEqual(response.body.negotiationItems, [])
const otherNetworkItem = negotiationItem('same-id', { networkId: 'network-b' })
response = await request({ body: switchboardRequest({ networkId: 'network-b', negotiationItems: [otherNetworkItem] }) })
assert.equal(response.status, 200)
response = await request({ body: switchboardRequest({ networkId: 'network-b', address: 'recipient-address' }) })
assert.deepEqual(response.body.negotiationItems.map(item => item.id), ['same-id'])
})
test('deduplicates concurrent retries and expires undelivered negotiations', async () => {
const concurrentItem = negotiationItem('concurrent-id', { forAddress: 'concurrent-recipient' })
await Promise.all(Array.from({ length: 10 }, () => request({ body: switchboardRequest({ negotiationItems: [concurrentItem] }) })))
let response = await request({ body: switchboardRequest({ address: 'concurrent-recipient' }) })
assert.deepEqual(response.body.negotiationItems.map(item => item.id), ['concurrent-id'])
const expiringItem = negotiationItem('expiring-id', { forAddress: 'expiry-recipient' })
await request({ body: switchboardRequest({ networkId: 'expiry-network', negotiationItems: [expiringItem] }) })
const originalNow = Date.now
Date.now = () => originalNow() + 30_001
try {
response = await request({ body: switchboardRequest({ networkId: 'expiry-network', address: 'expiry-recipient' }) })
assert.deepEqual(response.body.negotiationItems, [])
} finally {
Date.now = originalNow
}
})
test('enforces request and per-network negotiation capacity limits', async () => {
const tooManyItems = Array.from({ length: 101 }, (_, index) => negotiationItem(`request-limit-${index}`))
let response = await request({ body: switchboardRequest({ negotiationItems: tooManyItems }) })
assert.equal(response.status, 400)
for (let batch = 0; batch < 6; batch++) {
const negotiationItems = Array.from({ length: 100 }, (_, index) => negotiationItem(`capacity-${batch}-${index}`, {
fromAddress: 'capacity-sender',
forAddress: 'capacity-recipient',
networkId: 'capacity-network'
}))
response = await request({ body: switchboardRequest({ networkId: 'capacity-network', address: 'capacity-sender', negotiationItems }) })
assert.equal(response.status, 200)
}
response = await request({ body: switchboardRequest({ networkId: 'capacity-network', address: 'capacity-recipient' }) })
assert.equal(response.status, 200)
assert.equal(response.body.negotiationItems.length, 500)
}, { timeout: 10000 })