-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1692 lines (1605 loc) · 62.1 KB
/
Copy pathcli.js
File metadata and controls
executable file
·1692 lines (1605 loc) · 62.1 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
#!/usr/bin/env node
// Copyright 2026 will Farrell, and sast-json-schema contributors.
// SPDX-License-Identifier: MIT
import { lookup as dnsLookup } from "node:dns/promises";
import { readFile, stat } from "node:fs/promises";
import { relative, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { parseArgs } from "node:util";
import Ajv from "ajv/dist/2020.js";
import { isSafePattern } from "redos-detector";
import schema201909 from "./2019-09.json" with { type: "json" };
import schema202012 from "./2020-12.json" with { type: "json" };
import schemaDraft04 from "./draft-04.json" with { type: "json" };
import schemaDraft06 from "./draft-06.json" with { type: "json" };
import schemaDraft07 from "./draft-07.json" with { type: "json" };
import pkg from "./package.json" with { type: "json" };
const defaultOptions = {
strictTypes: false,
allErrors: true,
};
const DEFAULT_VERSION = "2020-12";
export const DNS_TIMEOUT_MS = 5_000;
export const DNS_CONCURRENCY = 10;
export const MAX_SSRF_HOSTNAMES = 256;
export const DNS_TOTAL_TIMEOUT_MS = 30_000;
// Pre-compiled SAST meta-schema validators, keyed by draft version. Compiled
// once at module load so every sast() / analyze() call reuses the same
// validator.
const builtSchemas = new Map(
[
["2020-12", schema202012],
["2019-09", schema201909],
["draft-07", schemaDraft07],
["draft-06", schemaDraft06],
["draft-04", schemaDraft04],
].map(([version, metaSchema]) => [
version,
// allErrors:true is required so a single pass surfaces EVERY meta-schema
// violation for the security report; the schemas are trusted, not attacker
// input, so unbounded error allocation is not a DoS vector here.
// nosemgrep: javascript.ajv.security.audit.ajv-allerrors-true.ajv-allerrors-true
new Ajv(defaultOptions).compile(metaSchema),
]),
);
// Known $schema URLs mapped to their draft version. URLs are stored in
// normalised form (no protocol, no trailing #) so callers can pass any
// http/https variant with or without a fragment.
const knownSchemaUrls = new Map([
["json-schema.org/draft/2020-12/schema", "2020-12"],
["json-schema.org/draft/2019-09/schema", "2019-09"],
["json-schema.org/draft-07/schema", "draft-07"],
["json-schema.org/draft-06/schema", "draft-06"],
["json-schema.org/draft-04/schema", "draft-04"],
]);
// Maps a user schema's $schema URL to the matching draft version.
const schemaVersion = (url) => {
if (!url) return DEFAULT_VERSION;
// Stryker disable next-line Regex: dropping the ^/$ anchors only changes the
// result for URLs with an interior "//" or "#", none of which are in the known
// set, so they resolve to the same (unsupported) lookup either way.
const normalized = url.replace(/^(?:https?:)?\/\//, "").replace(/#$/, "");
return knownSchemaUrls.get(normalized);
};
export const MAX_DEPTH = 32;
export const MAX_SCHEMA_SIZE = 64 * 1024 * 1024; // 64 MiB
// Hard cap on the total number of remote $ref/$dynamicRef entries crawlSchema
// will collect into result.refs. The distinct-hostname cap (MAX_SSRF_HOSTNAMES)
// only applies later, after every ref has already been buffered, so a schema
// with a huge number of refs to the same few hosts would still accumulate an
// unbounded array. This is a backstop (overall bounded by MAX_SCHEMA_SIZE); set
// well above what realistic schemas need (multiple refs per distinct host).
export const MAX_COLLECTED_REFS = 4 * MAX_SSRF_HOSTNAMES;
// Per-pattern budget for ReDoS analysis. Patterns that exceed this are
// fail-closed (reported as unsafe with reason "timedOut") to keep total
// scan time bounded on adversarial input.
export const REDOS_TIMEOUT_MS = 1_000;
// HEAP CIRCUIT BREAKER: the PRIMARY memory bound for ReDoS analysis. The
// `timeout` option bounds time but NOT memory, and redos-detector's `maxSteps`
// cannot serve as the memory control: a value low enough to bound a catastrophic
// pattern (which retains ~7MB post-GC and ~270MB pre-GC each, so a handful OOM a
// 600MB heap) also wrongly fail-closes legitimate complex-but-safe patterns
// (e.g. semver is reported hitMaxSteps at maxSteps<=250 but is SAFE at the
// library default). So we drop maxSteps and instead read the live heap before
// each pattern: once it has grown beyond this budget above the phase baseline,
// analysis STOPS and one fail-closed (incomplete) finding is emitted. Chosen at
// 128MB: a single catastrophic pattern grows the heap by ~270MB at the default,
// so the breaker fires after the FIRST evil pattern (delta ~270MB > 128MB) and
// before the second, keeping peak well under --max-old-space-size=600; meanwhile
// realistic schemas with many SIMPLE patterns retain almost nothing and never
// approach 128MB. Injectable via crawlSchema options for deterministic testing.
export const REDOS_HEAP_BUDGET_BYTES = 128 * 1024 * 1024;
// Defense in depth: a hard cap on the TOTAL number of regex patterns crawlSchema
// will ReDoS-analyze in a single crawl. The heap circuit breaker above is the
// primary memory control; this is an independent backstop against an adversary
// supplying a huge number of patterns. Set well above what realistic schemas
// need (they can legitimately carry hundreds of simple patterns, which are
// cheap).
export const MAX_REDOS_PATTERNS = 256;
export const ANALYSIS_TIMEOUT_MS = 60_000;
// Property names that act as deserialization / type-confusion vectors in
// each downstream language ecosystem. Selected at the analyze() / CLI layer
// via the `lang` option (default: "default", the union of every named lang,
// because JSON specs typically flow through multiple language toolchains
// and the safe default is to catch them all). Set --lang explicitly to
// narrow scope when you control the consumer environment.
//
// "default": union of every named language entry below. Most paranoid baseline.
// "js": V8 prototype-pollution: __proto__, constructor, prototype.
// "py": js + Python introspection / pickle gadget keys.
// "rb": js + Ruby reflection / JSON.load(create_additions: true).
// "rs": js baseline (Rust serde itself is type-safe, but specs often
// pass through JS tooling that is not).
// "java": js + Jackson/Fastjson polymorphic deserialization markers.
// "kotlin": alias of java (JVM/Jackson).
// "clojure": alias of java (JVM/Cheshire).
// "cs": js + .NET JSON deserialization markers. Covers C#, VB.NET,
// ASP.NET, and ASPX (they all share the same serializer stack:
// Json.NET $type, DataContractJsonSerializer __type, OData @odata.type).
// "vb": alias of cs (.NET stack).
// "fsharp": alias of cs (.NET stack).
// "php": js + PHP magic methods invoked during object hydration
// (Symfony Serializer / JMS Serializer / unserialize gadget chains).
// "objc": js + Objective-C runtime keys: isa, class, superclass,
// description, init, _cmd (KVC + performSelector: vectors).
// "swift": alias of objc (Obj-C runtime exposure via interop; pure Codable
// is type-safe but mixed projects share the same surface).
// "ex": js + Elixir/BEAM struct-identifier keys: __struct__,
// __exception__, __protocol__ (auto-recognized when JSON is
// decoded with :keys => :atoms and hydrated into a struct).
// "lua": js + Lua metamethod names (__index, __newindex, __call,
// __metatable, __tostring, __gc, __close, etc.) for libraries
// that auto-bind metatables onto JSON-decoded tables.
//
// There is no "off" switch: the meta-schema enforces __proto__/constructor/
// prototype universally, so the narrowest opt-out is --lang js (which adds
// no extras over the meta-schema baseline). For per-path false positives,
// use --ignore <instancePath>.
export const DANGEROUS_NAMES_BY_LANG = {
js: ["__proto__", "constructor", "prototype"],
py: [
"__proto__",
"constructor",
"prototype",
"__class__",
"__init__",
"__globals__",
"__builtins__",
"__import__",
"__reduce__",
"__subclasses__",
"__dict__",
"__mro__",
],
rb: [
"__proto__",
"constructor",
"prototype",
"__send__",
"json_class",
"instance_eval",
"instance_variable_set",
"singleton_class",
],
rs: ["__proto__", "constructor", "prototype"],
java: ["__proto__", "constructor", "prototype", "@type", "@class"],
kotlin: ["__proto__", "constructor", "prototype", "@type", "@class"],
clojure: ["__proto__", "constructor", "prototype", "@type", "@class"],
cs: [
"__proto__",
"constructor",
"prototype",
"$type",
"__type",
"@odata.type",
],
vb: [
"__proto__",
"constructor",
"prototype",
"$type",
"__type",
"@odata.type",
],
fsharp: [
"__proto__",
"constructor",
"prototype",
"$type",
"__type",
"@odata.type",
],
php: [
"__proto__",
"constructor",
"prototype",
"__construct",
"__destruct",
"__wakeup",
"__sleep",
"__serialize",
"__unserialize",
"__call",
"__callStatic",
"__get",
"__set",
"__isset",
"__unset",
"__toString",
"__invoke",
"__set_state",
"__clone",
"__debugInfo",
],
objc: [
"__proto__",
"constructor",
"prototype",
"isa",
"class",
"superclass",
"description",
"init",
"_cmd",
],
swift: [
"__proto__",
"constructor",
"prototype",
"isa",
"class",
"superclass",
"description",
"init",
"_cmd",
],
ex: [
"__proto__",
"constructor",
"prototype",
"__struct__",
"__exception__",
"__protocol__",
],
lua: [
"__proto__",
"constructor",
"prototype",
"__index",
"__newindex",
"__call",
"__metatable",
"__tostring",
"__name",
"__pairs",
"__eq",
"__lt",
"__le",
"__add",
"__sub",
"__mul",
"__div",
"__mod",
"__pow",
"__concat",
"__len",
"__unm",
"__band",
"__bor",
"__bxor",
"__bnot",
"__shl",
"__shr",
"__idiv",
"__close",
"__gc",
],
};
DANGEROUS_NAMES_BY_LANG.default = [
...new Set(Object.values(DANGEROUS_NAMES_BY_LANG).flat()),
];
export const DEFAULT_LANG = "default";
const resolveDangerousNames = (lang) => {
if (lang == null) return DANGEROUS_NAMES_BY_LANG[DEFAULT_LANG];
if (Array.isArray(lang)) return lang;
const list = DANGEROUS_NAMES_BY_LANG[lang];
if (!list) {
throw new TypeError(
`unknown lang "${lang}", expected one of: ${Object.keys(DANGEROUS_NAMES_BY_LANG).join(", ")}`,
);
}
return list;
};
// AJV schema paths used by override filters. Verified by regression tests
// in cli.analyze.test.js to match what AJV actually emits.
const SCHEMA_PATH_MAX_ITEMS = "#/$defs/safeArrayItemsLimits/maxItems";
const SCHEMA_PATH_MAX_PROPERTIES =
"#/$defs/safeObjectPropertiesLimits/maxProperties";
// Returns the pre-compiled SAST validator for the draft declared by
// `schema.$schema`. Defaults to 2020-12 when $schema is absent.
export const sast = (schema) => {
const version = schemaVersion(schema?.$schema);
const validate = builtSchemas.get(version);
if (!validate) {
// Stryker disable next-line OptionalChaining: reaching this throw requires a
// non-null schema object (a null schema resolves to the default and validates),
// so schema?.$schema and schema.$schema are equivalent here.
throw new Error(`Unsupported $schema: ${schema?.$schema}`);
}
return validate;
};
export default sast;
// Checks whether a numeric schema's min/max bounds describe an impossible
// range. Returns an AJV-style error object when they do, or null otherwise.
const checkNumericRange = (current, path) => {
// Number.isFinite is true only for an actual finite number, so it already
// implies `typeof === "number"`; no separate type check is needed.
const hasMin =
Object.hasOwn(current, "minimum") && Number.isFinite(current.minimum);
const hasExMin =
Object.hasOwn(current, "exclusiveMinimum") &&
Number.isFinite(current.exclusiveMinimum);
const hasMax =
Object.hasOwn(current, "maximum") && Number.isFinite(current.maximum);
const hasExMax =
Object.hasOwn(current, "exclusiveMaximum") &&
Number.isFinite(current.exclusiveMaximum);
if (!(hasMin || hasExMin) || !(hasMax || hasExMax)) return null;
let effectiveMin;
let minIsExclusive = false;
if (hasMin && hasExMin) {
if (current.exclusiveMinimum >= current.minimum) {
effectiveMin = current.exclusiveMinimum;
minIsExclusive = true;
} else {
effectiveMin = current.minimum;
}
} else if (hasExMin) {
effectiveMin = current.exclusiveMinimum;
minIsExclusive = true;
} else {
effectiveMin = current.minimum;
}
let effectiveMax;
let maxIsExclusive = false;
if (hasMax && hasExMax) {
if (current.exclusiveMaximum <= current.maximum) {
effectiveMax = current.exclusiveMaximum;
maxIsExclusive = true;
} else {
effectiveMax = current.maximum;
}
} else if (hasExMax) {
effectiveMax = current.exclusiveMaximum;
maxIsExclusive = true;
} else {
effectiveMax = current.maximum;
}
const impossible =
minIsExclusive || maxIsExclusive
? !(effectiveMin < effectiveMax)
: effectiveMin > effectiveMax;
if (!impossible) return null;
const keyword = maxIsExclusive
? "exclusiveMaximum"
: minIsExclusive
? "exclusiveMinimum"
: "minimum";
return {
instancePath: path,
schemaPath: `#/${keyword}`,
keyword,
params: {
...(hasMin && { minimum: current.minimum }),
...(hasExMin && { exclusiveMinimum: current.exclusiveMinimum }),
...(hasMax && { maximum: current.maximum }),
...(hasExMax && { exclusiveMaximum: current.exclusiveMaximum }),
},
message: "numeric range is unsatisfiable",
};
};
const INSTANCE_DATA_KEYS = new Set(["const", "enum", "default", "examples"]);
// RFC 6901 JSON Pointer token escaping: ~ → ~0, / → ~1.
// https://datatracker.ietf.org/doc/html/rfc6901#section-3
const escapeJsonPointer = (token) =>
token.replace(/~/g, "~0").replace(/\//g, "~1");
// Single-pass crawler that records: max depth, range/length inconsistencies,
// ReDoS patterns, and remote $ref URLs (for later SSRF resolution).
// Depth semantics: each object-valued key counts as one level, so a schema
// `{properties: {a: {properties: {b: {...}}}}}` reaches depth 5 (root,
// properties, a, properties, b). With MAX_DEPTH=32 this corresponds to roughly
// 16 levels of real schema nesting.
export const crawlSchema = (obj, maxDepth = MAX_DEPTH, options = {}) => {
const result = {
depth: 0,
depthExceeded: false,
timedOut: false,
errors: [],
refs: [],
};
if (typeof obj !== "object" || obj === null) return result;
const deadline = options.deadline;
// Injectable monotonic clock (defaults to the real wall clock). Reading the
// clock through this indirection lets tests drive the deadline branches
// deterministically (the same pattern as options.memoryUsage below).
const now = typeof options.now === "function" ? options.now : Date.now;
const denylist = resolveDangerousNames(options.lang);
const denySet = new Set(denylist);
const visited = new WeakSet();
visited.add(obj);
result.depth = 1;
const stack = [[obj, "", 1]];
// Defense in depth: total number of regex patterns ReDoS-analyzed so far.
// Shared across top-level `pattern` and patternProperties keys. Once it
// exceeds MAX_REDOS_PATTERNS, no further pattern is analyzed and a single
// fail-closed budget finding is emitted (see redosBudgetExceeded).
let redosPatternCount = 0;
let redosBudgetReported = false;
// One-time flag: have we already recorded the collected-refs truncation
// finding? (See MAX_COLLECTED_REFS in the $ref/$dynamicRef collection below.)
let refsTruncated = false;
// Pushes the timeout finding and flags the result as timed out. Used both at
// the top of the stack loop and before each individual ReDoS analysis (the
// per-pattern loops can run many isSafePattern() calls in one stack frame, so
// the once-per-pop check is not enough on adversarial input).
const timeoutBail = () => {
result.errors.push({
instancePath: "",
schemaPath: "#/timeout",
keyword: "timeout",
params: {},
message: "schema analysis exceeded time budget",
});
result.timedOut = true;
};
// True when a deadline is configured and has passed. The `> deadline` boundary
// is exclusive (a clock reading EXACTLY at the deadline does NOT bail), pinned by
// the injected-clock deadline tests in cli.crawl.test.js, which also kill the
// whole-condition ConditionalExpression mutant (expired clock bails, future clock
// does not). The `deadline != null` guard sits on its own line so ONLY its
// genuinely-equivalent mutant is disabled.
const deadlineConfigured = () =>
// Stryker disable next-line ConditionalExpression: forcing this `!= null` guard
// true is equivalent; when deadline is absent, now() > undefined is false anyway
// (deadlinePassed short-circuits the same way), so no input distinguishes it.
deadline != null;
const deadlinePassed = () => deadlineConfigured() && now() > deadline;
// Returns true (and emits one #/redos-budget finding the first time) when the
// total-pattern cap has been exceeded, so callers can skip further analysis.
// Marked incomplete:true so --ignore cannot suppress it (analysis stopped).
const redosBudgetExceeded = (path) => {
if (redosPatternCount <= MAX_REDOS_PATTERNS) return false;
if (!redosBudgetReported) {
redosBudgetReported = true;
result.errors.push({
instancePath: path,
schemaPath: "#/redos-budget",
keyword: "pattern",
params: { limit: MAX_REDOS_PATTERNS, incomplete: true },
message: `refusing to ReDoS-analyze more than ${MAX_REDOS_PATTERNS} patterns; remaining patterns not analyzed`,
});
}
return true;
};
// HEAP CIRCUIT BREAKER (primary memory bound). Reads live heap usage before
// each pattern; once it has grown beyond redosHeapBudgetBytes above the
// baseline captured at the first pattern, analysis stops and one fail-closed
// finding is emitted. Marked incomplete:true so --ignore cannot suppress it.
// Injectable: options.memoryUsage / options.redosHeapBudgetBytes for tests.
const memoryUsage =
typeof options.memoryUsage === "function"
? options.memoryUsage
: () => process.memoryUsage().heapUsed;
const redosHeapBudgetBytes =
// Stryker disable next-line ConditionalExpression: when absent the default
// const is used; any test exercising the override passes it explicitly.
options.redosHeapBudgetBytes != null
? options.redosHeapBudgetBytes
: REDOS_HEAP_BUDGET_BYTES;
let redosHeapBaseline = null;
let redosHeapReported = false;
// Returns true (and emits one #/redos-budget heap finding the first time) when
// the heap has grown more than the budget above the baseline. The first call
// captures the baseline (delta 0, never trips), so the breaker only fires once
// a real allocation has crossed the budget.
const redosHeapExceeded = (path) => {
const current = memoryUsage();
if (redosHeapBaseline === null) redosHeapBaseline = current;
if (current - redosHeapBaseline <= redosHeapBudgetBytes) return false;
if (!redosHeapReported) {
redosHeapReported = true;
result.errors.push({
instancePath: path,
schemaPath: "#/redos-budget",
keyword: "heap",
params: { budget: redosHeapBudgetBytes, incomplete: true },
message: `ReDoS analysis heap budget of ${redosHeapBudgetBytes} bytes exceeded; remaining patterns not analyzed`,
});
}
return true;
};
while (stack.length > 0) {
if (deadlinePassed()) {
timeoutBail();
return result;
}
const [current, path, currentDepth] = stack.pop();
const currentType = current.type;
const isType = (t) =>
currentType === t ||
(Array.isArray(currentType) && currentType.includes(t));
if (
isType("string") &&
Object.hasOwn(current, "minLength") &&
Object.hasOwn(current, "maxLength") &&
current.minLength > current.maxLength
) {
result.errors.push({
instancePath: path,
schemaPath: "#/minLength",
keyword: "minLength",
params: {
minLength: current.minLength,
maxLength: current.maxLength,
},
message: "minLength must be less than or equal to maxLength",
});
}
if (isType("integer") || isType("number")) {
const rangeError = checkNumericRange(current, path);
if (rangeError) result.errors.push(rangeError);
}
if (
isType("array") &&
Object.hasOwn(current, "minItems") &&
Object.hasOwn(current, "maxItems") &&
current.minItems > current.maxItems
) {
result.errors.push({
instancePath: path,
schemaPath: "#/minItems",
keyword: "minItems",
params: {
minItems: current.minItems,
maxItems: current.maxItems,
},
message: "minItems must be less than or equal to maxItems",
});
}
if (
isType("array") &&
Object.hasOwn(current, "minContains") &&
Object.hasOwn(current, "maxContains") &&
current.minContains > current.maxContains
) {
result.errors.push({
instancePath: path,
schemaPath: "#/minContains",
keyword: "minContains",
params: {
minContains: current.minContains,
maxContains: current.maxContains,
},
message: "minContains must be less than or equal to maxContains",
});
}
if (
isType("object") &&
Object.hasOwn(current, "minProperties") &&
Object.hasOwn(current, "maxProperties") &&
current.minProperties > current.maxProperties
) {
result.errors.push({
instancePath: path,
schemaPath: "#/minProperties",
keyword: "minProperties",
params: {
minProperties: current.minProperties,
maxProperties: current.maxProperties,
},
message: "minProperties must be less than or equal to maxProperties",
});
}
if (
Object.hasOwn(current, "pattern") &&
typeof current.pattern === "string"
) {
// Check the deadline BEFORE the (potentially expensive) analysis: the
// once-per-pop check above is not enough when one stack frame holds many
// patterns. Bail to the timeout path on an expired deadline. Exercised
// deterministically by an injected clock that is under-deadline at the
// once-per-pop check and over it here (see cli.crawl.test.js).
if (deadlinePassed()) {
timeoutBail();
return result;
}
redosPatternCount++;
// Skip analysis (of this and every later pattern) once a backstop trips:
// the total-pattern cap or the heap circuit breaker (primary memory bound).
if (
!redosBudgetExceeded(`${path}/pattern`) &&
!redosHeapExceeded(`${path}/pattern`)
) {
try {
// The timeout bounds analysis TIME; the heap breaker above bounds
// MEMORY. No maxSteps: it would fail-close legitimate safe patterns.
// Stryker disable next-line ObjectLiteral: the timeout option bounds
// analysis TIME only; for any pattern fast enough for a test the
// safe/unsafe verdict is identical with or without it, so dropping it
// (-> {}) is an equivalent (timing-only) mutant.
const patternResult = isSafePattern(current.pattern, {
timeout: REDOS_TIMEOUT_MS,
});
if (!patternResult.safe) {
// Stryker disable next-line LogicalOperator,StringLiteral: redos-detector
// always reports error:"hitMaxScore" for these, so the ?? fallback is
// defensive dead-weight here.
const reason = patternResult.error ?? "hitMaxScore";
// timedOut/hitMaxSteps reasons only arise on a real library timeout,
// which cannot be triggered deterministically in a fast test.
// Stryker disable ConditionalExpression,StringLiteral
const message =
reason === "timedOut"
? `pattern analysis timed out after ${REDOS_TIMEOUT_MS}ms (fail-closed as ReDoS)`
: reason === "hitMaxSteps"
? "pattern analysis exceeded step limit (fail-closed as ReDoS)"
: "pattern is vulnerable to ReDoS";
// Stryker restore ConditionalExpression,StringLiteral
result.errors.push({
instancePath: `${path}/pattern`,
schemaPath: "#/redos",
keyword: "pattern",
params: { pattern: current.pattern, reason },
message,
});
}
} catch {
result.errors.push({
instancePath: `${path}/pattern`,
schemaPath: "#/redos",
keyword: "pattern",
params: { pattern: current.pattern, reason: "parseError" },
message: "pattern could not be parsed for ReDoS analysis",
});
}
}
}
// Stryker disable next-line ConditionalExpression,EqualityOperator: this only
// skips the dangerous-name loops when the denylist is empty; entering with an
// empty denySet matches nothing, so it is a pure (equivalent) optimization.
if (denylist.length > 0) {
for (const siteKey of [
"properties",
"$defs",
"definitions",
"dependentSchemas",
"dependentRequired",
]) {
const site = current[siteKey];
if (typeof site === "object" && site !== null && !Array.isArray(site)) {
for (const name of Object.keys(site)) {
if (denySet.has(name)) {
result.errors.push({
instancePath: `${path}/${siteKey}/${escapeJsonPointer(name)}`,
schemaPath: "#/dangerous-name",
keyword: siteKey,
params: { name, lang: options.lang ?? DEFAULT_LANG },
message: `${siteKey} key "${name}" is a deserialization vector for lang="${options.lang ?? DEFAULT_LANG}"`,
});
}
}
}
}
if (Array.isArray(current.required)) {
for (const [i, name] of current.required.entries()) {
// Stryker disable next-line ConditionalExpression: denySet only holds
// strings, so denySet.has(non-string) is already false.
if (typeof name === "string" && denySet.has(name)) {
result.errors.push({
instancePath: `${path}/required/${i}`,
schemaPath: "#/dangerous-name",
keyword: "required",
params: { name, lang: options.lang ?? DEFAULT_LANG },
message: `required entry "${name}" is a deserialization vector for lang="${options.lang ?? DEFAULT_LANG}"`,
});
}
}
}
if (
typeof current.dependentRequired === "object" &&
current.dependentRequired !== null &&
!Array.isArray(current.dependentRequired)
) {
for (const [trigger, deps] of Object.entries(
current.dependentRequired,
)) {
// Stryker disable next-line ConditionalExpression: a non-array deps has
// no length, so the loop below simply never runs.
if (Array.isArray(deps)) {
for (const [i, name] of deps.entries()) {
// Stryker disable next-line ConditionalExpression,LogicalOperator: denySet
// only holds strings, so has(non-string) is already false.
if (typeof name === "string" && denySet.has(name)) {
result.errors.push({
instancePath: `${path}/dependentRequired/${escapeJsonPointer(trigger)}/${i}`,
schemaPath: "#/dangerous-name",
keyword: "dependentRequired",
params: { name, lang: options.lang ?? DEFAULT_LANG },
message: `dependentRequired entry "${name}" is a deserialization vector for lang="${options.lang ?? DEFAULT_LANG}"`,
});
}
}
}
}
}
}
// ReDoS scanning of patternProperties keys is independent of the
// dangerous-name denylist, so it runs unconditionally; the dangerous-name
// match below self-gates (filtering an empty denylist yields no matches).
if (
typeof current.patternProperties === "object" &&
current.patternProperties !== null &&
!Array.isArray(current.patternProperties)
) {
for (const patternKey of Object.keys(current.patternProperties)) {
const keyPath = `${path}/patternProperties/${escapeJsonPointer(patternKey)}`;
// Check the deadline before each key: a single object can carry many
// patternProperties keys, all analyzed in ONE stack frame, so the
// once-per-pop check above never fires between them. Exercised with an
// injected clock that crosses the deadline before a later key (see
// cli.crawl.test.js).
if (deadlinePassed()) {
timeoutBail();
return result;
}
redosPatternCount++;
// Stop analyzing further patterns once a backstop trips: the
// total-pattern cap or the heap circuit breaker (primary memory bound).
if (redosBudgetExceeded(keyPath) || redosHeapExceeded(keyPath)) break;
let patternSafe = true;
try {
// The timeout bounds analysis TIME; the heap breaker above bounds
// MEMORY. No maxSteps: it would fail-close legitimate safe patterns.
// Stryker disable next-line ObjectLiteral: the timeout option bounds
// analysis TIME only; for any key fast enough for a test the verdict
// is identical with or without it, so dropping it is timing-equivalent.
const patternResult = isSafePattern(patternKey, {
timeout: REDOS_TIMEOUT_MS,
});
if (!patternResult.safe) {
patternSafe = false;
result.errors.push({
instancePath: keyPath,
schemaPath: "#/redos",
keyword: "patternProperties",
params: {
pattern: patternKey,
// Stryker disable next-line LogicalOperator,StringLiteral: redos-detector
// always reports error:"hitMaxScore"; the ?? fallback is dead-weight.
reason: patternResult.error ?? "hitMaxScore",
},
message: `patternProperties key "${patternKey}" is vulnerable to ReDoS`,
});
}
} catch {}
if (!patternSafe) continue;
try {
// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp
const re = new RegExp(patternKey);
const matches = denylist.filter((n) => re.test(n));
if (matches.length > 0) {
result.errors.push({
instancePath: keyPath,
schemaPath: "#/dangerous-name",
keyword: "patternProperties",
params: {
pattern: patternKey,
matches,
lang: options.lang ?? DEFAULT_LANG,
},
message: `patternProperties key "${patternKey}" matches deserialization vector(s) for lang="${options.lang ?? DEFAULT_LANG}": ${matches.join(", ")}`,
});
}
} catch {
// unparseable regex; meta-schema safePattern rejects it
}
}
}
// Collect remote $ref and $dynamicRef (2020-12) URLs as SSRF fetch targets.
// $id is deliberately NOT collected: it declares a base URI identifier, not
// a fetch target, and the -r/--ref-schema-files flag uses $id hostnames as
// the SAFE list, so flagging $id would self-flag the user's own schema.
for (const refKey of ["$ref", "$dynamicRef"]) {
const refValue = current[refKey];
if (
Object.hasOwn(current, refKey) &&
typeof refValue === "string" &&
!refValue.startsWith("#")
) {
try {
const url = new URL(refValue);
if (url.hostname) {
// Backstop: stop buffering once the collected-refs cap is reached,
// recording one truncation finding. Without this, a schema with a
// huge number of refs could accumulate an unbounded array before
// the later distinct-hostname cap ever applies.
if (result.refs.length >= MAX_COLLECTED_REFS) {
if (!refsTruncated) {
refsTruncated = true;
result.errors.push({
instancePath: `${path}/${refKey}`,
schemaPath: "#/refs-truncated",
keyword: "$ref",
params: { limit: MAX_COLLECTED_REFS, incomplete: true },
message: `more than ${MAX_COLLECTED_REFS} remote $ref(s); remaining refs not collected for SSRF analysis`,
});
}
} else {
result.refs.push({
hostname: url.hostname,
ref: refValue,
path: `${path}/${refKey}`,
});
}
}
} catch {
// not a valid URL, skip
}
}
}
for (const key in current) {
if (Object.hasOwn(current, key) && !INSTANCE_DATA_KEYS.has(key)) {
const value = current[key];
if (
typeof value === "object" &&
value !== null &&
!visited.has(value)
) {
visited.add(value);
const newDepth = currentDepth + 1;
// Stryker disable next-line ConditionalExpression,EqualityOperator: this only
// tracks the max depth seen; > vs >= and always-assign reach the same maximum.
if (newDepth > result.depth) result.depth = newDepth;
if (result.depth > maxDepth) {
result.depthExceeded = true;
return result;
}
stack.push([value, `${path}/${escapeJsonPointer(key)}`, newDepth]);
}
}
}
}
return result;
};
// RFC 1918 + loopback + link-local + CGN + TEST-NETs + multicast + reserved.
// IPv6 covered: :: and ::1, unique-local fc00::/7, link-local fe80::/10 and
// site-local fec0::/10 (combined fe80-feff), multicast ff00::/8, IPv4-mapped
// ::ffff:0:0/96, NAT64 64:ff9b::/96, 6to4 2002::/16, and documentation
// 2001:db8::/32. NAT64/6to4/IPv4-mapped recurse on their embedded IPv4.
// Used to block $ref URLs whose hostname resolves to an internal/private IP.
// Fail-closed: malformed IPv6 (e.g. invalid hex groups, wrong group count) is
// treated as private (returns true) so it is blocked rather than allowed
// through as a forged public address. Tests in cli.ip.test.js pin the
// boundary cases.
export const isPrivateIP = (ip) => {
const parts = ip.split(".").map(Number);
if (
parts.length === 4 &&
parts.every((p) => Number.isInteger(p) && p >= 0 && p <= 255)
) {
const [a, b] = parts;
if (a === 0) return true; // 0.0.0.0/8 "this" network
if (a === 10) return true; // 10.0.0.0/8 private
if (a === 127) return true; // 127.0.0.0/8 loopback
if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 CGN
if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local
if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 private
if (a === 192 && b === 0 && parts[2] === 0) return true; // 192.0.0.0/24 IETF
if (a === 192 && b === 0 && parts[2] === 2) return true; // 192.0.2.0/24 TEST-NET-1
if (a === 192 && b === 168) return true; // 192.168.0.0/16 private
if (a === 198 && (b === 18 || b === 19)) return true; // 198.18.0.0/15 benchmark
if (a === 198 && b === 51 && parts[2] === 100) return true; // 198.51.100.0/24 TEST-NET-2
if (a === 203 && b === 0 && parts[2] === 113) return true; // 203.0.113.0/24 TEST-NET-3
// Stryker disable next-line ConditionalExpression: octets are validated to
// 0-255 and 240-255 is already private via the next line, so the `a <= 239`
// bound is redundant; dropping it is an equivalent mutant (no input changes).
if (a >= 224 && a <= 239) return true; // 224.0.0.0/4 multicast
if (a >= 240) return true; // 240.0.0.0/4 reserved + 255.255.255.255 broadcast
}
// Normalize IPv6: expand :: and remove leading zeros for consistent matching
const lower = ip.toLowerCase();
if (lower.includes(":")) {
// Strip IPv6 zone ID (e.g. %eth0) before further parsing
const zoneIdx = lower.indexOf("%");
const addr = zoneIdx !== -1 ? lower.slice(0, zoneIdx) : lower;
// Handle IPv4-mapped forms with dotted notation (e.g. ::ffff:127.0.0.1)
// before general expansion since the dotted part counts as 2 groups
const lastColon = addr.lastIndexOf(":");
const tail = addr.slice(lastColon + 1);
if (tail.includes(".")) {
// Recursively check the IPv4 portion
return isPrivateIP(tail);
}
// Expand :: notation to full 8-group form
let groups;
if (addr.includes("::")) {
const [left, right] = addr.split("::");
const leftGroups = left ? left.split(":") : [];
const rightGroups = right ? right.split(":") : [];
const missing = 8 - leftGroups.length - rightGroups.length;
groups = [...leftGroups, ...Array(missing).fill("0"), ...rightGroups].map(
(g) => g.replace(/^0+(?=.)/, ""),
);
} else {
groups = addr.split(":").map((g) => g.replace(/^0+(?=.)/, ""));
}
if (groups.length === 8) {
const normalized = groups.join(":");
if (normalized === "0:0:0:0:0:0:0:0" || normalized === "0:0:0:0:0:0:0:1")
return true;
// Decode two normalized hex groups into a dotted IPv4 and recurse.
// Fail-closed: invalid hex parses as NaN, and NaN bit-math would forge a
// public-looking IPv4. Block (return true) instead.
const embeddedIPv4Private = (hiGroup, loGroup) => {
const hi = Number.parseInt(hiGroup, 16);
const lo = Number.parseInt(loGroup, 16);
if (Number.isNaN(hi) || Number.isNaN(lo)) return true;
return isPrivateIP(`${hi >> 8}.${hi & 0xff}.${lo >> 8}.${lo & 0xff}`);
};
if (groups[0].startsWith("fc") || groups[0].startsWith("fd")) return true; // unique local fc00::/7
if (groups[0].startsWith("ff")) return true; // multicast ff00::/8
// First-group numeric ranges. Fail-closed on NaN (malformed hex) and on
// values > 0xffff (an over-long group such as "fe800" is malformed IPv6).
const g0 = Number.parseInt(groups[0], 16);
// Stryker disable next-line EqualityOperator: 0xffff (and above) starts with
// "ff" and is already returned by the multicast check, so the boundary value
// is unreachable here; `>` vs `>=` is an equivalent mutant.
if (Number.isNaN(g0) || g0 > 0xffff) return true;
// fe80-feff covers link-local fe80::/10 (fe80-febf) and site-local
// fec0::/10 (fec0-feff); the old check only matched the literal "fe80".
// Stryker disable next-line ConditionalExpression,EqualityOperator: the "ff"
// startsWith and `g0 > 0xffff` returns above already exclude every g0 above
// 0xfeff, so the upper-bound conjunct is always true here; dropping or
// loosening it is an equivalent mutant (no reachable input changes).
if (g0 >= 0xfe80 && g0 <= 0xfeff) return true;
// 2002::/16 6to4: embedded IPv4 sits in groups 1 and 2.
if (groups[0] === "2002")
return embeddedIPv4Private(groups[1], groups[2]);
// 2001:db8::/32 documentation (the IPv6 analog of the IPv4 TEST-NETs).
if (groups[0] === "2001" && groups[1] === "db8") return true;
// 64:ff9b::/96 NAT64 well-known prefix (RFC 6052): normalized form is
// 64:ff9b:0:0:0:0:X:Y with the IPv4 embedded in the last two groups.