-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathindex.ts
More file actions
385 lines (325 loc) · 11.6 KB
/
index.ts
File metadata and controls
385 lines (325 loc) · 11.6 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
/**
* Copyright 2026 GitProxy Contributors
*
* 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
*
* http://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 { Router, Request, Response, NextFunction, RequestHandler } from 'express';
import proxy from 'express-http-proxy';
import { PassThrough } from 'stream';
import getRawBody from 'raw-body';
import { executeChain } from '../chain';
import { processUrlPath, validGitRequest } from './helper';
import { getAllProxiedHosts } from '../../db';
import { ProxyOptions } from 'express-http-proxy';
import { handleErrorAndLog } from '../../utils/errors';
import { getUpstreamProxyConfig } from '../../config';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { OutgoingHttpHeaders, RequestOptions } from 'http';
enum ActionType {
ALLOWED = 'Allowed',
ERROR = 'Error',
BLOCKED = 'Blocked',
}
const logAction = (
url: string,
host: string | null | undefined,
userAgent: string | null | undefined,
type: ActionType,
message?: string,
) => {
let msg = `Action processed: ${type}
Request URL: ${url}
Host: ${host}
User-Agent: ${userAgent}`;
if (message && type !== ActionType.ALLOWED) {
msg += `\n ${type}: ${message}`;
}
console.log(msg);
};
const proxyFilter: ProxyOptions['filter'] = async (req, res) => {
try {
const urlComponents = processUrlPath(req.url);
if (
!urlComponents ||
urlComponents.gitPath === undefined ||
!validGitRequest(urlComponents.gitPath, req.headers)
) {
const message = 'Invalid request received';
logAction(req.url, req.headers.host, req.headers['user-agent'], ActionType.ERROR, message);
res.status(200).send(handleMessage(message));
return false;
}
// For POST pack requests, use the raw body extracted by extractRawBody middleware
if (isPackPost(req) && req.bodyRaw) {
req.body = req.bodyRaw;
// Clean up the bodyRaw property before forwarding the request
delete req.bodyRaw;
}
const action = await executeChain(req, res);
if (action.error || action.blocked) {
const message = action.errorMessage ?? action.blockedMessage ?? 'Unknown error';
const type = action.error ? ActionType.ERROR : ActionType.BLOCKED;
logAction(req.url, req.headers.host, req.headers['user-agent'], type, message);
sendErrorResponse(req, res, message);
return false;
}
logAction(req.url, req.headers.host, req.headers['user-agent'], ActionType.ALLOWED);
// this is the only case where we do not respond directly, instead we return true to proxy the request
return true;
} catch (error: unknown) {
const message = handleErrorAndLog(error, 'Error occurred in proxy filter function');
logAction(req.url, req.headers.host, req.headers['user-agent'], ActionType.ERROR, message);
sendErrorResponse(req, res, message);
return false;
}
};
const sendErrorResponse = (req: Request, res: Response, message: string): void => {
// GET requests to /info/refs (used to check refs for many git operations) must use Git protocol error packet format
if (req.method === 'GET' && req.url.includes('/info/refs')) {
res.set('content-type', 'application/x-git-upload-pack-advertisement');
res.status(200).send(handleRefsErrorMessage(message));
return;
}
// Standard git receive-pack response
res.set('content-type', 'application/x-git-receive-pack-result');
res.set('expires', 'Fri, 01 Jan 1980 00:00:00 GMT');
res.set('pragma', 'no-cache');
res.set('cache-control', 'no-cache, max-age=0, must-revalidate');
res.set('vary', 'Accept-Encoding');
res.set('x-frame-options', 'DENY');
res.set('connection', 'close');
res.status(200).send(handleMessage(message));
};
const handleMessage = (message: string): string => {
const body = `\t${message}`;
const len = (6 + Buffer.byteLength(body)).toString(16).padStart(4, '0');
return `${len}\x02${body}\n0000`;
};
const handleRefsErrorMessage = (message: string): string => {
// Git protocol for GET /info/refs error packets: PKT-LINE("ERR" SP explanation-text)
const errorBody = `ERR ${message}`;
const len = (4 + Buffer.byteLength(errorBody)).toString(16).padStart(4, '0');
return `${len}${errorBody}\n0000`;
};
const getRequestPathResolver: (prefix: string) => ProxyOptions['proxyReqPathResolver'] = (
prefix,
) => {
return (req) => {
let url;
// try to prevent too many slashes in the URL
if (prefix.endsWith('/') && req.originalUrl.startsWith('/')) {
url = prefix.substring(0, prefix.length - 1) + req.originalUrl;
} else {
url = prefix + req.originalUrl;
}
console.log(`Request resolved to ${url}`);
return url;
};
};
const getEnvProxyUrl = () =>
process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy;
const getEnvNoProxyList = (): string[] => {
const noProxy = process.env.NO_PROXY || process.env.no_proxy;
if (!noProxy) {
return [];
}
return noProxy
.split(',')
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
};
const hostMatchesNoProxy = (host: string | null | undefined, noProxyList: string[]): boolean => {
if (!host) {
return false;
}
const hostname = host.split(':')[0];
return noProxyList.some((pattern) => {
if (!pattern) {
return false;
}
const trimmed = pattern.trim().replace(/^\./, ''); // strip leading dot
if (trimmed === '*') return true; // wildcard - bypass all
if (trimmed === '') {
return false;
}
// Exact match
if (hostname === trimmed) {
return true;
}
// Domain suffix match, e.g. example.com matches foo.example.com
if (hostname.endsWith(`.${trimmed}`)) {
return true;
}
return false;
});
};
// WARNING: proxyUrl may contain plaintext credentials in the userinfo portion
// (e.g. http://user:pass@proxy.corp.local:8080). Never log it directly — use
// redactProxyUrl() from config for any log statements involving this value.
let _cachedProxyAgent: { proxyUrl: string; agent: HttpsProxyAgent<string> } | null = null;
const getOrCreateProxyAgent = (proxyUrl: string): HttpsProxyAgent<string> => {
if (!_cachedProxyAgent || _cachedProxyAgent.proxyUrl !== proxyUrl) {
try {
new URL(proxyUrl);
} catch {
throw new Error(
`Invalid upstream proxy URL: check your upstreamProxy.url config or HTTPS_PROXY env var`,
);
}
_cachedProxyAgent = { proxyUrl, agent: new HttpsProxyAgent(proxyUrl) };
}
return _cachedProxyAgent.agent;
};
const buildUpstreamProxyAgent = (
proxyReqOpts: Omit<RequestOptions, 'headers'> & {
headers: OutgoingHttpHeaders;
},
) => {
const { enabled, url, noProxy } = getUpstreamProxyConfig();
const proxyUrl = url || getEnvProxyUrl();
if (enabled === false || !proxyUrl) {
return undefined;
}
const host: string | null | undefined = proxyReqOpts.host || proxyReqOpts.hostname;
const combinedNoProxy = [...(noProxy || []), ...getEnvNoProxyList()];
if (hostMatchesNoProxy(host, combinedNoProxy)) {
return undefined;
}
return getOrCreateProxyAgent(proxyUrl);
};
const proxyReqOptDecorator: ProxyOptions['proxyReqOptDecorator'] = (proxyReqOpts, _srcReq) => {
const agent = buildUpstreamProxyAgent(proxyReqOpts);
if (!agent) {
return proxyReqOpts;
}
return {
...proxyReqOpts,
agent,
};
};
const proxyReqBodyDecorator: ProxyOptions['proxyReqBodyDecorator'] = (bodyContent, srcReq) => {
if (srcReq.method === 'GET') {
return '';
}
return bodyContent;
};
const proxyErrorHandler: ProxyOptions['proxyErrorHandler'] = (err, _res, next) => {
console.log(`ERROR=${err}`);
next(err);
};
const isPackPost = (req: Request) =>
req.method === 'POST' &&
/^(?:\/[^/]+)*\/[^/]+\.git\/(?:git-upload-pack|git-receive-pack)$/.test(req.url);
const extractRawBody = async (req: Request, res: Response, next: NextFunction) => {
if (!isPackPost(req)) {
return next();
}
const proxyStream = new PassThrough({
highWaterMark: 4 * 1024 * 1024,
});
const pluginStream = new PassThrough({
highWaterMark: 4 * 1024 * 1024,
});
req.pipe(proxyStream);
req.pipe(pluginStream);
try {
const buf = await getRawBody(pluginStream, { limit: '1gb' });
req.bodyRaw = buf;
req.pipe = (dest, opts) => proxyStream.pipe(dest, opts);
next();
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
proxyStream.destroy(error);
} else {
console.error(String(error));
proxyStream.destroy(new Error(String(error)));
}
res.status(500).end('Proxy error');
}
};
const getRouter = async () => {
const router = Router();
router.use(extractRawBody);
const originsToProxy = await getAllProxiedHosts();
const proxyKeys: string[] = [];
const proxies: RequestHandler[] = [];
console.log(`Initializing proxy router for origins: '${JSON.stringify(originsToProxy)}'`);
// we need to wrap multiple proxy middlewares in a custom middleware as middlewares
// with path are processed in descending path order (/ then /github.com etc.) and
// we want the fallback proxy to go last.
originsToProxy.forEach((origin) => {
console.log(`\tsetting up origin: '${origin}'`);
proxyKeys.push(`/${origin}/`);
proxies.push(
proxy('https://' + origin, {
parseReqBody: false,
preserveHostHdr: false,
filter: proxyFilter,
proxyReqPathResolver: getRequestPathResolver('https://'), // no need to add host as it's in the URL
proxyReqOptDecorator: proxyReqOptDecorator,
proxyReqBodyDecorator: proxyReqBodyDecorator,
proxyErrorHandler: proxyErrorHandler,
stream: true,
} as any),
);
});
console.log('\tsetting up catch-all route (github.com) for backwards compatibility');
const fallbackProxy: RequestHandler = proxy('https://github.com', {
parseReqBody: false,
preserveHostHdr: false,
filter: proxyFilter,
proxyReqPathResolver: getRequestPathResolver('https://github.com'),
proxyReqOptDecorator: proxyReqOptDecorator,
proxyReqBodyDecorator: proxyReqBodyDecorator,
proxyErrorHandler: proxyErrorHandler,
stream: true,
} as any);
console.log('proxy keys registered: ', JSON.stringify(proxyKeys));
router.use('/', ((req, res, next) => {
if (req.path === '/healthcheck') {
res.set('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
res.set('Surrogate-Control', 'no-store');
return res.status(200).send('OK');
}
console.log(
`processing request URL: '${req.url}' against registered proxy keys: ${JSON.stringify(proxyKeys)}`,
);
for (let i = 0; i < proxyKeys.length; i++) {
if (req.url.startsWith(proxyKeys[i])) {
console.log(`\tusing proxy ${proxyKeys[i]}`);
return proxies[i](req, res, next);
}
}
// fallback
console.log(`\tusing fallback`);
return fallbackProxy(req, res, next);
}) as RequestHandler);
return router;
};
export {
proxyFilter,
getRouter,
handleMessage,
handleRefsErrorMessage,
isPackPost,
extractRawBody,
validGitRequest,
buildUpstreamProxyAgent,
hostMatchesNoProxy,
};