Repository navigation
Expand file tree
/
Copy pathenterpriseWriteRequest.ts
More file actions
629 lines (535 loc) · 17.9 KB
/
Copy pathenterpriseWriteRequest.ts
File metadata and controls
629 lines (535 loc) · 17.9 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import {
normalizeInstanceUrl,
type NormalizedInstance,
} from "../credentials/credentialRules";
import { getEnterpriseWriteCredentialReadiness } from "../credentials/enterpriseV3Credentials";
import type { SessionCredentials } from "../domain/types";
import { MAX_CONTENT_REPLACEMENT_ROUTE_BODY_BYTES } from "../writeTools/contentReplacement/limits";
export const MAX_WRITE_ROUTE_BYTES = MAX_CONTENT_REPLACEMENT_ROUTE_BODY_BYTES;
const DEFAULT_REDACTION_MARKER = "[redacted]";
const INVALID_JSON_MESSAGE = "Request body must contain valid JSON.";
const OVERSIZED_BODY_MESSAGE = "Request body exceeds the 4 MiB limit.";
const REDACTOR_CANDIDATES = Symbol("redactorCandidates");
const SAFE_JSON_FALLBACKS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] as const;
export type EnterpriseWriteContextFailureCode =
| "invalid_instance_url"
| "enterprise_credentials_required"
| "unsupported_enterprise_instance"
| "invalid_enterprise_credentials";
export type EnterpriseWriteContextResult =
| {
ok: true;
credentials: SessionCredentials;
instance: NormalizedInstance;
redact: (value: string) => string;
}
| {
ok: false;
code: EnterpriseWriteContextFailureCode;
status: 400;
message: string;
};
export type BoundedJsonRequestResult =
| { ok: true; value: unknown }
| { ok: false; response: Response };
export type JsonRedactionPathSegment = string | number;
export interface JsonRedactionPolicy {
preserveKey?: (path: readonly JsonRedactionPathSegment[], key: string) => boolean;
preserveStringValue?: (
path: readonly JsonRedactionPathSegment[],
value: string,
) => boolean;
}
export function prepareEnterpriseWriteContext(
credentials: SessionCredentials,
): EnterpriseWriteContextResult {
const normalizedCredentials = normalizeWriteCredentials(credentials);
const redact = createCredentialRedactor(credentials, normalizedCredentials);
const readiness = getEnterpriseWriteCredentialReadiness(normalizedCredentials);
if (!readiness.valid) {
return {
ok: false,
code: readiness.code === "origin_mismatch" ? "unsupported_enterprise_instance" : readiness.code,
status: 400,
message: serverWriteFailureMessage(readiness.code, readiness.message),
};
}
const instance = normalizeInstanceUrl(readiness.origin);
return {
ok: true,
credentials: readiness.credentials,
instance,
redact,
};
}
export function redactedJsonResponse<T>(
body: T,
status: number,
redact: (value: string) => string,
policy: JsonRedactionPolicy = {},
): Response {
const sanitized = sanitizeForJson(body, redact, policy, [], new WeakSet<object>());
const serialized = serializeWithoutCredentials(sanitized, getRedactorCandidates(redact));
return serializedJsonResponse(serialized, status);
}
export async function readBoundedJsonRequest(
request: Request,
): Promise<BoundedJsonRequestResult> {
const contentLength = request.headers.get("content-length");
if (contentLength !== null && isOversizedContentLength(contentLength)) {
return { ok: false, response: jsonErrorResponse(OVERSIZED_BODY_MESSAGE, 413) };
}
let body: string;
try {
body = await request.text();
} catch {
return { ok: false, response: jsonErrorResponse(INVALID_JSON_MESSAGE, 400) };
}
if (new TextEncoder().encode(body).byteLength > MAX_WRITE_ROUTE_BYTES) {
return { ok: false, response: jsonErrorResponse(OVERSIZED_BODY_MESSAGE, 413) };
}
try {
return { ok: true, value: JSON.parse(body) as unknown };
} catch {
return { ok: false, response: jsonErrorResponse(INVALID_JSON_MESSAGE, 400) };
}
}
function normalizeWriteCredentials(credentials: SessionCredentials): SessionCredentials {
const normalizedCredentials: SessionCredentials = { ...credentials };
const apiKey = normalizeOptionalToken(credentials.apiKey);
const accessToken = normalizeOptionalToken(credentials.accessToken);
const pat = normalizeOptionalToken(credentials.pat);
if (apiKey) {
normalizedCredentials.apiKey = apiKey;
} else {
delete normalizedCredentials.apiKey;
}
if (accessToken) {
normalizedCredentials.accessToken = accessToken;
} else {
delete normalizedCredentials.accessToken;
}
if (pat) {
normalizedCredentials.pat = pat;
} else {
delete normalizedCredentials.pat;
}
return normalizedCredentials;
}
function normalizeOptionalToken(token: string | undefined): string | undefined {
const trimmedToken = token?.trim();
return trimmedToken ? trimmedToken : undefined;
}
function serverWriteFailureMessage(code: string, fallback: string): string {
if (code === "invalid_instance_url") return "Enterprise write request requires a valid instance URL.";
if (code === "enterprise_credentials_required") return "Enterprise write request requires Enterprise session credentials.";
if (code === "unsupported_enterprise_instance" || code === "origin_mismatch") {
return "Enterprise write request requires a Stack Enterprise instance URL.";
}
return fallback;
}
function createCredentialRedactor(
rawCredentials: SessionCredentials,
normalizedCredentials: SessionCredentials,
): (value: string) => string {
const secretCandidates = [
createRawSecretCandidate(rawCredentials.apiKey),
createRawSecretCandidate(rawCredentials.accessToken),
createRawSecretCandidate(rawCredentials.pat),
createNormalizedSecretCandidate(normalizedCredentials.apiKey),
createNormalizedSecretCandidate(normalizedCredentials.accessToken),
createNormalizedSecretCandidate(normalizedCredentials.pat),
].filter(isSecretCandidate);
const uniqueSecretCandidates = [...new Map(
secretCandidates.map((candidate) => [candidate.secret, candidate]),
).values()].sort((left, right) => right.secret.length - left.secret.length);
const compiledCandidates = uniqueSecretCandidates.map(compileSecretCandidate);
const marker = chooseRedactionMarker(compiledCandidates);
const boundaryGuard = chooseBoundaryGuard(compiledCandidates);
const redact = (value: string) => {
const matches = findLongestCredentialMatches(value, compiledCandidates);
const redacted = renderCredentialMatches(value, compiledCandidates, matches, marker);
if (!containsCredential(redacted, compiledCandidates)) {
return redacted;
}
const guarded = renderCredentialMatches(
value,
compiledCandidates,
matches,
marker,
boundaryGuard,
);
return containsCredential(guarded, compiledCandidates) ? boundaryGuard : guarded;
};
Object.defineProperty(redact, REDACTOR_CANDIDATES, {
value: compiledCandidates,
});
return redact;
}
interface SecretCandidate {
secret: string;
prefix: string;
suffix: string;
}
interface CompiledSecretCandidate extends SecretCandidate {
failureTable: Uint32Array;
}
function createRawSecretCandidate(value: string | undefined): SecretCandidate | null {
if (!isNonBlankString(value)) {
return null;
}
const normalizedValue = value.trim();
const normalizedStart = value.indexOf(normalizedValue);
return {
secret: value,
prefix: value.slice(0, normalizedStart),
suffix: value.slice(normalizedStart + normalizedValue.length),
};
}
function createNormalizedSecretCandidate(value: string | undefined): SecretCandidate | null {
return isNonBlankString(value)
? { secret: value, prefix: "", suffix: "" }
: null;
}
function isSecretCandidate(value: SecretCandidate | null): value is SecretCandidate {
return value !== null;
}
function compileSecretCandidate(candidate: SecretCandidate): CompiledSecretCandidate {
return {
...candidate,
failureTable: buildKmpFailureTable(candidate.secret),
};
}
function buildKmpFailureTable(pattern: string): Uint32Array {
const failureTable = new Uint32Array(pattern.length);
let prefixLength = 0;
for (let index = 1; index < pattern.length; index += 1) {
while (prefixLength > 0 && pattern[index] !== pattern[prefixLength]) {
prefixLength = failureTable[prefixLength - 1];
}
if (pattern[index] === pattern[prefixLength]) {
prefixLength += 1;
}
failureTable[index] = prefixLength;
}
return failureTable;
}
function chooseRedactionMarker(candidates: SecretCandidate[]): string {
if (isSafeMarker(DEFAULT_REDACTION_MARKER, candidates)) {
return DEFAULT_REDACTION_MARKER;
}
for (let codePoint = 0xe000; codePoint <= 0x10ffff; codePoint += 1) {
const marker = String.fromCodePoint(codePoint);
if (isSafeMarker(marker, candidates)) {
return marker;
}
}
return "";
}
function isSafeMarker(marker: string, candidates: SecretCandidate[]): boolean {
return candidates.every((candidate) => !marker.includes(candidate.secret));
}
function chooseBoundaryGuard(candidates: SecretCandidate[]): string {
const credentialCodePoints = new Set<number>();
for (const candidate of candidates) {
for (const character of candidate.secret) {
const codePoint = character.codePointAt(0);
if (codePoint !== undefined) {
credentialCodePoints.add(codePoint);
}
}
}
for (let codePoint = 0xe000; codePoint <= 0x10ffff; codePoint += 1) {
if (!credentialCodePoints.has(codePoint)) {
return String.fromCodePoint(codePoint);
}
}
return "";
}
function containsCredential(value: string, candidates: CompiledSecretCandidate[]): boolean {
return candidates.some((candidate) => hasKmpMatch(value, candidate));
}
function hasKmpMatch(value: string, candidate: CompiledSecretCandidate): boolean {
let matchedLength = 0;
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
while (
matchedLength > 0 &&
value[valueIndex] !== candidate.secret[matchedLength]
) {
matchedLength = candidate.failureTable[matchedLength - 1];
}
if (value[valueIndex] === candidate.secret[matchedLength]) {
matchedLength += 1;
}
if (matchedLength === candidate.secret.length) {
return true;
}
}
return false;
}
function getRedactorCandidates(
redact: (value: string) => string,
): readonly CompiledSecretCandidate[] {
const redactor = redact as typeof redact & {
[REDACTOR_CANDIDATES]?: readonly CompiledSecretCandidate[];
};
return redactor[REDACTOR_CANDIDATES] ?? [];
}
function serializeWithoutCredentials(
value: unknown,
candidates: readonly CompiledSecretCandidate[],
): string {
const compact = JSON.stringify(value) ?? "null";
if (candidates.length === 0) {
return compact;
}
const spaced = JSON.stringify(value, null, 1) ?? "null";
const representations = [
compact,
spaced,
escapeAllJsonStrings(compact),
escapeAllJsonStrings(spaced),
];
const safeRepresentation = representations.find(
(representation) => !containsAnyCandidate(representation, candidates),
);
if (safeRepresentation !== undefined) {
return safeRepresentation;
}
return (
SAFE_JSON_FALLBACKS.find((fallback) => !containsAnyCandidate(fallback, candidates)) ?? "0"
);
}
function containsAnyCandidate(
value: string,
candidates: readonly CompiledSecretCandidate[],
): boolean {
return candidates.some((candidate) => hasKmpMatch(value, candidate));
}
function escapeAllJsonStrings(serialized: string): string {
let escaped = "";
let index = 0;
while (index < serialized.length) {
if (serialized[index] !== '"') {
escaped += serialized[index];
index += 1;
continue;
}
const start = index;
index += 1;
while (index < serialized.length) {
if (serialized[index] === "\\") {
index += 2;
} else if (serialized[index] === '"') {
index += 1;
break;
} else {
index += 1;
}
}
const decoded = JSON.parse(serialized.slice(start, index)) as string;
escaped += encodeJsonStringWithUnicodeEscapes(decoded);
}
return escaped;
}
function encodeJsonStringWithUnicodeEscapes(value: string): string {
let encoded = '"';
for (let index = 0; index < value.length; index += 1) {
encoded += `\\u${value.charCodeAt(index).toString(16).padStart(4, "0")}`;
}
return `${encoded}"`;
}
function findLongestCredentialMatches(
value: string,
candidates: CompiledSecretCandidate[],
): Uint8Array {
const matches = new Uint8Array(value.length);
for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex += 1) {
const candidate = candidates[candidateIndex];
let matchedLength = 0;
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
while (
matchedLength > 0 &&
value[valueIndex] !== candidate.secret[matchedLength]
) {
matchedLength = candidate.failureTable[matchedLength - 1];
}
if (value[valueIndex] === candidate.secret[matchedLength]) {
matchedLength += 1;
}
if (matchedLength === candidate.secret.length) {
const matchStart = valueIndex - candidate.secret.length + 1;
if (matches[matchStart] === 0) {
matches[matchStart] = candidateIndex + 1;
}
matchedLength = candidate.failureTable[matchedLength - 1];
}
}
}
return matches;
}
function renderCredentialMatches(
value: string,
candidates: CompiledSecretCandidate[],
matches: Uint8Array,
marker: string,
boundaryGuard = "",
): string {
const chunks: string[] = [];
let index = 0;
let unchangedStart = 0;
while (index < value.length) {
const candidateIndex = matches[index] - 1;
if (candidateIndex >= 0) {
const candidate = candidates[candidateIndex];
if (unchangedStart < index) {
chunks.push(value.slice(unchangedStart, index));
}
chunks.push(
`${boundaryGuard}${candidate.prefix}${marker}${candidate.suffix}${boundaryGuard}`,
);
index += candidate.secret.length;
unchangedStart = index;
} else {
index += 1;
}
}
if (unchangedStart < value.length) {
chunks.push(value.slice(unchangedStart));
}
return chunks.join("");
}
function sanitizeForJson(
value: unknown,
redact: (value: string) => string,
policy: JsonRedactionPolicy,
path: readonly JsonRedactionPathSegment[],
ancestors: WeakSet<object>,
): unknown {
try {
return sanitizeForJsonUnsafe(value, redact, policy, path, ancestors);
} catch {
return "";
}
}
function sanitizeForJsonUnsafe(
value: unknown,
redact: (value: string) => string,
policy: JsonRedactionPolicy,
path: readonly JsonRedactionPathSegment[],
ancestors: WeakSet<object>,
): unknown {
if (typeof value === "string") {
return policy.preserveStringValue?.(path, value) ? value : redact(value);
}
if (typeof value === "bigint") {
return redact(String(value));
}
if ((typeof value !== "object" && typeof value !== "function") || value === null) {
return value;
}
if (ancestors.has(value)) {
return "";
}
ancestors.add(value);
try {
const descriptors = Object.getOwnPropertyDescriptors(value);
if (Array.isArray(value)) {
return sanitizeArray(descriptors, redact, policy, path, ancestors);
}
return sanitizeObject(descriptors, redact, policy, path, ancestors);
} finally {
ancestors.delete(value);
}
}
function sanitizeArray(
descriptors: PropertyDescriptorMap,
redact: (value: string) => string,
policy: JsonRedactionPolicy,
path: readonly JsonRedactionPathSegment[],
ancestors: WeakSet<object>,
): unknown[] {
const lengthValue = descriptors.length?.value;
const length = Number.isSafeInteger(lengthValue) && lengthValue >= 0 ? lengthValue : 0;
const sanitized = new Array<unknown>(length);
for (const [key, descriptor] of Object.entries(descriptors)) {
if (!isArrayIndex(key, length) || !("value" in descriptor)) {
continue;
}
const index = Number(key);
sanitized[index] = sanitizeForJson(
descriptor.value,
redact,
policy,
[...path, index],
ancestors,
);
}
return sanitized;
}
function sanitizeObject(
descriptors: PropertyDescriptorMap,
redact: (value: string) => string,
policy: JsonRedactionPolicy,
path: readonly JsonRedactionPathSegment[],
ancestors: WeakSet<object>,
): Record<string, unknown> {
const sanitized = Object.create(null) as Record<string, unknown>;
const trustedByOutputKey = new Map<string, boolean>();
for (const [key, descriptor] of Object.entries(descriptors)) {
if (key === "toJSON" || !descriptor.enumerable || !("value" in descriptor)) {
continue;
}
const isTrustedKey = policy.preserveKey?.(path, key) === true;
const outputKey = isTrustedKey ? key : redact(key);
const existingKeyIsTrusted = trustedByOutputKey.get(outputKey);
if (existingKeyIsTrusted !== undefined && (existingKeyIsTrusted || !isTrustedKey)) {
continue;
}
Object.defineProperty(sanitized, outputKey, {
value: sanitizeForJson(
descriptor.value,
redact,
policy,
[...path, key],
ancestors,
),
enumerable: true,
configurable: true,
writable: true,
});
trustedByOutputKey.set(outputKey, isTrustedKey);
}
return sanitized;
}
function isArrayIndex(key: string, length: number): boolean {
if (!/^(0|[1-9]\d*)$/.test(key)) {
return false;
}
const index = Number(key);
return Number.isSafeInteger(index) && index >= 0 && index < length;
}
function isOversizedContentLength(value: string): boolean {
if (!/^\d+$/.test(value)) {
return false;
}
const contentLength = Number(value);
return Number.isFinite(contentLength) && contentLength > MAX_WRITE_ROUTE_BYTES;
}
function jsonErrorResponse(error: string, status: number): Response {
return jsonResponse({ ok: false, error }, status);
}
function jsonResponse(body: unknown, status: number): Response {
return serializedJsonResponse(JSON.stringify(body), status);
}
function serializedJsonResponse(body: string | undefined, status: number): Response {
return new Response(body, {
status,
headers: {
"Content-Type": "application/json",
},
});
}
function isNonBlankString(value: string | undefined): value is string {
return typeof value === "string" && value.trim().length > 0;
}