-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathproxy-request.js
More file actions
484 lines (437 loc) · 16.5 KB
/
proxy-request.js
File metadata and controls
484 lines (437 loc) · 16.5 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
'use strict';
/**
* AWF API Proxy — HTTP Proxy Core and shared exports.
*
* Security note: proxyRequest is the credential injection path. Any change here
* should be reviewed carefully for header-injection and SSRF risks.
*/
const https = require('https');
const { HttpsProxyAgent } = require('https-proxy-agent');
const { generateRequestId, sanitizeForLog, logRequest } = require('./logging');
const metrics = require('./metrics');
const rateLimiter = require('./rate-limiter');
const { buildUpstreamPath, shouldStripHeader } = require('./proxy-utils');
const { sanitizeNullToolCallTypes, injectSteeringMessage } = require('./body-transform');
const { createRateLimitChecker } = require('./rate-limit');
const { createProxyWebSocket } = require('./websocket-proxy');
const {
applyEffectiveTokenUsage,
getEffectiveTokenBlockState,
getEffectiveTokenReflectState,
resetEffectiveTokenGuardForTests,
buildEffectiveTokenLimitError,
getAndClearPendingSteeringMessage,
} = require('./guards/effective-token-guard');
const {
applyMaxRunsInvocation,
getMaxRunsBlockState,
getMaxRunsReflectState,
resetMaxRunsGuardForTests,
buildMaxRunsExceededError,
} = require('./guards/max-runs-guard');
const {
getAndClearPendingTimeoutSteeringMessage,
resetTimeoutSteeringForTests,
} = require('./guards/timeout-steering');
// ── Optional token tracker (graceful degradation when not bundled) ────────────
let trackTokenUsage;
let trackWebSocketTokenUsage;
try {
({ trackTokenUsage, trackWebSocketTokenUsage } = require('./token-tracker'));
} catch (err) {
if (err && err.code === 'MODULE_NOT_FOUND') {
trackTokenUsage = () => {};
trackWebSocketTokenUsage = () => {};
} else {
throw err;
}
}
// ── Module-level constants (read from env at load time) ───────────────────────
const HTTPS_PROXY = process.env.HTTPS_PROXY || process.env.HTTP_PROXY;
const proxyAgent = HTTPS_PROXY ? new HttpsProxyAgent(HTTPS_PROXY) : undefined;
/** Maximum request body size: 10 MB to prevent DoS via large payloads. */
const MAX_BODY_SIZE = 10 * 1024 * 1024;
/** Shared RateLimiter instance. */
const limiter = rateLimiter.create();
/** When false, token-budget warnings are never injected into request bodies. */
const isSteeringEnabled = () => process.env.AWF_ENABLE_TOKEN_STEERING === 'true';
// ── Billing header extraction ─────────────────────────────────────────────────
/**
* Extract billing/quota information from upstream response headers.
*
* CAPI returns quota snapshots as `X-Quota-Snapshot-<Type>` headers with
* URL-encoded fields: ent (entitlement), ov (overage), ovPerm (overage allowed),
* rem (remaining %), rst (reset date).
*
* Also captures X-RateLimit-* headers from CAPI responses.
*
* @param {Record<string, string|string[]>} headers - Response headers
* @returns {object|null} Billing info object, or null if no billing headers present
*/
function extractBillingHeaders(headers) {
const billing = {};
let hasBilling = false;
for (const [name, value] of Object.entries(headers)) {
const lower = name.toLowerCase();
if (lower.startsWith('x-quota-snapshot-')) {
const quotaType = lower.slice('x-quota-snapshot-'.length);
try {
const params = new URLSearchParams(String(value));
const snapshot = {};
for (const [k, v] of params) snapshot[k] = v;
billing[`quota_${quotaType}`] = snapshot;
} catch {
billing[`quota_${quotaType}_raw`] = String(value);
}
hasBilling = true;
}
}
if (headers['x-ratelimit-limit']) {
billing.rate_limit = headers['x-ratelimit-limit'];
billing.rate_remaining = headers['x-ratelimit-remaining'];
billing.rate_reset = headers['x-ratelimit-reset'];
hasBilling = true;
}
return hasBilling ? billing : null;
}
// ── Utility ───────────────────────────────────────────────────────────────────
/**
* Return true if id is a safe, non-empty request-ID string.
* Limits length and character set to prevent log injection.
* @param {unknown} id
* @returns {boolean}
*/
function isValidRequestId(id) {
return typeof id === 'string' && id.length <= 128 && /^[\w\-\.]+$/.test(id);
}
function handleRequestError(err, {
res,
requestId,
provider,
req,
targetHost,
startTime,
statusCode,
clientMessage,
extraMetrics,
}) {
const duration = Date.now() - startTime;
metrics.gaugeDec('active_requests', { provider });
metrics.increment('requests_errors_total', { provider });
if (extraMetrics) extraMetrics(duration);
logRequest('error', 'request_error', {
request_id: requestId, provider, method: req.method,
path: sanitizeForLog(req.url), duration_ms: duration,
error: sanitizeForLog(err.message), upstream_host: targetHost,
});
if (!res.headersSent) res.writeHead(statusCode, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: clientMessage, message: err.message }));
}
const checkRateLimit = createRateLimitChecker({
limiter,
metrics,
logRequest,
generateRequestId,
isValidRequestId,
});
const proxyWebSocket = createProxyWebSocket({
limiter,
HTTPS_PROXY,
metrics,
logRequest,
sanitizeForLog,
generateRequestId,
buildUpstreamPath,
shouldStripHeader,
isValidRequestId,
getEffectiveTokenBlockState,
buildEffectiveTokenLimitError,
getMaxRunsBlockState,
buildMaxRunsExceededError,
trackWebSocketTokenUsage,
applyEffectiveTokenUsage,
});
// ── Core proxy: HTTP ──────────────────────────────────────────────────────────
/**
* Forward a request to the target API, injecting auth headers and routing through Squid.
*
* @param {import('http').IncomingMessage} req
* @param {import('http').ServerResponse} res
* @param {string} targetHost - Upstream hostname
* @param {object} injectHeaders - Auth headers to inject
* @param {string} provider - Provider name for logging and metrics
* @param {string} [basePath=''] - Optional base-path prefix
* @param {((body: Buffer) => Buffer | null) | null} [bodyTransform=null]
*/
function proxyRequest(req, res, targetHost, injectHeaders, provider, basePath = '', bodyTransform = null) {
const clientRequestId = req.headers['x-request-id'];
const requestId = isValidRequestId(clientRequestId) ? clientRequestId : generateRequestId();
const startTime = Date.now();
res.setHeader('X-Request-ID', requestId);
metrics.gaugeInc('active_requests', { provider });
logRequest('info', 'request_start', {
request_id: requestId,
provider,
method: req.method,
path: sanitizeForLog(req.url),
upstream_host: targetHost,
});
if (!req.url || !req.url.startsWith('/') || req.url.startsWith('//')) {
const duration = Date.now() - startTime;
metrics.gaugeDec('active_requests', { provider });
metrics.increment('requests_total', { provider, method: req.method, status_class: '4xx' });
logRequest('warn', 'request_complete', {
request_id: requestId,
provider,
method: req.method,
path: sanitizeForLog(req.url),
status: 400,
duration_ms: duration,
upstream_host: targetHost,
});
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Bad Request', message: 'URL must be a relative path' }));
return;
}
const upstreamPath = buildUpstreamPath(req.url, targetHost, basePath);
const chunks = [];
let totalBytes = 0;
let rejected = false;
let errored = false;
req.on('error', (err) => {
if (errored) return;
errored = true;
handleRequestError(err, {
res,
requestId,
provider,
req,
targetHost,
startTime,
statusCode: 400,
clientMessage: 'Client error',
});
});
req.on('data', chunk => {
if (rejected || errored) return;
totalBytes += chunk.length;
if (totalBytes > MAX_BODY_SIZE) {
rejected = true;
const duration = Date.now() - startTime;
metrics.gaugeDec('active_requests', { provider });
metrics.increment('requests_total', { provider, method: req.method, status_class: '4xx' });
logRequest('warn', 'request_complete', {
request_id: requestId, provider, method: req.method,
path: sanitizeForLog(req.url), status: 413, duration_ms: duration,
request_bytes: totalBytes, upstream_host: targetHost,
});
if (!res.headersSent) res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload Too Large', message: 'Request body exceeds 10 MB limit' }));
return;
}
chunks.push(chunk);
});
req.on('end', () => {
if (rejected || errored) return;
let body = Buffer.concat(chunks);
const inboundBytes = body.length;
if (bodyTransform && (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH')) {
const transformed = bodyTransform(body);
if (transformed) body = transformed;
}
if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
const sanitized = sanitizeNullToolCallTypes(body);
if (sanitized) {
body = sanitized.body;
logRequest('info', 'request_sanitized', {
request_id: requestId,
provider,
normalized_tool_calls: sanitized.normalizedCount,
dropped_tool_calls: sanitized.droppedCount,
});
}
}
if (isSteeringEnabled() && (req.method === 'POST' || req.method === 'PUT')) {
const steeringMessages = [
{ type: 'timeout', message: getAndClearPendingTimeoutSteeringMessage() },
{ type: 'token', message: getAndClearPendingSteeringMessage() },
];
for (const { type, message } of steeringMessages) {
if (!message) continue;
const steered = injectSteeringMessage(body, provider, message);
if (steered) {
body = steered;
logRequest('info', `${type}_steering`, {
request_id: requestId,
provider,
message,
});
}
}
}
const requestBytes = body.length;
metrics.increment('request_bytes_total', { provider }, requestBytes);
const headers = {};
for (const [name, value] of Object.entries(req.headers)) {
if (!shouldStripHeader(name)) headers[name] = value;
}
headers['x-request-id'] = requestId;
Object.assign(headers, injectHeaders);
const isCopilotHost =
targetHost === 'githubcopilot.com' ||
targetHost.endsWith('.githubcopilot.com');
if (isCopilotHost && !headers['x-initiator']) {
headers['x-initiator'] = 'agent';
}
if (body.length !== inboundBytes) {
headers['content-length'] = String(body.length);
delete headers['transfer-encoding'];
}
const injectedKey = Object.entries(injectHeaders).find(([k]) =>
['x-api-key', 'authorization', 'x-goog-api-key'].includes(k.toLowerCase())
)?.[1];
if (injectedKey) {
const keyPreview = injectedKey.length > 8
? `${injectedKey.substring(0, 8)}...${injectedKey.substring(injectedKey.length - 4)}`
: '(short)';
logRequest('debug', 'auth_inject', {
request_id: requestId, provider,
key_length: injectedKey.length, key_preview: keyPreview,
has_anthropic_version: !!headers['anthropic-version'],
});
}
const etBlock = getEffectiveTokenBlockState();
if (etBlock && etBlock.maxExceeded) {
const duration = Date.now() - startTime;
metrics.gaugeDec('active_requests', { provider });
metrics.increment('requests_total', { provider, method: req.method, status_class: '4xx' });
metrics.observe('request_duration_ms', duration, { provider });
logRequest('warn', 'effective_tokens_limit_exceeded', {
request_id: requestId,
provider,
total_effective_tokens: etBlock.totalEffectiveTokens,
max_effective_tokens: etBlock.maxEffectiveTokens,
});
res.writeHead(429, { 'Content-Type': 'application/json', 'X-Request-ID': requestId });
res.end(JSON.stringify(buildEffectiveTokenLimitError(etBlock)));
return;
}
const mrBlock = getMaxRunsBlockState();
if (mrBlock && mrBlock.maxExceeded) {
const duration = Date.now() - startTime;
metrics.gaugeDec('active_requests', { provider });
metrics.increment('requests_total', { provider, method: req.method, status_class: '4xx' });
metrics.observe('request_duration_ms', duration, { provider });
logRequest('warn', 'max_runs_exceeded', {
request_id: requestId,
provider,
invocation_count: mrBlock.invocationCount,
max_runs: mrBlock.maxRuns,
});
res.writeHead(429, { 'Content-Type': 'application/json', 'X-Request-ID': requestId });
res.end(JSON.stringify(buildMaxRunsExceededError(mrBlock)));
return;
}
const options = {
hostname: targetHost, port: 443, path: upstreamPath,
method: req.method, headers,
agent: proxyAgent,
};
const proxyReq = https.request(options, (proxyRes) => {
let responseBytes = 0;
proxyRes.on('data', (chunk) => { responseBytes += chunk.length; });
proxyRes.on('error', (err) => {
handleRequestError(err, {
res,
requestId,
provider,
req,
targetHost,
startTime,
statusCode: 502,
clientMessage: 'Response stream error',
});
});
const billingInfo = extractBillingHeaders(proxyRes.headers);
const initiatorSent = headers['x-initiator'] || null;
proxyRes.on('end', () => {
const duration = Date.now() - startTime;
const sc = metrics.statusClass(proxyRes.statusCode);
metrics.gaugeDec('active_requests', { provider });
metrics.increment('requests_total', { provider, method: req.method, status_class: sc });
metrics.increment('response_bytes_total', { provider }, responseBytes);
metrics.observe('request_duration_ms', duration, { provider });
if (proxyRes.statusCode >= 200 && proxyRes.statusCode < 300) {
applyMaxRunsInvocation();
}
const logFields = {
request_id: requestId, provider, method: req.method,
path: sanitizeForLog(req.url), status: proxyRes.statusCode,
duration_ms: duration, request_bytes: requestBytes,
response_bytes: responseBytes, upstream_host: targetHost,
};
if (initiatorSent) logFields.x_initiator = initiatorSent;
if (billingInfo) logFields.billing = billingInfo;
logRequest('info', 'request_complete', logFields);
});
const resHeaders = { ...proxyRes.headers, 'x-request-id': requestId };
if (proxyRes.statusCode === 400 || proxyRes.statusCode === 401 || proxyRes.statusCode === 403) {
logRequest('warn', 'upstream_auth_error', {
request_id: requestId, provider, status: proxyRes.statusCode,
upstream_host: targetHost, path: sanitizeForLog(req.url),
message: `Upstream returned ${proxyRes.statusCode} — check that the API key is valid and correctly formatted`,
});
}
res.writeHead(proxyRes.statusCode, resHeaders);
proxyRes.pipe(res);
trackTokenUsage(proxyRes, {
requestId,
provider,
path: sanitizeForLog(req.url),
startTime,
metrics,
billingInfo,
initiatorSent,
onUsage: (normalizedUsage, model) => {
applyEffectiveTokenUsage(normalizedUsage, model);
},
});
});
proxyReq.on('error', (err) => {
handleRequestError(err, {
res,
requestId,
provider,
req,
targetHost,
startTime,
statusCode: 502,
clientMessage: 'Proxy error',
extraMetrics: (duration) => {
metrics.increment('requests_total', { provider, method: req.method, status_class: '5xx' });
metrics.observe('request_duration_ms', duration, { provider });
},
});
});
if (body.length > 0) proxyReq.write(body);
proxyReq.end();
});
}
module.exports = {
isValidRequestId,
checkRateLimit,
proxyRequest,
proxyWebSocket,
extractBillingHeaders,
limiter,
proxyAgent,
HTTPS_PROXY,
getEffectiveTokenReflectState,
getMaxRunsReflectState,
resetEffectiveTokenGuardForTests,
resetMaxRunsGuardForTests,
resetTimeoutSteeringForTests,
getAndClearPendingSteeringMessage,
getAndClearPendingTimeoutSteeringMessage,
injectSteeringMessage,
};