forked from G-Research/git-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
253 lines (215 loc) · 8 KB
/
index.ts
File metadata and controls
253 lines (215 loc) · 8 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
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, getAllProxiedHosts } from './helper';
import { ProxyOptions } from 'express-http-proxy';
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 as any).bodyRaw) {
(req as any).body = (req as any).bodyRaw;
// Clean up the bodyRaw property before forwarding the request
delete (req as any).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 (e) {
const message = `Error occurred in proxy filter function ${(e as Error).message ?? e}`;
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 proxyReqOptDecorator: ProxyOptions['proxyReqOptDecorator'] = (proxyReqOpts) => proxyReqOpts;
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 as any).bodyRaw = buf;
(req as any).pipe = (dest: any, opts: any) => proxyStream.pipe(dest, opts);
next();
} catch (e) {
console.error(e);
proxyStream.destroy(e as 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,
};