visual-access-contract 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vac/contract.py ADDED
@@ -0,0 +1,256 @@
1
+ """Explicit synthetic data-visibility contracts."""
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ import re
6
+ from urllib.parse import urlsplit
7
+
8
+ import yaml
9
+
10
+
11
+ _IDENTIFIER = re.compile(r"[A-Za-z0-9_.-]+")
12
+ _JSON_PATH = re.compile(r"\$\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*")
13
+ _LOOPBACK = {"localhost", "127.0.0.1", "::1"}
14
+
15
+
16
+ class ContractError(ValueError):
17
+ """Invalid contract, with a message suitable for CI logs."""
18
+
19
+
20
+ class UniqueLoader(yaml.SafeLoader):
21
+ """Reject duplicate keys rather than silently changing a policy."""
22
+
23
+
24
+ def _unique_mapping(loader, node):
25
+ keys = set()
26
+ for key, _ in node.value:
27
+ if not isinstance(key, yaml.ScalarNode) or key.value in keys:
28
+ raise ContractError("Contract mappings require unique scalar keys")
29
+ keys.add(key.value)
30
+ return yaml.SafeLoader.construct_mapping(loader, node)
31
+
32
+
33
+ UniqueLoader.add_constructor("tag:yaml.org,2002:map", _unique_mapping)
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Session:
38
+ mode: str
39
+ secret_env: str | None = None
40
+ cookie_name: str | None = None
41
+ identity_path: str | None = None
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Rule:
46
+ id: str
47
+ field: str
48
+ full: str
49
+ roles: dict[str, str]
50
+ json_path: str
51
+ dom_selector: str
52
+ visual_selector: str
53
+
54
+ def check_config(self) -> dict:
55
+ return {
56
+ "id": self.id,
57
+ "synthetic_values": {"full": self.full},
58
+ "roles": {
59
+ role: {"visibility": visibility, "mask_format": "last_4"}
60
+ for role, visibility in self.roles.items()
61
+ },
62
+ }
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Scenario:
67
+ id: str
68
+ page_path: str
69
+ api_path: str
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Contract:
74
+ origin: str
75
+ roles: dict[str, Session]
76
+ rules: tuple[Rule, ...]
77
+ scenarios: tuple[Scenario, ...]
78
+
79
+
80
+ def _mapping(value: object, allowed: set[str], name: str) -> dict:
81
+ if not isinstance(value, dict) or value.keys() - allowed:
82
+ raise ContractError(f"Invalid {name} mapping or unsupported key")
83
+ return value
84
+
85
+
86
+ def _sequence(value: object, name: str) -> list:
87
+ if not isinstance(value, list) or not value:
88
+ raise ContractError(f"{name} must be a nonempty list")
89
+ return value
90
+
91
+
92
+ def _required(value: object, name: str, pattern: re.Pattern | None = None) -> str:
93
+ if not isinstance(value, str) or not value.strip() or (pattern and not pattern.fullmatch(value)):
94
+ raise ContractError(f"Invalid or missing {name}")
95
+ return value
96
+
97
+
98
+ def _path(value: object, name: str) -> str:
99
+ path = _required(value, name)
100
+ parsed = urlsplit(path)
101
+ if not path.startswith("/") or path.startswith("//") or "\\" in path or parsed.fragment:
102
+ raise ContractError(f"{name} must be an origin-relative URL without a fragment")
103
+ if any(ord(character) <= 32 for character in path):
104
+ raise ContractError(f"{name} must not contain whitespace or control characters")
105
+ return path
106
+
107
+
108
+ def _origin(value: object) -> str:
109
+ raw = _required(value, "origin")
110
+ parsed = urlsplit(raw)
111
+ if (
112
+ parsed.scheme not in {"https", "http"}
113
+ or not parsed.hostname
114
+ or parsed.username is not None
115
+ or parsed.password is not None
116
+ or parsed.path not in {"", "/"}
117
+ or parsed.query
118
+ or parsed.fragment
119
+ or (parsed.scheme == "http" and parsed.hostname not in _LOOPBACK)
120
+ ):
121
+ raise ContractError("Use an HTTPS origin or HTTP loopback origin with no credentials or path")
122
+ host = parsed.hostname.lower()
123
+ if ":" in host:
124
+ host = f"[{host}]"
125
+ default_port = 443 if parsed.scheme == "https" else 80
126
+ port = f":{parsed.port}" if parsed.port and parsed.port != default_port else ""
127
+ return f"{parsed.scheme}://{host}{port}"
128
+
129
+
130
+ def _session(value: object, origin: str) -> Session:
131
+ data = _mapping(value, {"mode", "secret_env", "cookie_name", "identity_path"}, "session")
132
+ mode = data.get("mode")
133
+ identity_path = _path(data.get("identity_path"), "identity_path")
134
+ if mode == "none" and data.keys() == {"mode", "identity_path"}:
135
+ return Session(mode, identity_path=identity_path)
136
+ if mode not in ("bearer", "cookie", "sso_stub"):
137
+ raise ContractError("Session mode must be none, bearer, cookie, or sso_stub")
138
+ env = _required(data.get("secret_env"), "secret_env", re.compile(r"[A-Z_][A-Z0-9_]*"))
139
+ if mode == "bearer" and "cookie_name" not in data:
140
+ return Session(mode, env, identity_path=identity_path)
141
+ if mode not in ("cookie", "sso_stub"):
142
+ raise ContractError("Bearer sessions cannot specify a cookie name")
143
+ if mode == "sso_stub" and urlsplit(origin).hostname not in _LOOPBACK:
144
+ raise ContractError("SSO stub sessions are restricted to loopback origins")
145
+ return Session(mode, env, _required(data.get("cookie_name"), "cookie_name", _IDENTIFIER), identity_path)
146
+
147
+
148
+ def _rule(value: object, roles: dict[str, Session]) -> Rule:
149
+ data = _mapping(value, {"id", "field", "synthetic_value", "roles", "locators"}, "rule")
150
+ policy = _mapping(data.get("roles"), set(roles), "rule roles")
151
+ if not policy or any(visibility not in ("full", "masked") for visibility in policy.values()):
152
+ raise ContractError("Each rule needs declared roles with full or masked visibility")
153
+ full = _required(data.get("synthetic_value"), "synthetic_value", re.compile(r"[0-9][0-9 .-]*[0-9]"))
154
+ if len(re.sub(r"[^0-9]", "", full)) < 5:
155
+ raise ContractError("Synthetic numeric identifiers require at least five digits")
156
+ locators = _mapping(data.get("locators"), {"json_path", "dom_selector", "visual_selector"}, "locators")
157
+ return Rule(
158
+ _required(data.get("id"), "rule id", _IDENTIFIER),
159
+ _required(data.get("field"), "field", _IDENTIFIER),
160
+ full, policy,
161
+ _required(locators.get("json_path"), "json_path", _JSON_PATH),
162
+ _required(locators.get("dom_selector"), "dom_selector"),
163
+ _required(locators.get("visual_selector"), "visual_selector"),
164
+ )
165
+
166
+
167
+ def _read_contract(path: Path) -> object:
168
+ try:
169
+ return yaml.load(path.read_text(encoding="utf-8"), Loader=UniqueLoader)
170
+ except (OSError, UnicodeError, yaml.YAMLError) as exc:
171
+ raise ContractError("Could not read or parse the contract") from exc
172
+
173
+
174
+ def _parse_contract(raw: object) -> Contract:
175
+ root = _mapping(raw, {"schema_version", "synthetic_only", "origin", "roles", "rules", "scenarios"}, "contract")
176
+ if root.get("schema_version") != "1.0" or root.get("synthetic_only") is not True:
177
+ raise ContractError('Require schema_version "1.0" and synthetic_only: true')
178
+ origin = _origin(root.get("origin"))
179
+ if not isinstance(root.get("roles"), dict) or not root["roles"]:
180
+ raise ContractError("Declare at least one role")
181
+ roles = {
182
+ _required(role, "role", _IDENTIFIER): _session(session, origin)
183
+ for role, session in root["roles"].items()
184
+ }
185
+ rules = tuple(_rule(item, roles) for item in _sequence(root.get("rules"), "rules"))
186
+ scenarios = []
187
+ for item in _sequence(root.get("scenarios"), "scenarios"):
188
+ scenario = _mapping(item, {"id", "page_path", "api_path"}, "scenario")
189
+ scenarios.append(Scenario(
190
+ _required(scenario.get("id"), "scenario id", _IDENTIFIER),
191
+ _path(scenario.get("page_path"), "page_path"),
192
+ _path(scenario.get("api_path"), "api_path"),
193
+ ))
194
+ if len({rule.id for rule in rules}) != len(rules) or len({item.id for item in scenarios}) != len(scenarios):
195
+ raise ContractError("Rule and scenario IDs must be unique")
196
+ if set(roles) != {role for rule in rules for role in rule.roles}:
197
+ raise ContractError("Each declared role must have at least one rule")
198
+ return Contract(origin, roles, rules, tuple(scenarios))
199
+
200
+
201
+ def load_contract(path: Path) -> Contract:
202
+ """Load the runnable version 1 contract."""
203
+ try:
204
+ return _parse_contract(_read_contract(path))
205
+ except ContractError:
206
+ raise
207
+ except ValueError as exc:
208
+ raise ContractError("Invalid contract URL") from exc
209
+
210
+
211
+ def _validate_fixture_contract(raw: object) -> None:
212
+ root = _mapping(raw, {"schema_version", "rules"}, "fixture contract")
213
+ ids = set()
214
+ for item in _sequence(root.get("rules"), "fixture rules"):
215
+ rule = _mapping(item, {"id", "field", "description", "roles", "locators", "synthetic_values"}, "fixture rule")
216
+ rule_id = _required(rule.get("id"), "rule id", _IDENTIFIER)
217
+ if rule_id in ids:
218
+ raise ContractError("Rule IDs must be unique")
219
+ ids.add(rule_id)
220
+ _required(rule.get("field"), "field", _IDENTIFIER)
221
+ if "description" in rule:
222
+ _required(rule["description"], "description")
223
+ if not isinstance(rule.get("roles"), dict) or not rule["roles"]:
224
+ raise ContractError("Each fixture rule needs a role")
225
+ for role, config in rule["roles"].items():
226
+ _required(role, "role", _IDENTIFIER)
227
+ policy = _mapping(config, {"visibility", "mask_format"}, "fixture role policy")
228
+ if policy.get("visibility") not in ("full", "masked") or policy.get("mask_format", "last_4") != "last_4":
229
+ raise ContractError("Unsupported fixture visibility or mask format")
230
+ values = _mapping(rule.get("synthetic_values"), {"full", "masked", "last_4"}, "fixture synthetic values")
231
+ full = _required(values.get("full"), "synthetic full value", re.compile(r"[0-9][0-9 .-]*[0-9]"))
232
+ suffix = _required(values.get("last_4"), "synthetic last_4", re.compile(r"[0-9]{4}"))
233
+ masked = _required(values.get("masked"), "synthetic masked value")
234
+ if len(re.sub(r"[^0-9]", "", full)) < 5 or not full.endswith(suffix) or not masked.endswith(suffix) or full == masked:
235
+ raise ContractError("Synthetic full and masked values must agree with last_4")
236
+ locators = _mapping(rule.get("locators", {}), {"structured", "visual"}, "fixture locators")
237
+ for kind, keys in (("structured", {"json_paths", "dom_selectors"}), ("visual", {"region_selectors"})):
238
+ settings = _mapping(locators.get(kind, {}), keys, "fixture locator group")
239
+ for name, locators_for_name in settings.items():
240
+ for locator in _sequence(locators_for_name, name):
241
+ _required(locator, name)
242
+
243
+
244
+ def validate_contract(path: Path) -> str:
245
+ """Validate the runnable schema or the preserved fixture schema offline."""
246
+ raw = _read_contract(path)
247
+ if isinstance(raw, dict) and raw.get("schema_version") == "0.1":
248
+ _validate_fixture_contract(raw)
249
+ return "0.1"
250
+ try:
251
+ _parse_contract(raw)
252
+ except ContractError:
253
+ raise
254
+ except ValueError as exc:
255
+ raise ContractError("Invalid contract URL") from exc
256
+ return "1.0"
vac/demo-contract.yaml ADDED
@@ -0,0 +1,46 @@
1
+ schema_version: "1.0"
2
+ synthetic_only: true
3
+ origin: http://127.0.0.1
4
+ roles:
5
+ admin:
6
+ mode: cookie
7
+ cookie_name: vac_demo
8
+ secret_env: VAC_DEMO_ADMIN
9
+ identity_path: /identity
10
+ support_agent:
11
+ mode: cookie
12
+ cookie_name: vac_demo
13
+ secret_env: VAC_DEMO_SUPPORT_AGENT
14
+ identity_path: /identity
15
+ viewer:
16
+ mode: cookie
17
+ cookie_name: vac_demo
18
+ secret_env: VAC_DEMO_VIEWER
19
+ identity_path: /identity
20
+ scenarios:
21
+ - id: account-review
22
+ page_path: /accounts
23
+ api_path: /api/accounts
24
+ rules:
25
+ - id: account-number
26
+ field: account_number
27
+ synthetic_value: "4532-7891-2345-6789"
28
+ roles:
29
+ admin: full
30
+ support_agent: masked
31
+ viewer: masked
32
+ locators:
33
+ json_path: $.account_number
34
+ dom_selector: "#account-number"
35
+ visual_selector: "#account-number"
36
+ - id: reference-number
37
+ field: reference_number
38
+ synthetic_value: "9081-2345-8765"
39
+ roles:
40
+ admin: full
41
+ support_agent: masked
42
+ viewer: masked
43
+ locators:
44
+ json_path: $.reference_number
45
+ dom_selector: "#reference-number"
46
+ visual_selector: "#reference-visual"
vac/demo.py ADDED
@@ -0,0 +1,53 @@
1
+ """Run the packaged synthetic demo and write its evidence files."""
2
+
3
+ import asyncio
4
+ from dataclasses import replace
5
+ from importlib.resources import as_file, files
6
+ import logging
7
+ from pathlib import Path
8
+
9
+ from playwright.async_api import Error
10
+
11
+ from evidence.reporter import format_ci_annotation, print_ci_report
12
+ from vac.contract import ContractError, load_contract
13
+ from vac.demo_fixture import serve
14
+ from vac.html_report import write_html_report
15
+ from vac.output import write_reports
16
+ from vac.runner import run_with_role_secrets
17
+
18
+ _EXPECTED_FAILURES = {
19
+ ("support_agent", "account-number", "structured"),
20
+ ("viewer", "reference-number", "visual"),
21
+ }
22
+
23
+
24
+ def main() -> int:
25
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
26
+ try:
27
+ with as_file(files("vac").joinpath("demo-contract.yaml")) as path:
28
+ contract = load_contract(path)
29
+ with serve(contract) as origin:
30
+ configured = replace(contract, origin=origin)
31
+ results = asyncio.run(run_with_role_secrets(configured, {role: role for role in contract.roles}))
32
+ for role in contract.roles:
33
+ print(f"Role: {role} · synthetic demo")
34
+ print_ci_report([format_ci_annotation(result) for result in results if result.role == role])
35
+
36
+ report = Path("vac-demo-report.json")
37
+ sarif = Path("vac-demo-report.sarif")
38
+ html = Path("vac-demo-report.html")
39
+ write_reports(results, contract, "vac/demo-contract.yaml", report, sarif)
40
+ write_html_report(results, contract, html)
41
+ print(f"Synthetic evidence: {html}, {sarif}, {report}")
42
+ except (ContractError, Error, OSError):
43
+ logging.error("Demo could not run. Check the Chromium and Tesseract installation and output folder.")
44
+ return 2
45
+
46
+ failures = {(result.role, result.rule_id, result.check_type) for result in results if result.status == "fail"}
47
+ expected_count = len(contract.scenarios) * sum(len(rule.roles) for rule in contract.rules) * 3
48
+ if len(results) != expected_count or failures != _EXPECTED_FAILURES or any(
49
+ result.status == "inconclusive" for result in results
50
+ ):
51
+ logging.error("Demo results differed from the expected synthetic outcomes.")
52
+ return 1
53
+ return 0
vac/demo_fixture.py ADDED
@@ -0,0 +1,86 @@
1
+ """Loopback-only synthetic app for the packaged demo."""
2
+
3
+ from collections.abc import Iterator
4
+ from contextlib import contextmanager
5
+ from html import escape
6
+ from http.cookies import SimpleCookie
7
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
8
+ import json
9
+ from threading import Thread
10
+
11
+ from vac.contract import Contract
12
+
13
+
14
+ def _mask(value: str) -> str:
15
+ return "XXXX-" + value[-4:]
16
+
17
+
18
+ def _account_page(role: str, account: str, reference: str) -> str:
19
+ reference_text = _mask(reference) if role != "admin" else reference
20
+ visual = f"<span>{escape(reference_text)}</span>"
21
+ if role == "viewer":
22
+ label = json.dumps(f"Reference {reference}")
23
+ visual = (
24
+ '<canvas id="reference-canvas" width="520" height="64"></canvas>'
25
+ '<script>const ctx = document.querySelector("#reference-canvas").getContext("2d");'
26
+ 'ctx.fillStyle = "white"; ctx.fillRect(0, 0, 520, 64);'
27
+ 'ctx.fillStyle = "black"; ctx.font = "28px monospace";'
28
+ f'ctx.fillText({label}, 12, 40);</script>'
29
+ )
30
+ shown_account = account if role == "admin" else _mask(account)
31
+ return (
32
+ '<!doctype html><html lang="en"><meta charset="utf-8"><title>Synthetic accounts</title>'
33
+ '<body style="font:26px monospace;color:black;background:white">'
34
+ f'<div id="account-number">Account {escape(shown_account)}</div>'
35
+ f'<div id="reference-number">Reference {escape(reference_text)}</div>'
36
+ f'<div id="reference-visual">{visual}</div></body></html>'
37
+ )
38
+
39
+
40
+ @contextmanager
41
+ def serve(contract: Contract) -> Iterator[str]:
42
+ """Bind an ephemeral port and always stop the fixture when the run ends."""
43
+ fields = {rule.field: rule.full for rule in contract.rules}
44
+ account = fields["account_number"]
45
+ reference = fields["reference_number"]
46
+
47
+ class Handler(BaseHTTPRequestHandler):
48
+ def do_GET(self) -> None:
49
+ cookies = SimpleCookie(self.headers.get("Cookie", ""))
50
+ cookie = cookies.get("vac_demo")
51
+ role = cookie.value if cookie else None
52
+ if role not in contract.roles:
53
+ self.send_error(401)
54
+ return
55
+ if self.path == "/identity":
56
+ self.reply(json.dumps({"role": role}), "application/json")
57
+ elif self.path == "/accounts":
58
+ self.reply(_account_page(role, account, reference), "text/html")
59
+ elif self.path == "/api/accounts":
60
+ self.reply(json.dumps({
61
+ "account_number": account if role in {"admin", "support_agent"} else _mask(account),
62
+ "reference_number": reference if role == "admin" else _mask(reference),
63
+ }), "application/json")
64
+ else:
65
+ self.send_error(404)
66
+
67
+ def reply(self, body: str, media_type: str) -> None:
68
+ payload = body.encode("utf-8")
69
+ self.send_response(200)
70
+ self.send_header("Content-Type", f"{media_type}; charset=utf-8")
71
+ self.send_header("Content-Length", str(len(payload)))
72
+ self.end_headers()
73
+ self.wfile.write(payload)
74
+
75
+ def log_message(self, *_args: object) -> None:
76
+ # The runner reports outcomes without logging requests or bodies.
77
+ return
78
+
79
+ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
80
+ thread = Thread(target=server.serve_forever, daemon=True)
81
+ thread.start()
82
+ try:
83
+ yield f"http://127.0.0.1:{server.server_port}"
84
+ finally:
85
+ server.shutdown()
86
+ thread.join()
vac/html_report.py ADDED
@@ -0,0 +1,92 @@
1
+ """Self-contained HTML evidence for selected checks."""
2
+
3
+ from collections import Counter, defaultdict
4
+ from html import escape
5
+ from pathlib import Path
6
+ import re
7
+
8
+ from checks.structured_check import CheckResult
9
+ from vac.contract import Contract
10
+
11
+ _CHECKS = {"structured": "API", "structured_dom": "DOM", "visual": "OCR"}
12
+ _STATUSES = {"pass": "Pass", "fail": "Fail", "inconclusive": "Inconclusive"}
13
+ _REDACTED_MATCH = re.compile(r"\*+[0-9]{4}")
14
+
15
+
16
+ def _cell(result: CheckResult | None) -> str:
17
+ if result is None:
18
+ return "<td>—</td>"
19
+ status = result.status
20
+ return f'<td class="{status}">{_STATUSES[status]}</td>'
21
+
22
+
23
+ def _ocr_matches(result: CheckResult) -> str:
24
+ # Retain only the match already masked by the OCR check. Discard other
25
+ # page text and reject anything that does not have the expected shape.
26
+ matches = dict.fromkeys(value for value in result.found_values if _REDACTED_MATCH.fullmatch(value))
27
+ return ", ".join(matches) or "[redacted]"
28
+
29
+
30
+ def write_html_report(results: list[CheckResult], contract: Contract, destination: Path) -> None:
31
+ """Render the check matrix and redacted OCR matches without raw capture data."""
32
+ fields = {rule.id: rule.field for rule in contract.rules}
33
+ counts = Counter(result.status for result in results)
34
+ grouped = defaultdict(dict)
35
+ for result in results:
36
+ grouped[(result.case, result.role, result.rule_id)][result.check_type] = result
37
+
38
+ rows = []
39
+ evidence = []
40
+ for (scenario, role, rule_id), checks in grouped.items():
41
+ field = fields[rule_id]
42
+ rows.append(
43
+ f"<tr><td>{escape(scenario)}</td><td>{escape(role)}</td>"
44
+ f"<th scope='row'>{escape(field)}</th>"
45
+ + "".join(_cell(checks.get(kind)) for kind in _CHECKS)
46
+ + "</tr>"
47
+ )
48
+ for kind, result in checks.items():
49
+ if result.status != "fail":
50
+ continue
51
+ ocr = f"<p>Redacted OCR match <code>{escape(_ocr_matches(result))}</code></p>" if kind == "visual" else ""
52
+ evidence.append(
53
+ f"<li><strong>{_CHECKS[kind]} · {escape(field)}</strong>"
54
+ f"<p>{escape(role)} · {escape(scenario)} · {escape(rule_id)}</p>{ocr}</li>"
55
+ )
56
+
57
+ findings = "<ul>" + "".join(evidence) + "</ul>" if evidence else "<p>No selected check reported a violation.</p>"
58
+ summary = " · ".join(f"{counts[key]} {label.lower()}" for key, label in _STATUSES.items())
59
+ content = f"""<!doctype html>
60
+ <html lang="en">
61
+ <meta charset="utf-8">
62
+ <meta name="viewport" content="width=device-width, initial-scale=1">
63
+ <title>Visual Access Contract | Evidence report</title>
64
+ <style>
65
+ body {{font:16px/1.5 system-ui,sans-serif;color:#16232d;background:#f5f8fa;margin:0}}
66
+ main {{max-width:72rem;margin:auto;padding:2rem}}
67
+ h1,h2 {{line-height:1.2}} table {{border-collapse:collapse;width:100%;background:white}}
68
+ th,td {{padding:.65rem;text-align:left;border-bottom:1px solid #c9d5dc}}
69
+ thead {{background:#e4eef4}} .pass {{color:#116446}} .fail {{color:#a22536}}
70
+ .inconclusive {{color:#7b4b08}} .pass,.fail,.inconclusive {{font-weight:650}}
71
+ section {{margin-top:2rem}} li {{margin-bottom:1rem}} li p {{margin:.15rem 0}}
72
+ .table-wrap {{overflow-x:auto}} code {{background:#e4eef4;padding:.15rem .35rem}}
73
+ </style>
74
+ <main>
75
+ <h1>Visual Access Contract</h1>
76
+ <p>Synthetic evidence report · Selected API, DOM, and OCR checks</p>
77
+ <p><strong>{summary}</strong></p>
78
+ <section aria-labelledby="matrix">
79
+ <h2 id="matrix">Results by role and field</h2>
80
+ <div class="table-wrap"><table>
81
+ <thead><tr><th scope="col">Scenario</th><th scope="col">Role</th><th scope="col">Field</th>
82
+ <th scope="col">API</th><th scope="col">DOM</th><th scope="col">OCR</th></tr></thead>
83
+ <tbody>{''.join(rows)}</tbody>
84
+ </table></div>
85
+ </section>
86
+ <section aria-labelledby="evidence"><h2 id="evidence">Failed checks and evidence</h2>
87
+ {findings}
88
+ </section>
89
+ </main>
90
+ </html>
91
+ """
92
+ destination.write_text(content, encoding="utf-8")
vac/output.py ADDED
@@ -0,0 +1,71 @@
1
+ """Machine-readable reports with metadata-only evidence."""
2
+
3
+ from hashlib import sha256
4
+ import json
5
+ from pathlib import Path
6
+ from urllib.parse import quote
7
+
8
+ from checks.structured_check import CheckResult
9
+ from evidence.reporter import format_ci_annotation, summarize_cases
10
+ from vac.contract import Contract
11
+
12
+
13
+ def write_reports(
14
+ results: list[CheckResult], contract: Contract, contract_uri: str, report: Path | None, sarif: Path,
15
+ ) -> None:
16
+ annotations = []
17
+ for result in results:
18
+ item = format_ci_annotation(result)
19
+ item.pop("found_values_redacted", None)
20
+ annotations.append(item)
21
+
22
+ by_role = {
23
+ role: {
24
+ rule.id: summarize_cases([
25
+ item for item in annotations if item["role"] == role and item["rule_id"] == rule.id
26
+ ])
27
+ for rule in contract.rules if role in rule.roles
28
+ }
29
+ for role in contract.roles
30
+ }
31
+ payload = {"schema_version": "1.0", "annotations": annotations, "by_role": by_role}
32
+ if report is not None:
33
+ report.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
34
+ sarif.write_text(json.dumps(_sarif(results, contract, contract_uri), indent=2) + "\n", encoding="utf-8")
35
+ if report is None:
36
+ print(json.dumps(payload, separators=(",", ":")), flush=True)
37
+
38
+
39
+ def _sarif(results: list[CheckResult], contract: Contract, contract_uri: str) -> dict:
40
+ location = {
41
+ "physicalLocation": {"artifactLocation": {"uri": quote(contract_uri, safe="/")}, "region": {"startLine": 1}}
42
+ }
43
+ findings = []
44
+ for result in results:
45
+ if result.status != "fail":
46
+ continue
47
+ key = "::".join((contract_uri, result.rule_id, result.role, result.case, result.check_type))
48
+ findings.append({
49
+ "ruleId": result.rule_id,
50
+ "level": "error",
51
+ "message": {"text": (
52
+ f"Masking violation for role {result.role}, scenario {result.case}, "
53
+ f"selected check {result.check_type}."
54
+ )},
55
+ "locations": [location],
56
+ "partialFingerprints": {"vacFindingFingerprint/v1": sha256(key.encode()).hexdigest()},
57
+ "properties": {"role": result.role, "scenario": result.case, "check": result.check_type},
58
+ })
59
+
60
+ return {
61
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
62
+ "version": "2.1.0",
63
+ "runs": [{
64
+ "tool": {"driver": {
65
+ "name": "Visual Access Contract",
66
+ "rules": [{"id": rule.id, "shortDescription": {"text": f"Masking policy for {rule.field}"}}
67
+ for rule in contract.rules],
68
+ }},
69
+ "results": findings,
70
+ }],
71
+ }