Repository navigation
Expand file tree
/
Copy pathproxy.test.ts
More file actions
404 lines (378 loc) · 13.3 KB
/
Copy pathproxy.test.ts
File metadata and controls
404 lines (378 loc) · 13.3 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*
Copyright 2022 Expedia, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { handler } from "./proxy";
import { parseRequestBody } from "./parse-request-body";
import type { AxiosRequestHeaders, AxiosResponse } from "axios";
import { readFileSync } from "fs";
import { Agent } from "https";
import { APIGatewayProxyWithLambdaAuthorizerEvent } from "aws-lambda";
import { VALID_PING_EVENT } from "../fixtures/valid-ping-payload";
import { VALID_PUSH_PAYLOAD } from "../fixtures/valid-push-payload";
import { VALID_PUSH_PAYLOAD_USER_REPO } from "../fixtures/valid-push-payload-user-repo";
import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
const urlencodedPayload = readFileSync(
"fixtures/invalid-payload-urlencoded.txt",
).toString();
const axiosResponse: AxiosResponse = {
status: 200,
data: {
some: "data",
},
headers: {
response: "headers",
},
statusText: "status",
config: {
headers: {} as AxiosRequestHeaders,
},
};
const axiosPostMock = mock(() => axiosResponse);
mock.module("axios", () => ({
default: {
post: axiosPostMock,
},
}));
const fileMap: Record<string, string> = {
"allowed-destination-hosts.json": JSON.stringify([
"approved.host",
"another.approved.host",
"a.wildcard.*.host",
]),
};
const readFileFromLayerMock = mock((fileName: string) => fileMap[fileName]);
mock.module("./file-readers", () => ({
readFileFromLayer: readFileFromLayerMock,
getPublicCerts: mock(),
}));
const expectedResponseObject = {
statusCode: 200,
body: '{"some":"data"}',
headers: { response: "headers" },
};
const stringifiedPayload = JSON.stringify(VALID_PUSH_PAYLOAD);
const baseEvent: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
body: stringifiedPayload,
headers: {
Accept: "*/*",
"content-type": "application/json",
Host: "some-api.us-west-2.amazonaws.com",
},
pathParameters: {
endpointId: encodeURIComponent("https://approved.host/github-webhook/"),
},
multiValueHeaders: {},
httpMethod: "POST",
isBase64Encoded: false,
path: "",
queryStringParameters: {},
multiValueQueryStringParameters: {},
stageVariables: {},
requestContext: {} as any,
resource: "",
};
describe("proxy", () => {
beforeEach(() => {
process.env.ENTERPRISE_SLUG = "some_enterprise";
process.env.ENTERPRISE_MANAGED_USER_SUFFIX = "";
});
afterEach(() => {
mock.clearAllMocks();
});
it("should reject a request with an invalid urlencoded payload", async () => {
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
headers: {
...baseEvent.headers,
"content-type": "application/x-www-form-urlencoded",
},
body: urlencodedPayload,
};
const result = await handler(event);
expect(result).toEqual({ statusCode: 403, body: "Access denied" });
expect(axiosPostMock).not.toHaveBeenCalled();
});
it("should reject a request with an endpointId which is not an encoded URL", async () => {
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
pathParameters: {
endpointId: "some-invalid-endpoint",
},
};
const result = await handler(event);
expect(result).toEqual({ statusCode: 403, body: "Access denied" });
expect(axiosPostMock).not.toHaveBeenCalled();
});
it("should allow a request from a managed user suffix when supplied", async () => {
process.env.ENTERPRISE_MANAGED_USER_SUFFIX = "suffix";
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
body: JSON.stringify(VALID_PUSH_PAYLOAD_USER_REPO),
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual(expectedResponseObject);
expect(axiosPostMock).toHaveBeenCalled();
});
it("should forward a request when header is Content-Type", async () => {
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
headers: {
Accept: "*/*",
"Content-Type": "application/json",
Host: "some-api.us-west-2.amazonaws.com",
},
body: JSON.stringify(VALID_PUSH_PAYLOAD),
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual(expectedResponseObject);
expect(axiosPostMock).toHaveBeenCalled();
});
it("should not forward a request that does not come from an enterprise or managed user suffix", async () => {
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const payload = {
...VALID_PUSH_PAYLOAD,
enterprise: undefined,
};
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
body: JSON.stringify(payload),
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual({ statusCode: 403, body: "Access denied" });
expect(axiosPostMock).not.toHaveBeenCalled();
});
it("should not forward a request that does not have an approved host", async () => {
const destinationUrl = "https://not-an-approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual({ statusCode: 403, body: "Access denied" });
expect(axiosPostMock).not.toHaveBeenCalled();
});
it("should forward a request that has an approved host which matches a wildcard", async () => {
const destinationUrl = "https://a.wildcard.test.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual(expectedResponseObject);
});
it("should forward a request from an enterprise and github org without supplied certs", async () => {
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(axiosPostMock).toHaveBeenCalledWith(
destinationUrl,
stringifiedPayload,
{
headers: {
Accept: "*/*",
"content-type": "application/json",
},
},
);
expect(result).toEqual(expectedResponseObject);
});
it("should forward a request from an enterprise and github org with supplied certs", async () => {
const newFileMap: Record<string, string> = {
...fileMap,
"ca.pem": "some ca",
"cert.pem": "some cert",
};
readFileFromLayerMock.mockImplementation(
(fileName: string) => newFileMap[fileName],
);
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(axiosPostMock).toHaveBeenCalledWith(
destinationUrl,
stringifiedPayload,
{
headers: {
Accept: "*/*",
"content-type": "application/json",
},
httpsAgent: expect.any(Agent),
},
);
expect(result).toEqual(expectedResponseObject);
});
it("should return a 404 when no endpointId is found", async () => {
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
pathParameters: {},
};
const result = await handler(event);
expect(result).toEqual({ statusCode: 404, body: "Not found" });
expect(axiosPostMock).not.toHaveBeenCalled();
});
it("should forward a ping event from a managed user suffix when supplied", async () => {
process.env.ENTERPRISE_MANAGED_USER_SUFFIX = "suffix";
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
body: JSON.stringify(VALID_PING_EVENT),
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual(expectedResponseObject);
expect(axiosPostMock).toHaveBeenCalled();
});
it("should return error response from axios", async () => {
const axiosErrorResponse: AxiosResponse = {
status: 400,
data: {
some: "error",
},
headers: {
response: "headers",
},
statusText: "bad request",
config: {
headers: {} as AxiosRequestHeaders,
},
};
axiosPostMock.mockImplementationOnce(() => axiosErrorResponse);
process.env.ENTERPRISE_MANAGED_USER_SUFFIX = "suffix";
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
body: JSON.stringify(VALID_PUSH_PAYLOAD_USER_REPO),
pathParameters: {
endpointId,
},
};
const result = await handler(event);
expect(result).toEqual({
statusCode: 400,
body: '{"some":"error"}',
headers: { response: "headers" },
});
expect(axiosPostMock).toHaveBeenCalled();
});
it("should forward a urlencoded webhook whose JSON contains literal '%' characters", async () => {
const payloadWithPercent = {
...VALID_PUSH_PAYLOAD,
head_commit: {
...(VALID_PUSH_PAYLOAD as any).head_commit,
message:
"Roll out 30% threshold; reference %USERPROFILE% on Windows; WHERE x LIKE '%foo%'",
},
};
const urlencodedBody =
"payload=" + encodeURIComponent(JSON.stringify(payloadWithPercent));
const destinationUrl = "https://approved.host/github-webhook/";
const endpointId = encodeURIComponent(destinationUrl);
const event: APIGatewayProxyWithLambdaAuthorizerEvent<any> = {
...baseEvent,
headers: {
...baseEvent.headers,
"content-type": "application/x-www-form-urlencoded",
},
body: urlencodedBody,
pathParameters: { endpointId },
};
const result = await handler(event);
expect(result).toEqual(expectedResponseObject);
expect(axiosPostMock).toHaveBeenCalled();
});
});
describe("parseRequestBody — urlencoded payloads with literal '%' characters", () => {
const headers = { "content-type": "application/x-www-form-urlencoded" };
const cases: Array<{ label: string; userContent: string }> = [
{ label: "percentage in PR title", userContent: "30% threshold rollout" },
{ label: "trailing percent", userContent: "rate: 5%" },
{
label: "Windows env var reference",
userContent: "set %USERPROFILE% to ~",
},
{
label: "SQL LIKE wildcard",
userContent: "WHERE name LIKE '%foo%' AND status = 1",
},
{
label: "C-style format string",
userContent: 'printf("%s\\n", val);',
},
{ label: "Go format verb", userContent: 'log.Printf("%v", obj)' },
{
label: "bare % followed by non-hex",
userContent: "look here: %g and %h",
},
];
for (const c of cases) {
it(`parses a webhook whose JSON contains literal '%' (${c.label})`, () => {
const json = JSON.stringify({
action: "opened",
pull_request: { title: c.userContent, body: c.userContent },
});
const body = "payload=" + encodeURIComponent(json);
const result = parseRequestBody(body, headers);
expect(result).toBeDefined();
expect((result as any).pull_request.title).toBe(c.userContent);
});
}
it("still parses payloads with no '%' characters (control)", () => {
const json = JSON.stringify({ action: "opened", number: 42 });
const body = "payload=" + encodeURIComponent(json);
const result = parseRequestBody(body, headers);
expect(result).toBeDefined();
expect((result as any).number).toBe(42);
});
it("correctly preserves valid percent-escapes (%20 → space) inside JSON string values", () => {
const literalText = "encoded as %20 example";
const json = JSON.stringify({ comment: { body: literalText } });
const body = "payload=" + encodeURIComponent(json);
const result = parseRequestBody(body, headers);
expect((result as any).comment.body).toBe(literalText);
});
});