0
# Core Validation Functions
1
2
Main validation entry points for different input types including files, strings, Python dictionaries, and parsed JSON objects. These functions provide flexible validation capabilities for STIX documents from various sources and formats.
3
4
## Capabilities
5
6
### File Validation
7
8
Validates STIX JSON documents from files on the filesystem, handling file I/O, JSON parsing, and comprehensive validation reporting.
9
10
```python { .api }
11
def validate_file(fn, options=None):
12
"""
13
Validate the input document according to the options passed in.
14
15
Parameters:
16
- fn (str): The filename of the JSON file to be validated
17
- options (ValidationOptions, optional): An instance of ValidationOptions
18
19
Returns:
20
FileValidationResults: An instance of FileValidationResults
21
22
Raises:
23
NoJSONFileFoundError: If the file cannot be found or read
24
ValidationError: If validation cannot be completed due to system errors
25
"""
26
```
27
28
**Example Usage:**
29
30
```python
31
from stix2validator import validate_file, ValidationOptions
32
33
# Basic file validation
34
results = validate_file("threat_report.json")
35
36
# File validation with custom options
37
options = ValidationOptions(version="2.1", strict=True)
38
results = validate_file("indicators.json", options)
39
40
# Check results
41
if results.is_valid:
42
print(f"File {results.filepath} is valid")
43
else:
44
print(f"Validation failed for {results.filepath}")
45
for obj_result in results.object_results:
46
for error in obj_result.errors:
47
print(f" Error in object {obj_result.object_id}: {error}")
48
```
49
50
### String Validation
51
52
Validates STIX JSON content from string input, useful for processing JSON received from APIs, generated dynamically, or stored in variables.
53
54
```python { .api }
55
def validate_string(string, options=None):
56
"""
57
Validate the input string according to the options passed in.
58
59
Parameters:
60
- string (str): The string containing the JSON to be validated
61
- options (ValidationOptions, optional): An instance of ValidationOptions
62
63
Returns:
64
Union[ObjectValidationResults, List[ObjectValidationResults]]: Single result for single object, list for multiple objects
65
66
Raises:
67
ValidationError: If the string cannot be parsed or validated
68
"""
69
```
70
71
**Example Usage:**
72
73
```python
74
from stix2validator import validate_string
75
76
# Single STIX object validation
77
stix_indicator = '''
78
{
79
"type": "indicator",
80
"spec_version": "2.1",
81
"id": "indicator--12345678-1234-1234-1234-123456789012",
82
"created": "2023-01-01T00:00:00.000Z",
83
"modified": "2023-01-01T00:00:00.000Z",
84
"pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",
85
"labels": ["malicious-activity"]
86
}
87
'''
88
89
result = validate_string(stix_indicator)
90
print(f"Indicator valid: {result.is_valid}")
91
92
# Bundle validation (multiple objects)
93
stix_bundle = '''
94
{
95
"type": "bundle",
96
"id": "bundle--12345678-1234-1234-1234-123456789012",
97
"objects": [...]
98
}
99
'''
100
101
results = validate_string(stix_bundle)
102
if isinstance(results, list):
103
for result in results:
104
print(f"Object {result.object_id}: {result.is_valid}")
105
```
106
107
### Instance Validation
108
109
Validates Python dictionaries representing STIX objects, enabling validation of programmatically constructed STIX data without serialization.
110
111
```python { .api }
112
def validate_instance(instance, options=None):
113
"""
114
Perform STIX JSON Schema validation against STIX input.
115
116
Parameters:
117
- instance (dict): A Python dictionary representing a STIX object with a 'type' property
118
- options (ValidationOptions, optional): Validation options for this validation run
119
120
Returns:
121
ObjectValidationResults: An instance of ObjectValidationResults
122
123
Raises:
124
ValidationError: If the instance cannot be validated
125
"""
126
```
127
128
**Example Usage:**
129
130
```python
131
from stix2validator import validate_instance, ValidationOptions
132
133
# Validate a Python dictionary
134
stix_object = {
135
"type": "malware",
136
"spec_version": "2.1",
137
"id": "malware--12345678-1234-1234-1234-123456789012",
138
"created": "2023-01-01T00:00:00.000Z",
139
"modified": "2023-01-01T00:00:00.000Z",
140
"name": "BadMalware",
141
"labels": ["trojan"]
142
}
143
144
# Validate with strict checking
145
options = ValidationOptions(strict=True, strict_types=True)
146
result = validate_instance(stix_object, options)
147
148
print(f"Malware object valid: {result.is_valid}")
149
if not result.is_valid:
150
for error in result.errors:
151
print(f"Error: {error}")
152
```
153
154
### Parsed JSON Validation
155
156
Validates already parsed JSON objects or lists, useful when working with JSON data that has already been loaded by other parts of your application.
157
158
```python { .api }
159
def validate_parsed_json(obj_json, options=None):
160
"""
161
Validate objects from parsed JSON.
162
163
Parameters:
164
- obj_json: The parsed json (dict or list)
165
- options (ValidationOptions, optional): Validation options
166
167
Returns:
168
Union[ObjectValidationResults, List[ObjectValidationResults]]: Single result or list based on input
169
170
Raises:
171
ValidationError: If validation cannot be completed
172
"""
173
```
174
175
**Example Usage:**
176
177
```python
178
import json
179
from stix2validator import validate_parsed_json
180
181
# Load JSON from various sources
182
with open("stix_data.json") as f:
183
parsed_json = json.load(f)
184
185
# Validate the parsed data
186
results = validate_parsed_json(parsed_json)
187
188
# Handle single object or list of objects
189
if isinstance(results, list):
190
for result in results:
191
print(f"Object {result.object_id}: {'VALID' if result.is_valid else 'INVALID'}")
192
else:
193
print(f"Object {results.object_id}: {'VALID' if results.is_valid else 'INVALID'}")
194
```
195
196
### Stream Validation
197
198
Validates STIX JSON content from a textual stream, useful for processing data from stdin or file-like objects.
199
200
```python { .api }
201
def validate(in_, options=None):
202
"""
203
Validate objects from JSON data in a textual stream.
204
205
Parameters:
206
- in_: A textual stream of JSON data
207
- options (ValidationOptions, optional): Validation options
208
209
Returns:
210
Union[ObjectValidationResults, List[ObjectValidationResults]]: Single result or list based on content
211
212
Raises:
213
ValidationError: If validation cannot be completed
214
"""
215
```
216
217
**Example Usage:**
218
219
```python
220
import sys
221
from stix2validator import validate
222
223
# Validate from stdin
224
if not sys.stdin.isatty():
225
results = validate(sys.stdin)
226
if isinstance(results, list):
227
for result in results:
228
print(f"Object {result.object_id}: {'VALID' if result.is_valid else 'INVALID'}")
229
else:
230
print(f"Object {results.object_id}: {'VALID' if results.is_valid else 'INVALID'}")
231
232
# Validate from any file-like object
233
from io import StringIO
234
stix_stream = StringIO('{"type": "indicator", ...}')
235
result = validate(stix_stream)
236
print(f"Stream validation: {result.is_valid}")
237
```
238
239
### Batch Validation
240
241
Runs validation based on command line options, processing multiple files and directories with comprehensive reporting.
242
243
```python { .api }
244
def run_validation(options):
245
"""
246
Validate files based on command line options.
247
248
Parameters:
249
- options (ValidationOptions): An instance of ValidationOptions containing options for this validation run
250
251
Returns:
252
List[FileValidationResults]: List of validation results for all processed files
253
254
Raises:
255
ValidationError: If validation cannot be completed
256
NoJSONFileFoundError: If specified files cannot be found
257
"""
258
```
259
260
**Example Usage:**
261
262
```python
263
from stix2validator import run_validation, ValidationOptions
264
265
# Configure batch validation options
266
options = ValidationOptions(
267
files=["stix_files/", "single_file.json"],
268
recursive=True,
269
version="2.1",
270
verbose=True,
271
strict=False
272
)
273
274
# Run batch validation
275
results = run_validation(options)
276
277
# Process results
278
valid_count = sum(1 for result in results if result.is_valid)
279
total_count = len(results)
280
281
print(f"Validation complete: {valid_count}/{total_count} files valid")
282
283
for result in results:
284
if not result.is_valid:
285
print(f"FAILED: {result.filepath}")
286
for obj_result in result.object_results:
287
for error in obj_result.errors:
288
print(f" - {error}")
289
```
290
291
## Utility Functions
292
293
### File Discovery
294
295
```python { .api }
296
def is_json(fn):
297
"""
298
Check if file has JSON extension.
299
300
Parameters:
301
- fn (str): Filename to check
302
303
Returns:
304
bool: True if file has .json extension
305
"""
306
307
def list_json_files(directory, recursive=False):
308
"""
309
List JSON files in directory.
310
311
Parameters:
312
- directory (str): Directory path to search
313
- recursive (bool): Whether to search subdirectories
314
315
Returns:
316
List[str]: List of JSON file paths
317
"""
318
319
def get_json_files(files, recursive=False):
320
"""
321
Get JSON files from file list or directories.
322
323
Parameters:
324
- files (List[str]): List of files and/or directories
325
- recursive (bool): Whether to search directories recursively
326
327
Returns:
328
List[str]: List of JSON file paths
329
"""
330
```