File size: 13,219 Bytes
1fa57f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# sovereign_external_verifier_v2.py
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any, Dict, List, Optional

from sovereign_crypto_seal import SovereignCryptoSeal


def _load_json(path: str) -> Dict[str, Any]:
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(f"File not found: {path}")
    data = json.loads(p.read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise ValueError(f"JSON root must be an object: {path}")
    return data


class SovereignExternalVerifierV2:
    """
    Extended independent verifier for Sovereign artifacts.

    Supported artifact families:
      - runtime result bundles
      - benchmark bundles
      - validation report bundles
      - manifest bundles
      - validation manifest bundles
      - technical identity bundles with nested verification
    """

    def __init__(self, sealer: Optional[SovereignCryptoSeal] = None) -> None:
        self.sealer = sealer or SovereignCryptoSeal()

    # ------------------------------------------------------------------
    # Base verify helpers
    # ------------------------------------------------------------------
    def _verify_object_with_seal(
        self,
        *,
        artifact_type: str,
        obj: Dict[str, Any],
        seal: Dict[str, Any],
    ) -> Dict[str, Any]:
        verified = self.sealer.verify_object(obj, seal)
        return {
            "ok": bool(verified.get("ok")),
            "artifact_type": artifact_type,
            "verified": bool(verified.get("verified")),
            "verification": verified,
        }

    # ------------------------------------------------------------------
    # Runtime result
    # ------------------------------------------------------------------
    def verify_runtime_result_bundle(self, bundle: Dict[str, Any]) -> Dict[str, Any]:
        seal = bundle.get("crypto_seal")
        if not isinstance(seal, dict):
            return {
                "ok": False,
                "artifact_type": "runtime_result",
                "verified": False,
                "error": "missing_runtime_crypto_seal",
            }

        obj = dict(bundle)
        obj.pop("crypto_seal", None)
        obj.pop("sealed", None)

        return self._verify_object_with_seal(
            artifact_type="runtime_result",
            obj=obj,
            seal=seal,
        )

    # ------------------------------------------------------------------
    # Benchmark
    # ------------------------------------------------------------------
    def verify_benchmark_bundle(self, bundle: Dict[str, Any]) -> Dict[str, Any]:
        seal = bundle.get("crypto_seal")
        report = bundle.get("report")

        if not isinstance(seal, dict):
            return {
                "ok": False,
                "artifact_type": "benchmark_bundle",
                "verified": False,
                "error": "missing_benchmark_crypto_seal",
            }

        if not isinstance(report, dict):
            return {
                "ok": False,
                "artifact_type": "benchmark_bundle",
                "verified": False,
                "error": "missing_benchmark_report",
            }

        return self._verify_object_with_seal(
            artifact_type="benchmark_bundle",
            obj=report,
            seal=seal,
        )

    # ------------------------------------------------------------------
    # Validation report
    # ------------------------------------------------------------------
    def verify_validation_report_bundle(self, bundle: Dict[str, Any]) -> Dict[str, Any]:
        seal = bundle.get("crypto_seal")
        report = bundle.get("report")

        if not isinstance(seal, dict):
            return {
                "ok": False,
                "artifact_type": "validation_report_bundle",
                "verified": False,
                "error": "missing_validation_crypto_seal",
            }

        if not isinstance(report, dict):
            return {
                "ok": False,
                "artifact_type": "validation_report_bundle",
                "verified": False,
                "error": "missing_validation_report",
            }

        return self._verify_object_with_seal(
            artifact_type="validation_report_bundle",
            obj=report,
            seal=seal,
        )

    # ------------------------------------------------------------------
    # Generic manifest bundle
    # ------------------------------------------------------------------
    def verify_manifest_bundle(self, bundle: Dict[str, Any], artifact_type: str = "manifest_bundle") -> Dict[str, Any]:
        manifest_bundle = bundle.get("manifest_bundle")
        if not isinstance(manifest_bundle, dict):
            return {
                "ok": False,
                "artifact_type": artifact_type,
                "verified": False,
                "error": "missing_manifest_bundle",
            }

        manifest = manifest_bundle.get("manifest")
        seal = manifest_bundle.get("seal")

        if not isinstance(manifest, dict):
            return {
                "ok": False,
                "artifact_type": artifact_type,
                "verified": False,
                "error": "missing_manifest_object",
            }

        if not isinstance(seal, dict):
            return {
                "ok": False,
                "artifact_type": artifact_type,
                "verified": False,
                "error": "missing_manifest_seal",
            }

        return self._verify_object_with_seal(
            artifact_type=artifact_type,
            obj=manifest,
            seal=seal,
        )

    def verify_validation_manifest_bundle(self, bundle: Dict[str, Any]) -> Dict[str, Any]:
        return self.verify_manifest_bundle(
            bundle=bundle,
            artifact_type="validation_manifest_bundle",
        )

    # ------------------------------------------------------------------
    # Technical identity bundle
    # ------------------------------------------------------------------
    def verify_technical_identity_bundle(self, bundle: Dict[str, Any]) -> Dict[str, Any]:
        identity = bundle.get("technical_identity")
        if not isinstance(identity, dict):
            return {
                "ok": False,
                "artifact_type": "technical_identity_bundle",
                "verified": False,
                "error": "missing_technical_identity",
            }

        seal = identity.get("crypto_seal")
        if not isinstance(seal, dict):
            return {
                "ok": False,
                "artifact_type": "technical_identity_bundle",
                "verified": False,
                "error": "missing_technical_identity_seal",
            }

        identity_obj = dict(identity)
        identity_obj.pop("crypto_seal", None)
        identity_obj.pop("sealed", None)

        identity_verification = self._verify_object_with_seal(
            artifact_type="technical_identity",
            obj=identity_obj,
            seal=seal,
        )

        nested_checks: List[Dict[str, Any]] = []

        runtime_result = bundle.get("runtime_result")
        if isinstance(runtime_result, dict):
            nested_checks.append(self.verify_runtime_result_bundle(runtime_result))

        benchmark_bundle = bundle.get("benchmark_bundle")
        if isinstance(benchmark_bundle, dict):
            nested_checks.append(self.verify_benchmark_bundle(benchmark_bundle))

        manifest_bundle = bundle.get("manifest_bundle")
        if isinstance(manifest_bundle, dict):
            nested_checks.append(self.verify_manifest_bundle({"manifest_bundle": manifest_bundle}))

        validation_bundle = bundle.get("validation_bundle")
        if isinstance(validation_bundle, dict):
            if "report" in validation_bundle and "crypto_seal" in validation_bundle:
                nested_checks.append(self.verify_validation_report_bundle(validation_bundle))
            elif "manifest_bundle" in validation_bundle:
                nested_checks.append(self.verify_validation_manifest_bundle(validation_bundle))

        all_nested_ok = all(bool(x.get("verified")) for x in nested_checks) if nested_checks else True

        return {
            "ok": bool(identity_verification.get("ok")) and all_nested_ok,
            "artifact_type": "technical_identity_bundle",
            "verified": bool(identity_verification.get("verified")) and all_nested_ok,
            "technical_identity_verification": identity_verification,
            "nested_verifications": nested_checks,
        }

    # ------------------------------------------------------------------
    # Auto-detect
    # ------------------------------------------------------------------
    def verify_auto(self, obj: Dict[str, Any]) -> Dict[str, Any]:
        # technical identity bundle
        if "technical_identity" in obj:
            return self.verify_technical_identity_bundle(obj)

        # validation report bundle
        if "report" in obj and "crypto_seal" in obj:
            report = obj.get("report")
            if isinstance(report, dict):
                suite_name = str(report.get("suite_name", "")).lower()
                if "false positive" in suite_name or "validation" in suite_name:
                    return self.verify_validation_report_bundle(obj)
                if "benchmark" in str(report.get("benchmark_name", "")).lower():
                    return self.verify_benchmark_bundle(obj)

        # manifest bundle
        if "manifest_bundle" in obj:
            manifest_bundle = obj.get("manifest_bundle") or {}
            manifest = manifest_bundle.get("manifest") if isinstance(manifest_bundle, dict) else {}
            manifest_type = ""
            if isinstance(manifest, dict):
                manifest_type = str(manifest.get("manifest_type", "")).lower()

            if "validation" in manifest_type:
                return self.verify_validation_manifest_bundle(obj)
            return self.verify_manifest_bundle(obj)

        # runtime result bundle
        if "crypto_seal" in obj:
            return self.verify_runtime_result_bundle(obj)

        return {
            "ok": False,
            "verified": False,
            "artifact_type": "unknown",
            "error": "could_not_detect_artifact_type",
        }

    def verify_file(self, path: str) -> Dict[str, Any]:
        obj = _load_json(path)
        result = self.verify_auto(obj)
        result["source_file"] = path
        return result

    # ------------------------------------------------------------------
    # Human-readable summary
    # ------------------------------------------------------------------
    def summarize(self, result: Dict[str, Any]) -> Dict[str, Any]:
        artifact_type = result.get("artifact_type", "unknown")
        verified = bool(result.get("verified", False))

        summary = {
            "artifact_type": artifact_type,
            "verified": verified,
            "status": "VALID" if verified else "INVALID",
        }

        if result.get("source_file"):
            summary["source_file"] = result["source_file"]

        verification = result.get("verification", {}) or {}
        if isinstance(verification, dict):
            if verification.get("object_digest"):
                summary["object_digest"] = verification["object_digest"]
            if verification.get("seal_digest"):
                summary["seal_digest"] = verification["seal_digest"]

        if artifact_type == "technical_identity_bundle":
            tiv = result.get("technical_identity_verification", {}) or {}
            nested = result.get("nested_verifications", []) or []
            summary["technical_identity_verified"] = bool(
                (tiv.get("verification") or {}).get("verified", tiv.get("verified", False))
            )
            summary["nested_verified_count"] = sum(1 for x in nested if x.get("verified"))
            summary["nested_total"] = len(nested)

        return summary


VERIFIER = SovereignExternalVerifierV2()


def verify_artifact_file_v2(path: str) -> Dict[str, Any]:
    return VERIFIER.verify_file(path)


def summarize_verification_v2(result: Dict[str, Any]) -> Dict[str, Any]:
    return VERIFIER.summarize(result)


def _build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Extended independent verifier for Sovereign bank-grade artifacts."
    )
    parser.add_argument(
        "--file",
        required=True,
        help="Path to JSON artifact file to verify.",
    )
    parser.add_argument(
        "--summary-only",
        action="store_true",
        help="Print only compact summary instead of full verification result.",
    )
    return parser


if __name__ == "__main__":
    parser = _build_arg_parser()
    args = parser.parse_args()

    verification = verify_artifact_file_v2(args.file)

    if args.summary_only:
        print(json.dumps(summarize_verification_v2(verification), ensure_ascii=False, indent=2))
    else:
        print(json.dumps(verification, ensure_ascii=False, indent=2))