CWE Domain
Types and operations for CWE (Common Weakness Enumeration) analysis, validation, and relationship tracking.
CWE Results
ci.transparency.cwe.types.cwe.results
CWE domain result types and operations using composition.
__all__ = ['CweLoadingResult', 'CweValidationResult', 'CweRelationshipResult', 'CweRelationshipDict', 'CweRelationshipLike', 'CweDataDict', 'CweItemDict', 'ValidationResultsDict', 'ValidationDetailsDict', 'SeverityCountsDict', 'ErrorSummaryDict', 'LoadingSummaryDict', 'ValidationSummaryDict', 'RelationshipStatisticsDict', 'RelationshipSummaryDict', 'RelationshipType', 'add_cwe', 'track_invalid_file', 'track_skipped_cwe_file', 'validate_cwe', 'validate_cwe_field', 'batch_validate_cwes', 'analyze_relationships', 'get_cwe_loading_summary', 'get_cwe_validation_summary', 'get_relationship_summary']
module-attribute
CweDataDict = dict[str, CweItemDict]
CweRelationshipLike = CweRelationshipDict | str
ErrorSummaryDict = dict[str, Any]
LoadingSummaryDict = dict[str, Any]
RelationshipDepthsDict = dict[str, int]
RelationshipMapDict = dict[str, list[str]]
RelationshipStatisticsDict = dict[str, Any]
RelationshipSummaryDict = dict[str, Any]
RelationshipType = Literal['related', 'parent', 'child', 'variant', 'requires', 'causes', 'consequence', 'unknown']
RelationshipTypesDict = dict[str, int]
SeverityCountsDict = dict[str, int]
ValidationDetailsDict = dict[str, list[str]]
ValidationResultsDict = dict[str, bool]
ValidationSummaryDict = dict[str, Any]
CategoryCollection
dataclass
Tracks statistics for categories.
Attributes
category_stats : dict[str, int] Dictionary mapping category names to their counts.
category_count
property
Return the number of categories tracked in the collection.
most_common_category
property
Return the most common category based on the highest count.
Returns
str or None The category with the highest count, or None if there are no categories.
CweItemDict
Bases: TypedDict
Minimal shape of a single CWE record (extend as needed).
CweLoadingResult
dataclass
Represents the result of loading CWE data using composition.
Composes base building blocks for clean separation of concerns.
Attributes
cwes : CweDataDict Dictionary of loaded CWE data. loading : LoadingCounts Statistics about loading success and failures. messages : MessageCollection Collection of error, warning, and info messages. files : FileCollection Tracking of processed, failed, and skipped files. categories : CategoryCollection Statistics for categories encountered. duplicates : DuplicateCollection Tracking of duplicate IDs and their associated files.
cwe_count
property
Return the number of CWEs loaded.
is_successful
property
Return True if loading is successful and there are no error messages.
loaded_cwe_ids
property
All loaded CWE IDs (sorted for stable output).
add_error(msg)
Add error message (added by decorator).
add_info(msg)
Add info message (added by decorator).
add_warning(msg)
Add warning message (added by decorator).
get_cwe(cwe_id)
Get CWE data by ID.
get_cwes_by_category(category)
Get CWEs filtered by category.
has_cwe(cwe_id)
Check if a CWE ID was loaded.
search_cwes(search_term)
Search CWEs by name or description.
CweRelationshipDict
Bases: TypedDict
Typed structure for CWE relationship data.
CweRelationshipResult
dataclass
Result from CWE relationship validation and analysis using composition.
Tracks CWE relationship consistency, circular dependency detection, and relationship graph analysis.
Attributes
validation : ValidationCounts Statistics about relationship validation. messages : MessageCollection Collection of error, warning, and info messages. references : ReferenceCollection Tracking of references between CWEs. relationship_depths : RelationshipDepthsDict Depth of each CWE in the relationship graph. relationship_types : RelationshipTypesDict Count of relationship types. circular_dependencies : list[str] CWEs involved in circular dependencies.
circular_dependency_count
property
Number of circular dependencies detected.
has_circular_dependencies
property
True if circular dependencies were detected.
is_successful
property
Return True if relationship analysis is successful.
max_relationship_depth
property
Maximum relationship depth in the graph.
add_error(msg)
Add error message (added by decorator).
add_info(msg)
Add info message (added by decorator).
add_warning(msg)
Add warning message (added by decorator).
find_relationship_path(from_cwe, to_cwe)
Find shortest path between two CWEs.
get_related_cwes(cwe_id, max_depth=1)
Get all CWEs related to a given CWE up to max_depth.
get_relationship_depth(cwe_id)
Get relationship depth for a specific CWE.
get_relationship_statistics()
Get comprehensive relationship statistics.
get_relationships(cwe_id)
Get all relationships for a specific CWE.
CweValidationResult
dataclass
Represents the result of validating CWE data using composition.
Attributes
validation_results : ValidationResultsDict Dictionary of validation results for each CWE item. validation : ValidationCounts Statistics about validation success and failures. messages : MessageCollection Collection of error, warning, and info messages. field_errors : list[str] Field-level validation errors. validation_details : ValidationDetailsDict Detailed validation errors per CWE. severity_counts : SeverityCountsDict Count of issues by severity level.
field_error_count
property
Number of field-level validation errors.
has_field_errors
property
True if any field-level validation errors occurred.
is_successful
property
Return True if validation is successful and there are no error messages.
validated_count
property
Return the number of items that have been validated.
validation_rate
property
Validation success rate (0.0 to 1.0).
add_error(msg)
Add error message (added by decorator).
add_info(msg)
Add info message (added by decorator).
add_warning(msg)
Add warning message (added by decorator).
get_error_summary()
Get comprehensive error summary.
get_failed_cwes()
Get list of CWE IDs that failed validation.
get_most_common_errors(limit=5)
Get most common validation errors.
get_passed_cwes()
Get list of CWE IDs that passed validation.
get_validation_errors(cwe_id)
Get validation errors for a specific CWE.
DuplicateCollection
dataclass
Tracks duplicate IDs and their associated file paths.
Attributes
duplicate_ids : dict[str, list[Path]] Dictionary mapping duplicate IDs to lists of file paths where duplicates were found.
duplicate_count
property
Return the number of duplicate IDs tracked in the collection.
Returns
int The number of duplicate IDs.
has_duplicates
property
Return True if there are any duplicate IDs, otherwise False.
FileCollection
dataclass
Tracks processed, failed, and skipped files.
Attributes
processed_files : list[Path] list of files that have been processed. failed_files : list[Path] list of files that failed to process. skipped_files : list[Path] list of files that were skipped.
failed_file_count
property
Return the number of failed files.
processed_file_count
property
Return the number of processed files.
skipped_file_count
property
Return the number of skipped files.
total_files
property
Return the total number of files (processed, failed, skipped).
LoadingCounts
dataclass
Tracks the number of successfully loaded and failed items.
Attributes
loaded_count : int Number of items successfully loaded. failed_count : int Number of items that failed to load.
is_successful
property
Return True if there are no failed validations, otherwise False.
success_rate
property
Return the rate of successful loads as a float between 0 and 1.
total_attempted
property
Return the total number of attempted loads (successful + failed).
MessageCollection
dataclass
Collects error, warning, and info messages.
Attributes
errors : list[str] list of error messages. warnings : list[str] list of warning messages. infos : list[str] list of informational messages.
error_count
property
Return the number of error messages.
has_errors
property
Return True if there are any error messages, otherwise False.
has_warnings
property
Return True if there are any warning messages, otherwise False.
info_count
property
Return the number of informational messages.
total_messages
property
Return the total number of messages (errors, warnings, infos).
warning_count
property
Return the number of warning messages.
ReferenceCollection
dataclass
Tracks references between items and their validity.
Could be reused for any domain that has inter-item references.
has_invalid_references
property
True if there are invalid references.
has_orphaned_items
property
True if there are orphaned items.
invalid_reference_count
property
Number of invalid references.
orphaned_item_count
property
Number of items with no references.
total_references_count
property
Total number of references tracked.
add_invalid_reference(reference_desc)
Add an invalid reference.
add_orphaned_item(item_id)
Add an orphaned item.
add_reference(from_item, to_item)
Add a reference between items.
ValidationCounts
dataclass
Tracks the number of passed and failed validations.
Attributes
passed_count : int Number of items that passed validation. failed_count : int Number of items that failed validation.
is_successful
property
Return True if there are no failed validations, otherwise False.
pass_rate
property
Return the rate of passed validations as a float between 0 and 1.
total_validated
property
Return the total number of validated items (passed + failed).
_add_category(categories, category)
Add or increment a category count.
_add_duplicate(duplicates, item_id, file_path)
Add a duplicate ID with its file path.
_add_failed_file(files, file_path)
Add a failed file.
_add_message(messages, level, message)
Add a message to the message collection.
_add_processed_file(files, file_path)
Add a processed file.
_add_skipped_file(files, file_path)
Add a skipped file.
_build_relationship_map(cwe_dict)
Build relationship map and identify invalid references and orphaned items.
_calculate_relationship_depth(relationship_map, cwe_id, visited)
Calculate relationship depth recursively with cycle detection.
_detect_circular_dependencies(relationship_map)
Detect circular dependencies in relationship map using DFS.
_find_shortest_path(relationship_map, start, end)
Find shortest path between two CWEs using BFS.
_increment_loading_counts(counts, *, succeeded=0, failed=0)
Increment loading counts.
_increment_validation_counts(counts, *, passed=0, failed=0)
Increment validation counts.
_is_valid_category(category)
Validate CWE category.
_is_valid_cwe_id(cwe_id)
Validate CWE ID format.
_max_severity(*labels)
Return the highest-severity label among the provided ones.
_process_relationship_item(relationship, _relationship_types)
_raise_severity(current, candidate)
Return the higher-severity label according to _severity_order().
_severity_order(severity)
Get severity order for comparison.
_validate_optional_fields(cwe_data)
Validate optional-but-constrained fields: category.
_validate_relationships(cwe_data)
Validate relationships: presence of cwe_id and its format.
_validate_required_fields(cwe_data)
Validate required CWE fields: id, name, description (recommended).
add_cwe(result, cwe_id, cwe_data, *, file_path=None)
Add successfully loaded CWE to the result.
analyze_relationships(result, cwe_dict)
Analyze CWE relationships for consistency and detect issues.
batch_validate_cwes(result, cwe_dict)
Validate multiple CWEs in batch.
get_cwe_loading_summary(result)
Generate CWE loading summary.
get_cwe_validation_summary(result)
Generate CWE validation summary.
get_relationship_summary(result)
Generate CWE relationship summary.
track_invalid_file(result, file_path, reason)
Track an invalid CWE file.
track_skipped_cwe_file(result, file_path, reason)
Track a skipped CWE file.
validate_cwe(result, cwe_id, cwe_data)
Validate a CWE definition with comprehensive field validation.
validate_cwe_field(result, cwe_id, field_path, field_value, validation_rule)
Validate a specific CWE field.
with_message_methods(cls)
Add message methods to result classes.
Decorator that adds add_error(), add_warning(), and add_info() methods to any result class with a MessageCollection field.
options: showsource: false show_signature: true group_by_category: true filters: - "!^"
CWE Errors
ci.transparency.cwe.types.cwe.errors
CWE domain error types using enhanced base classes.
Domain-specific error hierarchy for CWE operations. Each error inherits from exactly one enhanced base error class and leverages the flexible context system for CWE-specific information.
Design principles
- Single inheritance: each error extends exactly one base error class
- Context-rich: uses the flexible context system for CWE details
- Consistent: maintains uniform error formatting across all errors
- Minimal: leverages base class functionality rather than duplicating code
Usage patterns
- File operations → FileError, LoadingError, ParsingError
- Validation operations → ValidationError
- Processing operations → OperationError
- General operations → BaseTransparencyError
Typical usage
from ci.transparency.cwe.types.cwe import CweValidationError
raise CweValidationError( "Field validation failed", item_id="CWE-79", field_path="relationships[0].id", validation_rule="required_field", file_path="cwe-79.yaml" )
Output: "Field validation failed | Item: CWE-79 | Field: relationships[0].id | Rule: required_field | File: cwe-79.yaml"
__all__ = ['CweCircularRelationshipError', 'CweConfigurationError', 'CweConstraintViolationError', 'CweDuplicateError', 'CweFieldValidationError', 'CweFileNotFoundError', 'CweIntegrityError', 'CweInvalidFormatError', 'CweInvalidReferenceError', 'CweLoadingError', 'CweMissingFieldError', 'CweOrphanedError', 'CweParsingError', 'CweProcessingError', 'CweRelationshipError', 'CweSchemaValidationError', 'CweValidationError']
module-attribute
BaseTransparencyError
Bases: Exception
Enhanced base exception for all transparency operations.
Provides flexible context tracking for common error patterns without requiring all errors to specify every possible context field.
get_context_parts()
Get contextual information parts for error formatting.
Returns context in order of importance: 1. Operation identification (phase, operation, stage) 2. Progress information (processed/total counts) 3. Resource information (timeouts, limits) 4. File/item context 5. Validation context 6. Error flow context (abort reason, error code)
Returns:
Type | Description |
---|---|
list[str]
|
List of context strings (e.g., ["Phase: validation", "Progress: 150/500"]) |
CweCircularRelationshipError
CweConfigurationError
CweConstraintViolationError
CweDuplicateError
CweFieldValidationError
CweFileNotFoundError
CweIntegrityError
CweInvalidFormatError
CweInvalidReferenceError
CweLoadingError
CweMissingFieldError
CweOrphanedError
CweParsingError
CweProcessingError
CweRelationshipError
CweSchemaValidationError
CweValidationError
FileError
Bases: BaseTransparencyError
Base exception for file-based operations.
Convenient base for file loading, parsing, and other file-related errors.
LoadingError
OperationError
Bases: BaseTransparencyError
Base exception for operations with progress tracking.
Convenient base for batch processing, phase validation, and other operations that process multiple items with progress tracking.
ParsingError
ValidationError
Bases: BaseTransparencyError
Base exception for validation operations.
Convenient base for schema validation, rule checking, and other validation-related errors.
options: showsource: false show_signature: true group_by_category: true filters: - "!^"