-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathindex.ts
More file actions
456 lines (414 loc) · 12.7 KB
/
index.ts
File metadata and controls
456 lines (414 loc) · 12.7 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
import { DEFAULT_BRAINTRUST_APP_URL } from "@lib/constants";
import { flushMetrics } from "@lib/metrics";
import { proxyV1, SpanLogger, LogHistogramFn, BillingEvent } from "@lib/proxy";
import { isEmpty } from "@lib/util";
import { MeterProvider } from "@opentelemetry/sdk-metrics";
import { APISecret, APISecretSchema, getModelEndpointTypes } from "@schema";
import { verifyTempCredentials, isTempCredential } from "utils";
import {
decryptMessage,
EncryptedMessage,
encryptMessage,
} from "utils/encrypt";
// FlushingHttpMetricExporter moved to cloudflare-specific code to avoid Edge Runtime issues
export interface EdgeContext {
waitUntil(promise: Promise<any>): void;
}
export interface CacheSetOptions {
ttl?: number;
}
export interface Cache {
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, options?: { ttl?: number }): Promise<void>;
}
export interface ProxyOpts {
getRelativeURL(request: Request): string;
cors?: boolean;
credentialsCache?: Cache;
completionsCache?: Cache;
braintrustApiUrl?: string;
meterProvider?: MeterProvider;
logHistogram?: LogHistogramFn;
whitelist?: (string | RegExp)[];
spanLogger?: SpanLogger;
billingOrgId?: string;
onBillingEvent?: (event: BillingEvent) => void;
spanId?: string;
spanExport?: string;
nativeInferenceSecretKey?: string;
}
const defaultWhitelist: (string | RegExp)[] = [
"https://www.braintrustdata.com",
"https://www.braintrust.dev",
new RegExp("https://.*-braintrustdata.vercel.app"),
new RegExp("https://.*.preview.braintrust.dev"),
];
const baseCorsHeaders = {
"access-control-allow-credentials": "true",
"access-control-allow-methods": "GET,OPTIONS,POST",
};
export function getCorsHeaders(
request: Request,
whitelist: (string | RegExp)[] | undefined,
) {
whitelist = whitelist || defaultWhitelist;
// If the host is not in the whitelist, return a 403.
const origin = request.headers.get("Origin");
if (
origin &&
!whitelist.some(
(w) => w === origin || (w instanceof RegExp && w.test(origin)),
)
) {
throw new Error("Forbidden");
}
return origin
? {
"access-control-allow-origin": origin,
...baseCorsHeaders,
}
: {};
}
// https://developers.cloudflare.com/workers/examples/cors-header-proxy/
async function handleOptions(
request: Request,
corsHeaders: Record<string, string>,
) {
if (
request.headers.get("Origin") !== null &&
request.headers.get("Access-Control-Request-Method") !== null &&
request.headers.get("Access-Control-Request-Headers") !== null
) {
// Handle CORS preflight requests.
return new Response(null, {
headers: {
...corsHeaders,
"access-control-allow-headers": request.headers.get(
"Access-Control-Request-Headers",
)!,
},
});
} else {
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
});
}
}
export async function digestMessage(message: string) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await crypto.subtle.digest("SHA-256", data);
return btoa(String.fromCharCode(...new Uint8Array(hash)));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
export function makeFetchApiSecrets({
ctx,
opts,
}: {
ctx: EdgeContext;
opts: ProxyOpts;
}) {
return async (
useCache: boolean,
authToken: string,
model: string | null,
org_name?: string,
project_id?: string,
): Promise<APISecret[]> => {
// Project-level secrets are not supported on the edge proxy since they are
// stored in the data plane
if (project_id) {
throw new Error(
"Project-level AI provider secrets are not supported on the edge proxy. " +
"Please use the hosted API proxy or remove the x-bt-project-id header.",
);
}
// First try to decode & verify as JWT. We gate this on Braintrust JWT
// format, not just any JWT, in case a future model provider uses JWT as
// the auth token.
if (opts.credentialsCache && isTempCredential(authToken)) {
try {
const { jwtPayload, credentialCacheValue } =
await verifyTempCredentials({
jwt: authToken,
cacheGet: opts.credentialsCache.get,
});
// Overwrite parameters with those from JWT.
authToken = credentialCacheValue.authToken;
model = jwtPayload.bt.model || null;
org_name = jwtPayload.bt.org_name || undefined;
// Fall through to normal secrets lookup.
} catch (error) {
// Re-throw to filter out everything except `message`.
console.error(error);
throw new Error(error instanceof Error ? error.message : undefined);
}
}
const cacheKey = await digestMessage(
`${model}/${org_name ? org_name + ":" : ""}${authToken}`,
);
const response =
useCache &&
opts.credentialsCache &&
(await encryptedGet(opts.credentialsCache, cacheKey, cacheKey));
if (response) {
console.log("API KEY CACHE HIT");
return JSON.parse(response);
} else {
console.log("API KEY CACHE MISS");
}
let secrets: APISecret[] = [];
let lookupFailed = false;
// Only cache API keys for 60 seconds. This reduces the load on the database but ensures
// that changes roll out quickly enough too.
const ttl = 60;
try {
const response = await fetch(
`${opts.braintrustApiUrl || DEFAULT_BRAINTRUST_APP_URL}/api/secret`,
{
method: "POST",
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
org_name,
mode: "full",
...(opts.nativeInferenceSecretKey
? { can_execute_native_inference: true }
: {}),
}),
},
);
if (response.ok) {
const responseJson: unknown = await response.json();
if (
isRecord(responseJson) &&
responseJson.encrypted === true &&
typeof responseJson.iv === "string" &&
typeof responseJson.data === "string"
) {
if (!opts.nativeInferenceSecretKey) {
throw new Error(
"Received encrypted response but NATIVE_INFERENCE_SECRET_KEY is not configured",
);
}
const keys = opts.nativeInferenceSecretKey
.split(",")
.map((k) => k.trim())
.filter((k) => k.length > 0);
let decrypted: string | null | undefined = null;
for (const key of keys) {
const encryptionKey = await digestMessage(key);
try {
decrypted = await decryptMessage(
encryptionKey,
responseJson.iv,
responseJson.data,
);
if (decrypted) break;
} catch {}
}
if (!decrypted) {
throw new Error(
"Failed to decrypt native inference response (tried all keys)",
);
}
const parsed: unknown = JSON.parse(decrypted);
if (!Array.isArray(parsed)) {
throw new Error("Decrypted response is not an array");
}
secrets = parsed.map((s: unknown) => APISecretSchema.parse(s));
} else {
if (!Array.isArray(responseJson)) {
throw new Error("Response is not an array");
}
secrets = responseJson.map((s: unknown) => APISecretSchema.parse(s));
}
} else {
const responseText = await response.text();
if (response.status === 400) {
throw new Error(
`Failed to lookup api key: ${response.status}: ${responseText}`,
);
}
lookupFailed = true;
console.warn("Failed to lookup api key", responseText);
}
} catch (e) {
if (
e instanceof Error &&
e.message.startsWith("Failed to lookup api key: 400:")
) {
throw e;
}
lookupFailed = true;
console.warn("Failed to lookup api key. Falling back to provided key", e);
}
if (lookupFailed) {
const endpointTypes = !isEmpty(model) ? getModelEndpointTypes(model) : [];
secrets.push({
secret: authToken,
type: endpointTypes[0] ?? "openai",
});
}
if (opts.credentialsCache && !lookupFailed) {
ctx.waitUntil(
encryptedPut(
opts.credentialsCache,
cacheKey,
cacheKey,
JSON.stringify(secrets),
{
ttl,
},
),
);
}
return secrets;
};
}
// Metric logging functions are now created in the calling layer (e.g., Cloudflare proxy)
export function EdgeProxyV1(opts: ProxyOpts) {
return async (request: Request, ctx: EdgeContext) => {
let corsHeaders = {};
try {
if (opts.cors) {
corsHeaders = getCorsHeaders(request, opts.whitelist);
}
} catch (e) {
return new Response("Forbidden", { status: 403 });
}
if (request.method === "OPTIONS" && opts.cors) {
return handleOptions(request, corsHeaders);
}
if (request.method !== "GET" && request.method !== "POST") {
return new Response("Method not allowed", {
status: 405,
headers: { "Content-Type": "text/plain" },
});
}
const relativeURL = opts.getRelativeURL(request);
// Create an identity TransformStream (a.k.a. a pipe).
// The readable side will become our new response body.
const { readable, writable } = new TransformStream();
let status = 200;
const headers: Record<string, string> = opts.cors ? corsHeaders : {};
const setStatus = (code: number) => {
status = code;
};
const setHeader = (name: string, value: string) => {
headers[name] = value;
};
const proxyHeaders: Record<string, string> = {};
request.headers.forEach((value, name) => {
proxyHeaders[name] = value;
});
const cacheGet = async (encryptionKey: string, key: string) => {
if (opts.completionsCache) {
return (
(await encryptedGet(opts.completionsCache, encryptionKey, key)) ??
null
);
} else {
return null;
}
};
const fetchApiSecrets = makeFetchApiSecrets({ ctx, opts });
// Set span headers if available
if (opts.spanId) {
setHeader("x-bt-span-id", opts.spanId);
}
if (opts.spanExport) {
setHeader("x-bt-span-export", opts.spanExport);
}
const cachePut = async (
encryptionKey: string,
key: string,
value: string,
ttl_seconds?: number,
): Promise<void> => {
if (opts.completionsCache) {
const ret = encryptedPut(
opts.completionsCache,
encryptionKey,
key,
value,
{
// 1 week if not specified
ttl: ttl_seconds ?? 60 * 60 * 24 * 7,
},
);
ctx.waitUntil(ret);
return ret;
}
};
try {
await proxyV1({
method: request.method,
url: relativeURL,
proxyHeaders,
body: await request.text(),
setHeader,
setStatusCode: setStatus,
res: writable,
getApiSecrets: fetchApiSecrets,
cacheGet,
cachePut,
digest: digestMessage,
logHistogram: opts.logHistogram,
spanLogger: opts.spanLogger,
billingOrgId: opts.billingOrgId,
onBillingEvent: opts.onBillingEvent,
});
} catch (e) {
return new Response(`${e}`, {
status: 400,
headers: { "Content-Type": "text/plain" },
});
}
const meterProvider = opts.meterProvider;
const responseBody = meterProvider
? readable.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
flush() {
ctx.waitUntil(flushMetrics(meterProvider));
},
}),
)
: readable;
return new Response(responseBody, {
status,
headers,
});
};
}
// We rely on the fact that Upstash will automatically serialize and deserialize things for us
export async function encryptedGet(
cache: Cache,
encryptionKey: string,
key: string,
) {
const message = await cache.get<EncryptedMessage>(key);
if (isEmpty(message)) {
return null;
}
return await decryptMessage(encryptionKey, message.iv, message.data);
}
export async function encryptedPut(
cache: Cache,
encryptionKey: string,
key: string,
value: string,
options?: { ttl?: number },
) {
options = options || {};
const encryptedValue = await encryptMessage(encryptionKey, value);
await cache.set(key, encryptedValue, options);
}