statement-fetch 0.5.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.
- statement_fetch/__init__.py +126 -0
- statement_fetch/_contracts.py +532 -0
- statement_fetch/_playwright.py +518 -0
- statement_fetch/_registry.py +132 -0
- statement_fetch/_runner.py +538 -0
- statement_fetch/_staging.py +409 -0
- statement_fetch/_validators.py +242 -0
- statement_fetch/api.py +133 -0
- statement_fetch/cli.py +686 -0
- statement_fetch/demo.py +111 -0
- statement_fetch/providers/__init__.py +1 -0
- statement_fetch/providers/example_bank.py +152 -0
- statement_fetch/py.typed +0 -0
- statement_fetch/sinks/__init__.py +1 -0
- statement_fetch/sinks/directory.py +260 -0
- statement_fetch-0.5.0.dist-info/METADATA +95 -0
- statement_fetch-0.5.0.dist-info/RECORD +20 -0
- statement_fetch-0.5.0.dist-info/WHEEL +4 -0
- statement_fetch-0.5.0.dist-info/entry_points.txt +8 -0
- statement_fetch-0.5.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Atomic `0600` isolated staging, portable manifest I/O, and filename sanitization."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import errno
|
|
5
|
+
import hashlib
|
|
6
|
+
import importlib.metadata
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import secrets
|
|
11
|
+
import tempfile
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from datetime import date, datetime, timezone
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, BinaryIO
|
|
16
|
+
|
|
17
|
+
from ._contracts import (
|
|
18
|
+
API_VERSION,
|
|
19
|
+
MANIFEST_SCHEMA_VERSION,
|
|
20
|
+
Artifact,
|
|
21
|
+
ProviderSpec,
|
|
22
|
+
ValidationResult,
|
|
23
|
+
ValidatorFn,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_SAFE_FILENAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$")
|
|
27
|
+
_RESERVED_STAGE_NAMES = frozenset({"manifest.json"})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def sha256_file(path: Path) -> str:
|
|
31
|
+
h = hashlib.sha256()
|
|
32
|
+
with path.open("rb") as fh:
|
|
33
|
+
for chunk in iter(lambda: fh.read(65536), b""):
|
|
34
|
+
h.update(chunk)
|
|
35
|
+
return h.hexdigest()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def open_private_exclusive(path: Path) -> BinaryIO:
|
|
39
|
+
"""Create and open a new file atomically with `0o600` permissions from birth (no umask exposure window)."""
|
|
40
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
41
|
+
if hasattr(os, "O_NOFOLLOW"):
|
|
42
|
+
flags |= os.O_NOFOLLOW
|
|
43
|
+
fd = os.open(str(path), flags, 0o600)
|
|
44
|
+
try:
|
|
45
|
+
return os.fdopen(fd, "wb")
|
|
46
|
+
except BaseException:
|
|
47
|
+
os.close(fd)
|
|
48
|
+
raise
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def write_private_text_atomic(dest: Path, text: str) -> None:
|
|
52
|
+
"""Atomically write UTF-8 text to `dest` via an exclusive `0o600` temp file."""
|
|
53
|
+
tmp = dest.parent / f".{dest.name}.{os.getpid()}.{secrets.token_hex(6)}.part"
|
|
54
|
+
try:
|
|
55
|
+
with open_private_exclusive(tmp) as wf:
|
|
56
|
+
wf.write(text.encode("utf-8"))
|
|
57
|
+
tmp.replace(dest)
|
|
58
|
+
except BaseException:
|
|
59
|
+
tmp.unlink(missing_ok=True)
|
|
60
|
+
raise
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def publish_exclusive_file(tmp: Path, dest: Path) -> None:
|
|
64
|
+
"""Publish `tmp` to `dest` without overwriting an existing `dest`.
|
|
65
|
+
|
|
66
|
+
Uses `os.link(tmp, dest)` + unlink on POSIX filesystems that support hardlinks,
|
|
67
|
+
falling back to `O_CREAT|O_EXCL` copy (at `0o600`) on filesystems without hardlink
|
|
68
|
+
support (e.g. exFAT, SMB, FUSE). Raises `FileExistsError` if `dest` already exists.
|
|
69
|
+
"""
|
|
70
|
+
try:
|
|
71
|
+
os.link(tmp, dest)
|
|
72
|
+
tmp.unlink(missing_ok=True)
|
|
73
|
+
return
|
|
74
|
+
except FileExistsError:
|
|
75
|
+
raise
|
|
76
|
+
except OSError as exc:
|
|
77
|
+
if exc.errno not in (errno.EPERM, errno.EOPNOTSUPP, errno.EXDEV, errno.ENOTSUP, errno.EACCES):
|
|
78
|
+
raise
|
|
79
|
+
# Fallback for filesystems without hardlink support: exclusive create + stream copy.
|
|
80
|
+
try:
|
|
81
|
+
with tmp.open("rb") as rf, open_private_exclusive(dest) as wf:
|
|
82
|
+
while True:
|
|
83
|
+
chunk = rf.read(65536)
|
|
84
|
+
if not chunk:
|
|
85
|
+
break
|
|
86
|
+
wf.write(chunk)
|
|
87
|
+
except FileExistsError:
|
|
88
|
+
raise
|
|
89
|
+
except BaseException:
|
|
90
|
+
dest.unlink(missing_ok=True)
|
|
91
|
+
raise
|
|
92
|
+
tmp.unlink(missing_ok=True)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def sanitize_filename(name: str) -> str:
|
|
96
|
+
"""Normalize a filename into a portable ASCII basename while preserving its extension."""
|
|
97
|
+
base = Path(name).name
|
|
98
|
+
if not base or base in (".", ".."):
|
|
99
|
+
raise ValueError(f"Unsafe staged filename: {name!r}")
|
|
100
|
+
p = Path(base)
|
|
101
|
+
raw_stem = p.stem if p.suffix else base
|
|
102
|
+
raw_ext = p.suffix.lower() if p.suffix else ""
|
|
103
|
+
clean_ext = re.sub(r"[^a-z0-9]", "", raw_ext.lstrip("."))
|
|
104
|
+
ext = f".{clean_ext[:16]}" if clean_ext else ""
|
|
105
|
+
clean_stem = re.sub(r"[^A-Za-z0-9._-]+", "_", raw_stem).strip("._-")
|
|
106
|
+
if not clean_stem:
|
|
107
|
+
digest = hashlib.sha256(base.encode("utf-8", errors="replace")).hexdigest()[:10]
|
|
108
|
+
clean_stem = f"artifact-{digest}"
|
|
109
|
+
max_stem = 180 - len(ext)
|
|
110
|
+
candidate = f"{clean_stem[:max_stem]}{ext}"
|
|
111
|
+
if candidate.lower() in _RESERVED_STAGE_NAMES or candidate.startswith(".manifest"):
|
|
112
|
+
raise ValueError(f"Reserved staged filename: {name!r}")
|
|
113
|
+
if not _SAFE_FILENAME_RE.fullmatch(candidate):
|
|
114
|
+
raise ValueError(f"Unsafe staged filename: {name!r}")
|
|
115
|
+
return candidate
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class Stage:
|
|
119
|
+
"""Isolated per-run staging directory producing a portable, atomic `manifest.json`."""
|
|
120
|
+
|
|
121
|
+
def __init__(
|
|
122
|
+
self,
|
|
123
|
+
provider_id: str,
|
|
124
|
+
stage_dir: Path | None = None,
|
|
125
|
+
*,
|
|
126
|
+
spec: ProviderSpec | None = None,
|
|
127
|
+
) -> None:
|
|
128
|
+
self.provider_id = provider_id
|
|
129
|
+
self.spec = spec
|
|
130
|
+
self.owns_dir = stage_dir is None
|
|
131
|
+
if stage_dir is None:
|
|
132
|
+
raw = Path(tempfile.mkdtemp(prefix=f"sf-{provider_id}-"))
|
|
133
|
+
os.chmod(raw, 0o700)
|
|
134
|
+
self.root = raw.resolve()
|
|
135
|
+
else:
|
|
136
|
+
stage_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
137
|
+
self.root = stage_dir.resolve()
|
|
138
|
+
self._artifacts: list[Artifact] = []
|
|
139
|
+
self._skipped: list[dict[str, str]] = []
|
|
140
|
+
self._errors: list[str] = []
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def artifacts(self) -> tuple[Artifact, ...]:
|
|
144
|
+
return tuple(self._artifacts)
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def skipped(self) -> tuple[dict[str, str], ...]:
|
|
148
|
+
return tuple(self._skipped)
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def errors(self) -> tuple[str, ...]:
|
|
152
|
+
return tuple(self._errors)
|
|
153
|
+
|
|
154
|
+
def add(
|
|
155
|
+
self,
|
|
156
|
+
src: Path,
|
|
157
|
+
*,
|
|
158
|
+
artifact_id: str,
|
|
159
|
+
kind: str,
|
|
160
|
+
period: str,
|
|
161
|
+
filename: str | None = None,
|
|
162
|
+
currency: str = "",
|
|
163
|
+
meta: Mapping[str, str] | None = None,
|
|
164
|
+
validator: ValidatorFn | None = None,
|
|
165
|
+
move: bool = True,
|
|
166
|
+
) -> Artifact:
|
|
167
|
+
raw_src = Path(src)
|
|
168
|
+
if raw_src.is_symlink():
|
|
169
|
+
raise ValueError(f"Refusing to stage symlink source: {src}")
|
|
170
|
+
src_path = raw_src.resolve()
|
|
171
|
+
if not src_path.is_file():
|
|
172
|
+
raise FileNotFoundError(f"Source artifact not found: {src}")
|
|
173
|
+
safe_name = sanitize_filename(filename or src_path.name)
|
|
174
|
+
dest = (self.root / safe_name).resolve()
|
|
175
|
+
if dest.parent != self.root:
|
|
176
|
+
raise ValueError(f"Staged path escapes stage root: {safe_name!r}")
|
|
177
|
+
if dest.exists():
|
|
178
|
+
raise FileExistsError(f"Staged artifact already exists (refusing overwrite): {safe_name!r}")
|
|
179
|
+
|
|
180
|
+
eff_validator = validator
|
|
181
|
+
if self.spec is not None:
|
|
182
|
+
amap = self.spec.artifact_map()
|
|
183
|
+
if artifact_id not in amap:
|
|
184
|
+
raise ValueError(f"Undeclared artifact_id {artifact_id!r} for provider {self.spec.id!r}")
|
|
185
|
+
if eff_validator is None:
|
|
186
|
+
eff_validator = amap[artifact_id].validator
|
|
187
|
+
|
|
188
|
+
# Single-pass atomic copy + SHA-256 into an exclusive 0o600 temp file preserving extension before validation.
|
|
189
|
+
tmp = self.root / f".part-{os.getpid()}-{secrets.token_hex(6)}-{safe_name}"
|
|
190
|
+
h = hashlib.sha256()
|
|
191
|
+
size_bytes = 0
|
|
192
|
+
try:
|
|
193
|
+
with src_path.open("rb") as rf, open_private_exclusive(tmp) as wf:
|
|
194
|
+
while True:
|
|
195
|
+
chunk = rf.read(65536)
|
|
196
|
+
if not chunk:
|
|
197
|
+
break
|
|
198
|
+
h.update(chunk)
|
|
199
|
+
wf.write(chunk)
|
|
200
|
+
size_bytes += len(chunk)
|
|
201
|
+
val = eff_validator(tmp) if eff_validator is not None else ValidationResult(valid=size_bytes > 0)
|
|
202
|
+
publish_exclusive_file(tmp, dest)
|
|
203
|
+
except BaseException:
|
|
204
|
+
tmp.unlink(missing_ok=True)
|
|
205
|
+
raise
|
|
206
|
+
|
|
207
|
+
if move and src_path != dest:
|
|
208
|
+
src_path.unlink(missing_ok=True)
|
|
209
|
+
|
|
210
|
+
art = Artifact(
|
|
211
|
+
artifact_id=artifact_id,
|
|
212
|
+
path=dest,
|
|
213
|
+
name=safe_name,
|
|
214
|
+
sha256=h.hexdigest(),
|
|
215
|
+
bytes=size_bytes,
|
|
216
|
+
provider=self.provider_id,
|
|
217
|
+
kind=kind,
|
|
218
|
+
period=period,
|
|
219
|
+
currency=currency or val.currency,
|
|
220
|
+
valid=val.valid,
|
|
221
|
+
error=val.error,
|
|
222
|
+
observed_start=val.date_from,
|
|
223
|
+
observed_end=val.date_to,
|
|
224
|
+
meta={str(k): str(v) for k, v in (meta or {}).items() if str(v)},
|
|
225
|
+
)
|
|
226
|
+
self._artifacts.append(art)
|
|
227
|
+
if not val.valid:
|
|
228
|
+
self._errors.append(f"{safe_name}: {val.error or 'validation failed'}")
|
|
229
|
+
return art
|
|
230
|
+
|
|
231
|
+
def reuse_existing(
|
|
232
|
+
self,
|
|
233
|
+
filename: str,
|
|
234
|
+
*,
|
|
235
|
+
artifact_id: str,
|
|
236
|
+
kind: str,
|
|
237
|
+
period: str,
|
|
238
|
+
currency: str = "",
|
|
239
|
+
meta: Mapping[str, str] | None = None,
|
|
240
|
+
validator: ValidatorFn | None = None,
|
|
241
|
+
) -> Artifact | None:
|
|
242
|
+
"""Validate and register an already-staged file in `stage.root` (for `--skip-existing` reruns)."""
|
|
243
|
+
safe_name = sanitize_filename(filename)
|
|
244
|
+
for existing in self._artifacts:
|
|
245
|
+
if existing.name == safe_name:
|
|
246
|
+
return existing
|
|
247
|
+
raw_dest = self.root / safe_name
|
|
248
|
+
if raw_dest.is_symlink():
|
|
249
|
+
return None
|
|
250
|
+
dest = raw_dest.resolve()
|
|
251
|
+
if dest.parent != self.root or not dest.is_file():
|
|
252
|
+
return None
|
|
253
|
+
eff_validator = validator
|
|
254
|
+
if self.spec is not None:
|
|
255
|
+
amap = self.spec.artifact_map()
|
|
256
|
+
if artifact_id not in amap:
|
|
257
|
+
raise ValueError(f"Undeclared artifact_id {artifact_id!r} for provider {self.spec.id!r}")
|
|
258
|
+
if eff_validator is None:
|
|
259
|
+
eff_validator = amap[artifact_id].validator
|
|
260
|
+
size_bytes = dest.stat().st_size
|
|
261
|
+
val = eff_validator(dest) if eff_validator is not None else ValidationResult(valid=size_bytes > 0)
|
|
262
|
+
if not val.valid:
|
|
263
|
+
# Remove the invalid prior staged file so the provider can re-download and re-stage cleanly.
|
|
264
|
+
dest.unlink(missing_ok=True)
|
|
265
|
+
return None
|
|
266
|
+
art = Artifact(
|
|
267
|
+
artifact_id=artifact_id,
|
|
268
|
+
path=dest,
|
|
269
|
+
name=safe_name,
|
|
270
|
+
sha256=sha256_file(dest),
|
|
271
|
+
bytes=size_bytes,
|
|
272
|
+
provider=self.provider_id,
|
|
273
|
+
kind=kind,
|
|
274
|
+
period=period,
|
|
275
|
+
currency=currency or val.currency,
|
|
276
|
+
valid=True,
|
|
277
|
+
observed_start=val.date_from,
|
|
278
|
+
observed_end=val.date_to,
|
|
279
|
+
meta={str(k): str(v) for k, v in (meta or {}).items() if str(v)},
|
|
280
|
+
)
|
|
281
|
+
self._artifacts.append(art)
|
|
282
|
+
return art
|
|
283
|
+
|
|
284
|
+
def add_bytes(
|
|
285
|
+
self,
|
|
286
|
+
data: bytes,
|
|
287
|
+
*,
|
|
288
|
+
artifact_id: str,
|
|
289
|
+
kind: str,
|
|
290
|
+
period: str,
|
|
291
|
+
filename: str,
|
|
292
|
+
currency: str = "",
|
|
293
|
+
meta: Mapping[str, str] | None = None,
|
|
294
|
+
validator: ValidatorFn | None = None,
|
|
295
|
+
) -> Artifact:
|
|
296
|
+
"""Stage in-memory bytes atomically with `0o600` permissions, SHA-256 hashing, and validation."""
|
|
297
|
+
safe_name = sanitize_filename(filename)
|
|
298
|
+
tmp = self.root / f".{safe_name}.{os.getpid()}.{secrets.token_hex(6)}.src"
|
|
299
|
+
try:
|
|
300
|
+
with open_private_exclusive(tmp) as wf:
|
|
301
|
+
wf.write(data)
|
|
302
|
+
return self.add(
|
|
303
|
+
tmp,
|
|
304
|
+
artifact_id=artifact_id,
|
|
305
|
+
kind=kind,
|
|
306
|
+
period=period,
|
|
307
|
+
filename=safe_name,
|
|
308
|
+
currency=currency,
|
|
309
|
+
meta=meta,
|
|
310
|
+
validator=validator,
|
|
311
|
+
move=True,
|
|
312
|
+
)
|
|
313
|
+
finally:
|
|
314
|
+
tmp.unlink(missing_ok=True)
|
|
315
|
+
|
|
316
|
+
def rename_artifact(
|
|
317
|
+
self,
|
|
318
|
+
old_name: str,
|
|
319
|
+
new_filename: str,
|
|
320
|
+
*,
|
|
321
|
+
meta_updates: Mapping[str, str] | None = None,
|
|
322
|
+
) -> Artifact | None:
|
|
323
|
+
"""Atomically rename an already-staged artifact and optionally update its `meta`."""
|
|
324
|
+
safe_new = sanitize_filename(new_filename)
|
|
325
|
+
for idx, art in enumerate(self._artifacts):
|
|
326
|
+
if art.name != old_name:
|
|
327
|
+
continue
|
|
328
|
+
new_path = (self.root / safe_new).resolve()
|
|
329
|
+
if new_path.parent != self.root:
|
|
330
|
+
raise ValueError(f"Renamed path escapes stage root: {safe_new!r}")
|
|
331
|
+
if new_path != art.path:
|
|
332
|
+
if new_path.exists():
|
|
333
|
+
raise FileExistsError(f"Cannot rename onto existing artifact: {safe_new!r}")
|
|
334
|
+
publish_exclusive_file(art.path, new_path)
|
|
335
|
+
merged_meta = dict(art.meta)
|
|
336
|
+
if meta_updates:
|
|
337
|
+
for k, v in meta_updates.items():
|
|
338
|
+
if str(v):
|
|
339
|
+
merged_meta[str(k)] = str(v)
|
|
340
|
+
else:
|
|
341
|
+
merged_meta.pop(str(k), None)
|
|
342
|
+
updated = Artifact(
|
|
343
|
+
artifact_id=art.artifact_id,
|
|
344
|
+
path=new_path,
|
|
345
|
+
name=safe_new,
|
|
346
|
+
sha256=art.sha256,
|
|
347
|
+
bytes=art.bytes,
|
|
348
|
+
provider=art.provider,
|
|
349
|
+
kind=art.kind,
|
|
350
|
+
period=art.period,
|
|
351
|
+
currency=art.currency,
|
|
352
|
+
valid=art.valid,
|
|
353
|
+
error=art.error,
|
|
354
|
+
observed_start=art.observed_start,
|
|
355
|
+
observed_end=art.observed_end,
|
|
356
|
+
meta=merged_meta,
|
|
357
|
+
)
|
|
358
|
+
self._artifacts[idx] = updated
|
|
359
|
+
return updated
|
|
360
|
+
return None
|
|
361
|
+
|
|
362
|
+
def skip(self, artifact_id: str, reason: str) -> None:
|
|
363
|
+
if self.spec is not None and artifact_id not in self.spec.artifact_map():
|
|
364
|
+
raise ValueError(f"Undeclared artifact_id {artifact_id!r} for provider {self.spec.id!r}")
|
|
365
|
+
self._skipped.append({"artifact": artifact_id, "reason": reason})
|
|
366
|
+
|
|
367
|
+
def error(self, message: str) -> None:
|
|
368
|
+
self._errors.append(message)
|
|
369
|
+
|
|
370
|
+
def write_manifest(
|
|
371
|
+
self,
|
|
372
|
+
*,
|
|
373
|
+
timings_s: dict[str, float] | None = None,
|
|
374
|
+
period_start: date | None = None,
|
|
375
|
+
period_end: date | None = None,
|
|
376
|
+
) -> Path:
|
|
377
|
+
manifest_path = self.root / "manifest.json"
|
|
378
|
+
try:
|
|
379
|
+
tool_version = importlib.metadata.version("statement-fetch")
|
|
380
|
+
except importlib.metadata.PackageNotFoundError:
|
|
381
|
+
tool_version = "0.0.0-dev"
|
|
382
|
+
payload: dict[str, Any] = {
|
|
383
|
+
"schema_version": MANIFEST_SCHEMA_VERSION,
|
|
384
|
+
"api_version": API_VERSION,
|
|
385
|
+
"tool_version": tool_version,
|
|
386
|
+
"created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
387
|
+
"provider": self.provider_id,
|
|
388
|
+
"artifacts": [a.to_manifest_dict() for a in self._artifacts],
|
|
389
|
+
"skipped": list(self._skipped),
|
|
390
|
+
"errors": list(self._errors),
|
|
391
|
+
"timings_s": dict(timings_s or {}),
|
|
392
|
+
}
|
|
393
|
+
if period_start is not None:
|
|
394
|
+
payload["period_start"] = period_start.isoformat()
|
|
395
|
+
if period_end is not None:
|
|
396
|
+
payload["period_end"] = period_end.isoformat()
|
|
397
|
+
write_private_text_atomic(manifest_path, json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
|
|
398
|
+
return manifest_path
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def load_manifest(path: Path) -> tuple[Path, dict[str, Any]]:
|
|
402
|
+
"""Load and validate a `manifest.json`, returning `(manifest_path, payload)`."""
|
|
403
|
+
target = (path / "manifest.json" if path.is_dir() else path).resolve()
|
|
404
|
+
raw = json.loads(target.read_text(encoding="utf-8"))
|
|
405
|
+
if not isinstance(raw, dict) or raw.get("schema_version") != MANIFEST_SCHEMA_VERSION:
|
|
406
|
+
raise ValueError(f"Unsupported or invalid manifest: {target}")
|
|
407
|
+
if not isinstance(raw.get("artifacts"), list):
|
|
408
|
+
raise ValueError(f"Manifest missing artifacts list: {target}")
|
|
409
|
+
return target, raw
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Single unified structural validator pipeline shared by `Stage`, `inspect`, and sinks."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import csv
|
|
5
|
+
import hmac
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import stat
|
|
9
|
+
import xml.etree.ElementTree as ET
|
|
10
|
+
import zipfile
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ._contracts import ValidationResult
|
|
16
|
+
from ._staging import load_manifest, sha256_file
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def validate_pdf(path: Path) -> ValidationResult:
|
|
20
|
+
raw = path.read_bytes()
|
|
21
|
+
if not raw.lstrip().startswith(b"%PDF-"):
|
|
22
|
+
return ValidationResult(valid=False, kind="pdf", error="missing %PDF- magic header")
|
|
23
|
+
if len(raw) >= 128 and b"%%EOF" not in raw[-4096:]:
|
|
24
|
+
return ValidationResult(valid=False, kind="pdf", error="missing %%EOF trailer (truncated PDF)")
|
|
25
|
+
return ValidationResult(valid=True, kind="pdf")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def validate_csv(path: Path) -> ValidationResult:
|
|
29
|
+
raw = path.read_bytes()
|
|
30
|
+
if not raw.strip():
|
|
31
|
+
return ValidationResult(valid=False, kind="csv", error="empty CSV file")
|
|
32
|
+
try:
|
|
33
|
+
text = raw.decode("utf-8-sig")
|
|
34
|
+
except UnicodeDecodeError:
|
|
35
|
+
return ValidationResult(valid=False, kind="csv", error="CSV is not valid UTF-8")
|
|
36
|
+
stripped = text.lstrip()
|
|
37
|
+
if stripped.startswith(("<", "{", "[")):
|
|
38
|
+
return ValidationResult(valid=False, kind="csv", error="file looks like HTML/XML or JSON, not CSV")
|
|
39
|
+
first_line = next((ln for ln in stripped.splitlines() if ln.strip()), "")
|
|
40
|
+
delim = next((d for d in (",", ";", "\t") if d in first_line), "")
|
|
41
|
+
if not delim:
|
|
42
|
+
return ValidationResult(valid=False, kind="csv", error="CSV header missing delimiter")
|
|
43
|
+
rows = [r for r in csv.reader(io.StringIO(text), delimiter=delim) if any(cell.strip() for cell in r)]
|
|
44
|
+
if not rows or len(rows[0]) < 2:
|
|
45
|
+
return ValidationResult(valid=False, kind="csv", error="CSV header has fewer than 2 columns")
|
|
46
|
+
return ValidationResult(valid=True, kind="csv", rows=max(0, len(rows) - 1))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def validate_json(path: Path) -> ValidationResult:
|
|
50
|
+
try:
|
|
51
|
+
json.loads(path.read_text(encoding="utf-8-sig"))
|
|
52
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
53
|
+
return ValidationResult(valid=False, kind="json", error=f"invalid JSON: {exc}")
|
|
54
|
+
return ValidationResult(valid=True, kind="json")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _is_unsafe_zip_member(name: str) -> bool:
|
|
58
|
+
if not name or "\x00" in name:
|
|
59
|
+
return True
|
|
60
|
+
if name.startswith(("/", "\\")):
|
|
61
|
+
return True
|
|
62
|
+
p_posix = PurePosixPath(name)
|
|
63
|
+
if p_posix.is_absolute() or ".." in p_posix.parts:
|
|
64
|
+
return True
|
|
65
|
+
p_win = PureWindowsPath(name)
|
|
66
|
+
if p_win.is_absolute() or bool(p_win.drive) or ".." in p_win.parts:
|
|
67
|
+
return True
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def validate_zip(
|
|
72
|
+
path: Path,
|
|
73
|
+
*,
|
|
74
|
+
max_entries: int = 200,
|
|
75
|
+
max_uncompressed_bytes: int = 64 * 1024 * 1024,
|
|
76
|
+
) -> ValidationResult:
|
|
77
|
+
"""Validate a ZIP archive with bounded entry count, total uncompressed size, and traversal checks."""
|
|
78
|
+
if not zipfile.is_zipfile(path):
|
|
79
|
+
return ValidationResult(valid=False, kind="zip", error="invalid ZIP archive")
|
|
80
|
+
try:
|
|
81
|
+
with zipfile.ZipFile(path, "r") as zf:
|
|
82
|
+
infos = zf.infolist()
|
|
83
|
+
if not infos:
|
|
84
|
+
return ValidationResult(valid=False, kind="zip", error="empty ZIP archive")
|
|
85
|
+
if len(infos) > max_entries:
|
|
86
|
+
return ValidationResult(
|
|
87
|
+
valid=False,
|
|
88
|
+
kind="zip",
|
|
89
|
+
error=f"ZIP entry count {len(infos)} exceeds limit {max_entries}",
|
|
90
|
+
)
|
|
91
|
+
total_uncompressed = 0
|
|
92
|
+
for info in infos:
|
|
93
|
+
if _is_unsafe_zip_member(info.filename):
|
|
94
|
+
return ValidationResult(
|
|
95
|
+
valid=False,
|
|
96
|
+
kind="zip",
|
|
97
|
+
error=f"unsafe ZIP member path: {info.filename!r}",
|
|
98
|
+
)
|
|
99
|
+
if stat.S_ISLNK(info.external_attr >> 16):
|
|
100
|
+
return ValidationResult(
|
|
101
|
+
valid=False,
|
|
102
|
+
kind="zip",
|
|
103
|
+
error=f"ZIP symlink member not allowed: {info.filename!r}",
|
|
104
|
+
)
|
|
105
|
+
if info.file_size < 0 or info.compress_size < 0:
|
|
106
|
+
return ValidationResult(valid=False, kind="zip", error="negative ZIP member size")
|
|
107
|
+
total_uncompressed += info.file_size
|
|
108
|
+
if total_uncompressed > max_uncompressed_bytes:
|
|
109
|
+
return ValidationResult(
|
|
110
|
+
valid=False,
|
|
111
|
+
kind="zip",
|
|
112
|
+
error=f"ZIP uncompressed size {total_uncompressed} exceeds limit {max_uncompressed_bytes}",
|
|
113
|
+
)
|
|
114
|
+
except (zipfile.BadZipFile, OSError) as exc:
|
|
115
|
+
return ValidationResult(valid=False, kind="zip", error=f"corrupt ZIP archive: {exc}")
|
|
116
|
+
return ValidationResult(valid=True, kind="zip", rows=len(infos))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass(frozen=True)
|
|
120
|
+
class Inspection:
|
|
121
|
+
"""Internal structural inspection summary used by `statement-fetch inspect`."""
|
|
122
|
+
|
|
123
|
+
kind: str
|
|
124
|
+
valid: bool
|
|
125
|
+
summary: str
|
|
126
|
+
error: str = ""
|
|
127
|
+
rows: int = 0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def inspect_generic_file(path: Path) -> Inspection:
|
|
131
|
+
"""Inspect a local file using the exact same structural validators as `Stage`."""
|
|
132
|
+
suffix = path.suffix.lower()
|
|
133
|
+
size_kb = path.stat().st_size / 1024
|
|
134
|
+
if suffix == ".csv":
|
|
135
|
+
res = validate_csv(path)
|
|
136
|
+
if not res.valid:
|
|
137
|
+
return Inspection("csv", False, f"[CSV] {path.name}: INVALID ({res.error})", error=res.error)
|
|
138
|
+
return Inspection("csv", True, f"[CSV] {path.name} ({res.rows} rows, {size_kb:.1f} KB)", rows=res.rows)
|
|
139
|
+
if suffix == ".pdf":
|
|
140
|
+
res = validate_pdf(path)
|
|
141
|
+
if not res.valid:
|
|
142
|
+
return Inspection("pdf", False, f"[PDF] {path.name}: INVALID ({res.error})", error=res.error)
|
|
143
|
+
return Inspection("pdf", True, f"[PDF] {path.name} ({size_kb:.1f} KB)")
|
|
144
|
+
if suffix == ".json":
|
|
145
|
+
res = validate_json(path)
|
|
146
|
+
if not res.valid:
|
|
147
|
+
return Inspection("json", False, f"[JSON] {path.name}: INVALID ({res.error})", error=res.error)
|
|
148
|
+
return Inspection("json", True, f"[JSON] {path.name} ({size_kb:.1f} KB)")
|
|
149
|
+
if suffix == ".xlsx":
|
|
150
|
+
raw = path.read_bytes()
|
|
151
|
+
if not raw.startswith(b"PK\x03\x04"):
|
|
152
|
+
return Inspection("xlsx", False, f"[XLSX] {path.name}: INVALID missing OOXML PK header", error="invalid XLSX header")
|
|
153
|
+
return Inspection("xlsx", True, f"[XLSX] {path.name} ({size_kb:.1f} KB)")
|
|
154
|
+
if suffix == ".zip":
|
|
155
|
+
res = validate_zip(path)
|
|
156
|
+
if not res.valid:
|
|
157
|
+
return Inspection("zip", False, f"[ZIP] {path.name}: INVALID ({res.error})", error=res.error)
|
|
158
|
+
return Inspection("zip", True, f"[ZIP] {path.name} ({res.rows} entries, {size_kb:.1f} KB)", rows=res.rows)
|
|
159
|
+
if suffix == ".xml":
|
|
160
|
+
try:
|
|
161
|
+
ET.fromstring(path.read_bytes())
|
|
162
|
+
except ET.ParseError:
|
|
163
|
+
return Inspection("xml", False, f"[XML] {path.name}: INVALID XML payload", error="invalid XML")
|
|
164
|
+
return Inspection("xml", True, f"[XML] {path.name} ({size_kb:.1f} KB)")
|
|
165
|
+
if suffix in (".png", ".jpg", ".jpeg", ".webp", ".heic"):
|
|
166
|
+
return Inspection("image", True, f"[Image] {path.name} ({size_kb:.1f} KB)")
|
|
167
|
+
return Inspection("other", True, f"[File] {path.name} ({size_kb:.1f} KB)")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@dataclass(frozen=True)
|
|
171
|
+
class ManifestArtifact:
|
|
172
|
+
"""Verified manifest artifact entry resolved safely inside its staging directory."""
|
|
173
|
+
|
|
174
|
+
name: str
|
|
175
|
+
path: Path
|
|
176
|
+
sha256: str
|
|
177
|
+
entry: dict[str, Any]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def iter_verified_manifest_artifacts(
|
|
181
|
+
manifest_path: Path,
|
|
182
|
+
*,
|
|
183
|
+
verify_sha256: bool = True,
|
|
184
|
+
) -> tuple[Path, dict[str, Any], list[ManifestArtifact], list[dict[str, str]]]:
|
|
185
|
+
"""Load `manifest.json` and validate all entries (relative non-symlink containment, `valid=True`, optional SHA-256).
|
|
186
|
+
|
|
187
|
+
Returns `(resolved_manifest_path, manifest_payload, verified_items, errors)`.
|
|
188
|
+
"""
|
|
189
|
+
resolved_mp, mdata = load_manifest(manifest_path)
|
|
190
|
+
stage_root = resolved_mp.parent.resolve()
|
|
191
|
+
artifacts = mdata.get("artifacts") or []
|
|
192
|
+
verified: list[ManifestArtifact] = []
|
|
193
|
+
errors: list[dict[str, str]] = []
|
|
194
|
+
for idx, entry in enumerate(artifacts):
|
|
195
|
+
if not isinstance(entry, dict):
|
|
196
|
+
errors.append({"name": f"artifacts[{idx}]", "error": "malformed manifest artifact entry"})
|
|
197
|
+
continue
|
|
198
|
+
name = str(entry.get("name") or "")
|
|
199
|
+
raw_rel = str(entry.get("path") or name)
|
|
200
|
+
label = name or raw_rel or f"artifacts[{idx}]"
|
|
201
|
+
if entry.get("valid") is not True:
|
|
202
|
+
errors.append({"name": label, "error": str(entry.get("error") or "artifact marked invalid")})
|
|
203
|
+
continue
|
|
204
|
+
expected_sha = str(entry.get("sha256") or "").strip().lower()
|
|
205
|
+
if not expected_sha:
|
|
206
|
+
errors.append({"name": label, "error": "manifest missing sha256"})
|
|
207
|
+
continue
|
|
208
|
+
if not raw_rel or "\x00" in raw_rel:
|
|
209
|
+
errors.append({"name": label, "error": "invalid artifact path"})
|
|
210
|
+
continue
|
|
211
|
+
rel_path = Path(raw_rel)
|
|
212
|
+
if rel_path.is_absolute() or ".." in rel_path.parts:
|
|
213
|
+
errors.append({"name": label, "error": "artifact path outside manifest directory (must be relative)"})
|
|
214
|
+
continue
|
|
215
|
+
raw_src = stage_root / rel_path
|
|
216
|
+
if raw_src.is_symlink():
|
|
217
|
+
errors.append({"name": label, "error": "artifact symlink not allowed"})
|
|
218
|
+
continue
|
|
219
|
+
src = raw_src.resolve()
|
|
220
|
+
if not src.is_file() or not src.is_relative_to(stage_root):
|
|
221
|
+
errors.append({"name": label, "error": "artifact missing or outside manifest directory"})
|
|
222
|
+
continue
|
|
223
|
+
if verify_sha256:
|
|
224
|
+
actual_sha = sha256_file(src)
|
|
225
|
+
if not hmac.compare_digest(actual_sha, expected_sha):
|
|
226
|
+
errors.append({"name": label, "error": "sha256 mismatch"})
|
|
227
|
+
continue
|
|
228
|
+
verified.append(ManifestArtifact(name=name or src.name, path=src, sha256=expected_sha, entry=dict(entry)))
|
|
229
|
+
return resolved_mp, mdata, verified, errors
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def verify_manifest_artifacts(manifest_path: Path) -> dict[str, Any]:
|
|
233
|
+
"""Verify a manifest's schema, artifact file presence, stage containment, and SHA-256 digests."""
|
|
234
|
+
resolved_mp, mdata, verified, errors = iter_verified_manifest_artifacts(manifest_path, verify_sha256=True)
|
|
235
|
+
artifacts = mdata.get("artifacts") or []
|
|
236
|
+
return {
|
|
237
|
+
"manifest": str(resolved_mp),
|
|
238
|
+
"ok": not errors,
|
|
239
|
+
"artifacts": len(artifacts),
|
|
240
|
+
"verified": len(verified),
|
|
241
|
+
"errors": errors,
|
|
242
|
+
}
|