autographos 0.0.1__tar.gz

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.
@@ -0,0 +1,19 @@
1
+ name: ci
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ jobs:
7
+ test:
8
+ runs-on: ubuntu-latest
9
+ strategy:
10
+ fail-fast: false
11
+ matrix:
12
+ python: ["3.10", "3.13"]
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: ${{ matrix.python }}
18
+ - run: pip install -e . pytest
19
+ - run: pytest -q
@@ -0,0 +1,25 @@
1
+ name: publish
2
+ # Publishing a GitHub release uploads to PyPI through Trusted Publishing (no API token).
3
+ # The `pypi` environment should require a reviewer's approval.
4
+ on:
5
+ release:
6
+ types: [published]
7
+ jobs:
8
+ pypi:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write
13
+ contents: read
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.12"
19
+ - run: pip install pytest -e . && pytest -q
20
+ - name: Check the release tag matches the package version
21
+ run: |
22
+ version=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
23
+ test "v$version" = "${GITHUB_REF_NAME}" || { echo "tag ${GITHUB_REF_NAME} != v$version"; exit 1; }
24
+ - run: pip install build && python -m build
25
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ dist/
4
+ build/
5
+ *.egg-info/
6
+ .venv/
7
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AutographOS Corp.
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,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: autographos
3
+ Version: 0.0.1
4
+ Summary: Python client for the AutographOS Verify API
5
+ Project-URL: Homepage, https://github.com/Prosper-Labs/public-python-verifier
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: requests>=2.31
13
+ Description-Content-Type: text/markdown
14
+
15
+ # autographos
16
+
17
+ Python client for the AutographOS Verify API (v1). It sends 1–25 files of one claim and returns a
18
+ badge per file: `verified`, `altered`, `high_risk`, `needs_review` or `not_checked`.
19
+
20
+ ```
21
+ pip install autographos
22
+ ```
23
+
24
+ Depends only on `requests`. No native code, no file or OS access.
25
+
26
+ ## Use
27
+
28
+ ```python
29
+ from autographos import VerifyClient, VerifyFile, VerifyError, VerifyResponseError
30
+
31
+ client = VerifyClient(api_key, url="https://<verify host>/v1/verify")
32
+
33
+ try:
34
+ response = client.verify("clm_123", [VerifyFile("photo-1", photo_bytes)])
35
+ except VerifyError as e:
36
+ # Request-level failure. Retry later only if e.retryable.
37
+ ...
38
+ except VerifyResponseError:
39
+ # The answer didn't match the v1 contract. Never act on it.
40
+ ...
41
+
42
+ for result in response.results: # same order as the files you sent
43
+ print(result.file_id, result.badge, result.reasons)
44
+ if not result.ok:
45
+ print("not checked:", result.error.code, "retryable:", result.error.retryable)
46
+ ```
47
+
48
+ - **Safe retries.** If you don't pass `request_id`, one is derived from the claim and the exact
49
+ files, so sending the same request again replays the earlier answer instead of counting as a
50
+ new submission.
51
+ - **Fails closed.** Every 200 response is checked against the v1 contract (ids, order, digests,
52
+ badge/pass consistency). Anything off raises `VerifyResponseError`.
53
+ - **Retries.** Network errors, 429 and 5xx are retried once by default (`max_retries`), honouring
54
+ `Retry-After` up to 30 s.
55
+ - **Privacy.** File parts are always sent with the name `file`, since real file names can carry
56
+ personal data. The full API result (including any GPS) is in `result.raw`; store it only where
57
+ your access rules allow.
58
+
59
+ `result.raw` and `response.raw` hold the full JSON for fields this client doesn't model yet
60
+ (`capture`, `c2pa`, `matches`, PDF `items`).
61
+
62
+ ## Releasing
63
+
64
+ Bump `version` in `pyproject.toml` and `__version__` in `src/autographos/__init__.py`, then publish
65
+ a GitHub release tagged `v<version>`. The `publish` workflow tests, builds and uploads to PyPI
66
+ through Trusted Publishing.
67
+
68
+ ## License
69
+
70
+ MIT
@@ -0,0 +1,56 @@
1
+ # autographos
2
+
3
+ Python client for the AutographOS Verify API (v1). It sends 1–25 files of one claim and returns a
4
+ badge per file: `verified`, `altered`, `high_risk`, `needs_review` or `not_checked`.
5
+
6
+ ```
7
+ pip install autographos
8
+ ```
9
+
10
+ Depends only on `requests`. No native code, no file or OS access.
11
+
12
+ ## Use
13
+
14
+ ```python
15
+ from autographos import VerifyClient, VerifyFile, VerifyError, VerifyResponseError
16
+
17
+ client = VerifyClient(api_key, url="https://<verify host>/v1/verify")
18
+
19
+ try:
20
+ response = client.verify("clm_123", [VerifyFile("photo-1", photo_bytes)])
21
+ except VerifyError as e:
22
+ # Request-level failure. Retry later only if e.retryable.
23
+ ...
24
+ except VerifyResponseError:
25
+ # The answer didn't match the v1 contract. Never act on it.
26
+ ...
27
+
28
+ for result in response.results: # same order as the files you sent
29
+ print(result.file_id, result.badge, result.reasons)
30
+ if not result.ok:
31
+ print("not checked:", result.error.code, "retryable:", result.error.retryable)
32
+ ```
33
+
34
+ - **Safe retries.** If you don't pass `request_id`, one is derived from the claim and the exact
35
+ files, so sending the same request again replays the earlier answer instead of counting as a
36
+ new submission.
37
+ - **Fails closed.** Every 200 response is checked against the v1 contract (ids, order, digests,
38
+ badge/pass consistency). Anything off raises `VerifyResponseError`.
39
+ - **Retries.** Network errors, 429 and 5xx are retried once by default (`max_retries`), honouring
40
+ `Retry-After` up to 30 s.
41
+ - **Privacy.** File parts are always sent with the name `file`, since real file names can carry
42
+ personal data. The full API result (including any GPS) is in `result.raw`; store it only where
43
+ your access rules allow.
44
+
45
+ `result.raw` and `response.raw` hold the full JSON for fields this client doesn't model yet
46
+ (`capture`, `c2pa`, `matches`, PDF `items`).
47
+
48
+ ## Releasing
49
+
50
+ Bump `version` in `pyproject.toml` and `__version__` in `src/autographos/__init__.py`, then publish
51
+ a GitHub release tagged `v<version>`. The `publish` workflow tests, builds and uploads to PyPI
52
+ through Trusted Publishing.
53
+
54
+ ## License
55
+
56
+ MIT
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "autographos"
7
+ version = "0.0.1"
8
+ description = "Python client for the AutographOS Verify API"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["requests>=2.31"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ "Typing :: Typed",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/Prosper-Labs/public-python-verifier"
22
+
23
+ [dependency-groups]
24
+ dev = ["pytest>=8"]
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/autographos"]
28
+
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
31
+ pythonpath = ["src"]
@@ -0,0 +1,24 @@
1
+ """AutographOS Verify API client."""
2
+ from .client import (
3
+ API_VERSION,
4
+ FileError,
5
+ FileResult,
6
+ VerifyClient,
7
+ VerifyFile,
8
+ VerifyResponse,
9
+ default_request_id,
10
+ )
11
+ from .errors import VerifyError, VerifyResponseError
12
+
13
+ __version__ = "0.0.1"
14
+ __all__ = [
15
+ "API_VERSION",
16
+ "FileError",
17
+ "FileResult",
18
+ "VerifyClient",
19
+ "VerifyError",
20
+ "VerifyFile",
21
+ "VerifyResponse",
22
+ "VerifyResponseError",
23
+ "default_request_id",
24
+ ]
@@ -0,0 +1,293 @@
1
+ """Client for AutographOS Verify API v1.
2
+
3
+ One call verifies 1-25 files that belong to one claim. The response is checked against the
4
+ v1 contract before anything is returned: a body that doesn't match raises
5
+ VerifyResponseError, so a caller never acts on a badge it couldn't parse.
6
+ """
7
+ import hashlib
8
+ import json
9
+ import re
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Dict, List, Optional, Sequence
13
+
14
+ import requests
15
+
16
+ from .errors import VerifyError, VerifyResponseError
17
+
18
+ API_VERSION = "1"
19
+ MAX_FILES = 25
20
+
21
+ BADGES = ("verified", "altered", "high_risk", "needs_review", "not_checked")
22
+ MATCH_TYPES = ("exact", "perceptual", "none")
23
+
24
+ ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,64}")
25
+ REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
26
+ CODE_RE = re.compile(r"[a-z][a-z0-9_]{0,63}")
27
+ REF_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")
28
+ VERSION_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,31}")
29
+ SHA256_RE = re.compile(r"[0-9a-f]{64}")
30
+ TIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{2}:\d{2})")
31
+ MAX_REASONS = 32
32
+ MAX_RETRY_AFTER = 30.0
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class VerifyFile:
37
+ """One file to verify. file_id is your stable id for the stored file (1-64 of [A-Za-z0-9._:-])."""
38
+
39
+ file_id: str
40
+ content: bytes
41
+ sha256: str = ""
42
+
43
+ def digest(self) -> str:
44
+ return self.sha256 or hashlib.sha256(self.content).hexdigest()
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class FileError:
49
+ code: str
50
+ retryable: bool
51
+ message: str = ""
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class FileResult:
56
+ """Verify's answer for one file. `raw` is the full result object from the API."""
57
+
58
+ file_id: str
59
+ status: str
60
+ badge: str
61
+ passed: bool
62
+ match_type: str
63
+ reasons: List[str]
64
+ error: Optional[FileError]
65
+ raw: Dict[str, Any] = field(repr=False)
66
+
67
+ @property
68
+ def ok(self) -> bool:
69
+ return self.status == "ok"
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class VerifyResponse:
74
+ request_id: str
75
+ claim_id: str
76
+ verification_id: str
77
+ rules_version: str
78
+ verified_at: str
79
+ replayed: bool
80
+ results: List[FileResult]
81
+ raw: Dict[str, Any] = field(repr=False)
82
+
83
+
84
+ def default_request_id(claim_id: str, files: Sequence[VerifyFile]) -> str:
85
+ """Stable for the same claim and the same ordered files, so a retry replays the
86
+ earlier answer instead of counting as a new submission."""
87
+ listing = "\n".join(f.file_id + ":" + f.digest() for f in files)
88
+ return "req:" + hashlib.sha256((claim_id + "\n" + listing).encode("utf-8")).hexdigest()[:40]
89
+
90
+
91
+ class VerifyClient:
92
+ """
93
+ client = VerifyClient(api_key, url="https://<host>/v1/verify")
94
+ response = client.verify("clm_123", [VerifyFile("photo-1", data)])
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ api_key: str,
100
+ url: str,
101
+ connect_timeout: float = 5.0,
102
+ read_timeout: float = 60.0,
103
+ max_retries: int = 1,
104
+ session: Optional[requests.Session] = None,
105
+ ) -> None:
106
+ if not api_key:
107
+ raise ValueError("api_key is required")
108
+ if not url.startswith("https://"):
109
+ raise ValueError("url must be https")
110
+ self.api_key = api_key
111
+ self.url = url
112
+ self.timeout = (connect_timeout, read_timeout)
113
+ self.max_retries = max(0, int(max_retries))
114
+ self.session = session or requests.Session()
115
+
116
+ def verify(
117
+ self,
118
+ claim_id: str,
119
+ files: Sequence[VerifyFile],
120
+ request_id: Optional[str] = None,
121
+ ) -> VerifyResponse:
122
+ """Verify 1-25 files of one claim. Results come back in the order of `files`.
123
+
124
+ Raises VerifyError for a request-level failure (check .retryable) and
125
+ VerifyResponseError when the answer doesn't match the v1 contract.
126
+ """
127
+ files = list(files)
128
+ check_request(claim_id, files)
129
+ digests = [f.digest() for f in files]
130
+ request_id = request_id or default_request_id(claim_id, files)
131
+ if not REQUEST_ID_RE.fullmatch(request_id):
132
+ raise ValueError("request_id must be 1-128 characters from [A-Za-z0-9._:-]")
133
+
134
+ request_part = json.dumps({
135
+ "request_id": request_id,
136
+ "claim_id": claim_id,
137
+ "files": [{"file_id": f.file_id, "sha256": d} for f, d in zip(files, digests)],
138
+ })
139
+ # The request part must come first, then one file part per files[] entry, in order.
140
+ # filename is always "file": real names can carry personal data.
141
+ parts = [("request", (None, request_part, "application/json"))]
142
+ parts += [("file", ("file", f.content, "application/octet-stream")) for f in files]
143
+ headers = {"X-API-Key": self.api_key, "Accept": "application/json"}
144
+
145
+ attempt = 0
146
+ while True:
147
+ try:
148
+ resp = self.session.post(
149
+ self.url, headers=headers, files=parts, timeout=self.timeout, allow_redirects=False
150
+ )
151
+ except requests.RequestException as exc:
152
+ error = VerifyError("network_error", None, True, str(exc.__class__.__name__))
153
+ wait = 2.0
154
+ else:
155
+ if resp.status_code == 200:
156
+ return parse_response(json_body(resp), request_id, files, digests)
157
+ error = error_from(resp)
158
+ wait = retry_after(resp)
159
+ if not error.retryable or attempt >= self.max_retries:
160
+ raise error
161
+ attempt += 1
162
+ time.sleep(wait)
163
+
164
+ def health(self) -> Dict[str, Any]:
165
+ """GET <base>/v1/health next to the verify URL. Raises VerifyError if not ok."""
166
+ url = self.url.rsplit("/", 1)[0] + "/health"
167
+ resp = self.session.get(url, timeout=self.timeout, allow_redirects=False)
168
+ body = json_body(resp)
169
+ if resp.status_code != 200 or not isinstance(body, dict):
170
+ raise VerifyError("unavailable", resp.status_code, True, "health check failed")
171
+ return body
172
+
173
+
174
+ def check_request(claim_id: str, files: List[VerifyFile]) -> None:
175
+ if not isinstance(claim_id, str) or not ID_RE.fullmatch(claim_id):
176
+ raise ValueError("claim_id must be 1-64 characters from [A-Za-z0-9._:-]")
177
+ if not 1 <= len(files) <= MAX_FILES:
178
+ raise ValueError("send 1-%d files per call" % MAX_FILES)
179
+ seen = set()
180
+ for f in files:
181
+ if not isinstance(f, VerifyFile):
182
+ raise TypeError("files must be VerifyFile objects")
183
+ if not ID_RE.fullmatch(f.file_id):
184
+ raise ValueError("file_id must be 1-64 characters from [A-Za-z0-9._:-]")
185
+ if f.file_id in seen:
186
+ raise ValueError("duplicate file_id: " + f.file_id)
187
+ seen.add(f.file_id)
188
+ if not isinstance(f.content, (bytes, bytearray)):
189
+ raise TypeError("content must be bytes")
190
+ if f.sha256 and not SHA256_RE.fullmatch(f.sha256):
191
+ raise ValueError("sha256 must be 64 lowercase hex characters")
192
+
193
+
194
+ def json_body(resp: requests.Response) -> Any:
195
+ try:
196
+ return resp.json()
197
+ except ValueError:
198
+ return None
199
+
200
+
201
+ def error_from(resp: requests.Response) -> VerifyError:
202
+ status = resp.status_code
203
+ body = json_body(resp)
204
+ err = body.get("error") if isinstance(body, dict) else None
205
+ if isinstance(err, dict) and isinstance(err.get("code"), str):
206
+ retryable = err.get("retryable")
207
+ if not isinstance(retryable, bool):
208
+ retryable = status == 429 or status >= 500
209
+ return VerifyError(err["code"], status, retryable, str(err.get("message") or ""))
210
+ # A non-JSON 5xx (for example a Cloud Run timeout) is always retryable.
211
+ return VerifyError("http_%d" % status, status, status == 429 or status >= 500, "")
212
+
213
+
214
+ def retry_after(resp: requests.Response) -> float:
215
+ try:
216
+ return min(MAX_RETRY_AFTER, max(0.0, float(resp.headers.get("Retry-After", "2"))))
217
+ except ValueError:
218
+ return 2.0
219
+
220
+
221
+ def fail(reason: str) -> VerifyResponseError:
222
+ return VerifyResponseError("response does not match the v1 contract: " + reason)
223
+
224
+
225
+ def parse_response(body: Any, request_id: str, files: List[VerifyFile], digests: List[str]) -> VerifyResponse:
226
+ if not isinstance(body, dict):
227
+ raise fail("body is not a JSON object")
228
+ if body.get("request_id") != request_id:
229
+ raise fail("request_id")
230
+ results = body.get("results")
231
+ if not isinstance(results, list) or len(results) != len(files):
232
+ raise fail("results length")
233
+ ref, rules, at = body.get("verification_id"), body.get("rules_version"), body.get("verified_at")
234
+ if not (isinstance(ref, str) and REF_RE.fullmatch(ref)):
235
+ raise fail("verification_id")
236
+ if not (isinstance(rules, str) and VERSION_RE.fullmatch(rules)):
237
+ raise fail("rules_version")
238
+ if not (isinstance(at, str) and TIME_RE.fullmatch(at)):
239
+ raise fail("verified_at")
240
+ parsed = [parse_result(r, f.file_id, d) for r, f, d in zip(results, files, digests)]
241
+ return VerifyResponse(
242
+ request_id=request_id,
243
+ claim_id=str(body.get("claim_id", "")),
244
+ verification_id=ref,
245
+ rules_version=rules,
246
+ verified_at=at,
247
+ replayed=body.get("replayed") is True,
248
+ results=parsed,
249
+ raw=body,
250
+ )
251
+
252
+
253
+ def parse_result(result: Any, file_id: str, digest: str) -> FileResult:
254
+ if not isinstance(result, dict) or result.get("file_id") != file_id:
255
+ raise fail("file_id order")
256
+ badge, passed, match_type = result.get("badge"), result.get("pass"), result.get("match_type")
257
+ if badge not in BADGES:
258
+ raise fail("badge")
259
+ if not isinstance(passed, bool) or passed != (badge == "verified"):
260
+ raise fail("pass")
261
+ if match_type not in MATCH_TYPES:
262
+ raise fail("match_type")
263
+ reasons = result.get("reasons")
264
+ if not isinstance(reasons, list) or len(reasons) > MAX_REASONS:
265
+ raise fail("reasons")
266
+ for reason in reasons:
267
+ if not (isinstance(reason, str) and CODE_RE.fullmatch(reason)):
268
+ raise fail("reason code")
269
+ status = result.get("status")
270
+ error = None
271
+ if status == "ok":
272
+ facts = result.get("file")
273
+ if not isinstance(facts, dict) or facts.get("sha256") != digest:
274
+ raise fail("file.sha256")
275
+ elif status == "error":
276
+ err = result.get("error")
277
+ if (badge != "not_checked" or not isinstance(err, dict)
278
+ or not (isinstance(err.get("code"), str) and CODE_RE.fullmatch(err["code"]))
279
+ or not isinstance(err.get("retryable"), bool)):
280
+ raise fail("file error")
281
+ error = FileError(err["code"], err["retryable"], str(err.get("message") or ""))
282
+ else:
283
+ raise fail("status")
284
+ return FileResult(
285
+ file_id=file_id,
286
+ status=status,
287
+ badge=badge,
288
+ passed=passed,
289
+ match_type=match_type,
290
+ reasons=list(reasons),
291
+ error=error,
292
+ raw=result,
293
+ )
@@ -0,0 +1,17 @@
1
+ from typing import Optional
2
+
3
+
4
+ class VerifyError(Exception):
5
+ """A request-level failure. `retryable` says whether sending the same request again can help."""
6
+
7
+ def __init__(self, code: str, http_status: Optional[int], retryable: bool, message: str = "") -> None:
8
+ super().__init__("%s%s" % (code, (": " + message) if message else ""))
9
+ self.code = code
10
+ self.http_status = http_status
11
+ self.retryable = retryable
12
+ self.message = message
13
+
14
+
15
+ class VerifyResponseError(Exception):
16
+ """Verify answered 200 but the body doesn't match the v1 contract. Treat as a failure:
17
+ never act on a badge from a response that raised this."""
File without changes
@@ -0,0 +1,171 @@
1
+ import hashlib
2
+ import json
3
+
4
+ import pytest
5
+ import requests
6
+
7
+ from autographos import VerifyClient, VerifyError, VerifyFile, VerifyResponseError, default_request_id
8
+
9
+ URL = "https://verify.example.test/v1/verify"
10
+ KEY = "avk_test_aaaaaaaaaaaa_" + "b" * 52
11
+ PHOTO = b"\xff\xd8\xff fake jpeg bytes"
12
+ PHOTO_SHA = hashlib.sha256(PHOTO).hexdigest()
13
+
14
+
15
+ class FakeResponse:
16
+ def __init__(self, status, body=None, text=None, headers=None):
17
+ self.status_code = status
18
+ self.body = body
19
+ self.text = text
20
+ self.headers = headers or {}
21
+
22
+ def json(self):
23
+ if self.body is None:
24
+ raise ValueError("no json")
25
+ return self.body
26
+
27
+
28
+ class FakeSession:
29
+ def __init__(self, responses):
30
+ self.responses = list(responses)
31
+ self.calls = []
32
+
33
+ def post(self, url, **kwargs):
34
+ self.calls.append((url, kwargs))
35
+ item = self.responses.pop(0)
36
+ if isinstance(item, Exception):
37
+ raise item
38
+ return item
39
+
40
+ def get(self, url, **kwargs):
41
+ self.calls.append((url, kwargs))
42
+ return self.responses.pop(0)
43
+
44
+
45
+ def ok_body(request_id, results):
46
+ return {
47
+ "api_version": "1",
48
+ "rules_version": "2026-11-24-draft",
49
+ "verification_id": "ver_01JABCDEFGHJKMNPQRSTVWXYZ0",
50
+ "request_id": request_id,
51
+ "claim_id": "clm_1",
52
+ "replayed": False,
53
+ "verified_at": "2026-12-02T23:00:00Z",
54
+ "results": results,
55
+ }
56
+
57
+
58
+ def ok_result(file_id="f1", sha=PHOTO_SHA, badge="verified"):
59
+ return {
60
+ "index": 0, "file_id": file_id, "status": "ok", "error": None, "badge": badge,
61
+ "pass": badge == "verified", "match_type": "exact", "reasons": ["registry_exact"],
62
+ "file": {"sha256": sha},
63
+ }
64
+
65
+
66
+ @pytest.fixture(autouse=True)
67
+ def no_sleep(monkeypatch):
68
+ monkeypatch.setattr("autographos.client.time.sleep", lambda s: None)
69
+
70
+
71
+ def client(responses, **kw):
72
+ session = FakeSession(responses)
73
+ return VerifyClient(KEY, URL, session=session, **kw), session
74
+
75
+
76
+ def test_verify_ok_and_request_layout():
77
+ files = [VerifyFile("f1", PHOTO)]
78
+ rid = default_request_id("clm_1", files)
79
+ c, s = client([FakeResponse(200, ok_body(rid, [ok_result()]))])
80
+ resp = c.verify("clm_1", files)
81
+ assert resp.results[0].badge == "verified" and resp.results[0].passed and resp.results[0].ok
82
+ url, kw = s.calls[0]
83
+ assert url == URL and kw["headers"]["X-API-Key"] == KEY
84
+ assert kw["allow_redirects"] is False
85
+ parts = kw["files"]
86
+ assert parts[0][0] == "request" and parts[1] == ("file", ("file", PHOTO, "application/octet-stream"))
87
+ sent = json.loads(parts[0][1][1])
88
+ assert sent == {"request_id": rid, "claim_id": "clm_1", "files": [{"file_id": "f1", "sha256": PHOTO_SHA}]}
89
+
90
+
91
+ def test_request_id_is_stable_and_depends_on_files():
92
+ a = default_request_id("clm_1", [VerifyFile("f1", PHOTO)])
93
+ assert a == default_request_id("clm_1", [VerifyFile("f1", PHOTO)])
94
+ assert a != default_request_id("clm_1", [VerifyFile("f1", PHOTO + b"x")])
95
+
96
+
97
+ def test_file_error_result():
98
+ files = [VerifyFile("f1", PHOTO)]
99
+ result = {
100
+ "file_id": "f1", "status": "error", "badge": "not_checked", "pass": False, "match_type": "none",
101
+ "reasons": ["corrupt_file"], "error": {"code": "corrupt_file", "retryable": False, "message": "x"},
102
+ }
103
+ c, _ = client([FakeResponse(200, ok_body("r1", [result]))])
104
+ r = c.verify("clm_1", files, request_id="r1").results[0]
105
+ assert not r.ok and r.error.code == "corrupt_file" and r.error.retryable is False
106
+
107
+
108
+ @pytest.mark.parametrize("mutate", [
109
+ lambda b: b.update(request_id="other"),
110
+ lambda b: b.update(results=[]),
111
+ lambda b: b.update(verified_at="yesterday"),
112
+ lambda b: b["results"][0].update(badge="great"),
113
+ lambda b: b["results"][0].update(**{"pass": True, "badge": "altered"}),
114
+ lambda b: b["results"][0].update(file={"sha256": "0" * 64}),
115
+ lambda b: b["results"][0].update(file_id="f2"),
116
+ lambda b: b["results"][0].update(reasons=["Bad Code"]),
117
+ ])
118
+ def test_bad_response_fails_closed(mutate):
119
+ body = ok_body("r1", [ok_result()])
120
+ mutate(body)
121
+ c, _ = client([FakeResponse(200, body)])
122
+ with pytest.raises(VerifyResponseError):
123
+ c.verify("clm_1", [VerifyFile("f1", PHOTO)], request_id="r1")
124
+
125
+
126
+ def test_non_retryable_error_raises_without_retry():
127
+ body = {"error": {"code": "unauthorized", "message": "nope", "retryable": False}}
128
+ c, s = client([FakeResponse(401, body)])
129
+ with pytest.raises(VerifyError) as e:
130
+ c.verify("clm_1", [VerifyFile("f1", PHOTO)])
131
+ assert e.value.code == "unauthorized" and not e.value.retryable and len(s.calls) == 1
132
+
133
+
134
+ def test_retryable_then_ok():
135
+ files = [VerifyFile("f1", PHOTO)]
136
+ rid = default_request_id("clm_1", files)
137
+ c, s = client([FakeResponse(502, text="<html>"), FakeResponse(200, ok_body(rid, [ok_result()]))])
138
+ assert c.verify("clm_1", files).results[0].badge == "verified"
139
+ assert len(s.calls) == 2
140
+
141
+
142
+ def test_network_error_retried_then_raised():
143
+ c, s = client([requests.ConnectionError(), requests.ConnectionError()])
144
+ with pytest.raises(VerifyError) as e:
145
+ c.verify("clm_1", [VerifyFile("f1", PHOTO)])
146
+ assert e.value.code == "network_error" and e.value.retryable and len(s.calls) == 2
147
+
148
+
149
+ @pytest.mark.parametrize("claim, files", [
150
+ ("bad claim", [VerifyFile("f1", PHOTO)]),
151
+ ("clm_1", []),
152
+ ("clm_1", [VerifyFile("f1", PHOTO), VerifyFile("f1", PHOTO)]),
153
+ ("clm_1", [VerifyFile("f%d" % i, PHOTO) for i in range(26)]),
154
+ ("clm_1", [VerifyFile("f1", PHOTO, sha256="ABC")]),
155
+ ])
156
+ def test_invalid_requests_rejected_locally(claim, files):
157
+ c, s = client([])
158
+ with pytest.raises(ValueError):
159
+ c.verify(claim, files)
160
+ assert s.calls == []
161
+
162
+
163
+ def test_requires_https():
164
+ with pytest.raises(ValueError):
165
+ VerifyClient(KEY, "http://insecure.test/v1/verify")
166
+
167
+
168
+ def test_health_url():
169
+ c, s = client([FakeResponse(200, {"status": "ok", "api_version": "1"})])
170
+ assert c.health()["status"] == "ok"
171
+ assert s.calls[0][0] == "https://verify.example.test/v1/health"