-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultValidator.java
More file actions
535 lines (484 loc) · 18.4 KB
/
Copy pathDefaultValidator.java
File metadata and controls
535 lines (484 loc) · 18.4 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
package com.retailsvc.http.validate;
import com.retailsvc.http.ValidationException;
import com.retailsvc.http.spec.schema.AdditionalProperties;
import com.retailsvc.http.spec.schema.AllOfSchema;
import com.retailsvc.http.spec.schema.AlwaysSchema;
import com.retailsvc.http.spec.schema.AnyOfSchema;
import com.retailsvc.http.spec.schema.ArraySchema;
import com.retailsvc.http.spec.schema.BooleanSchema;
import com.retailsvc.http.spec.schema.ConstSchema;
import com.retailsvc.http.spec.schema.EnumSchema;
import com.retailsvc.http.spec.schema.IntegerSchema;
import com.retailsvc.http.spec.schema.NeverSchema;
import com.retailsvc.http.spec.schema.NotSchema;
import com.retailsvc.http.spec.schema.NullSchema;
import com.retailsvc.http.spec.schema.NumberSchema;
import com.retailsvc.http.spec.schema.ObjectSchema;
import com.retailsvc.http.spec.schema.OneOfSchema;
import com.retailsvc.http.spec.schema.RefSchema;
import com.retailsvc.http.spec.schema.Schema;
import com.retailsvc.http.spec.schema.StringSchema;
import com.retailsvc.http.spec.schema.TypeName;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.DoublePredicate;
import java.util.function.Function;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public final class DefaultValidator implements Validator {
private static final String FORMAT_KEYWORD = "format";
private record FormatCheck(Predicate<String> isValid, String message) {}
private record IntegerFormatCheck(LongPredicate isValid, String message) {}
private record NumberFormatCheck(DoublePredicate isValid, String message) {}
private static final Pattern EMAIL = Pattern.compile("^[^\\s@]++@[^\\s@.]++\\.[^\\s@]++$");
private static final Pattern HOSTNAME =
Pattern.compile(
"^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?"
+ "(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*+$");
private static final Map<String, FormatCheck> FORMAT_CHECKS =
Map.ofEntries(
Map.entry("uuid", new FormatCheck(DefaultValidator::isUuid, "not a valid uuid")),
Map.entry("date", new FormatCheck(DefaultValidator::isDate, "not a valid date")),
Map.entry(
"date-time", new FormatCheck(DefaultValidator::isDateTime, "not a valid date-time")),
Map.entry("email", new FormatCheck(s -> EMAIL.matcher(s).matches(), "not a valid email")),
Map.entry("uri", new FormatCheck(DefaultValidator::isUri, "not a valid uri")),
Map.entry(
"uri-reference",
new FormatCheck(DefaultValidator::isUriReference, "not a valid uri-reference")),
Map.entry(
"hostname",
new FormatCheck(s -> HOSTNAME.matcher(s).matches(), "not a valid hostname")),
Map.entry("ipv4", new FormatCheck(DefaultValidator::isIpv4, "not a valid ipv4")),
Map.entry("ipv6", new FormatCheck(DefaultValidator::isIpv6, "not a valid ipv6")),
Map.entry("regex", new FormatCheck(DefaultValidator::isRegex, "not a valid regex")),
Map.entry("byte", new FormatCheck(DefaultValidator::isByte, "not valid base64")),
Map.entry("binary", new FormatCheck(s -> true, "not valid binary")),
Map.entry("password", new FormatCheck(s -> true, "not valid password")));
private static final Map<String, IntegerFormatCheck> INTEGER_FORMAT_CHECKS =
Map.of(
"int32",
new IntegerFormatCheck(
n -> n >= Integer.MIN_VALUE && n <= Integer.MAX_VALUE, "value does not fit in int32"),
"int64",
new IntegerFormatCheck(n -> true, "value does not fit in int64"));
private static final Map<String, NumberFormatCheck> NUMBER_FORMAT_CHECKS =
Map.of(
"float",
new NumberFormatCheck(
n -> !Double.isNaN(n) && !Double.isInfinite(n) && Math.abs(n) <= Float.MAX_VALUE,
"value does not fit in float"),
"double",
new NumberFormatCheck(n -> true, "value does not fit in double"));
private final Function<String, Schema> refResolver;
private final ConcurrentMap<String, Pattern> compiledPatterns = new ConcurrentHashMap<>();
public DefaultValidator(Function<String, Schema> refResolver) {
this.refResolver = refResolver;
}
@Override
public void validate(Object value, Schema schema, String pointer) {
if (value == null && schema.types().contains(TypeName.NULL)) {
return;
}
switch (schema) {
case RefSchema(String ref) -> validate(value, refResolver.apply(ref), pointer);
case BooleanSchema _ -> validateBoolean(value, pointer);
case NullSchema _ -> require(value == null, pointer, "type", "expected null");
case StringSchema s -> validateString(value, s, pointer);
case IntegerSchema i -> validateInteger(value, i, pointer);
case NumberSchema n -> validateNumber(value, n, pointer);
case ObjectSchema o -> validateObject(value, o, pointer);
case ArraySchema a -> validateArray(value, a, pointer);
case EnumSchema(List<Object> values) ->
require(values.contains(value), pointer, "enum", "value not in enum");
case ConstSchema(Object expected) ->
require(Objects.equals(expected, value), pointer, "const", "value does not equal const");
case AllOfSchema(List<Schema> parts) -> {
for (Schema p : parts) {
validate(value, p, pointer);
}
}
case AnyOfSchema(List<Schema> options) -> validateAnyOf(value, options, pointer);
case OneOfSchema(List<Schema> options) -> validateOneOf(value, options, pointer);
case NotSchema(Schema inner) -> validateNot(value, inner, pointer);
case AlwaysSchema _ -> {
/* accepts any value, including null */
}
case NeverSchema _ -> fail(pointer, "false", "schema rejects all values", value);
}
}
private void validateBoolean(Object value, String pointer) {
require(value instanceof Boolean, pointer, "type", "expected boolean");
}
private void validateString(Object value, StringSchema s, String pointer) {
require(value instanceof String, pointer, "type", "expected string");
String str = (String) value;
if (s.minLength() != null && str.length() < s.minLength()) {
fail(pointer, "minLength", "string shorter than " + s.minLength(), str);
}
if (s.maxLength() != null && str.length() > s.maxLength()) {
fail(pointer, "maxLength", "string longer than " + s.maxLength(), str);
}
if (s.pattern() != null
&& !compiledPatterns
.computeIfAbsent(s.pattern(), Pattern::compile)
.matcher(str)
.matches()) {
fail(pointer, "pattern", "does not match pattern " + s.pattern(), str);
}
if (s.enumValues() != null && !s.enumValues().contains(str)) {
fail(pointer, "enum", "value not in enum", str);
}
if (s.format() != null) {
validateStringFormat(str, s.format(), pointer);
}
}
private void validateStringFormat(String str, String format, String pointer) {
FormatCheck check = FORMAT_CHECKS.get(format);
if (check == null) {
return;
}
if (!check.isValid().test(str)) {
fail(pointer, FORMAT_KEYWORD, check.message(), str);
}
}
private void validateIntegerFormat(long n, String format, String pointer) {
IntegerFormatCheck check = INTEGER_FORMAT_CHECKS.get(format);
if (check == null) {
return;
}
if (!check.isValid().test(n)) {
fail(pointer, FORMAT_KEYWORD, check.message(), n);
}
}
private void validateNumberFormat(double n, String format, String pointer) {
NumberFormatCheck check = NUMBER_FORMAT_CHECKS.get(format);
if (check == null) {
return;
}
if (!check.isValid().test(n)) {
fail(pointer, FORMAT_KEYWORD, check.message(), n);
}
}
private static boolean isUuid(String s) {
try {
UUID.fromString(s);
return true;
} catch (IllegalArgumentException _) {
return false;
}
}
private static boolean isDate(String s) {
try {
LocalDate.parse(s);
return true;
} catch (DateTimeParseException _) {
return false;
}
}
private static boolean isDateTime(String s) {
try {
OffsetDateTime.parse(s);
return true;
} catch (DateTimeParseException _) {
return false;
}
}
private static boolean isUri(String s) {
try {
return new URI(s).isAbsolute();
} catch (URISyntaxException _) {
return false;
}
}
private static boolean isRegex(String s) {
try {
Pattern.compile(s);
return true;
} catch (PatternSyntaxException _) {
return false;
}
}
private static boolean isByte(String s) {
try {
Base64.getDecoder().decode(s);
return true;
} catch (IllegalArgumentException _) {
return false;
}
}
private static boolean isUriReference(String s) {
try {
new URI(s);
return true;
} catch (URISyntaxException _) {
return false;
}
}
private static final int IPV4_OCTET_COUNT = 4;
private static final int IPV4_OCTET_MAX_DIGITS = 3;
private static final int IPV4_OCTET_MAX_VALUE = 255;
private static final int DECIMAL_RADIX = 10;
private static final int IPV6_HEXTET_COUNT = 8;
private static final int IPV6_HEXTET_MAX_DIGITS = 4;
private static boolean isIpv4(String s) {
String[] parts = s.split("\\.", -1);
if (parts.length != IPV4_OCTET_COUNT) {
return false;
}
for (String part : parts) {
if (!isIpv4Octet(part)) {
return false;
}
}
return true;
}
private static boolean isIpv4Octet(String part) {
int len = part.length();
if (len == 0 || len > IPV4_OCTET_MAX_DIGITS) {
return false;
}
if (len > 1 && part.charAt(0) == '0') {
return false;
}
int n = 0;
for (int i = 0; i < len; i++) {
char c = part.charAt(i);
if (c < '0' || c > '9') {
return false;
}
n = n * DECIMAL_RADIX + (c - '0');
}
return n <= IPV4_OCTET_MAX_VALUE;
}
private static boolean isIpv6(String s) {
int doubleColon = s.indexOf("::");
if (doubleColon != s.lastIndexOf("::")) {
return false;
}
boolean compressed = doubleColon >= 0;
String[] left;
String[] right;
if (compressed) {
String l = s.substring(0, doubleColon);
String r = s.substring(doubleColon + 2);
left = l.isEmpty() ? new String[0] : l.split(":", -1);
right = r.isEmpty() ? new String[0] : r.split(":", -1);
} else {
left = s.split(":", -1);
right = new String[0];
}
int total = left.length + right.length;
if (compressed ? total > IPV6_HEXTET_COUNT - 1 : total != IPV6_HEXTET_COUNT) {
return false;
}
return allHextets(left) && allHextets(right);
}
private static boolean allHextets(String[] parts) {
for (String hextet : parts) {
if (!isHextet(hextet)) {
return false;
}
}
return true;
}
private static boolean isHextet(String hextet) {
int len = hextet.length();
if (len == 0 || len > IPV6_HEXTET_MAX_DIGITS) {
return false;
}
for (int i = 0; i < len; i++) {
char c = hextet.charAt(i);
boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
if (!hex) {
return false;
}
}
return true;
}
private void validateInteger(Object value, IntegerSchema s, String pointer) {
if (!(value instanceof Number num)) {
fail(pointer, "type", "expected integer", value);
return;
}
long n = num.longValue();
if (s.minimum() != null && n < s.minimum()) {
fail(pointer, "minimum", "integer below minimum " + s.minimum(), n);
}
if (s.maximum() != null && n > s.maximum()) {
fail(pointer, "maximum", "integer above maximum " + s.maximum(), n);
}
if (s.exclusiveMinimum() != null && n <= s.exclusiveMinimum()) {
fail(pointer, "exclusiveMinimum", "integer not greater than " + s.exclusiveMinimum(), n);
}
if (s.exclusiveMaximum() != null && n >= s.exclusiveMaximum()) {
fail(pointer, "exclusiveMaximum", "integer not less than " + s.exclusiveMaximum(), n);
}
if (s.multipleOf() != null && n % s.multipleOf() != 0) {
fail(pointer, "multipleOf", "not a multiple of " + s.multipleOf(), n);
}
if (s.format() != null) {
validateIntegerFormat(n, s.format(), pointer);
}
}
private void validateNumber(Object value, NumberSchema s, String pointer) {
if (!(value instanceof Number num)) {
fail(pointer, "type", "expected number", value);
return;
}
double n = num.doubleValue();
if (s.minimum() != null && n < s.minimum().doubleValue()) {
fail(pointer, "minimum", "number below minimum " + s.minimum(), n);
}
if (s.maximum() != null && n > s.maximum().doubleValue()) {
fail(pointer, "maximum", "number above maximum " + s.maximum(), n);
}
if (s.exclusiveMinimum() != null && n <= s.exclusiveMinimum().doubleValue()) {
fail(pointer, "exclusiveMinimum", "number not greater than " + s.exclusiveMinimum(), n);
}
if (s.exclusiveMaximum() != null && n >= s.exclusiveMaximum().doubleValue()) {
fail(pointer, "exclusiveMaximum", "number not less than " + s.exclusiveMaximum(), n);
}
if (s.multipleOf() != null && !isMultipleOf(n, s.multipleOf().doubleValue())) {
fail(pointer, "multipleOf", "not a multiple of " + s.multipleOf(), n);
}
if (s.format() != null) {
validateNumberFormat(n, s.format(), pointer);
}
}
/**
* Returns whether {@code value} is an exact multiple of {@code divisor}, using {@link BigDecimal}
* to avoid floating-point rounding artifacts that {@code (value / divisor) % 1 == 0} would
* produce (e.g., {@code 0.3 / 0.1} is not exactly {@code 3.0} as a double).
*/
private static boolean isMultipleOf(double value, double divisor) {
BigDecimal v = BigDecimal.valueOf(value);
BigDecimal d = BigDecimal.valueOf(divisor);
return v.remainder(d).compareTo(BigDecimal.ZERO) == 0;
}
@SuppressWarnings("unchecked")
private void validateObject(Object value, ObjectSchema s, String pointer) {
require(value instanceof Map, pointer, "type", "expected object");
Map<String, Object> map = (Map<String, Object>) value;
for (String required : s.required()) {
require(
map.containsKey(required),
pointer + "/" + required,
"required",
"required property missing");
}
if (s.minProperties() != null && map.size() < s.minProperties()) {
fail(pointer, "minProperties", "fewer than " + s.minProperties() + " properties", map.size());
}
if (s.maxProperties() != null && map.size() > s.maxProperties()) {
fail(pointer, "maxProperties", "more than " + s.maxProperties() + " properties", map.size());
}
for (var entry : map.entrySet()) {
String childPointer = pointer + "/" + entry.getKey();
Schema propSchema = s.properties().get(entry.getKey());
if (propSchema != null) {
validate(entry.getValue(), propSchema, childPointer);
} else {
switch (s.additionalProperties()) {
case AdditionalProperties.Allowed _ -> {
/* no-op: additional properties are permitted by default */
}
case AdditionalProperties.Forbidden _ ->
fail(
childPointer,
"additionalProperties",
"additional property not allowed",
entry.getKey());
case AdditionalProperties.SchemaConstraint(Schema constraint) ->
validate(entry.getValue(), constraint, childPointer);
}
}
}
}
private void validateArray(Object value, ArraySchema s, String pointer) {
require(value instanceof Iterable, pointer, "type", "expected array");
Iterable<?> it = (Iterable<?>) value;
List<Object> elements = new ArrayList<>();
for (Object o : it) {
elements.add(o);
}
if (s.minItems() != null && elements.size() < s.minItems()) {
fail(pointer, "minItems", "fewer than " + s.minItems() + " items", elements.size());
}
if (s.maxItems() != null && elements.size() > s.maxItems()) {
fail(pointer, "maxItems", "more than " + s.maxItems() + " items", elements.size());
}
if (s.uniqueItems()) {
Set<Object> seen = new HashSet<>();
for (Object e : elements) {
if (!seen.add(e)) {
fail(pointer, "uniqueItems", "duplicate item", e);
}
}
}
for (int i = 0; i < elements.size(); i++) {
validate(elements.get(i), s.items(), pointer + "/" + i);
}
}
private static void fail(String pointer, String keyword, String message, Object rejectedValue) {
throw new ValidationException(new ValidationError(pointer, keyword, message, rejectedValue));
}
static void require(boolean condition, String pointer, String keyword, String message) {
if (!condition) {
throw new ValidationException(new ValidationError(pointer, keyword, message, null));
}
}
private void validateAnyOf(Object value, List<Schema> options, String pointer) {
for (Schema o : options) {
try {
validate(value, o, pointer);
return;
} catch (ValidationException ignored) {
// try next branch
}
}
fail(pointer, "anyOf", "did not match any anyOf branch", value);
}
private void validateOneOf(Object value, List<Schema> options, String pointer) {
int matched = 0;
for (Schema o : options) {
try {
validate(value, o, pointer);
matched++;
} catch (ValidationException ignored) {
// branch did not match; continue
}
}
if (matched != 1) {
fail(
pointer,
"oneOf",
"matched " + matched + " of " + options.size() + " oneOf branches",
value);
}
}
private void validateNot(Object value, Schema inner, String pointer) {
try {
validate(value, inner, pointer);
} catch (ValidationException expected) {
return;
}
fail(pointer, "not", "value matched 'not' schema", value);
}
}