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.
- checks/__init__.py +0 -0
- checks/structured_check.py +175 -0
- checks/visual_check.py +163 -0
- evidence/__init__.py +0 -0
- evidence/reporter.py +148 -0
- vac/__init__.py +0 -0
- vac/__main__.py +40 -0
- vac/cli.py +98 -0
- vac/contract.py +256 -0
- vac/demo-contract.yaml +46 -0
- vac/demo.py +53 -0
- vac/demo_fixture.py +86 -0
- vac/html_report.py +92 -0
- vac/output.py +71 -0
- vac/runner.py +151 -0
- vac/session.py +63 -0
- visual_access_contract-0.2.1.dist-info/METADATA +146 -0
- visual_access_contract-0.2.1.dist-info/RECORD +22 -0
- visual_access_contract-0.2.1.dist-info/WHEEL +5 -0
- visual_access_contract-0.2.1.dist-info/entry_points.txt +2 -0
- visual_access_contract-0.2.1.dist-info/licenses/LICENSE +202 -0
- visual_access_contract-0.2.1.dist-info/top_level.txt +3 -0
checks/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Structured Data Check (Check 1)
|
|
3
|
+
Inspects the API response and page DOM for field values that violate
|
|
4
|
+
the access contract. No vision — pure text/data matching.
|
|
5
|
+
|
|
6
|
+
Returns a CheckResult with pass/fail and what was found.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class CheckResult:
|
|
16
|
+
check_type: str
|
|
17
|
+
case: str
|
|
18
|
+
role: str
|
|
19
|
+
rule_id: str
|
|
20
|
+
status: str # "pass", "fail", "inconclusive"
|
|
21
|
+
detail: str
|
|
22
|
+
found_values: list = field(default_factory=list)
|
|
23
|
+
inspected_sources: list = field(default_factory=list)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_patterns(contract_rule: dict) -> list:
|
|
27
|
+
"""Build regex patterns from the synthetic values in the contract.
|
|
28
|
+
|
|
29
|
+
For a masked rule, we look for the FULL value — if it's present,
|
|
30
|
+
the check fails. We also verify the masked/last-4 value is present
|
|
31
|
+
where expected.
|
|
32
|
+
"""
|
|
33
|
+
full_value = contract_rule["synthetic_values"]["full"]
|
|
34
|
+
# Escape for regex and allow flexible separators (dash, space, none)
|
|
35
|
+
digits = re.sub(r"[^0-9]", "", full_value)
|
|
36
|
+
# Match the full number with any separator style
|
|
37
|
+
flexible = r"[\s\-\.]*".join(digits)
|
|
38
|
+
return [re.compile(flexible)]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_api_response(
|
|
42
|
+
response_body: str,
|
|
43
|
+
contract_rule: dict,
|
|
44
|
+
role: str,
|
|
45
|
+
case: str,
|
|
46
|
+
) -> CheckResult:
|
|
47
|
+
"""Check whether the API response contains a value that violates
|
|
48
|
+
the contract for the given role."""
|
|
49
|
+
|
|
50
|
+
rule_id = contract_rule["id"]
|
|
51
|
+
role_config = contract_rule["roles"].get(role)
|
|
52
|
+
|
|
53
|
+
if not role_config:
|
|
54
|
+
return CheckResult(
|
|
55
|
+
check_type="structured",
|
|
56
|
+
case=case,
|
|
57
|
+
role=role,
|
|
58
|
+
rule_id=rule_id,
|
|
59
|
+
status="inconclusive",
|
|
60
|
+
detail=f"Role '{role}' not defined in contract rule {rule_id}",
|
|
61
|
+
inspected_sources=["api_response"],
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if role_config["visibility"] == "full":
|
|
65
|
+
# This role is allowed to see everything — always passes
|
|
66
|
+
return CheckResult(
|
|
67
|
+
check_type="structured",
|
|
68
|
+
case=case,
|
|
69
|
+
role=role,
|
|
70
|
+
rule_id=rule_id,
|
|
71
|
+
status="pass",
|
|
72
|
+
detail="Role has full visibility — no restriction to enforce",
|
|
73
|
+
inspected_sources=["api_response"],
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# Role should see masked only — check if full value is present
|
|
77
|
+
patterns = build_patterns(contract_rule)
|
|
78
|
+
full_value = contract_rule["synthetic_values"]["full"]
|
|
79
|
+
found = []
|
|
80
|
+
|
|
81
|
+
for pattern in patterns:
|
|
82
|
+
matches = pattern.findall(response_body)
|
|
83
|
+
for match in matches:
|
|
84
|
+
found.append(match)
|
|
85
|
+
|
|
86
|
+
if found:
|
|
87
|
+
return CheckResult(
|
|
88
|
+
check_type="structured",
|
|
89
|
+
case=case,
|
|
90
|
+
role=role,
|
|
91
|
+
rule_id=rule_id,
|
|
92
|
+
status="fail",
|
|
93
|
+
detail=(
|
|
94
|
+
f"Full value found in API response for role '{role}' "
|
|
95
|
+
f"which should only see {role_config['visibility']} "
|
|
96
|
+
f"({role_config.get('mask_format', 'masked')})"
|
|
97
|
+
),
|
|
98
|
+
found_values=[_redact(v) for v in found],
|
|
99
|
+
inspected_sources=["api_response"],
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
return CheckResult(
|
|
103
|
+
check_type="structured",
|
|
104
|
+
case=case,
|
|
105
|
+
role=role,
|
|
106
|
+
rule_id=rule_id,
|
|
107
|
+
status="pass",
|
|
108
|
+
detail=f"Full value not found in API response — masking intact",
|
|
109
|
+
inspected_sources=["api_response"],
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def check_dom_text(
|
|
114
|
+
page_text: str,
|
|
115
|
+
contract_rule: dict,
|
|
116
|
+
role: str,
|
|
117
|
+
case: str,
|
|
118
|
+
) -> CheckResult:
|
|
119
|
+
"""Check whether visible DOM text contains a value that violates
|
|
120
|
+
the contract for the given role."""
|
|
121
|
+
|
|
122
|
+
rule_id = contract_rule["id"]
|
|
123
|
+
role_config = contract_rule["roles"].get(role)
|
|
124
|
+
|
|
125
|
+
if not role_config or role_config["visibility"] == "full":
|
|
126
|
+
return CheckResult(
|
|
127
|
+
check_type="structured_dom",
|
|
128
|
+
case=case,
|
|
129
|
+
role=role,
|
|
130
|
+
rule_id=rule_id,
|
|
131
|
+
status="pass",
|
|
132
|
+
detail="Role has full visibility or is undefined",
|
|
133
|
+
inspected_sources=["dom_text"],
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
patterns = build_patterns(contract_rule)
|
|
137
|
+
found = []
|
|
138
|
+
|
|
139
|
+
for pattern in patterns:
|
|
140
|
+
matches = pattern.findall(page_text)
|
|
141
|
+
for match in matches:
|
|
142
|
+
found.append(match)
|
|
143
|
+
|
|
144
|
+
if found:
|
|
145
|
+
return CheckResult(
|
|
146
|
+
check_type="structured_dom",
|
|
147
|
+
case=case,
|
|
148
|
+
role=role,
|
|
149
|
+
rule_id=rule_id,
|
|
150
|
+
status="fail",
|
|
151
|
+
detail=(
|
|
152
|
+
f"Full value found in DOM text for role '{role}' "
|
|
153
|
+
f"which should only see {role_config['visibility']}"
|
|
154
|
+
),
|
|
155
|
+
found_values=[_redact(v) for v in found],
|
|
156
|
+
inspected_sources=["dom_text"],
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return CheckResult(
|
|
160
|
+
check_type="structured_dom",
|
|
161
|
+
case=case,
|
|
162
|
+
role=role,
|
|
163
|
+
rule_id=rule_id,
|
|
164
|
+
status="pass",
|
|
165
|
+
detail="Full value not found in visible DOM text",
|
|
166
|
+
inspected_sources=["dom_text"],
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _redact(value: str) -> str:
|
|
171
|
+
"""Redact a found value for the evidence report.
|
|
172
|
+
Keep only the last 4 characters visible."""
|
|
173
|
+
if len(value) <= 4:
|
|
174
|
+
return value
|
|
175
|
+
return "*" * (len(value) - 4) + value[-4:]
|
checks/visual_check.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Visual Rendering Check (Check 2)
|
|
3
|
+
Captures a screenshot of the page region and runs OCR to detect
|
|
4
|
+
field values rendered as pixels (canvas, charts, images) that
|
|
5
|
+
the structured check cannot see.
|
|
6
|
+
|
|
7
|
+
Uses the Tesseract OCR command-line program. Falls back to 'inconclusive'
|
|
8
|
+
if OCR cannot read the region or Tesseract is not installed.
|
|
9
|
+
|
|
10
|
+
Returns a CheckResult with pass/fail/inconclusive and what was found.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import io
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Optional
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from checks.structured_check import CheckResult
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _tesseract_available() -> bool:
|
|
24
|
+
"""Check if Tesseract is installed and accessible."""
|
|
25
|
+
try:
|
|
26
|
+
result = subprocess.run(
|
|
27
|
+
["tesseract", "--version"],
|
|
28
|
+
capture_output=True,
|
|
29
|
+
timeout=5,
|
|
30
|
+
)
|
|
31
|
+
return result.returncode == 0
|
|
32
|
+
except (FileNotFoundError, subprocess.TimeoutExpired):
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def ocr_from_image(image_path: str) -> Optional[str]:
|
|
37
|
+
"""Run Tesseract OCR on an image file and return extracted text.
|
|
38
|
+
Returns None if OCR fails or is unavailable."""
|
|
39
|
+
if not _tesseract_available():
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
result = subprocess.run(
|
|
44
|
+
["tesseract", image_path, "stdout", "--psm", "6"],
|
|
45
|
+
capture_output=True,
|
|
46
|
+
text=True,
|
|
47
|
+
timeout=30,
|
|
48
|
+
)
|
|
49
|
+
if result.returncode == 0:
|
|
50
|
+
return result.stdout.strip()
|
|
51
|
+
return None
|
|
52
|
+
except (subprocess.TimeoutExpired, Exception):
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def ocr_from_png_bytes(png_bytes: bytes) -> Optional[str]:
|
|
57
|
+
"""Run Tesseract OCR on PNG bytes via stdin.
|
|
58
|
+
Returns None if OCR fails or is unavailable."""
|
|
59
|
+
if not _tesseract_available():
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
try:
|
|
63
|
+
result = subprocess.run(
|
|
64
|
+
["tesseract", "stdin", "stdout", "--psm", "6"],
|
|
65
|
+
input=png_bytes,
|
|
66
|
+
capture_output=True,
|
|
67
|
+
timeout=30,
|
|
68
|
+
)
|
|
69
|
+
if result.returncode == 0:
|
|
70
|
+
return result.stdout.decode('utf-8').strip()
|
|
71
|
+
return None
|
|
72
|
+
except (OSError, subprocess.TimeoutExpired, UnicodeDecodeError):
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def check_visual_region(
|
|
77
|
+
ocr_text: Optional[str],
|
|
78
|
+
contract_rule: dict,
|
|
79
|
+
role: str,
|
|
80
|
+
case: str,
|
|
81
|
+
region_description: str = "visual_region",
|
|
82
|
+
) -> CheckResult:
|
|
83
|
+
"""Check whether OCR-extracted text from a visual region contains
|
|
84
|
+
a value that violates the contract for the given role.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
ocr_text: Text extracted by OCR, or None if OCR failed.
|
|
88
|
+
contract_rule: The contract rule to check against.
|
|
89
|
+
role: The role being checked.
|
|
90
|
+
case: The test case identifier.
|
|
91
|
+
region_description: Human-readable description of what was scanned.
|
|
92
|
+
"""
|
|
93
|
+
rule_id = contract_rule["id"]
|
|
94
|
+
role_config = contract_rule["roles"].get(role)
|
|
95
|
+
|
|
96
|
+
if not role_config or role_config["visibility"] == "full":
|
|
97
|
+
return CheckResult(
|
|
98
|
+
check_type="visual",
|
|
99
|
+
case=case,
|
|
100
|
+
role=role,
|
|
101
|
+
rule_id=rule_id,
|
|
102
|
+
status="pass",
|
|
103
|
+
detail="Role has full visibility or is undefined",
|
|
104
|
+
inspected_sources=[region_description],
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if ocr_text is None:
|
|
108
|
+
return CheckResult(
|
|
109
|
+
check_type="visual",
|
|
110
|
+
case=case,
|
|
111
|
+
role=role,
|
|
112
|
+
rule_id=rule_id,
|
|
113
|
+
status="inconclusive",
|
|
114
|
+
detail=f"OCR could not read the region: {region_description}",
|
|
115
|
+
inspected_sources=[region_description],
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# Build patterns to find the full value
|
|
119
|
+
full_value = contract_rule["synthetic_values"]["full"]
|
|
120
|
+
digits = re.sub(r"[^0-9]", "", full_value)
|
|
121
|
+
# OCR may introduce spaces, dashes, or miss separators
|
|
122
|
+
# Allow flexible matching with any separator or none
|
|
123
|
+
flexible = r"[\s\-\.]*".join(digits)
|
|
124
|
+
pattern = re.compile(flexible)
|
|
125
|
+
|
|
126
|
+
found = []
|
|
127
|
+
matches = pattern.findall(ocr_text)
|
|
128
|
+
for match in matches:
|
|
129
|
+
found.append(match)
|
|
130
|
+
|
|
131
|
+
if found:
|
|
132
|
+
return CheckResult(
|
|
133
|
+
check_type="visual",
|
|
134
|
+
case=case,
|
|
135
|
+
role=role,
|
|
136
|
+
rule_id=rule_id,
|
|
137
|
+
status="fail",
|
|
138
|
+
detail=(
|
|
139
|
+
f"Full value found via OCR in {region_description} "
|
|
140
|
+
f"for role '{role}' which should only see "
|
|
141
|
+
f"{role_config['visibility']} "
|
|
142
|
+
f"({role_config.get('mask_format', 'masked')})"
|
|
143
|
+
),
|
|
144
|
+
found_values=[_redact(v) for v in found],
|
|
145
|
+
inspected_sources=[region_description],
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
return CheckResult(
|
|
149
|
+
check_type="visual",
|
|
150
|
+
case=case,
|
|
151
|
+
role=role,
|
|
152
|
+
rule_id=rule_id,
|
|
153
|
+
status="pass",
|
|
154
|
+
detail=f"Full value not found via OCR in {region_description}",
|
|
155
|
+
inspected_sources=[region_description],
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _redact(value: str) -> str:
|
|
160
|
+
"""Redact a found value for the evidence report."""
|
|
161
|
+
if len(value) <= 4:
|
|
162
|
+
return value
|
|
163
|
+
return "*" * (len(value) - 4) + value[-4:]
|
evidence/__init__.py
ADDED
|
File without changes
|
evidence/reporter.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Evidence Reporter
|
|
3
|
+
Generates CI annotations from check results.
|
|
4
|
+
Raw screenshots stay in memory and are never written to disk or CI artifacts.
|
|
5
|
+
Visual evidence references point to redacted text files.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def format_ci_annotation(result, screenshot_path: Optional[str] = None) -> dict:
|
|
14
|
+
"""Format a check result as a CI annotation.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
result: A CheckResult from either check.
|
|
18
|
+
screenshot_path: Path to a redacted crop (already redacted),
|
|
19
|
+
or None if no visual evidence was captured.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
A dict suitable for JSON serialisation as a CI annotation.
|
|
23
|
+
"""
|
|
24
|
+
annotation = {
|
|
25
|
+
"tool": "visual-access-contract",
|
|
26
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
27
|
+
"mode": "reporting", # reporting mode — no blocking
|
|
28
|
+
"rule_id": result.rule_id,
|
|
29
|
+
"check_type": result.check_type,
|
|
30
|
+
"role": result.role,
|
|
31
|
+
"case": result.case,
|
|
32
|
+
"status": result.status,
|
|
33
|
+
"detail": result.detail,
|
|
34
|
+
"inspected_sources": result.inspected_sources,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if result.found_values:
|
|
38
|
+
# Values are already redacted by the check modules
|
|
39
|
+
annotation["found_values_redacted"] = result.found_values
|
|
40
|
+
|
|
41
|
+
if screenshot_path:
|
|
42
|
+
annotation["evidence_crop"] = screenshot_path
|
|
43
|
+
|
|
44
|
+
return annotation
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def summarize_cases(annotations: list) -> dict:
|
|
48
|
+
"""Count failed checks and distinct cases for each check group."""
|
|
49
|
+
group_by_type = {
|
|
50
|
+
"structured": "structured",
|
|
51
|
+
"structured_dom": "structured",
|
|
52
|
+
"visual": "visual",
|
|
53
|
+
}
|
|
54
|
+
outcomes = {"structured": {}, "visual": {}}
|
|
55
|
+
for annotation in annotations:
|
|
56
|
+
group = group_by_type.get(annotation["check_type"])
|
|
57
|
+
if group is not None:
|
|
58
|
+
case = annotation["case"].upper()
|
|
59
|
+
outcomes[group].setdefault(case, []).append(annotation["status"])
|
|
60
|
+
|
|
61
|
+
summary = {}
|
|
62
|
+
for group, cases in outcomes.items():
|
|
63
|
+
failures = {
|
|
64
|
+
case: statuses.count("fail")
|
|
65
|
+
for case, statuses in sorted(cases.items())
|
|
66
|
+
if "fail" in statuses
|
|
67
|
+
}
|
|
68
|
+
summary[group] = {
|
|
69
|
+
"cases_flagged": len(failures),
|
|
70
|
+
"flagged_cases": list(failures),
|
|
71
|
+
"individual_check_failures": sum(failures.values()),
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
# A catch is unique only when the other group ran and all its checks passed.
|
|
75
|
+
summary["unique_catches"] = {
|
|
76
|
+
group: [
|
|
77
|
+
case for case in summary[group]["flagged_cases"]
|
|
78
|
+
if set(outcomes[other].get(case, ())) == {"pass"}
|
|
79
|
+
]
|
|
80
|
+
for group, other in (("structured", "visual"), ("visual", "structured"))
|
|
81
|
+
}
|
|
82
|
+
return summary
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def print_ci_report(annotations: list) -> None:
|
|
86
|
+
"""Print a human-readable CI report to stdout."""
|
|
87
|
+
print("\n" + "=" * 70)
|
|
88
|
+
print(" VISUAL ACCESS CONTRACT — CI Report (Reporting Mode)")
|
|
89
|
+
print("=" * 70)
|
|
90
|
+
|
|
91
|
+
# --- Individual check results ---
|
|
92
|
+
print("\n Individual check results")
|
|
93
|
+
print(" " + "-" * 50)
|
|
94
|
+
|
|
95
|
+
for a in annotations:
|
|
96
|
+
icon = {"pass": "PASS", "fail": "FAIL", "inconclusive": " ? "}[a["status"]]
|
|
97
|
+
print(f"\n [{icon}] {a['check_type']:>16} | case={a['case']} "
|
|
98
|
+
f"role={a['role']} rule={a['rule_id']}")
|
|
99
|
+
print(f" {a['detail']}")
|
|
100
|
+
if a.get("found_values_redacted"):
|
|
101
|
+
print(f" found (redacted): {a['found_values_redacted']}")
|
|
102
|
+
if a.get("evidence_crop"):
|
|
103
|
+
print(f" evidence: {a['evidence_crop']}")
|
|
104
|
+
|
|
105
|
+
pass_count = sum(1 for a in annotations if a["status"] == "pass")
|
|
106
|
+
fail_count = sum(1 for a in annotations if a["status"] == "fail")
|
|
107
|
+
inconclusive_count = sum(1 for a in annotations if a["status"] == "inconclusive")
|
|
108
|
+
|
|
109
|
+
print(f"\n Totals: {pass_count} pass, {fail_count} fail, "
|
|
110
|
+
f"{inconclusive_count} inconclusive")
|
|
111
|
+
|
|
112
|
+
summary = summarize_cases(annotations)
|
|
113
|
+
print("\n Cases flagged and individual check failures")
|
|
114
|
+
print(" " + "-" * 50)
|
|
115
|
+
labels = {"structured": "Structured (API + DOM)", "visual": "Visual (OCR)"}
|
|
116
|
+
for group, label in labels.items():
|
|
117
|
+
result = summary[group]
|
|
118
|
+
cases = ", ".join(result["flagged_cases"])
|
|
119
|
+
case_list = f" ({cases})" if cases else ""
|
|
120
|
+
print(
|
|
121
|
+
f" {label}: {result['cases_flagged']} cases flagged{case_list}, "
|
|
122
|
+
f"{result['individual_check_failures']} individual check failures"
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
print("\n Unique catches")
|
|
126
|
+
for group, label in labels.items():
|
|
127
|
+
cases = ", ".join(summary["unique_catches"][group]) or "None"
|
|
128
|
+
print(f" {label}: {cases}")
|
|
129
|
+
|
|
130
|
+
print("=" * 70 + "\n")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def write_json_report(annotations: list, output_path: str) -> None:
|
|
134
|
+
"""Write annotations as a JSON report file."""
|
|
135
|
+
report = {
|
|
136
|
+
"tool": "visual-access-contract",
|
|
137
|
+
"schema_version": "0.1",
|
|
138
|
+
"mode": "reporting",
|
|
139
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
140
|
+
"total": len(annotations),
|
|
141
|
+
"pass": sum(1 for a in annotations if a["status"] == "pass"),
|
|
142
|
+
"fail": sum(1 for a in annotations if a["status"] == "fail"),
|
|
143
|
+
"inconclusive": sum(1 for a in annotations if a["status"] == "inconclusive"),
|
|
144
|
+
"summary": summarize_cases(annotations),
|
|
145
|
+
"annotations": annotations,
|
|
146
|
+
}
|
|
147
|
+
with open(output_path, "w") as f:
|
|
148
|
+
json.dump(report, f, indent=2)
|
vac/__init__.py
ADDED
|
File without changes
|
vac/__main__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Command-line entry point for the installed VAC package."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from vac.contract import ContractError, validate_contract
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main(argv: list[str] | None = None) -> int:
|
|
11
|
+
parser = argparse.ArgumentParser(prog="vac")
|
|
12
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
13
|
+
commands.add_parser("demo", help="Run the bundled synthetic application")
|
|
14
|
+
commands.add_parser("check", add_help=False, help="Run a configured contract")
|
|
15
|
+
validate = commands.add_parser("validate", help="Check contract syntax and schema offline")
|
|
16
|
+
validate.add_argument("--contract", type=Path, required=True)
|
|
17
|
+
|
|
18
|
+
args = sys.argv[1:] if argv is None else argv
|
|
19
|
+
if args and args[0] == "check":
|
|
20
|
+
from vac import cli
|
|
21
|
+
|
|
22
|
+
return cli.main(args[1:])
|
|
23
|
+
|
|
24
|
+
options = parser.parse_args(args)
|
|
25
|
+
if options.command == "validate":
|
|
26
|
+
try:
|
|
27
|
+
version = validate_contract(options.contract)
|
|
28
|
+
except ContractError as exc:
|
|
29
|
+
print(f"Invalid contract: {exc}", file=sys.stderr)
|
|
30
|
+
return 2
|
|
31
|
+
print(f"Valid contract (schema {version})")
|
|
32
|
+
return 0
|
|
33
|
+
|
|
34
|
+
from vac import demo
|
|
35
|
+
|
|
36
|
+
return demo.main()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
raise SystemExit(main())
|
vac/cli.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Run VAC against an explicitly scoped synthetic test environment."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from playwright.async_api import Error
|
|
11
|
+
|
|
12
|
+
from vac.contract import ContractError, load_contract
|
|
13
|
+
from vac.html_report import write_html_report
|
|
14
|
+
from vac.output import write_reports
|
|
15
|
+
from vac.runner import run
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _watch(args: argparse.Namespace) -> int:
|
|
19
|
+
logging.info("Watching contract for changes. Press Ctrl-C to stop.")
|
|
20
|
+
previous = None
|
|
21
|
+
latest_status = 2
|
|
22
|
+
try:
|
|
23
|
+
while True:
|
|
24
|
+
try:
|
|
25
|
+
snapshot = (True, args.contract.read_bytes())
|
|
26
|
+
except OSError:
|
|
27
|
+
snapshot = (False, b"")
|
|
28
|
+
if snapshot != previous:
|
|
29
|
+
previous = snapshot
|
|
30
|
+
logging.info("Running selected checks for the current contract.")
|
|
31
|
+
latest_status = _run_once(args)
|
|
32
|
+
if latest_status == 2:
|
|
33
|
+
logging.info("Check setup failed. Existing report files may reflect an earlier run.")
|
|
34
|
+
time.sleep(0.5)
|
|
35
|
+
except KeyboardInterrupt:
|
|
36
|
+
logging.info("Stopped watching.")
|
|
37
|
+
return latest_status
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(argv: list[str] | None = None) -> int:
|
|
41
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
42
|
+
parser.add_argument("--contract", type=Path, required=True)
|
|
43
|
+
parser.add_argument("--report", type=Path, default=Path("vac-results.json"),
|
|
44
|
+
help="Write JSON to this file unless --json-stdout is set")
|
|
45
|
+
parser.add_argument("--json-stdout", action="store_true", help="Stream the JSON report to stdout")
|
|
46
|
+
parser.add_argument("--quiet", action="store_true", help="Print only the summary and exit code to stderr")
|
|
47
|
+
parser.add_argument("--sarif", type=Path, default=Path("vac-results.sarif"))
|
|
48
|
+
parser.add_argument("--html", type=Path, nargs="?", const=Path("vac-results.html"),
|
|
49
|
+
help="Write a self-contained HTML report, optionally to a custom path")
|
|
50
|
+
parser.add_argument("--enforce", action="store_true", help="Fail on violations or inconclusive checks")
|
|
51
|
+
parser.add_argument("--watch", action="store_true", help="Rerun when the contract changes")
|
|
52
|
+
args = parser.parse_args(argv)
|
|
53
|
+
logging.basicConfig(
|
|
54
|
+
level=logging.WARNING if args.quiet else logging.INFO,
|
|
55
|
+
format="%(levelname)s %(name)s %(message)s",
|
|
56
|
+
)
|
|
57
|
+
return _watch(args) if args.watch else _run_once(args)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _run_once(args: argparse.Namespace) -> int:
|
|
61
|
+
try:
|
|
62
|
+
contract_path = args.contract.resolve()
|
|
63
|
+
contract_uri = contract_path.relative_to(Path.cwd()).as_posix()
|
|
64
|
+
report = None if args.json_stdout else args.report
|
|
65
|
+
outputs = [path for path in (report, args.sarif, args.html) if path is not None]
|
|
66
|
+
output_paths = {path.resolve() for path in outputs}
|
|
67
|
+
if len(output_paths) != len(outputs) or contract_path in output_paths:
|
|
68
|
+
raise ContractError("Choose distinct output paths away from the contract")
|
|
69
|
+
contract = load_contract(contract_path)
|
|
70
|
+
results = asyncio.run(run(contract))
|
|
71
|
+
if args.html is not None:
|
|
72
|
+
write_html_report(results, contract, args.html)
|
|
73
|
+
write_reports(results, contract, contract_uri, report, args.sarif)
|
|
74
|
+
except ContractError as exc:
|
|
75
|
+
return _run_error(args.quiet, f"Contract or session error: {exc}")
|
|
76
|
+
except (Error, OSError, ValueError):
|
|
77
|
+
return _run_error(args.quiet, "Run could not complete. Check the browser, paths and environment.")
|
|
78
|
+
counts = {status: sum(result.status == status for result in results)
|
|
79
|
+
for status in ("pass", "fail", "inconclusive")}
|
|
80
|
+
code = int(args.enforce and (counts["fail"] > 0 or counts["inconclusive"] > 0))
|
|
81
|
+
if args.quiet:
|
|
82
|
+
print(
|
|
83
|
+
f"VAC: {counts['pass']} pass, {counts['fail']} fail, "
|
|
84
|
+
f"{counts['inconclusive']} inconclusive (exit {code})",
|
|
85
|
+
file=sys.stderr,
|
|
86
|
+
flush=True,
|
|
87
|
+
)
|
|
88
|
+
else:
|
|
89
|
+
logging.info("Checks completed: %s (exit %d)", counts, code)
|
|
90
|
+
return code
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _run_error(quiet: bool, message: str) -> int:
|
|
94
|
+
if quiet:
|
|
95
|
+
print(f"VAC: {message} (exit 2)", file=sys.stderr, flush=True)
|
|
96
|
+
else:
|
|
97
|
+
logging.error("%s (exit 2)", message)
|
|
98
|
+
return 2
|