-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook.test.ts
More file actions
220 lines (198 loc) · 7.08 KB
/
Copy pathwebhook.test.ts
File metadata and controls
220 lines (198 loc) · 7.08 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
* Webhook transport tests.
*
* This is the only unauthenticated inbound surface in the program, so these are
* security tests rather than plumbing tests. Each case corresponds to a concrete
* way a forged or hostile request could otherwise get through.
*/
import assert from 'node:assert/strict';
import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http';
import { after, before, describe, it } from 'node:test';
import { close, createWebhookServer, listen } from '../src/telegram/webhook.js';
import type { TelegramUpdate } from '../src/telegram/api.js';
const SECRET = 'a-sufficiently-long-secret-token';
let server: Server;
let base: string;
let received: TelegramUpdate[] = [];
before(async () => {
server = createWebhookServer({
port: 0,
secretToken: SECRET,
onUpdate: async (update) => {
received.push(update);
},
});
// Port 0 lets the OS pick, so tests never collide with a real service.
await listen(server, 0);
const address = server.address() as AddressInfo;
base = `http://127.0.0.1:${address.port}`;
});
after(async () => {
await close(server);
});
function post(
path: string,
body: string,
headers: Record<string, string> = {},
): Promise<Response> {
return fetch(`${base}${path}`, { method: 'POST', body, headers });
}
const validUpdate = JSON.stringify({
update_id: 1,
message: { message_id: 1, chat: { id: 5, type: 'private' }, date: 0, text: '/status' },
});
describe('secret token verification', () => {
it('accepts a request carrying the correct secret', async () => {
received = [];
const response = await post('/telegram', validUpdate, {
'x-telegram-bot-api-secret-token': SECRET,
});
assert.equal(response.status, 200);
// The handler runs after the response is sent; give the microtask a turn.
await new Promise((r) => setTimeout(r, 20));
assert.equal(received.length, 1);
assert.equal(received[0]?.update_id, 1);
});
it('rejects a request with no secret header', async () => {
received = [];
const response = await post('/telegram', validUpdate);
assert.equal(response.status, 401);
assert.equal(received.length, 0);
});
it('rejects a wrong secret of the same length', async () => {
// The case a length check alone would let through.
const wrong = 'b'.repeat(SECRET.length);
const response = await post('/telegram', validUpdate, {
'x-telegram-bot-api-secret-token': wrong,
});
assert.equal(response.status, 401);
});
it('rejects a secret that is a prefix of the real one', async () => {
const response = await post('/telegram', validUpdate, {
'x-telegram-bot-api-secret-token': SECRET.slice(0, -1),
});
assert.equal(response.status, 401);
});
it('rejects an empty secret', async () => {
const response = await post('/telegram', validUpdate, {
'x-telegram-bot-api-secret-token': '',
});
assert.equal(response.status, 401);
});
/**
* A forged update naming an allowlisted chat is the actual attack: the command
* handler authorises on `chat.id`, so an unauthenticated caller who could post
* updates would be fully authorised. The secret check is what prevents it, and
* this asserts the forged update never reaches the handler at all.
*/
it('never dispatches a forged update to the handler', async () => {
received = [];
await post(
'/telegram',
JSON.stringify({
update_id: 99,
message: {
message_id: 1,
chat: { id: 5, type: 'private' },
date: 0,
text: '/watch npm evil',
},
}),
{ 'x-telegram-bot-api-secret-token': 'forged' },
);
await new Promise((r) => setTimeout(r, 20));
assert.equal(received.length, 0);
});
});
describe('request handling', () => {
it('rejects an oversized body', async () => {
// Enforced on the running total, not the declared content-length, so a lying
// client cannot get past it.
const huge = JSON.stringify({ update_id: 1, padding: 'x'.repeat(2 * 1024 * 1024) });
const response = await post('/telegram', huge, {
'x-telegram-bot-api-secret-token': SECRET,
});
assert.equal(response.status, 413);
});
it('rejects malformed JSON with a 400', async () => {
const response = await post('/telegram', '{not json', {
'x-telegram-bot-api-secret-token': SECRET,
});
assert.equal(response.status, 400);
});
it('returns 404 for an unknown path', async () => {
const response = await post('/not-the-webhook', validUpdate, {
'x-telegram-bot-api-secret-token': SECRET,
});
assert.equal(response.status, 404);
});
it('returns 404 for a GET on the webhook path', async () => {
assert.equal((await fetch(`${base}/telegram`)).status, 404);
});
it('serves an unauthenticated health check', async () => {
// Needed by orchestrators, so it deliberately sits outside the secret check
// and exposes nothing about internal state.
const response = await fetch(`${base}/healthz`);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { status: 'ok' });
});
it('leaks no internal detail in rejection bodies', async () => {
const response = await post('/telegram', validUpdate, {
'x-telegram-bot-api-secret-token': 'wrong',
});
assert.equal((await response.text()).length, 0);
});
it('still returns 200 when the handler throws', async () => {
// Telegram retries non-2xx and disables the webhook after enough failures.
// Losing one update beats losing the transport.
const throwing = createWebhookServer({
port: 0,
secretToken: SECRET,
onUpdate: async () => {
throw new Error('handler exploded');
},
});
await listen(throwing, 0);
const { port } = throwing.address() as AddressInfo;
try {
const response = await fetch(`http://127.0.0.1:${port}/telegram`, {
method: 'POST',
body: validUpdate,
headers: { 'x-telegram-bot-api-secret-token': SECRET },
});
assert.equal(response.status, 200);
await new Promise((r) => setTimeout(r, 20));
} finally {
await close(throwing);
}
});
it('acknowledges before running a slow handler', async () => {
// A slow handler must not stall the response, or Telegram's delivery timeout
// triggers a retry storm of duplicate updates.
let handlerFinished = false;
const slow = createWebhookServer({
port: 0,
secretToken: SECRET,
onUpdate: async () => {
await new Promise((r) => setTimeout(r, 300));
handlerFinished = true;
},
});
await listen(slow, 0);
const { port } = slow.address() as AddressInfo;
try {
const started = Date.now();
const response = await fetch(`http://127.0.0.1:${port}/telegram`, {
method: 'POST',
body: validUpdate,
headers: { 'x-telegram-bot-api-secret-token': SECRET },
});
assert.equal(response.status, 200);
assert.ok(Date.now() - started < 250, 'response waited on the handler');
assert.equal(handlerFinished, false);
} finally {
await close(slow);
}
});
});