/
LegacyValidator.java
562 lines (477 loc) · 22.1 KB
/
LegacyValidator.java
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
/*
* Copyright (c) 2010-2018 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.common.validator;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import com.evolveum.midpoint.prism.PrismParserNoIO;
import com.evolveum.midpoint.util.QNameUtil;
import org.apache.commons.lang.StringUtils;
import org.codehaus.staxmate.dom.DOMConverter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import com.evolveum.midpoint.prism.Objectable;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
/**
* Class to validate (and possible transform) large sets of objects.
*
* LEGACY: This is all very old code. And it is XML-only. It will be probably
* thrown away and re-written in a more reasonable way.
*
* @author Radovan Semancik
*
*/
public class LegacyValidator {
private static final Trace LOGGER = TraceManager.getTrace(LegacyValidator.class);
private static final String INPUT_STREAM_CHARSET = "utf-8";
private static final String OPERATION_PREFIX = LegacyValidator.class.getName() + ".";
private static final String OPERATION_RESOURCE_NAMESPACE_CHECK = OPERATION_PREFIX + "resourceNamespaceCheck";
private static final String OPERATION_RESOURCE_BASICS_CHECK = OPERATION_PREFIX + "objectBasicsCheck";
private static final String START_LINE_NUMBER = "startLineNumber";
private static final String END_LINE_NUMBER = "endLineNumber";
private boolean verbose = false;
private boolean validateSchemas = true;
private boolean validateName = true;
private boolean allowAnyType = false;
private EventHandler handler;
private PrismContext prismContext;
private Schema midPointJavaxSchema;
private javax.xml.validation.Validator xsdValidator;
private long progress = 0;
private long errors = 0;
private long stopAfterErrors = 0;
private boolean compatMode = false;
public LegacyValidator(PrismContext prismContext) {
this.prismContext = prismContext;
this.handler = null;
initialize();
}
public LegacyValidator(PrismContext prismContext, EventHandler handler) {
this.prismContext = prismContext;
this.handler = handler;
initialize();
}
private void initialize() {
if (prismContext == null) {
throw new IllegalStateException("No prism context set during validator initialization");
}
SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry();
midPointJavaxSchema = schemaRegistry.getJavaxSchema();
xsdValidator = midPointJavaxSchema.newValidator();
xsdValidator.setResourceResolver(prismContext.getEntityResolver());
}
public EventHandler getHandler() {
return handler;
}
public void setHandler(EventHandler handler) {
this.handler = handler;
}
public PrismContext getPrismContext() {
return prismContext;
}
public boolean getVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public void setValidateSchema(boolean validateSchemas) {
this.validateSchemas = validateSchemas;
}
public boolean getValidateSchema() {
return validateSchemas;
}
public boolean isValidateName() {
return validateName;
}
public void setValidateName(boolean validateName) {
this.validateName = validateName;
}
public void setAllowAnyType(boolean allowAnyType) {
this.allowAnyType = allowAnyType;
}
public boolean getAllowAnyType() {
return allowAnyType;
}
public long getStopAfterErrors() {
return stopAfterErrors;
}
public void setStopAfterErrors(long stopAfterErrors) {
this.stopAfterErrors = stopAfterErrors;
}
public long getProgress() {
return progress;
}
public long getErrors() {
return errors;
}
public boolean isCompatMode() {
return compatMode;
}
public void setCompatMode(boolean compatMode) {
this.compatMode = compatMode;
}
public void validate(String lexicalRepresentation, OperationResult validationResult, String objectResultOperationName) {
try {
try (ByteArrayInputStream is = new ByteArrayInputStream(lexicalRepresentation.getBytes(INPUT_STREAM_CHARSET))) {
validate(is, validationResult, objectResultOperationName);
}
} catch (IOException e) {
throw new SystemException(e); // shouldn't really occur
}
}
public void validate(InputStream inputStream, OperationResult validatorResult, String objectResultOperationName) {
DOMConverter domConverter = new DOMConverter();
XMLStreamReader stream;
try {
Map<String, String> rootNamespaceDeclarations = new HashMap<>();
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
stream = xmlInputFactory.createXMLStreamReader(inputStream);
int eventType = stream.nextTag();
if (eventType == XMLStreamConstants.DTD || eventType == XMLStreamConstants.ENTITY_DECLARATION
|| eventType == XMLStreamConstants.ENTITY_REFERENCE || eventType == XMLStreamConstants.NOTATION_DECLARATION) {
// We do not want those, e.g. we want to void XXE vulnerabilities. Make this check explicit.
throw new SystemException("Use of "+eventType+" in XML is prohibited");
}
if (eventType == XMLStreamConstants.START_ELEMENT) {
if (!QNameUtil.match(stream.getName(), SchemaConstants.C_OBJECTS)) {
// This has to be an import file with a single objects. Try
// to process it.
OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
progress++;
objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);
EventResult cont;
try {
cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations, validatorResult, domConverter);
} catch (RuntimeException e) {
// Make sure that unexpected error is recorded.
objectResult.recordFatalError(e);
throw e;
}
if (!cont.isCont()) {
String message;
if (cont.getReason() != null) {
message = cont.getReason();
} else {
message = "Object validation failed (no reason given)";
}
if (objectResult.isUnknown()) {
objectResult.recordFatalError(message);
}
validatorResult.recordFatalError(message);
return;
}
// return to avoid processing objects in loop
validatorResult.computeStatus("Validation failed", "Validation warnings");
return;
}
// Extract root namespace declarations
for (int i = 0; i < stream.getNamespaceCount(); i++) {
rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
}
} else {
throw new SystemException("StAX Malfunction?");
}
while (stream.hasNext()) {
eventType = stream.next();
if (eventType == XMLStreamConstants.START_ELEMENT) {
OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
progress++;
objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);
EventResult cont;
try {
// Read and validate individual object from the stream
cont = readFromStreamAndValidate(stream, objectResult,
rootNamespaceDeclarations, validatorResult, domConverter);
} catch (RuntimeException e) {
if (objectResult.isUnknown()) {
// Make sure that unexpected error is recorded.
objectResult.recordFatalError(e);
}
throw e;
}
if (objectResult.isError()) {
errors++;
}
objectResult.cleanupResult();
validatorResult.summarize();
if (cont.isStop()) {
if (cont.getReason() != null) {
validatorResult.recordFatalError("Processing has been stopped: "
+ cont.getReason());
} else {
validatorResult.recordFatalError("Processing has been stopped");
}
// This means total stop, no other objects will be
// processed
return;
}
if (!cont.isCont()) {
if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
if (errors == 1) {
validatorResult.recordFatalError("Stopping on error; " + (progress - errors) + " passed");
} else {
validatorResult.recordFatalError("Too many errors (" + errors + "); " + (progress - errors) + " passed");
}
return;
}
}
}
}
} catch (XMLStreamException ex) {
// validatorResult.recordFatalError("XML parsing error: " +
// ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
if (handler != null) {
handler.handleGlobalError(validatorResult);
}
return;
}
// Error count is sufficient. Detailed messages are in subresults
validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");
}
private EventResult readFromStreamAndValidate(XMLStreamReader stream, OperationResult objectResult,
Map<String, String> rootNamespaceDeclarations, OperationResult validatorResult,
DOMConverter domConverter) {
objectResult.addContext(START_LINE_NUMBER, stream.getLocation().getLineNumber());
Document objectDoc;
try {
// Parse the object from stream to DOM
objectDoc = domConverter.buildDocument(stream);
} catch (XMLStreamException ex) {
validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
if (handler != null) {
handler.handleGlobalError(validatorResult);
}
objectResult.recordFatalError(ex);
return EventResult.skipObject(ex.getMessage());
}
objectResult.addContext(END_LINE_NUMBER, stream.getLocation().getLineNumber());
// This element may not have complete namespace definitions for a
// stand-alone
// processing, therefore copy namespace definitions from the root
// element
Element objectElement = DOMUtil.getFirstChildElement(objectDoc);
DOMUtil.setNamespaceDeclarations(objectElement, rootNamespaceDeclarations);
return validateObjectInternal(objectElement, objectResult, validatorResult);
}
public EventResult validateObject(String stringXml, OperationResult objectResult) {
Document objectDoc = DOMUtil.parseDocument(stringXml);
Element objectElement = DOMUtil.getFirstChildElement(objectDoc);
return validateObjectInternal(objectElement, objectResult, objectResult);
}
public EventResult validateObject(Element objectElement, OperationResult objectResult) {
return validateObjectInternal(objectElement, objectResult, objectResult);
}
private EventResult validateObjectInternal(Element objectElement, OperationResult objectResult, OperationResult validatorResult) {
try {
Node postValidationTree = null;
if (validateSchemas) {
postValidationTree = validateSchema(objectElement, objectResult);
if (postValidationTree == null) {
// There was an error
return EventResult.skipObject(objectResult.getMessage());
}
}
if (handler != null) {
EventResult cont;
try {
cont = handler.preMarshall(objectElement, postValidationTree, objectResult);
} catch (RuntimeException e) {
objectResult.recordFatalError("Internal error: preMarshall call failed: "+e.getMessage(), e);
throw e;
}
if (!cont.isCont()) {
if (objectResult.isUnknown()) {
objectResult.recordFatalError("Stopped after preMarshall, no reason given");
}
return cont;
}
}
if (!objectResult.isAcceptable()) {
// Schema validation or preMarshall has failed. No point to
// continue with this object.
if (objectResult.isUnknown()) {
objectResult.recordFatalError("Result not acceptable after preMarshall, no reason given");
}
return EventResult.skipObject();
}
PrismParserNoIO parser = prismContext.parserFor(objectElement);
if (compatMode) {
parser = parser.compat();
}
PrismObject<? extends Objectable> object = parser.parse();
try {
object.checkConsistence();
} catch (RuntimeException e) {
objectResult.recordFatalError("Internal object inconsistence, probably a parser bug: "+e.getMessage(), e);
return EventResult.skipObject(e.getMessage());
}
Objectable objectType = object.asObjectable();
objectResult.addContext(OperationResult.CONTEXT_OBJECT, object.toString());
if (verbose) {
LOGGER.trace("Processing OID {}", objectType.getOid());
}
validateObject(objectType, objectResult);
if (handler != null) {
EventResult cont;
try {
cont = handler.postMarshall(object, objectElement, objectResult);
} catch (RuntimeException e) {
// Make sure that unhandled exceptions are recorded in object result before they are rethrown
objectResult.recordFatalError("Internal error: postMarshall call failed: "+e.getMessage(), e);
throw e;
}
if (!cont.isCont()) {
if (objectResult.isUnknown()) {
objectResult.recordFatalError("Stopped after postMarshall, no reason given");
}
return cont;
}
}
objectResult.recomputeStatus();
return EventResult.cont();
} catch (SchemaException ex) {
if (verbose) {
ex.printStackTrace();
}
if (handler != null) {
try {
handler.handleGlobalError(validatorResult);
} catch (RuntimeException e) {
// Make sure that unhandled exceptions are recorded in object result before they are rethrown
objectResult.recordFatalError("Internal error: handleGlobalError call failed: "+e.getMessage(), e);
throw e;
}
}
objectResult.recordFatalError(ex);
return EventResult.skipObject(ex.getMessage());
} catch (RuntimeException ex) {
validatorResult.recordFatalError("Couldn't parse object: " + ex.getMessage(), ex);
if (verbose) {
ex.printStackTrace();
}
if (handler != null) {
try {
handler.handleGlobalError(validatorResult);
} catch (RuntimeException e) {
// Make sure that unhandled exceptions are recorded in object result before they are rethrown
objectResult.recordFatalError("Internal error: handleGlobalError call failed: "+e.getMessage(), e);
throw e;
}
}
objectResult.recordFatalError(ex);
return EventResult.skipObject(ex.getMessage());
}
}
// this was made public to allow validation of pre-parsed non-prism documents
public Node validateSchema(Element objectDoc, OperationResult objectResult) {
OperationResult result = objectResult.createSubresult(LegacyValidator.class.getName() + ".validateSchema");
DOMResult validationResult = new DOMResult();
try {
xsdValidator.validate(new DOMSource(objectDoc), validationResult);
} catch (SAXException e) {
result.recordFatalError("Validation error: " + e.getMessage(), e);
objectResult.computeStatus("Validation error: " + e.getMessage());
return null;
} catch (IOException e) {
result.recordFatalError("IO error during validation: " + e.getMessage(), e);
objectResult.computeStatus("IO error during validation: " + e.getMessage());
return null;
}
result.recordSuccess();
return validationResult.getNode();
}
public void validateObject(Objectable object, OperationResult objectResult) {
// Check generic object properties
checkBasics(object, objectResult);
// Type-specific checks
if (object instanceof ResourceType) {
ResourceType resource = (ResourceType) object;
checkResource(resource, objectResult);
}
// TODO: more checks
objectResult.recomputeStatus("Object validation has failed", "Validation warning");
objectResult.recordSuccessIfUnknown();
}
// BIG checks - checks that create subresults
private void checkBasics(Objectable object, OperationResult objectResult) {
OperationResult subresult = objectResult.createSubresult(OPERATION_RESOURCE_BASICS_CHECK);
if (validateName) {
checkName(object, object.getName(), "name", subresult);
}
subresult.recordSuccessIfUnknown();
}
private void checkResource(ResourceType resource, OperationResult objectResult) {
OperationResult subresult = objectResult.createSubresult(OPERATION_RESOURCE_NAMESPACE_CHECK);
checkUri(resource, ResourceTypeUtil.getResourceNamespace(resource), "namespace", subresult);
subresult.recordSuccessIfUnknown();
}
// Small checks - checks that don't create subresults
private void checkName(Objectable object, PolyStringType value, String propertyName, OperationResult subResult) {
// TODO: check for all whitespaces
// TODO: check for bad characters
if (value == null) {
error("Null property", object, propertyName, subResult);
return;
}
String orig = value.getOrig();
if (orig == null || orig.isEmpty()) {
error("Empty property", object, propertyName, subResult);
}
}
private void checkUri(Objectable object, String value, String propertyName, OperationResult subResult) {
// TODO: check for all whitespaces
// TODO: check for bad characters
if (StringUtils.isEmpty(value)) {
error("Empty property", object, propertyName, subResult);
return;
}
try {
URI uri = new URI(value);
if (uri.getScheme() == null) {
error("URI is supposed to be absolute", object, propertyName, subResult);
}
} catch (URISyntaxException ex) {
error("Wrong URI syntax: " + ex, object, propertyName, subResult);
}
}
void error(String message, Objectable object, OperationResult subResult) {
subResult.addContext(OperationResult.CONTEXT_OBJECT, object.toString());
subResult.recordFatalError(message);
}
private void error(String message, Objectable object, String propertyName, OperationResult subResult) {
subResult.addContext(OperationResult.CONTEXT_OBJECT, object.toString());
subResult.addContext(OperationResult.CONTEXT_ITEM, propertyName);
subResult.recordFatalError("<" + propertyName + ">: " + message);
}
}