Coverage for src/governed_harness/checks/sarif.py: 99%

80 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""SARIF 2.1.0 results with the tool and rule versions that produced them. 

2 

3A finding is only reproducible when the record says which analyzer version and which rule 

4version raised it. ``governed_harness.validators.parsers.parse_sarif`` already extracts rule, 

5message, level, path and line; this module adds the provenance it drops, aligned result by result 

6with that parser's order (runs, then results).""" 

7 

8from __future__ import annotations 

9 

10import json 

11from collections.abc import Mapping, Sequence 

12from dataclasses import dataclass 

13from pathlib import Path 

14from typing import Any 

15 

16from governed_harness.validators.parsers import parse_sarif 

17 

18 

19@dataclass(frozen=True) 

20class SarifResult: 

21 rule_id: str 

22 level: str 

23 message: str 

24 path: str | None 

25 line: int | None 

26 tool: str 

27 tool_version: str | None 

28 rule_version: str | None 

29 

30 

31def _mapping(value: Any) -> Mapping[str, Any]: 

32 return value if isinstance(value, Mapping) else {} 

33 

34 

35def _text(value: Any) -> str | None: 

36 if isinstance(value, str | int | float) and not isinstance(value, bool) and str(value): 

37 return str(value) 

38 return None 

39 

40 

41def _sanitized(data: Mapping[str, Any]) -> dict[str, Any] | None: 

42 """The document with only well-formed runs and results, or None when it is not SARIF 2.x. 

43 

44 ``parse_sarif`` trusts the shape of the document; a tool's report is agent-influenced input, 

45 so malformed entries are dropped here instead of raising there.""" 

46 if not str(data.get("version", "")).startswith("2.") or not isinstance(data.get("runs"), list): 

47 return None 

48 runs: list[dict[str, Any]] = [] 

49 for run in data["runs"]: 

50 if not isinstance(run, Mapping): 

51 continue 

52 tool = _mapping(run.get("tool")) 

53 driver = _mapping(tool.get("driver")) 

54 results = run.get("results") 

55 runs.append( 

56 { 

57 **run, 

58 "tool": {**tool, "driver": dict(driver)}, 

59 "results": [ 

60 _sanitized_result(result) 

61 for result in (results if isinstance(results, list) else []) 

62 if isinstance(result, Mapping) 

63 ], 

64 } 

65 ) 

66 return {**data, "runs": runs} 

67 

68 

69def _sanitized_result(result: Mapping[str, Any]) -> dict[str, Any]: 

70 locations = result.get("locations") 

71 first = locations[0] if isinstance(locations, list) and locations else {} 

72 physical = _mapping(_mapping(first).get("physicalLocation")) 

73 artifact = { 

74 key: value 

75 for key, value in _mapping(physical.get("artifactLocation")).items() 

76 if key != "uri" or isinstance(value, str) 

77 } 

78 return { 

79 **result, 

80 "message": dict(_mapping(result.get("message"))), 

81 "locations": [ 

82 { 

83 "physicalLocation": { 

84 "artifactLocation": artifact, 

85 "region": dict(_mapping(physical.get("region"))), 

86 } 

87 } 

88 ], 

89 } 

90 

91 

92def _rule_for(result: Mapping[str, Any], rules: Sequence[Any]) -> Mapping[str, Any]: 

93 index = result.get("ruleIndex") 

94 if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < len(rules): 

95 return _mapping(rules[index]) 

96 rule_id = result.get("ruleId") 

97 for rule in rules: 

98 if isinstance(rule, Mapping) and rule.get("id") == rule_id: 98 ↛ 97line 98 didn't jump to line 97 because the condition on line 98 was always true

99 return rule 

100 return {} 

101 

102 

103def read_sarif(text: str, workspace: Path) -> list[SarifResult]: 

104 """The results of a SARIF 2.x document, with tool name and version and rule version. 

105 

106 Invalid JSON or a non-SARIF document yields ``[]``: the caller records "no parsable report", 

107 it does not crash. The rule version is the rule's ``properties.version`` (or 

108 ``properties.ruleVersion``) and falls back to the driver version.""" 

109 try: 

110 data = json.loads(text) 

111 except ValueError: 

112 return [] 

113 if not isinstance(data, Mapping): 

114 return [] 

115 document = _sanitized(data) 

116 if document is None: 

117 return [] 

118 parsed = parse_sarif(document, workspace) 

119 results: list[SarifResult] = [] 

120 position = 0 

121 for run in document["runs"]: 

122 driver = _mapping(run["tool"]["driver"]) 

123 tool = str(driver.get("name") or "sarif") 

124 tool_version = _text(driver.get("semanticVersion")) or _text(driver.get("version")) 

125 rules = driver.get("rules") 

126 rule_list: Sequence[Any] = rules if isinstance(rules, list) else [] 

127 for result in run["results"]: 

128 issue = parsed[position] 

129 position += 1 

130 rule = _rule_for(result, rule_list) 

131 properties = _mapping(rule.get("properties")) 

132 rule_version = ( 

133 _text(properties.get("version")) 

134 or _text(properties.get("ruleVersion")) 

135 or tool_version 

136 ) 

137 rule_id = issue.rule 

138 if not result.get("ruleId") and _text(rule.get("id")): 

139 rule_id = str(rule["id"]) 

140 results.append( 

141 SarifResult( 

142 rule_id=rule_id, 

143 level=issue.level, 

144 message=issue.message, 

145 path=issue.path, 

146 line=issue.line, 

147 tool=tool, 

148 tool_version=tool_version, 

149 rule_version=rule_version, 

150 ) 

151 ) 

152 return results