Repository navigation
Expand file tree
/
Copy pathsanitizer.ts
More file actions
1360 lines (1218 loc) · 46.7 KB
/
Copy pathsanitizer.ts
File metadata and controls
1360 lines (1218 loc) · 46.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
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Generic utility functions for sanitizing objects to prevent logging of secrets and credentials
* Uses a custom recursive approach for reliable deep object sanitization.
*/
import safeStringify from 'fast-safe-stringify';
import type { EvalRuntimeOptions, UnifiedConfig } from '../types';
const MAX_DEPTH = 4;
const DUMMY_BASE = 'http://placeholder';
export const REDACTED = '[REDACTED]';
// Query-parameter names that imply a credential value. Shared by sanitizeUrl's
// per-param redaction and the fail-closed decision for unparseable URLs.
const SENSITIVE_URL_PARAM_NAMES =
/(api[_-]?key|key|token|password|secret|signature|sig|access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|authorization)/i;
const OPAQUE_CREDENTIAL_PATH_SEGMENT =
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{32,}|(?:token|key|secret|credential|auth)[-_][a-z0-9._-]{8,}|eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)$/i;
/**
* Whether a `scheme://user:pass@host` userinfo password is present. Implemented
* with plain string scans rather than a regex to avoid polynomial backtracking
* on adversarial input (e.g. `://:::::…`).
*/
function hasUrlUserinfoPassword(url: string): boolean {
const schemeIndex = url.indexOf('://');
if (schemeIndex === -1) {
return false;
}
const authorityStart = schemeIndex + 3;
let authorityEnd = url.length;
for (let i = authorityStart; i < url.length; i++) {
const char = url[i];
if (char === '/' || char === '?' || char === '#') {
authorityEnd = i;
break;
}
}
const authority = url.slice(authorityStart, authorityEnd);
const atIndex = authority.indexOf('@');
return atIndex !== -1 && authority.slice(0, atIndex).includes(':');
}
/**
* Whether any `key=value` segment carries a credential — by a secret-looking
* value or a secret-named key. Splits on every URL pair delimiter (`? & ; #`),
* so it catches credentials the WHATWG URL parser does not isolate: values under
* a benign name in a malformed URL, and `;`-separated query pairs (URLSearchParams
* only splits on `&`). Linear: a single split plus per-segment checks.
*/
function hasSecretFormSegment(text: string): boolean {
for (const segment of text.split(/[?&;#]/)) {
const equalsIndex = segment.indexOf('=');
if (equalsIndex <= 0) {
continue;
}
const rawValue = segment.slice(equalsIndex + 1);
if (!rawValue) {
continue;
}
const decodedValue = decodeFormComponent(rawValue);
if (
looksLikeSecret(rawValue) ||
(decodedValue !== undefined && looksLikeSecret(decodedValue))
) {
return true;
}
const rawKey = segment.slice(0, equalsIndex);
const key = decodeFormComponent(rawKey) ?? rawKey;
const keyParts = key.split(/[._\-\[\]]+/).filter(Boolean);
if (key.toLowerCase() === 'key' || isSecretField(key) || keyParts.some(isSecretField)) {
return true;
}
}
return false;
}
/**
* Whether an unparseable URL string plausibly carries a credential. Used to keep
* sanitizeUrl fail-closed for credential-bearing junk while preserving ordinary
* non-URL strings (bare domains, relative paths, prose), which also flow through
* sanitizeObject for any field literally named `url` and would otherwise be
* destroyed in persisted eval results.
*
* Detection is structural — a `user:pass@` userinfo password, a whole value that
* looks like a secret, or a `key=value` form segment that carries one. We do NOT
* fail closed on a bare credential keyword appearing anywhere in the string:
* substring-matching `token`/`secret`/`sig`/etc. redacts benign values such as
* `my-tokenizer-model`, `secrets/config.yaml`, or `design-system` (contains `sig`),
* which is data loss with no corresponding leak. Genuine credential shapes all
* carry one of the structural markers above (the secret-named-key case is covered
* by `hasSecretFormSegment`, which normalizes keys like `api_key` before matching).
*/
function unparseableUrlMightLeakSecret(url: string): boolean {
return hasUrlUserinfoPassword(url) || looksLikeSecret(url.trim()) || hasSecretFormSegment(url);
}
/**
* Set of field names that should be redacted (case-insensitive, with hyphens/underscores normalized)
* Note: Keys are stored in their normalized form (lowercase, no hyphens/underscores)
*/
export const SECRET_FIELD_NAMES = new Set([
// Password variants
'password',
'passwd',
'pwd',
// Secret variants
'secret',
'secrets',
'secretkey',
'credentials',
// API keys and tokens
'apikey',
'apisecret',
'token',
'accesstoken',
'refreshtoken',
'idtoken',
'bearertoken',
'authtoken',
'clientsecret',
'webhooksecret',
'anthropicapikey',
'awsbearertokenbedrock',
// AWS SigV4 credentials. Both spellings are needed: normalizeFieldName strips
// underscores, so the env var AWS_SECRET_ACCESS_KEY collapses to
// 'awssecretaccesskey' while the documented provider config field
// `secretAccessKey` collapses to 'secretaccesskey'. These are first-class,
// documented Bedrock config fields (see site/docs/providers/aws-bedrock.md),
// so an inline credential otherwise reaches logs and shared configs in clear text.
'secretaccesskey',
'awssecretaccesskey',
'sessiontoken',
'awssessiontoken',
'accesskeyid',
'awsaccesskeyid',
'authorization',
'auth',
'bearer',
'apikeyenvar', // environment variable name for API key
// Header-specific patterns (normalized: hyphens removed)
'xapikey', // x-api-key
'xauthtoken', // x-auth-token
'xaccesstoken', // x-access-token
'xauth', // x-auth
'xsecret', // x-secret
'xcsrftoken', // x-csrf-token
// Portkey gateway credential headers. The provider derives these from `portkey*` config
// keys, so the vendor prefix keeps them out of the generic 'apikey' match.
'portkeyapikey', // portkeyApiKey config field
'portkeyvirtualkey', // portkeyVirtualKey config field
'xportkeyapikey', // x-portkey-api-key
'xportkeyvirtualkey', // x-portkey-virtual-key
'xportkeyawsaccesskeyid', // x-portkey-aws-access-key-id
'xportkeyawssecretaccesskey', // x-portkey-aws-secret-access-key
'xportkeyawssessiontoken', // x-portkey-aws-session-token
'xsessiondata', // x-session-data
'csrftoken', // csrf-token
'sessionid', // session-id
'session', // session
'cookie',
'setcookie', // set-cookie
// Certificate and encryption
'certificatepassword',
'keystorepassword',
'pfxpassword',
'privatekey',
'certkey',
'encryptionkey',
'signingkey',
'signature',
'sig',
'passphrase',
'certificatecontent',
'keystorecontent',
'pfx',
'pfxcontent',
'keycontent',
'certcontent',
]);
/**
* Normalize field names for comparison (lowercase, drop hyphens, underscores,
* whitespace, and stray `=`). Whitespace covers `Api Key` and `api+key` (which
* URL-decodes to `api key`); the `=` strip covers `api%3Dkey` (decodes to
* `api=key`). All collapse to `apikey` and match SECRET_FIELD_NAMES.
*/
export function normalizeFieldName(fieldName: string): string {
return fieldName.toLowerCase().replace(/[-_\s=]/g, '');
}
/**
* Check if a field name should be redacted
*/
export function isSecretField(fieldName: string): boolean {
return SECRET_FIELD_NAMES.has(normalizeFieldName(fieldName));
}
/**
* Matched as a whole `_`-delimited word only. `KEY` is short enough to sit inside ordinary
* words — `PORTKEY_API_BASE_URL` is a documented endpoint, `MONKEY` is a word — so the
* credential compounds that end in it are listed explicitly below instead.
*/
const ENV_SECRET_WHOLE_WORDS = new Set(['KEY']);
/**
* Matched as a whole word *or* a suffix, so fused vendor spellings are caught:
* `PGPASSWORD`, `GCP_PRIVATEKEY`, `DBPWD`, `DATABASEDSN`. Each is either long enough that a
* suffix match is unambiguous, or (like `PWD`/`DSN`) has no ordinary-word collisions.
*
* Singular on purpose: `MAX_TOKENS` ends with `TOKENS`, which does not end with `TOKEN`.
*/
const ENV_SECRET_SUFFIX_WORDS = [
'PASSWORD',
'PASSWD',
'PASSPHRASE',
'CREDENTIALS',
'CREDENTIAL',
'SECRET',
'TOKEN',
'PWD',
'DSN',
// Every credential name in SECRET_FIELD_NAMES that ends in `key`, so a prefixed spelling
// (`APP_ENCRYPTIONKEY`, `VENDOR_CERTKEY`) is still caught even though the exact-name match
// cannot see past the prefix. Derived rather than hand-listed so the two stay in sync; all
// are at least six characters, so none of them matches `PORTKEY` or `MONKEY`.
...[...SECRET_FIELD_NAMES].filter((name) => name.endsWith('key') && name.length > 3),
// Not in SECRET_FIELD_NAMES on its own — that set carries `accesskeyid` — but the bare
// compound shows up in env vars.
'accesskey',
].map((word) => word.toUpperCase());
/**
* Secret only as the final `_`-delimited word. `MLFLOW_BASIC_AUTH` and `NPM_CONFIG__AUTH`
* hold a credential; `WATSONX_AI_AUTH_TYPE` names a method and `OAUTH_SCOPE` is not an
* `AUTH` word at all.
*/
const ENV_SECRET_TERMINAL_WORDS = new Set(['AUTH']);
/**
* An environment-variable-shaped name. Leading underscores are legal and used in practice
* (`_GITHUB_TOKEN`), so they must not be a way around the check. Case is normalized before
* this is applied.
*/
const ENV_VAR_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;
/**
* Check whether an environment-variable name looks credential-bearing.
*
* `SECRET_FIELD_NAMES` matches exact names, which can never cover the project-specific
* names real environments use — `GITHUB_TOKEN`, `STRIPE_SECRET_KEY`, `PGPASSWORD` all
* slip through it. An `env` map is passed straight to a subprocess, so it is the one
* place a config is *expected* to hold credentials; treat a credential-worded key there
* as secret.
*
* Case is normalized first: nothing requires an env var to be uppercase, and a lowercase
* `github_token` reaches the subprocess exactly like `GITHUB_TOKEN` does.
*/
export function isSecretEnvVarName(name: string): boolean {
if (isSecretField(name)) {
return true;
}
const normalized = name.toUpperCase();
if (!ENV_VAR_NAME_RE.test(normalized)) {
return false;
}
const words = normalized.split('_');
if (ENV_SECRET_TERMINAL_WORDS.has(words[words.length - 1])) {
return true;
}
return words.some(
(word) =>
ENV_SECRET_WHOLE_WORDS.has(word) ||
ENV_SECRET_SUFFIX_WORDS.some((secret) => word.endsWith(secret)),
);
}
/**
* Sanitizes runtime options to ensure only JSON-serializable data is persisted or exported.
* Removes non-serializable fields like AbortSignal, functions, and symbols.
*/
export function sanitizeRuntimeOptions(
options?: EvalRuntimeOptions,
): EvalRuntimeOptions | undefined {
if (!options) {
return undefined;
}
// Create a copy to avoid mutating the original options object.
const sanitized = { ...options };
delete sanitized.abortSignal;
const sanitizedEntries = sanitized as Record<string, unknown>;
for (const [key, value] of Object.entries(sanitizedEntries)) {
if (typeof value === 'function' || typeof value === 'symbol') {
delete sanitizedEntries[key];
}
}
return sanitized;
}
/**
* Check if a value looks like a secret based on common patterns.
* Detects API keys, tokens, and other credential patterns.
*/
export function looksLikeSecret(value: string): boolean {
if (typeof value !== 'string') {
return false;
}
// OpenAI API keys (sk-...)
if (/^sk-[a-zA-Z0-9-_]{20,}/.test(value)) {
return true;
}
// OpenAI project keys (sk-proj-...)
if (/^sk-proj-[a-zA-Z0-9-_]{20,}/.test(value)) {
return true;
}
// Anthropic keys (sk-ant-...)
if (/^sk-ant-[a-zA-Z0-9-_]{20,}/.test(value)) {
return true;
}
// Generic API key patterns (key-...)
if (/^key-[a-zA-Z0-9]{20,}/.test(value)) {
return true;
}
// Bearer tokens
if (/^Bearer\s+.{20,}/i.test(value)) {
return true;
}
// Basic auth
if (/^Basic\s+.{20,}/i.test(value)) {
return true;
}
// AWS-style access keys (AKIA...)
if (/^AKIA[A-Z0-9]{16}/.test(value)) {
return true;
}
// Google API keys (AIza...)
if (/^AIza[a-zA-Z0-9_-]{35}/.test(value)) {
return true;
}
// Long base64-like strings (likely tokens/keys) - 64+ chars of alphanumeric
// Using 64 chars to reduce false positives on concatenated IDs, base64 content, or long model names
// Scan for disallowed characters without growing the regex stack for large values.
if (value.length >= 64 && !/[^a-zA-Z0-9+/=_-]/.test(value)) {
return true;
}
return false;
}
// Headers with standard non-credential meanings; other custom headers may authenticate a gateway.
const NON_CREDENTIAL_HEADERS = new Set([
'accept',
'content-type',
'openai-beta',
'openai-organization',
'openai-project',
'user-agent',
'x-openai-originator',
]);
export function isNonCredentialHeader(name: string): boolean {
return NON_CREDENTIAL_HEADERS.has(name.toLowerCase());
}
const SAFE_TRACING_CREDENTIAL_TEMPLATE =
/^(?:(?:bearer|basic|token|api[-_]?key)\s+)?\{\{\s*env(?:\.[A-Za-z_][A-Za-z0-9_]*|\[['"][A-Za-z_][A-Za-z0-9_]*['"]\])+\s*(?:\|\s*(?:trim|urlencode)\s*)*\}\}$/i;
interface TracingCredentialReference {
template: string;
renderedValue: string;
}
interface TracingCredentialReferences {
auth: Map<string, TracingCredentialReference>;
headers: Map<string, TracingCredentialReference>;
env: Map<string, TracingCredentialReference>;
}
const tracingCredentialReferences = new WeakMap<object, TracingCredentialReferences>();
const SAFE_TRACING_PROVIDER_HEADERS = new Set([
'accept',
'content-type',
'x-org-id',
'x-organization-id',
'x-scope-orgid',
'x-tenant-id',
]);
function isSafeTracingCredentialTemplate(value: unknown): value is string {
return typeof value === 'string' && SAFE_TRACING_CREDENTIAL_TEMPLATE.test(value.trim());
}
function isTracingCredentialHeader(name: string, value: string): boolean {
const normalizedName = name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
return (
isSecretField(name) ||
/(?:^|[-_\s])(?:api[-_\s]?key|access[-_\s]?key|auth(?:orization)?|token|password|passwd|secret|credentials?|cookie)(?:$|[-_\s])/i.test(
normalizedName,
) ||
normalizedName.replace(/[-_]/g, '') === 'xhoneycombteam' ||
/^(?:bearer|basic|token|api[-_]?key)\s+\S+/i.test(value.trim()) ||
looksLikeSecret(value.trim())
);
}
function isNonSensitiveTracingHeader(name: string, value: string): boolean {
return (
SAFE_TRACING_PROVIDER_HEADERS.has(name.toLowerCase()) && !isTracingCredentialHeader(name, value)
);
}
function getTracingTemplateEnvironmentVariable(template: string): string | undefined {
if (!isSafeTracingCredentialTemplate(template)) {
return undefined;
}
const match = template.match(
/\benv(?:\.([A-Za-z_][A-Za-z0-9_]*)|\[['"]([A-Za-z_][A-Za-z0-9_]*)['"]\])/,
);
return match?.[1] ?? match?.[2];
}
/**
* Retains safe credential references alongside their rendered provider without exposing
* internal bookkeeping through config serialization or provider-visible properties.
*/
export function preserveTracingCredentialReferences(
sourceConfig: Partial<UnifiedConfig>,
renderedConfig: Partial<UnifiedConfig>,
): void {
const sourceProvider = sourceConfig.tracing?.provider;
const renderedProvider = renderedConfig.tracing?.provider;
if (!sourceProvider || !renderedProvider) {
return;
}
const references: TracingCredentialReferences = {
auth: new Map(),
headers: new Map(),
env: new Map(),
};
for (const [key, template] of Object.entries(sourceProvider.auth ?? {})) {
if (key !== 'token' && key !== 'password') {
continue;
}
const renderedValue = Object.entries(renderedProvider.auth ?? {}).find(
([renderedKey]) => renderedKey === key,
)?.[1];
if (isSafeTracingCredentialTemplate(template) && typeof renderedValue === 'string') {
references.auth.set(key, { template, renderedValue });
}
}
for (const [name, template] of Object.entries(sourceProvider.headers ?? {})) {
const renderedValue = renderedProvider.headers?.[name];
if (isSafeTracingCredentialTemplate(template) && typeof renderedValue === 'string') {
references.headers.set(name, { template, renderedValue });
}
}
const credentialTemplates = [
...references.auth.values(),
...Array.from(references.headers.entries())
.filter(([name, reference]) => !isNonSensitiveTracingHeader(name, reference.renderedValue))
.map(([, reference]) => reference),
];
const sourceEnv = sourceConfig.env as Record<string, unknown> | undefined;
const renderedEnv = renderedConfig.env as Record<string, unknown> | undefined;
const visitedEnvironmentVariables = new Set<string>();
for (const { template } of credentialTemplates) {
let name = getTracingTemplateEnvironmentVariable(template);
while (name && !visitedEnvironmentVariables.has(name)) {
visitedEnvironmentVariables.add(name);
const sourceValue = sourceEnv?.[name];
const renderedValue = renderedEnv?.[name];
if (!isSafeTracingCredentialTemplate(sourceValue) || typeof renderedValue !== 'string') {
break;
}
references.env.set(name, { template: sourceValue, renderedValue });
name = getTracingTemplateEnvironmentVariable(sourceValue);
}
}
if (references.auth.size > 0 || references.headers.size > 0) {
tracingCredentialReferences.set(renderedProvider, references);
}
}
function getReferencedTracingCredentialEnvironmentVariables(
auth: Record<string, unknown> | undefined,
headers: Record<string, string> | undefined,
env: Record<string, unknown> | undefined,
references: TracingCredentialReferences | undefined,
): Set<string> {
const variables = new Set<string>();
for (const [name, value] of Object.entries(auth ?? {})) {
if ((name === 'token' || name === 'password') && typeof value === 'string') {
const variable = getTracingTemplateEnvironmentVariable(value);
if (variable) {
variables.add(variable);
}
}
}
for (const [name, value] of Object.entries(headers ?? {})) {
if (!isNonSensitiveTracingHeader(name, value)) {
const variable = getTracingTemplateEnvironmentVariable(value);
if (variable) {
variables.add(variable);
}
}
}
for (const name of variables) {
const value = env?.[name];
const reference = references?.env.get(name);
const template = isSafeTracingCredentialTemplate(value)
? value
: reference && reference.renderedValue === value
? reference.template
: undefined;
const variable = template ? getTracingTemplateEnvironmentVariable(template) : undefined;
if (variable) {
variables.add(variable);
}
}
return variables;
}
/**
* Keeps runtime trace-provider credentials out of persisted and exported eval configs.
* Safe environment references remain intact so resumed evaluations can resolve them again.
*/
export function sanitizeTracingConfigForPersistence(
config: Partial<UnifiedConfig>,
): Partial<UnifiedConfig> {
const provider = config.tracing?.provider;
if (!provider) {
return config;
}
let sanitizedEndpoint = provider.endpoint;
try {
const endpoint = new URL(provider.endpoint);
if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
endpoint.username = '';
endpoint.password = '';
endpoint.search = '';
endpoint.hash = '';
sanitizedEndpoint = endpoint.toString();
}
const safeEndpoint = sanitizeUrlForLogging(endpoint.toString());
if (safeEndpoint !== endpoint.toString()) {
sanitizedEndpoint = safeEndpoint;
}
} catch {
sanitizedEndpoint = sanitizeUrl(provider.endpoint);
}
const references = tracingCredentialReferences.get(provider);
const sanitizedAuth = provider.auth
? Object.fromEntries(
Object.entries(provider.auth).flatMap(([key, value]) => {
if ((key !== 'token' && key !== 'password') || isSafeTracingCredentialTemplate(value)) {
return [[key, value]];
}
const reference = references?.auth.get(key);
return reference && reference.renderedValue === value ? [[key, reference.template]] : [];
}),
)
: undefined;
const sanitizedHeaders = provider.headers
? Object.fromEntries(
Object.entries(provider.headers).flatMap(([name, value]) => {
if (typeof value !== 'string') {
return [];
}
const reference = references?.headers.get(name);
if (reference?.renderedValue === value) {
return [[name, reference.template]];
}
if (isSafeTracingCredentialTemplate(value) || isNonSensitiveTracingHeader(name, value)) {
return [[name, value]];
}
return [];
}),
)
: undefined;
const referencedCredentialEnvironmentVariables =
getReferencedTracingCredentialEnvironmentVariables(
sanitizedAuth,
sanitizedHeaders,
config.env as Record<string, unknown> | undefined,
references,
);
const sanitizedEnv = config.env
? Object.fromEntries(
Object.entries(config.env).flatMap(([name, value]) => {
if (!referencedCredentialEnvironmentVariables.has(name)) {
return [[name, value]];
}
if (isSafeTracingCredentialTemplate(value)) {
return [[name, value]];
}
const reference = references?.env.get(name);
return reference?.renderedValue === value ? [[name, reference.template]] : [];
}),
)
: undefined;
const sanitizedProvider = {
...provider,
endpoint: sanitizedEndpoint,
...(provider.auth && { auth: sanitizedAuth }),
...(provider.headers && { headers: sanitizedHeaders }),
} as typeof provider;
return {
...config,
...(config.env && { env: sanitizedEnv }),
tracing: {
...config.tracing!,
provider: sanitizedProvider,
},
};
}
/**
* Detect class instances (objects with custom prototypes and methods)
*/
function isClassInstance(obj: any): boolean {
const proto = Object.getPrototypeOf(obj);
// Bail out early if proto is null or Object.prototype
if (!proto || proto === Object.prototype) {
return false;
}
const hasMethods = Object.getOwnPropertyNames(proto).some(
(prop) => prop !== 'constructor' && typeof proto[prop] === 'function',
);
return hasMethods;
}
function redactAzureBlobSasToken(value: string): string {
if (!/^az:\/\//i.test(value)) {
return value;
}
const queryStart = value.indexOf('?');
if (queryStart === -1) {
return value;
}
const fragmentStart = value.indexOf('#', queryStart);
const queryEnd = fragmentStart === -1 ? value.length : fragmentStart;
let redacted = false;
const sanitizedQuery = value
.slice(queryStart + 1, queryEnd)
.split('&')
.map((parameter) => {
const equalsIndex = parameter.indexOf('=');
const encodedName = equalsIndex === -1 ? parameter : parameter.slice(0, equalsIndex);
let name: string;
try {
name = decodeURIComponent(encodedName.replace(/\+/g, ' '));
} catch {
return parameter;
}
if (name.toLowerCase() !== 'sig') {
return parameter;
}
redacted = true;
return `${encodedName}=${encodeURIComponent(REDACTED)}`;
})
.join('&');
return redacted
? `${value.slice(0, queryStart + 1)}${sanitizedQuery}${value.slice(queryEnd)}`
: value;
}
/**
* Redact SAS credentials embedded in Azure Blob config references without
* applying broader output sanitization to configuration consumed by clients.
*/
export function redactAzureBlobSasTokens<T>(value: T): T {
if (typeof value === 'string') {
return redactAzureBlobSasToken(value) as T;
}
if (Array.isArray(value)) {
return value.map((item) => redactAzureBlobSasTokens(item)) as T;
}
if (!value || typeof value !== 'object' || isClassInstance(value)) {
return value;
}
const redactedEntries = Object.entries(value).map(([key, item]) => [
key,
redactAzureBlobSasTokens(item),
]);
return Object.fromEntries(redactedEntries) as T;
}
type RestoreResult<T> = {
value: T;
restored: boolean;
};
function collectStoredAzureBlobSasTokens(
value: unknown,
tokensByRedactedUri = new Map<string, string>(),
): Map<string, string> {
if (typeof value === 'string') {
const redacted = redactAzureBlobSasToken(value);
if (redacted !== value && !tokensByRedactedUri.has(redacted)) {
tokensByRedactedUri.set(redacted, value);
}
return tokensByRedactedUri;
}
if (Array.isArray(value)) {
for (const item of value) {
collectStoredAzureBlobSasTokens(item, tokensByRedactedUri);
}
return tokensByRedactedUri;
}
if (!value || typeof value !== 'object' || isClassInstance(value)) {
return tokensByRedactedUri;
}
for (const item of Object.values(value)) {
collectStoredAzureBlobSasTokens(item, tokensByRedactedUri);
}
return tokensByRedactedUri;
}
function restoreAzureBlobSasTokensFromMap<T>(
value: T,
tokensByRedactedUri: ReadonlyMap<string, string>,
): RestoreResult<T> {
if (typeof value === 'string') {
const storedValue = tokensByRedactedUri.get(value);
return storedValue === undefined
? { value, restored: false }
: { value: storedValue as T, restored: true };
}
if (Array.isArray(value)) {
let restored = false;
const restoredItems = value.map((item) => {
const result = restoreAzureBlobSasTokensFromMap(item, tokensByRedactedUri);
restored ||= result.restored;
return result.value;
});
return restored ? { value: restoredItems as T, restored } : { value, restored };
}
if (!value || typeof value !== 'object' || isClassInstance(value)) {
return { value, restored: false };
}
let restored = false;
const restoredEntries = Object.entries(value).map(([key, item]) => {
const result = restoreAzureBlobSasTokensFromMap(item, tokensByRedactedUri);
restored ||= result.restored;
return [key, result.value];
});
return restored
? { value: Object.fromEntries(restoredEntries) as T, restored }
: { value, restored };
}
function restoreAzureBlobSasTokensWithResult<T>(value: T, storedValue: unknown): RestoreResult<T> {
if (typeof value === 'string') {
if (typeof storedValue === 'string' && value === redactAzureBlobSasToken(storedValue)) {
return { value: storedValue as T, restored: storedValue !== value };
}
return { value, restored: false };
}
if (Array.isArray(value)) {
const storedItems = Array.isArray(storedValue) ? storedValue : [];
const storedTokensByRedactedUri = collectStoredAzureBlobSasTokens(storedItems);
let restored = false;
const restoredItems = value.map((item, index) => {
const positional = restoreAzureBlobSasTokensWithResult(item, storedItems[index]);
// Positional restore fails when array entries are reordered, inserted, or
// edited outside the URI field. Also match by redacted URI identity so
// unchanged nested SAS references keep their stored signature.
const fallback = restoreAzureBlobSasTokensFromMap(
positional.value,
storedTokensByRedactedUri,
);
restored ||= positional.restored || fallback.restored;
return fallback.value;
});
return restored ? { value: restoredItems as T, restored } : { value, restored };
}
if (!value || typeof value !== 'object' || isClassInstance(value)) {
return { value, restored: false };
}
const storedObject =
storedValue && typeof storedValue === 'object' && !Array.isArray(storedValue)
? (storedValue as Record<string, unknown>)
: {};
let restored = false;
const restoredEntries = Object.entries(value).map(([key, item]) => {
const result = restoreAzureBlobSasTokensWithResult(item, storedObject[key]);
restored ||= result.restored;
return [key, result.value];
});
return restored
? { value: Object.fromEntries(restoredEntries) as T, restored }
: { value, restored };
}
/**
* Preserve stored SAS credentials when a sanitized config is written back unchanged.
* If the caller edits the resource or supplies a replacement token, retain its value.
*/
export function restoreAzureBlobSasTokens<T>(value: T, storedValue: unknown): T {
return restoreAzureBlobSasTokensWithResult(value, storedValue).value;
}
/**
* Parse and sanitize JSON strings, also check if the string looks like a secret
*/
function sanitizeJsonString(str: string, depth: number, maxDepth: number): string {
const redactedAzureBlobUri = redactAzureBlobSasToken(str);
if (redactedAzureBlobUri !== str) {
return redactedAzureBlobUri;
}
try {
const parsed = JSON.parse(str);
if (parsed && typeof parsed === 'object') {
const sanitized = recursiveSanitize(parsed, depth, maxDepth);
return JSON.stringify(sanitized);
}
} catch {
if (looksLikeUrlEncodedFormData(str)) {
const sanitizedUrlEncoded = sanitizeUrlEncodedString(str);
if (sanitizedUrlEncoded !== str) {
return sanitizedUrlEncoded;
}
}
// Not JSON - check if it looks like a secret
if (looksLikeSecret(str)) {
return REDACTED;
}
}
return str;
}
// `key=value` where the key is a typical form-data identifier (allow brackets
// for PHP/qs-style nested keys) and the value runs to the next separator. The
// first `=` is the separator within a pair; subsequent `=` (e.g. base64
// padding) belong to the value. Both `&` and `;` are accepted as pair
// separators since PHP/CGI/several Java stacks treat `;` as a `&` equivalent.
const URL_ENCODED_SEGMENT_RE = /^[A-Za-z0-9._~+%\[\]-]+=[^&;]*$/;
function looksLikeUrlEncodedFormData(value: string): boolean {
// Every non-empty separator-delimited chunk must be a `key=value` pair with
// safe key characters. Values may contain raw spaces because some clients
// emit non-canonical form bodies instead of encoding them as `+` or `%20`,
// but multiline/tab-delimited diagnostic text must not be collapsed into a
// single form field. Empty chunks (leading/trailing/consecutive separators)
// are tolerated. The strict key shape keeps prose and shell commands
// containing `=` from being treated as form data.
if (!value.includes('=') || /[\r\n\t]/.test(value)) {
return false;
}
const segments = value.split(/[&;]/).filter((segment) => segment.length > 0);
if (segments.length === 0) {
return false;
}
return segments.every((segment) => URL_ENCODED_SEGMENT_RE.test(segment));
}
// Matches one `key=value` pair. `[^=&;]+` for the key ensures we split on the
// FIRST `=` (so values can contain `=`, e.g. base64 padding); `[^&;]*` lets the
// value run to the next pair separator (`&` or `;`).
const URL_ENCODED_PAIR_RE = /(^|[&;])([^=&;]+)=([^&;]*)/g;
function decodeFormComponent(component: string): string | undefined {
try {
return decodeURIComponent(component.replace(/\+/g, ' '));
} catch {
return undefined;
}
}
/**
* When a form value URL-decodes to a JSON object/array, recursively sanitize
* it and return the serialized result — but only if sanitization actually
* changed something. Returns `null` when there is no JSON to sanitize or when
* the value is JSON but contains no secrets (so callers can preserve the
* original byte-for-byte).
*/
function redactNestedJsonValue(decoded: string | undefined): string | null {
if (decoded === undefined) {
return null;
}
const trimmed = decoded.trim();
if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {
return null;
}
if (!parsed || typeof parsed !== 'object') {
return null;
}
const sanitized = sanitizeObject(parsed);
const originalSerialized = JSON.stringify(parsed);
const sanitizedSerialized = JSON.stringify(sanitized);
return sanitizedSerialized === originalSerialized ? null : sanitizedSerialized;
}
// Matches one `{{ ... }}` Nunjucks placeholder. `[^{}]*` excludes braces so it
// cannot backtrack against the closing `}}` (linear, no ReDoS).
const NUNJUCKS_PLACEHOLDER = /\{\{[^{}]*\}\}/g;
// A value that is entirely Nunjucks placeholders (e.g. `{{password}}`) with no
// literal content is a config template, not a runtime secret. A value that merely
// CONTAINS a placeholder alongside literal text (e.g. `abc{{x}}def`) is not, so a
// secret-named key must still redact it.
function isPureTemplateValue(value: string): boolean {
return value.includes('{{') && value.replace(NUNJUCKS_PLACEHOLDER, '').trim() === '';
}
export function sanitizeUrlEncodedString(value: string): string {
if (!value.includes('=')) {
return value;
}
let changed = false;
const result = value.replace(URL_ENCODED_PAIR_RE, (match, separator, rawKey, rawValue) => {
if (rawValue.length === 0) {
// Preserve empty values verbatim so `password=` doesn't masquerade as a
// redacted secret.
return match;
}
// Preserve pure Nunjucks placeholders (e.g. a provider body template
// `password={{password}}`): these are config templates, not runtime secrets,
// and this string flows through sanitizeObject into persisted provider
// configs. Mirrors the template guard in sanitizeUrl. Checked before the
// secret-key redaction so a templated secret field is kept, but a value that
// only embeds a placeholder among literal text is not exempted.
if (isPureTemplateValue(rawValue)) {
return match;
}
// An undecodable key (stray `%` not forming %HH) only disables the key-NAME
// match — the value-pattern checks below must still run, otherwise a malformed
// key smuggles its secret value past redaction (e.g. `api%ZZkey=AKIA...`).
const decodedKey = decodeFormComponent(rawKey);
// Split nested-key syntax (`user[password]`, `a.b.password`) into parts so we
// can match the leaf name against SECRET_FIELD_NAMES.
const keyParts = decodedKey === undefined ? [] : decodedKey.split(/[.\[\]]+/).filter(Boolean);
const keyIsSecret = keyParts.some(isSecretField);
// A secret-named key redacts its ENTIRE value before any template skip or
// nested-JSON recursion, so a partial-template value (`password=abc{{x}}def`)
// or a JSON value (`password={"value":"plain"}`) can't leak a fragment.
if (keyIsSecret) {
changed = true;
// `encodeURIComponent(REDACTED)` keeps the output a valid form-encoded
// body; debug consumers that decode it see `[REDACTED]`.