APIs and scripts for validating STIX 2.x documents against specification requirements and best practices.
npx @tessl/cli install tessl/pypi-stix2-validator@3.2.00
# STIX2-Validator
1
2
A comprehensive Python library for validating STIX (Structured Threat Information eXpression) 2.x JSON documents against specification requirements and best practices. The validator ensures conformance with both mandatory "MUST" requirements and recommended "SHOULD" best practices from the STIX 2.0 and 2.1 specifications.
3
4
## Package Information
5
6
- **Package Name**: stix2-validator
7
- **Language**: Python
8
- **Installation**: `pip install stix2-validator`
9
10
## Core Imports
11
12
```python
13
import stix2validator
14
```
15
16
Common validation functions:
17
18
```python
19
from stix2validator import validate_file, validate_string, validate_instance, print_results
20
```
21
22
Configuration and utilities:
23
24
```python
25
from stix2validator import ValidationOptions, parse_args
26
```
27
28
Exception handling:
29
30
```python
31
from stix2validator import ValidationError, NoJSONFileFoundError
32
```
33
34
Exit codes and CLI utilities:
35
36
```python
37
from stix2validator import codes
38
from stix2validator.codes import get_code, EXIT_SUCCESS, EXIT_FAILURE
39
from stix2validator.scripts.stix2_validator import main
40
```
41
42
## Basic Usage
43
44
```python
45
from stix2validator import validate_file, print_results
46
47
# Validate a STIX JSON file
48
results = validate_file("stix_document.json")
49
print_results(results)
50
51
# Check if validation passed
52
if results.is_valid:
53
print("STIX document is valid!")
54
else:
55
print("Validation errors found")
56
for error in results.errors:
57
print(f"Error: {error}")
58
```
59
60
```python
61
from stix2validator import validate_string, ValidationOptions
62
63
# Validate STIX JSON from string with custom options
64
stix_json = '{"type": "indicator", "id": "indicator--12345678-1234-1234-1234-123456789012", ...}'
65
66
options = ValidationOptions(
67
version="2.1",
68
strict=True,
69
verbose=True
70
)
71
72
results = validate_string(stix_json, options)
73
print(f"Valid: {results.is_valid}")
74
```
75
76
## Architecture
77
78
The validator follows a layered architecture:
79
80
- **Validation Functions**: Core entry points (validate_file, validate_string, etc.) that handle different input types
81
- **ValidationOptions**: Configuration class for customizing validation behavior
82
- **Result Classes**: Structured result objects (FileValidationResults, ObjectValidationResults) for validation outcomes
83
- **Schema Validation**: JSON Schema-based validation for STIX object structure
84
- **Python Rule Validation**: Custom Python functions for rules that cannot be expressed in JSON Schema
85
- **Version-Specific Modules**: Separate validation logic for STIX 2.0 and 2.1 specifications
86
87
## Capabilities
88
89
### Core Validation Functions
90
91
Main validation entry points for different input types including files, strings, Python dictionaries, and parsed JSON objects. These functions form the foundation of STIX document validation.
92
93
```python { .api }
94
def validate_file(fn, options=None): ...
95
def validate_string(string, options=None): ...
96
def validate_instance(instance, options=None): ...
97
def validate_parsed_json(obj_json, options=None): ...
98
def validate(in_, options=None): ...
99
def run_validation(options): ...
100
```
101
102
[Core Validation](./core-validation.md)
103
104
### Configuration and Options
105
106
Comprehensive configuration system for customizing validation behavior, including version selection, strictness levels, custom schema directories, and selective enabling/disabling of validation checks.
107
108
```python { .api }
109
class ValidationOptions: ...
110
def parse_args(cmd_args, is_script=False): ...
111
```
112
113
[Configuration](./configuration.md)
114
115
### Result Processing
116
117
Structured result classes and output formatting functions for handling validation outcomes, including error reporting, success indicators, and formatted console output with color coding.
118
119
```python { .api }
120
class FileValidationResults: ...
121
class ObjectValidationResults: ...
122
def print_results(results): ...
123
```
124
125
[Results and Output](./results-output.md)
126
127
### Exception Handling
128
129
Comprehensive exception hierarchy for different validation error scenarios, enabling precise error handling and programmatic response to validation failures.
130
131
```python { .api }
132
class ValidationError(Exception): ...
133
class SchemaError(ValidationError): ...
134
class NoJSONFileFoundError(OSError): ...
135
```
136
137
[Exception Handling](./exception-handling.md)
138
139
### Exit Codes and Status
140
141
Exit code utilities for command-line integration and programmatic validation result processing, providing standardized status codes for different validation outcomes.
142
143
```python { .api }
144
def get_code(results): ...
145
EXIT_SUCCESS: int
146
EXIT_FAILURE: int
147
EXIT_SCHEMA_INVALID: int
148
EXIT_VALIDATION_ERROR: int
149
```
150
151
Exit codes module provides standardized status codes for validation results and CLI integration.
152
153
### Command-Line Interface
154
155
Command-line script entry point and utilities for standalone STIX validation from the command line with comprehensive option support.
156
157
```python { .api }
158
def main(): ...
159
```
160
161
The `stix2_validator` command-line script provides a complete CLI interface for STIX validation with all library features accessible via command-line arguments.
162
163
[CLI Utilities](./cli-utilities.md)
164
165
## Types
166
167
```python { .api }
168
from typing import Union, List
169
170
# Validation input types
171
FileInput = str # File path
172
StringInput = str # JSON string
173
InstanceInput = dict # Python dictionary representing STIX object
174
ParsedJsonInput = Union[dict, list] # Parsed JSON object or list
175
176
# Result types
177
FileValidationResult = FileValidationResults # For validate_file()
178
ObjectValidationResult = ObjectValidationResults # For validate_instance()
179
StreamValidationResult = Union[ObjectValidationResults, List[ObjectValidationResults]] # For validate_string(), validate_parsed_json(), validate()
180
BatchValidationResult = List[FileValidationResults] # For run_validation()
181
182
# Exit code constants
183
EXIT_SUCCESS = 0x0 # All documents valid
184
EXIT_FAILURE = 0x1 # Fatal system error
185
EXIT_SCHEMA_INVALID = 0x2 # Schema validation failed
186
EXIT_VALIDATION_ERROR = 0x10 # Validation error occurred
187
```