APIs and scripts for validating STIX 2.x documents against specification requirements and best practices.
Structured result classes and output formatting functions for handling validation outcomes, including error reporting, success indicators, and formatted console output with color coding.
Container for validation results when validating files, including file-level information and individual object validation results.
class FileValidationResults:
"""
Results for file validation operations.
Parameters:
- is_valid (bool): Whether the overall validation result is valid (default: False)
- filepath (str, optional): Which file was validated
- object_results (List[ObjectValidationResults], optional): Individual object validation results
- fatal (Exception, optional): A non-validation-related fatal error
Properties:
- object_result: Get the object result object, assuming there is only one
- object_results: Get all object results
- is_valid: Returns True if validation was successful and False otherwise
Methods:
- as_dict(): Return a dictionary representation
- log(): Print (log) these file validation results
- as_json(): Returns a JSON representation of this class instance
"""
def __init__(self, is_valid=False, filepath=None, object_results=None, fatal=None):
pass
@property
def object_result(self):
"""Get the single object result (for files with one STIX object)."""
pass
@property
def object_results(self):
"""Get all object results."""
pass
def as_dict(self):
"""Return dictionary representation of results."""
pass
def log(self):
"""Print these file validation results."""
pass
def as_json(self):
"""Return JSON representation of results."""
passExample Usage:
from stix2validator import validate_file
# Validate a file and examine results
results = validate_file("threat_indicators.json")
print(f"File: {results.filepath}")
print(f"Valid: {results.is_valid}")
# Access individual object results
if results.object_results:
for obj_result in results.object_results:
print(f"Object {obj_result.object_id}: {obj_result.is_valid}")
if obj_result.errors:
for error in obj_result.errors:
print(f" Error: {error}")
# For single-object files, use object_result property
if results.object_result:
single_result = results.object_result
print(f"Single object validation: {single_result.is_valid}")
# Convert to dictionary for serialization
result_dict = results.as_dict()
print(f"Result dict: {result_dict}")
# Log results with formatting
results.log()Container for validation results of individual STIX objects, including detailed error and warning information.
class ObjectValidationResults:
"""
Results for individual STIX object validation.
Parameters:
- is_valid (bool): The validation result (default: False)
- object_id (str, optional): ID of the STIX object
- errors (List[str], optional): List of validation error messages
- warnings (List[str], optional): List of validation warning messages
Properties:
- errors: A list of SchemaError validation errors
- is_valid: Returns True if validation was successful and False otherwise
Methods:
- as_dict(): A dictionary representation of the ObjectValidationResults instance
- log(): Print (log) these object validation results
- as_json(): Returns a JSON representation of this class instance
"""
def __init__(self, is_valid=False, object_id=None, errors=None, warnings=None):
pass
def as_dict(self):
"""Return dictionary representation of object results."""
pass
def log(self):
"""Print these object validation results."""
pass
def as_json(self):
"""Return JSON representation of results."""
passExample Usage:
from stix2validator import validate_string
# Validate a STIX object string
stix_json = '''
{
"type": "indicator",
"spec_version": "2.1",
"id": "indicator--12345678-1234-1234-1234-123456789012",
"created": "2023-01-01T00:00:00.000Z",
"modified": "2023-01-01T00:00:00.000Z",
"pattern": "[file:hashes.MD5 = 'invalid-hash']",
"labels": ["malicious-activity"]
}
'''
result = validate_string(stix_json)
# Examine object validation results
print(f"Object ID: {result.object_id}")
print(f"Valid: {result.is_valid}")
# Check for errors and warnings
if result.errors:
print("Errors:")
for error in result.errors:
print(f" - {error}")
if result.warnings:
print("Warnings:")
for warning in result.warnings:
print(f" - {warning}")
# Convert to structured data
result_data = result.as_dict()
json_data = result.as_json()
# Log with formatting
result.log()Special result container for handling validation exceptions and fatal errors during the validation process.
class ValidationErrorResults:
"""
Results for validation errors and exceptions.
Parameters:
- error (Exception): An Exception instance raised by validation code
Properties:
- is_valid: Always False
- error: The string representation of the Exception being passed in
- exception: The exception which produced these results
Methods:
- as_dict(): Return a dictionary representation
- as_json(): Returns a JSON representation of this class instance
"""
def __init__(self, error):
pass
@property
def is_valid(self):
"""Always returns False for error results."""
return False
def as_dict(self):
"""Return dictionary representation of error results."""
pass
def as_json(self):
"""Return JSON representation of error results."""
passFunctions for controlling and formatting validation output, including color-coded console output and verbosity control.
def print_results(results):
"""
Print results (the results of validation) to stdout with color coding.
Parameters:
- results (Union[List[FileValidationResults], List[ObjectValidationResults]]):
A list of validation result instances
Returns:
None
Description:
Formats and prints validation results with color coding:
- Green for successful validation
- Yellow for warnings
- Red for errors and failures
"""
def set_level(verbose_output=False):
"""
Set the output level for the application.
Parameters:
- verbose_output (bool): Enable verbose output mode (default: False)
Returns:
None
Description:
Controls output verbosity. When False, only results or fatal errors
are printed. When True, includes informational messages and detailed
error descriptions.
"""
def set_silent(silence_output=False):
"""
Set the silent flag for the application.
Parameters:
- silence_output (bool): Enable silent mode (default: False)
Returns:
None
Description:
When True, suppresses all output to stdout. Useful for programmatic
usage where only return values are needed.
"""
def error(msg):
"""
Print a message to stderr prepended by '[X]'.
Parameters:
- msg (str): The error message to print
Returns:
None
"""
def info(msg):
"""
Print a message to stdout, prepended by '[-]'.
Parameters:
- msg (str): The message to print
Returns:
None
Description:
Only prints if the application is running in verbose mode.
Returns immediately in non-verbose mode.
"""Example Usage:
from stix2validator import validate_file, print_results, set_level, set_silent
from stix2validator.output import error, info
# Configure output settings
set_level(verbose_output=True) # Enable verbose mode
# set_silent(silence_output=True) # Or enable silent mode
# Validate multiple files
file_results = []
files = ["indicators.json", "malware.json", "threat_report.json"]
for filename in files:
try:
result = validate_file(filename)
file_results.append(result)
# Custom result processing
if result.is_valid:
info(f"Successfully validated {filename}")
else:
error(f"Validation failed for {filename}")
except Exception as e:
error(f"Could not validate {filename}: {e}")
# Print all results with color coding
print_results(file_results)
# Manual result formatting
for result in file_results:
print(f"\n=== {result.filepath} ===")
if result.is_valid:
print("✓ VALID")
else:
print("✗ INVALID")
for obj_result in result.object_results:
if obj_result.errors:
print(f"Object {obj_result.object_id}:")
for error_msg in obj_result.errors:
print(f" • {error_msg}")from stix2validator import run_validation, ValidationOptions
# Run batch validation
options = ValidationOptions(
files=["stix_data/"],
recursive=True,
version="2.1"
)
results = run_validation(options)
# Analyze batch results
total_files = len(results)
valid_files = sum(1 for r in results if r.is_valid)
invalid_files = total_files - valid_files
print(f"Validation Summary:")
print(f" Total files: {total_files}")
print(f" Valid files: {valid_files}")
print(f" Invalid files: {invalid_files}")
print(f" Success rate: {(valid_files/total_files)*100:.1f}%")
# Detailed error analysis
error_types = {}
for result in results:
if not result.is_valid:
for obj_result in result.object_results:
for error in obj_result.errors:
error_type = str(error).split(':')[0]
error_types[error_type] = error_types.get(error_type, 0) + 1
print(f"\nError Type Distribution:")
for error_type, count in sorted(error_types.items()):
print(f" {error_type}: {count}")import json
from stix2validator import validate_file
# Validate and serialize results
result = validate_file("threat_data.json")
# Convert to dictionary for storage
result_dict = result.as_dict()
# Save to file
with open("validation_result.json", "w") as f:
json.dump(result_dict, f, indent=2)
# Or use built-in JSON serialization
json_result = result.as_json()
print(json_result)
# Load and process saved results
with open("validation_result.json", "r") as f:
loaded_result = json.load(f)
if loaded_result["is_valid"]:
print("Previous validation was successful")
else:
print("Previous validation failed:")
for obj in loaded_result.get("object_results", []):
for error in obj.get("errors", []):
print(f" - {error}")from stix2validator import validate_string, ValidationOptions
from stix2validator.output import set_silent
class ValidationResultHandler:
def __init__(self):
self.results = []
self.error_count = 0
self.warning_count = 0
def handle_result(self, result):
self.results.append(result)
if hasattr(result, 'object_results'):
# File result
for obj_result in result.object_results:
self.error_count += len(obj_result.errors or [])
self.warning_count += len(obj_result.warnings or [])
else:
# Object result
self.error_count += len(result.errors or [])
self.warning_count += len(result.warnings or [])
def summary(self):
return {
"total_validations": len(self.results),
"total_errors": self.error_count,
"total_warnings": self.warning_count
}
# Use custom handler
set_silent(True) # Disable standard output
handler = ValidationResultHandler()
stix_objects = [
'{"type": "indicator", ...}',
'{"type": "malware", ...}',
'{"type": "threat-actor", ...}'
]
for stix_json in stix_objects:
result = validate_string(stix_json)
handler.handle_result(result)
print(handler.summary())Install with Tessl CLI
npx tessl i tessl/pypi-stix2-validator