code-review-validator 0.1.0__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.
- code_review_validator/__init__.py +92 -0
- code_review_validator/_verify.py +48 -0
- code_review_validator/client.py +242 -0
- code_review_validator/errors.py +84 -0
- code_review_validator/gate.py +119 -0
- code_review_validator/models.py +106 -0
- code_review_validator/py.typed +0 -0
- code_review_validator-0.1.0.dist-info/METADATA +104 -0
- code_review_validator-0.1.0.dist-info/RECORD +12 -0
- code_review_validator-0.1.0.dist-info/WHEEL +5 -0
- code_review_validator-0.1.0.dist-info/licenses/LICENSE +21 -0
- code_review_validator-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Public SDK surface for code-review-validator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError
|
|
6
|
+
from importlib.metadata import version as _pkg_version
|
|
7
|
+
|
|
8
|
+
from .client import AsyncClient, SyncClient
|
|
9
|
+
from .errors import (
|
|
10
|
+
APIError,
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
BadRequestError,
|
|
13
|
+
ConnectionError,
|
|
14
|
+
CryptoNotAvailableError,
|
|
15
|
+
PaymentRequiredError,
|
|
16
|
+
RateLimitError,
|
|
17
|
+
ServiceUnavailableError,
|
|
18
|
+
TimeoutError,
|
|
19
|
+
ValidatorError,
|
|
20
|
+
)
|
|
21
|
+
from .gate import GateCheck, GatePolicy, GateResult, check_contract, evaluate
|
|
22
|
+
from .models import (
|
|
23
|
+
AttestationStatus,
|
|
24
|
+
EvidenceLevel,
|
|
25
|
+
Finding,
|
|
26
|
+
HealthResult,
|
|
27
|
+
OnChainStatus,
|
|
28
|
+
ReputationResult,
|
|
29
|
+
ReviewResult,
|
|
30
|
+
Severity,
|
|
31
|
+
StatsResult,
|
|
32
|
+
StatusResult,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
__version__ = _pkg_version("code-review-validator")
|
|
37
|
+
except PackageNotFoundError:
|
|
38
|
+
__version__ = "0.1.0"
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
from ._verify import canonical_serialize, decrypt_findings, verify_response_hash
|
|
42
|
+
except Exception as exc: # pragma: no cover - exercised via fallback wrappers
|
|
43
|
+
_CRYPTO_IMPORT_ERROR = exc
|
|
44
|
+
|
|
45
|
+
def _raise_crypto_error() -> None:
|
|
46
|
+
raise CryptoNotAvailableError(
|
|
47
|
+
"Crypto helpers require optional dependencies. Install with [crypto]."
|
|
48
|
+
) from _CRYPTO_IMPORT_ERROR
|
|
49
|
+
|
|
50
|
+
def canonical_serialize(data: dict) -> bytes: # type: ignore[override]
|
|
51
|
+
_raise_crypto_error()
|
|
52
|
+
|
|
53
|
+
def verify_response_hash(ipfs_payload: dict, on_chain_hash: str) -> bool: # type: ignore[override]
|
|
54
|
+
_raise_crypto_error()
|
|
55
|
+
|
|
56
|
+
def decrypt_findings(encrypted_payload: dict, private_key_hex: str) -> dict: # type: ignore[override]
|
|
57
|
+
_raise_crypto_error()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"APIError",
|
|
62
|
+
"AsyncClient",
|
|
63
|
+
"AttestationStatus",
|
|
64
|
+
"AuthenticationError",
|
|
65
|
+
"BadRequestError",
|
|
66
|
+
"ConnectionError",
|
|
67
|
+
"CryptoNotAvailableError",
|
|
68
|
+
"EvidenceLevel",
|
|
69
|
+
"Finding",
|
|
70
|
+
"GateCheck",
|
|
71
|
+
"GatePolicy",
|
|
72
|
+
"GateResult",
|
|
73
|
+
"HealthResult",
|
|
74
|
+
"OnChainStatus",
|
|
75
|
+
"PaymentRequiredError",
|
|
76
|
+
"RateLimitError",
|
|
77
|
+
"ReputationResult",
|
|
78
|
+
"ReviewResult",
|
|
79
|
+
"ServiceUnavailableError",
|
|
80
|
+
"Severity",
|
|
81
|
+
"StatsResult",
|
|
82
|
+
"StatusResult",
|
|
83
|
+
"SyncClient",
|
|
84
|
+
"TimeoutError",
|
|
85
|
+
"ValidatorError",
|
|
86
|
+
"__version__",
|
|
87
|
+
"canonical_serialize",
|
|
88
|
+
"check_contract",
|
|
89
|
+
"decrypt_findings",
|
|
90
|
+
"evaluate",
|
|
91
|
+
"verify_response_hash",
|
|
92
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Optional crypto helpers for payload verification and decryption."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from .errors import CryptoNotAvailableError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _normalize_hex(value: str) -> str:
|
|
11
|
+
return value.removeprefix("0x")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def canonical_serialize(data: dict) -> bytes:
|
|
15
|
+
"""Deterministic JSON encoding used for hashing."""
|
|
16
|
+
return json.dumps(data, sort_keys=True, separators=(",", ":")).encode()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def verify_response_hash(ipfs_payload: dict, on_chain_hash: str) -> bool:
|
|
20
|
+
"""Verify that payload hash matches on-chain response hash."""
|
|
21
|
+
try:
|
|
22
|
+
from web3 import Web3
|
|
23
|
+
except Exception as exc:
|
|
24
|
+
raise CryptoNotAvailableError(
|
|
25
|
+
"web3 is required for verify_response_hash. Install with [crypto]."
|
|
26
|
+
) from exc
|
|
27
|
+
|
|
28
|
+
computed = Web3.keccak(canonical_serialize(ipfs_payload)).hex()
|
|
29
|
+
return _normalize_hex(computed).lower() == _normalize_hex(on_chain_hash).lower()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def decrypt_findings(encrypted_payload: dict, private_key_hex: str) -> dict:
|
|
33
|
+
"""Decrypt findings payload using a secp256k1 private key."""
|
|
34
|
+
try:
|
|
35
|
+
import ecies
|
|
36
|
+
except Exception as exc:
|
|
37
|
+
raise CryptoNotAvailableError(
|
|
38
|
+
"eciespy is required for decrypt_findings. Install with [crypto]."
|
|
39
|
+
) from exc
|
|
40
|
+
|
|
41
|
+
encrypted_section = encrypted_payload.get("encrypted", encrypted_payload)
|
|
42
|
+
ciphertext_hex = encrypted_section.get("ciphertext")
|
|
43
|
+
if not isinstance(ciphertext_hex, str):
|
|
44
|
+
raise ValueError("encrypted payload is missing a hex ciphertext field")
|
|
45
|
+
|
|
46
|
+
ciphertext = bytes.fromhex(_normalize_hex(ciphertext_hex))
|
|
47
|
+
plaintext = ecies.decrypt(_normalize_hex(private_key_hex), ciphertext)
|
|
48
|
+
return json.loads(plaintext)
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""HTTP clients for the Code Review Validator API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from .errors import (
|
|
10
|
+
APIError,
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
BadRequestError,
|
|
13
|
+
ConnectionError,
|
|
14
|
+
PaymentRequiredError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
ServiceUnavailableError,
|
|
17
|
+
TimeoutError,
|
|
18
|
+
parse_error_detail,
|
|
19
|
+
)
|
|
20
|
+
from .models import HealthResult, ReputationResult, ReviewResult, StatsResult, StatusResult
|
|
21
|
+
|
|
22
|
+
_DEFAULT_BASE_URL = "https://code-review-validator.fly.dev"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _extract_remaining_reviews(headers: httpx.Headers) -> int | None:
|
|
26
|
+
value = headers.get("X-API-Key-Remaining") or headers.get("X-Free-Tier-Remaining")
|
|
27
|
+
if value is None:
|
|
28
|
+
return None
|
|
29
|
+
try:
|
|
30
|
+
return int(value)
|
|
31
|
+
except ValueError:
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _retry_after(headers: httpx.Headers) -> int | None:
|
|
36
|
+
raw = headers.get("Retry-After")
|
|
37
|
+
if raw is None:
|
|
38
|
+
return None
|
|
39
|
+
try:
|
|
40
|
+
return int(raw)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _raise_for_response(response: httpx.Response) -> None:
|
|
46
|
+
if response.status_code < 400:
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
payload = response.json()
|
|
51
|
+
except ValueError:
|
|
52
|
+
payload = None
|
|
53
|
+
|
|
54
|
+
fallback = response.text.strip() or "Request failed"
|
|
55
|
+
detail = parse_error_detail(payload, fallback)
|
|
56
|
+
status_code = response.status_code
|
|
57
|
+
|
|
58
|
+
if status_code == 400:
|
|
59
|
+
raise BadRequestError(status_code, detail, response)
|
|
60
|
+
if status_code == 401:
|
|
61
|
+
raise AuthenticationError(status_code, detail, response)
|
|
62
|
+
if status_code == 402:
|
|
63
|
+
raise PaymentRequiredError(status_code, detail, response)
|
|
64
|
+
if status_code == 429:
|
|
65
|
+
raise RateLimitError(
|
|
66
|
+
status_code,
|
|
67
|
+
detail,
|
|
68
|
+
response,
|
|
69
|
+
retry_after=_retry_after(response.headers),
|
|
70
|
+
)
|
|
71
|
+
if status_code == 503:
|
|
72
|
+
raise ServiceUnavailableError(status_code, detail, response)
|
|
73
|
+
if status_code == 504:
|
|
74
|
+
raise TimeoutError(detail)
|
|
75
|
+
|
|
76
|
+
raise APIError(status_code, detail, response)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class AsyncClient:
|
|
80
|
+
"""Async SDK client."""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
base_url: str = _DEFAULT_BASE_URL,
|
|
85
|
+
api_key: str | None = None,
|
|
86
|
+
timeout: float = 120.0,
|
|
87
|
+
_client: httpx.AsyncClient | None = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
self._owns_client = _client is None
|
|
90
|
+
if _client is None:
|
|
91
|
+
headers = {"X-API-Key": api_key} if api_key else None
|
|
92
|
+
self._client = httpx.AsyncClient(
|
|
93
|
+
base_url=base_url.rstrip("/"),
|
|
94
|
+
timeout=timeout,
|
|
95
|
+
headers=headers,
|
|
96
|
+
)
|
|
97
|
+
else:
|
|
98
|
+
self._client = _client
|
|
99
|
+
if api_key:
|
|
100
|
+
self._client.headers.setdefault("X-API-Key", api_key)
|
|
101
|
+
|
|
102
|
+
async def __aenter__(self) -> AsyncClient:
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
async def __aexit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
106
|
+
await self.close()
|
|
107
|
+
|
|
108
|
+
async def close(self) -> None:
|
|
109
|
+
if self._owns_client:
|
|
110
|
+
await self._client.aclose()
|
|
111
|
+
|
|
112
|
+
async def _request(self, method: str, path: str, *, json: dict[str, Any] | None = None) -> httpx.Response:
|
|
113
|
+
try:
|
|
114
|
+
response = await self._client.request(method, path, json=json)
|
|
115
|
+
except httpx.TimeoutException as exc:
|
|
116
|
+
raise TimeoutError(str(exc) or "Request timed out") from exc
|
|
117
|
+
except httpx.RequestError as exc:
|
|
118
|
+
raise ConnectionError(str(exc) or "Request failed") from exc
|
|
119
|
+
|
|
120
|
+
_raise_for_response(response)
|
|
121
|
+
return response
|
|
122
|
+
|
|
123
|
+
async def review(
|
|
124
|
+
self,
|
|
125
|
+
code: str,
|
|
126
|
+
*,
|
|
127
|
+
language: str = "solidity",
|
|
128
|
+
review_type: str = "security",
|
|
129
|
+
context: str = "",
|
|
130
|
+
encryption_key: str | None = None,
|
|
131
|
+
) -> ReviewResult:
|
|
132
|
+
payload: dict[str, Any] = {
|
|
133
|
+
"code": code,
|
|
134
|
+
"language": language,
|
|
135
|
+
"reviewType": review_type,
|
|
136
|
+
"context": context,
|
|
137
|
+
}
|
|
138
|
+
if encryption_key is not None:
|
|
139
|
+
payload["encryptionKey"] = encryption_key
|
|
140
|
+
|
|
141
|
+
response = await self._request("POST", "/review/", json=payload)
|
|
142
|
+
result = ReviewResult.model_validate(response.json())
|
|
143
|
+
return result.model_copy(update={"remaining_reviews": _extract_remaining_reviews(response.headers)})
|
|
144
|
+
|
|
145
|
+
async def status(self, request_hash: str) -> StatusResult:
|
|
146
|
+
response = await self._request("GET", f"/status/{request_hash}")
|
|
147
|
+
return StatusResult.model_validate(response.json())
|
|
148
|
+
|
|
149
|
+
async def reputation(self, agent_id: int) -> ReputationResult:
|
|
150
|
+
response = await self._request("GET", f"/reputation/{agent_id}")
|
|
151
|
+
return ReputationResult.model_validate(response.json())
|
|
152
|
+
|
|
153
|
+
async def health(self) -> HealthResult:
|
|
154
|
+
response = await self._request("GET", "/health")
|
|
155
|
+
return HealthResult.model_validate(response.json())
|
|
156
|
+
|
|
157
|
+
async def stats(self) -> StatsResult:
|
|
158
|
+
response = await self._request("GET", "/stats/")
|
|
159
|
+
return StatsResult.model_validate(response.json())
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class SyncClient:
|
|
163
|
+
"""Synchronous SDK client."""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
base_url: str = _DEFAULT_BASE_URL,
|
|
168
|
+
api_key: str | None = None,
|
|
169
|
+
timeout: float = 120.0,
|
|
170
|
+
_client: httpx.Client | None = None,
|
|
171
|
+
) -> None:
|
|
172
|
+
self._owns_client = _client is None
|
|
173
|
+
if _client is None:
|
|
174
|
+
headers = {"X-API-Key": api_key} if api_key else None
|
|
175
|
+
self._client = httpx.Client(
|
|
176
|
+
base_url=base_url.rstrip("/"),
|
|
177
|
+
timeout=timeout,
|
|
178
|
+
headers=headers,
|
|
179
|
+
)
|
|
180
|
+
else:
|
|
181
|
+
self._client = _client
|
|
182
|
+
if api_key:
|
|
183
|
+
self._client.headers.setdefault("X-API-Key", api_key)
|
|
184
|
+
|
|
185
|
+
def __enter__(self) -> SyncClient:
|
|
186
|
+
return self
|
|
187
|
+
|
|
188
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
189
|
+
self.close()
|
|
190
|
+
|
|
191
|
+
def close(self) -> None:
|
|
192
|
+
if self._owns_client:
|
|
193
|
+
self._client.close()
|
|
194
|
+
|
|
195
|
+
def _request(self, method: str, path: str, *, json: dict[str, Any] | None = None) -> httpx.Response:
|
|
196
|
+
try:
|
|
197
|
+
response = self._client.request(method, path, json=json)
|
|
198
|
+
except httpx.TimeoutException as exc:
|
|
199
|
+
raise TimeoutError(str(exc) or "Request timed out") from exc
|
|
200
|
+
except httpx.RequestError as exc:
|
|
201
|
+
raise ConnectionError(str(exc) or "Request failed") from exc
|
|
202
|
+
|
|
203
|
+
_raise_for_response(response)
|
|
204
|
+
return response
|
|
205
|
+
|
|
206
|
+
def review(
|
|
207
|
+
self,
|
|
208
|
+
code: str,
|
|
209
|
+
*,
|
|
210
|
+
language: str = "solidity",
|
|
211
|
+
review_type: str = "security",
|
|
212
|
+
context: str = "",
|
|
213
|
+
encryption_key: str | None = None,
|
|
214
|
+
) -> ReviewResult:
|
|
215
|
+
payload: dict[str, Any] = {
|
|
216
|
+
"code": code,
|
|
217
|
+
"language": language,
|
|
218
|
+
"reviewType": review_type,
|
|
219
|
+
"context": context,
|
|
220
|
+
}
|
|
221
|
+
if encryption_key is not None:
|
|
222
|
+
payload["encryptionKey"] = encryption_key
|
|
223
|
+
|
|
224
|
+
response = self._request("POST", "/review/", json=payload)
|
|
225
|
+
result = ReviewResult.model_validate(response.json())
|
|
226
|
+
return result.model_copy(update={"remaining_reviews": _extract_remaining_reviews(response.headers)})
|
|
227
|
+
|
|
228
|
+
def status(self, request_hash: str) -> StatusResult:
|
|
229
|
+
response = self._request("GET", f"/status/{request_hash}")
|
|
230
|
+
return StatusResult.model_validate(response.json())
|
|
231
|
+
|
|
232
|
+
def reputation(self, agent_id: int) -> ReputationResult:
|
|
233
|
+
response = self._request("GET", f"/reputation/{agent_id}")
|
|
234
|
+
return ReputationResult.model_validate(response.json())
|
|
235
|
+
|
|
236
|
+
def health(self) -> HealthResult:
|
|
237
|
+
response = self._request("GET", "/health")
|
|
238
|
+
return HealthResult.model_validate(response.json())
|
|
239
|
+
|
|
240
|
+
def stats(self) -> StatsResult:
|
|
241
|
+
response = self._request("GET", "/stats/")
|
|
242
|
+
return StatsResult.model_validate(response.json())
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""SDK exception hierarchy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ValidatorError(Exception):
|
|
11
|
+
"""Base exception for SDK errors."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class APIError(ValidatorError):
|
|
15
|
+
"""HTTP error returned by the validator API."""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
status_code: int,
|
|
20
|
+
detail: str,
|
|
21
|
+
response: httpx.Response | None = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
self.status_code = status_code
|
|
24
|
+
self.detail = detail
|
|
25
|
+
self.response = response
|
|
26
|
+
super().__init__(f"HTTP {status_code}: {detail}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BadRequestError(APIError):
|
|
30
|
+
"""400 from API."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AuthenticationError(APIError):
|
|
34
|
+
"""401 from API."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class PaymentRequiredError(APIError):
|
|
38
|
+
"""402 from API."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RateLimitError(APIError):
|
|
42
|
+
"""429 from API."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
status_code: int,
|
|
47
|
+
detail: str,
|
|
48
|
+
response: httpx.Response | None = None,
|
|
49
|
+
retry_after: int | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
self.retry_after = retry_after
|
|
52
|
+
super().__init__(status_code=status_code, detail=detail, response=response)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ServiceUnavailableError(APIError):
|
|
56
|
+
"""503 from API."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class TimeoutError(ValidatorError):
|
|
60
|
+
"""Timeout reaching API or 504 returned by API."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ConnectionError(ValidatorError):
|
|
64
|
+
"""Network/connectivity failure while calling API."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class CryptoNotAvailableError(ValidatorError):
|
|
68
|
+
"""Raised when crypto helper dependencies are unavailable."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parse_error_detail(payload: Any, fallback: str) -> str:
|
|
72
|
+
"""Extract a readable error string from API payload."""
|
|
73
|
+
if isinstance(payload, dict):
|
|
74
|
+
detail = payload.get("detail")
|
|
75
|
+
error = payload.get("error")
|
|
76
|
+
if isinstance(detail, str) and isinstance(error, str):
|
|
77
|
+
if detail == error:
|
|
78
|
+
return detail
|
|
79
|
+
return f"{error}: {detail}"
|
|
80
|
+
if isinstance(detail, str):
|
|
81
|
+
return detail
|
|
82
|
+
if isinstance(error, str):
|
|
83
|
+
return error
|
|
84
|
+
return fallback
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Deployment gate helpers for CI/CD policies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from .client import SyncClient
|
|
9
|
+
from .models import EvidenceLevel, ReviewResult, Severity
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class GatePolicy:
|
|
14
|
+
min_score: int = 70
|
|
15
|
+
min_confidence: float = 0.7
|
|
16
|
+
require_evidence: EvidenceLevel = EvidenceLevel.FULL
|
|
17
|
+
max_critical: int = 0
|
|
18
|
+
max_high: int = 2
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class GateCheck:
|
|
23
|
+
name: str
|
|
24
|
+
passed: bool
|
|
25
|
+
actual: str
|
|
26
|
+
threshold: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class GateResult:
|
|
31
|
+
passed: bool
|
|
32
|
+
checks: list[GateCheck]
|
|
33
|
+
severity_counts: dict[Severity, int]
|
|
34
|
+
normalized_confidence: float
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_EVIDENCE_ORDER: dict[EvidenceLevel, int] = {
|
|
38
|
+
EvidenceLevel.INSUFFICIENT: 0,
|
|
39
|
+
EvidenceLevel.PARTIAL: 1,
|
|
40
|
+
EvidenceLevel.FULL: 2,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_SEVERITY_ORDER: tuple[Severity, ...] = (
|
|
44
|
+
Severity.CRITICAL,
|
|
45
|
+
Severity.HIGH,
|
|
46
|
+
Severity.MEDIUM,
|
|
47
|
+
Severity.LOW,
|
|
48
|
+
Severity.INFO,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _evidence_meets_threshold(actual: EvidenceLevel, required: EvidenceLevel) -> bool:
|
|
53
|
+
return _EVIDENCE_ORDER[actual] >= _EVIDENCE_ORDER[required]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _count_severity(response: ReviewResult) -> dict[Severity, int]:
|
|
57
|
+
counts = Counter(finding.severity for finding in response.findings)
|
|
58
|
+
return {severity: counts.get(severity, 0) for severity in _SEVERITY_ORDER}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def evaluate(response: ReviewResult, policy: GatePolicy | None = None) -> GateResult:
|
|
62
|
+
"""Evaluate a review response against gating policy thresholds."""
|
|
63
|
+
effective_policy = policy or GatePolicy()
|
|
64
|
+
normalized_confidence = response.confidence if response.confidence is not None else 0.0
|
|
65
|
+
severity_counts = _count_severity(response)
|
|
66
|
+
|
|
67
|
+
checks = [
|
|
68
|
+
GateCheck(
|
|
69
|
+
name="score",
|
|
70
|
+
passed=response.score >= effective_policy.min_score,
|
|
71
|
+
actual=str(response.score),
|
|
72
|
+
threshold=f">= {effective_policy.min_score}",
|
|
73
|
+
),
|
|
74
|
+
GateCheck(
|
|
75
|
+
name="confidence",
|
|
76
|
+
passed=normalized_confidence >= effective_policy.min_confidence,
|
|
77
|
+
actual=f"{normalized_confidence:.2f}",
|
|
78
|
+
threshold=f">= {effective_policy.min_confidence:.2f}",
|
|
79
|
+
),
|
|
80
|
+
GateCheck(
|
|
81
|
+
name="evidence_level",
|
|
82
|
+
passed=_evidence_meets_threshold(response.evidence_level, effective_policy.require_evidence),
|
|
83
|
+
actual=response.evidence_level.value,
|
|
84
|
+
threshold=f">= {effective_policy.require_evidence.value}",
|
|
85
|
+
),
|
|
86
|
+
GateCheck(
|
|
87
|
+
name="critical_findings",
|
|
88
|
+
passed=severity_counts[Severity.CRITICAL] <= effective_policy.max_critical,
|
|
89
|
+
actual=str(severity_counts[Severity.CRITICAL]),
|
|
90
|
+
threshold=f"<= {effective_policy.max_critical}",
|
|
91
|
+
),
|
|
92
|
+
GateCheck(
|
|
93
|
+
name="high_findings",
|
|
94
|
+
passed=severity_counts[Severity.HIGH] <= effective_policy.max_high,
|
|
95
|
+
actual=str(severity_counts[Severity.HIGH]),
|
|
96
|
+
threshold=f"<= {effective_policy.max_high}",
|
|
97
|
+
),
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
return GateResult(
|
|
101
|
+
passed=all(check.passed for check in checks),
|
|
102
|
+
checks=checks,
|
|
103
|
+
severity_counts=severity_counts,
|
|
104
|
+
normalized_confidence=normalized_confidence,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def check_contract(
|
|
109
|
+
code: str,
|
|
110
|
+
*,
|
|
111
|
+
base_url: str = "https://code-review-validator.fly.dev",
|
|
112
|
+
api_key: str | None = None,
|
|
113
|
+
policy: GatePolicy | None = None,
|
|
114
|
+
timeout: float = 120.0,
|
|
115
|
+
) -> GateResult:
|
|
116
|
+
"""Submit contract code and evaluate gate policy in one call."""
|
|
117
|
+
with SyncClient(base_url=base_url, api_key=api_key, timeout=timeout) as client:
|
|
118
|
+
review = client.review(code)
|
|
119
|
+
return evaluate(review, policy)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Standalone SDK models mirroring API responses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SDKModel(BaseModel):
|
|
12
|
+
"""Base model configured for forward compatibility."""
|
|
13
|
+
|
|
14
|
+
model_config = ConfigDict(extra="ignore", populate_by_name=True)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Severity(str, Enum):
|
|
18
|
+
CRITICAL = "critical"
|
|
19
|
+
HIGH = "high"
|
|
20
|
+
MEDIUM = "medium"
|
|
21
|
+
LOW = "low"
|
|
22
|
+
INFO = "info"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class EvidenceLevel(str, Enum):
|
|
26
|
+
FULL = "full"
|
|
27
|
+
PARTIAL = "partial"
|
|
28
|
+
INSUFFICIENT = "insufficient"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AttestationStatus(str, Enum):
|
|
32
|
+
ATTESTED = "attested"
|
|
33
|
+
ANALYSIS_ONLY = "analysis_only"
|
|
34
|
+
CHAIN_FAILED = "chain_failed"
|
|
35
|
+
IPFS_FAILED = "ipfs_failed"
|
|
36
|
+
FREE = "free"
|
|
37
|
+
METADATA_ONLY = "metadata_only"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class OnChainStatus(str, Enum):
|
|
41
|
+
ATTESTED = "attested"
|
|
42
|
+
NOT_FOUND = "not_found"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Finding(SDKModel):
|
|
46
|
+
severity: Severity
|
|
47
|
+
category: str
|
|
48
|
+
line: int | None = None
|
|
49
|
+
function: str | None = None
|
|
50
|
+
description: str
|
|
51
|
+
recommendation: str
|
|
52
|
+
references: list[str] = Field(default_factory=list)
|
|
53
|
+
sources: list[str] = Field(default_factory=list)
|
|
54
|
+
confidence: float | None = Field(default=None, ge=0.0, le=1.0)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ReviewResult(SDKModel):
|
|
58
|
+
score: int = Field(ge=0, le=100)
|
|
59
|
+
evidence_level: EvidenceLevel
|
|
60
|
+
findings: list[Finding] = Field(default_factory=list)
|
|
61
|
+
recommendations: list[str] = Field(default_factory=list)
|
|
62
|
+
severity_counts: dict[str, int] | None = None
|
|
63
|
+
attestation: dict[str, Any] = Field(default_factory=dict)
|
|
64
|
+
attestation_status: AttestationStatus = AttestationStatus.FREE
|
|
65
|
+
ipfs_uri: str | None = None
|
|
66
|
+
confidence: float | None = Field(default=None, ge=0.0, le=1.0)
|
|
67
|
+
tx_hash: str | None = None
|
|
68
|
+
remaining_reviews: int | None = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class StatusResult(SDKModel):
|
|
72
|
+
request_hash: str
|
|
73
|
+
status: OnChainStatus
|
|
74
|
+
validator_address: str | None = None
|
|
75
|
+
agent_id: int | None = None
|
|
76
|
+
score: int | None = None
|
|
77
|
+
response_hash: str | None = None
|
|
78
|
+
tag: str | None = None
|
|
79
|
+
last_update: int = 0
|
|
80
|
+
response_uri: str | None = None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ReputationResult(SDKModel):
|
|
84
|
+
agent_id: int
|
|
85
|
+
status: str
|
|
86
|
+
feedback_count: int
|
|
87
|
+
summary_value: int
|
|
88
|
+
summary_value_decimals: int
|
|
89
|
+
summary_value_normalized: str
|
|
90
|
+
client_count: int
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class HealthResult(SDKModel):
|
|
94
|
+
status: str
|
|
95
|
+
chain_listener: str
|
|
96
|
+
stake_status: str
|
|
97
|
+
stake_eth: float
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class StatsResult(SDKModel):
|
|
101
|
+
total_reviews: int
|
|
102
|
+
avg_score: float
|
|
103
|
+
total_paid: int
|
|
104
|
+
total_free: int
|
|
105
|
+
earnings_usdc: float
|
|
106
|
+
reviews_today: int
|
|
File without changes
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: code-review-validator
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the Code Review Validator API
|
|
5
|
+
Author: Code Review Validator
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://code-review-validator.fly.dev
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/danielpwhite/code-review-validator
|
|
9
|
+
Project-URL: Documentation, https://gitlab.com/danielpwhite/code-review-validator/-/blob/master/sdk/python/README.md
|
|
10
|
+
Keywords: solidity,smart-contract,security,attestation,erc-8004,web3
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: httpx>=0.27.0
|
|
25
|
+
Requires-Dist: pydantic>=2.0.0
|
|
26
|
+
Provides-Extra: crypto
|
|
27
|
+
Requires-Dist: eciespy>=0.4.0; extra == "crypto"
|
|
28
|
+
Requires-Dist: coincurve>=20.0.0; extra == "crypto"
|
|
29
|
+
Requires-Dist: web3>=7.6.0; extra == "crypto"
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
32
|
+
Requires-Dist: anyio>=4.0.0; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# code-review-validator (Python SDK)
|
|
36
|
+
|
|
37
|
+
Python client for the Code Review Validator API.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install code-review-validator
|
|
43
|
+
# Optional crypto helpers
|
|
44
|
+
pip install "code-review-validator[crypto]"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Development Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install -e .
|
|
51
|
+
pip install -e ".[dev]"
|
|
52
|
+
# Optional crypto helpers while developing
|
|
53
|
+
pip install -e ".[dev,crypto]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Quickstart (async)
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from code_review_validator import AsyncClient
|
|
60
|
+
|
|
61
|
+
async def main() -> None:
|
|
62
|
+
async with AsyncClient(api_key="your-key") as client:
|
|
63
|
+
review = await client.review("contract C {}")
|
|
64
|
+
print(review.score, review.evidence_level)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Quickstart (sync)
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from code_review_validator import SyncClient
|
|
71
|
+
|
|
72
|
+
with SyncClient(api_key="your-key") as client:
|
|
73
|
+
review = client.review("contract C {}")
|
|
74
|
+
print(review.score, review.attestation_status)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## CI Gate
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from code_review_validator import GatePolicy, check_contract
|
|
81
|
+
|
|
82
|
+
policy = GatePolicy(min_score=80)
|
|
83
|
+
result = check_contract("contract C {}", api_key="your-key", policy=policy)
|
|
84
|
+
if not result.passed:
|
|
85
|
+
raise SystemExit(1)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Optional Crypto Helpers
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from code_review_validator import verify_response_hash, decrypt_findings
|
|
92
|
+
|
|
93
|
+
ok = verify_response_hash(ipfs_payload, on_chain_hash)
|
|
94
|
+
findings = decrypt_findings(ipfs_payload, private_key_hex)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Manual Publish Fallback
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
pip install build twine
|
|
101
|
+
cd sdk/python
|
|
102
|
+
python -m build
|
|
103
|
+
TWINE_USERNAME=__token__ TWINE_PASSWORD="$PYPI_TOKEN" twine upload dist/*
|
|
104
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
code_review_validator/__init__.py,sha256=LwNLMwytfDh9qlz-uMgGwB7x0Jdi3G4hWQJ01PEi37g,2353
|
|
2
|
+
code_review_validator/_verify.py,sha256=f96jZJgoqhPCrFMCVoXxUvZWJv6GDPVE9Lwu0Gtc3rI,1698
|
|
3
|
+
code_review_validator/client.py,sha256=bPG0qi_cw6ln-7_f66HPmXKTUuyPrUNaxdiKEQgfbUU,7837
|
|
4
|
+
code_review_validator/errors.py,sha256=hHXuioHRlv6Iv7JK4T6vbxYjIeOmINnhw-5cJ2OVEug,2032
|
|
5
|
+
code_review_validator/gate.py,sha256=aj59l_6AFvVoeVWsXtSxS0w9SGpQjBe_ZGbek-40sh8,3696
|
|
6
|
+
code_review_validator/models.py,sha256=KGnTv0JH8vIeOQ-huO6dGM-g2kvCiqk_fYE1rOWqg3U,2602
|
|
7
|
+
code_review_validator/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
code_review_validator-0.1.0.dist-info/licenses/LICENSE,sha256=5VS0Hbt5xXT7bNCKJDdroyydffccq5g6s-Xov3OS5CE,1091
|
|
9
|
+
code_review_validator-0.1.0.dist-info/METADATA,sha256=DpBg0c8SRf0RL2yQ8y8G2n05_4FAphA101l8fTZz7Yg,2902
|
|
10
|
+
code_review_validator-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
|
|
11
|
+
code_review_validator-0.1.0.dist-info/top_level.txt,sha256=dm37RkTeor0Gwhts5fALC8FAscw7FmAaTHTLk0pCUMA,22
|
|
12
|
+
code_review_validator-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Code Review Validator contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
code_review_validator
|