veritensor 1.0.0__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.
Files changed (36) hide show
  1. veritensor-1.0.0/LICENSE +201 -0
  2. veritensor-1.0.0/PKG-INFO +33 -0
  3. veritensor-1.0.0/README.md +2 -0
  4. veritensor-1.0.0/pyproject.toml +48 -0
  5. veritensor-1.0.0/setup.cfg +4 -0
  6. veritensor-1.0.0/src/veritensor/__init__.py +1 -0
  7. veritensor-1.0.0/src/veritensor/__main__.py +4 -0
  8. veritensor-1.0.0/src/veritensor/cli/__init__.py +1 -0
  9. veritensor-1.0.0/src/veritensor/cli/console.py +1 -0
  10. veritensor-1.0.0/src/veritensor/cli/errors.py +1 -0
  11. veritensor-1.0.0/src/veritensor/cli/main.py +287 -0
  12. veritensor-1.0.0/src/veritensor/core/__init__.py +1 -0
  13. veritensor-1.0.0/src/veritensor/core/cache.py +43 -0
  14. veritensor-1.0.0/src/veritensor/core/config.py +133 -0
  15. veritensor-1.0.0/src/veritensor/core/streaming.py +194 -0
  16. veritensor-1.0.0/src/veritensor/core/types.py +21 -0
  17. veritensor-1.0.0/src/veritensor/engines/__init__.py +1 -0
  18. veritensor-1.0.0/src/veritensor/engines/hashing/__init__.py +1 -0
  19. veritensor-1.0.0/src/veritensor/engines/hashing/calculator.py +115 -0
  20. veritensor-1.0.0/src/veritensor/engines/hashing/lfs.py +67 -0
  21. veritensor-1.0.0/src/veritensor/engines/hashing/readers.py +214 -0
  22. veritensor-1.0.0/src/veritensor/engines/static/__init__.py +1 -0
  23. veritensor-1.0.0/src/veritensor/engines/static/keras_engine.py +104 -0
  24. veritensor-1.0.0/src/veritensor/engines/static/pickle_engine.py +191 -0
  25. veritensor-1.0.0/src/veritensor/engines/static/rules.py +103 -0
  26. veritensor-1.0.0/src/veritensor/integrations/__init__.py +1 -0
  27. veritensor-1.0.0/src/veritensor/integrations/cosign.py +137 -0
  28. veritensor-1.0.0/src/veritensor/integrations/huggingface.py +115 -0
  29. veritensor-1.0.0/src/veritensor/reporting/json_dump.py +1 -0
  30. veritensor-1.0.0/src/veritensor/reporting/sarif.py +139 -0
  31. veritensor-1.0.0/src/veritensor.egg-info/PKG-INFO +33 -0
  32. veritensor-1.0.0/src/veritensor.egg-info/SOURCES.txt +34 -0
  33. veritensor-1.0.0/src/veritensor.egg-info/dependency_links.txt +1 -0
  34. veritensor-1.0.0/src/veritensor.egg-info/entry_points.txt +2 -0
  35. veritensor-1.0.0/src/veritensor.egg-info/requires.txt +6 -0
  36. veritensor-1.0.0/src/veritensor.egg-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: veritensor
3
+ Version: 1.0.0
4
+ Summary: Supply Chain Security for AI. Scans models (Pickle, PyTorch, Keras, GGUF) for malware and verifies integrity.
5
+ Author-email: Arsenii Brazhnyk <arsenii.brazhnyk@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ArseniiBrazhnyk/Veritensor
8
+ Project-URL: Bug Tracker, https://github.com/ArseniiBrazhnyk/Veritensor/issues
9
+ Project-URL: Documentation, https://github.com/ArseniiBrazhnyk/Veritensor#readme
10
+ Keywords: security,ai,mlops,malware-detection,supply-chain,devsecops
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Security
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: typer[all]>=0.9.0
25
+ Requires-Dist: rich>=13.0.0
26
+ Requires-Dist: requests>=2.31.0
27
+ Requires-Dist: pyyaml>=6.0
28
+ Requires-Dist: huggingface_hub>=0.19.0
29
+ Requires-Dist: fickling>=0.0.1
30
+ Dynamic: license-file
31
+
32
+ # Veritensor
33
+ Veritensor is the Zero-Trust security platform for the AI Supply Chain. We replace naive scanning with deep AST analysis and cryptographic signing. From CI/CD to Kubernetes runtime, Aegis ensures only verified, safe, and compliant models ever reach production. Stop guessing, start proving.
@@ -0,0 +1,2 @@
1
+ # Veritensor
2
+ Veritensor is the Zero-Trust security platform for the AI Supply Chain. We replace naive scanning with deep AST analysis and cryptographic signing. From CI/CD to Kubernetes runtime, Aegis ensures only verified, safe, and compliant models ever reach production. Stop guessing, start proving.
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "veritensor"
7
+ version = "1.0.0"
8
+ description = "Supply Chain Security for AI. Scans models (Pickle, PyTorch, Keras, GGUF) for malware and verifies integrity."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [
13
+ {name = "Arsenii Brazhnyk", email = "arsenii.brazhnyk@gmail.com"}
14
+ ]
15
+ keywords = ["security", "ai", "mlops", "malware-detection", "supply-chain", "devsecops"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: Science/Research",
20
+ "Topic :: Security",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ ]
28
+ dependencies = [
29
+ "typer[all]>=0.9.0",
30
+ "rich>=13.0.0",
31
+ "requests>=2.31.0",
32
+ "pyyaml>=6.0",
33
+ "huggingface_hub>=0.19.0",
34
+ "fickling>=0.0.1"
35
+ # Optional dependencies can be added here if needed in the future
36
+ ]
37
+
38
+ [project.urls]
39
+ "Homepage" = "https://github.com/ArseniiBrazhnyk/Veritensor"
40
+ "Bug Tracker" = "https://github.com/ArseniiBrazhnyk/Veritensor/issues"
41
+ "Documentation" = "https://github.com/ArseniiBrazhnyk/Veritensor#readme"
42
+
43
+ [project.scripts]
44
+ # This creates the 'veritensor' command in the terminal
45
+ veritensor = "veritensor.cli.main:app"
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from .cli.main import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
@@ -0,0 +1,287 @@
1
+ # Copyright 2025 Veritensor Security
2
+ #
3
+ # The Main CLI Entry Point.
4
+ # Orchestrates: Config -> Scan -> Verify -> Sign.
5
+
6
+ import sys
7
+ import typer
8
+ import logging
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Optional, List
13
+ from rich.console import Console
14
+ from rich.table import Table
15
+ from rich.panel import Panel
16
+ from rich.progress import Progress, SpinnerColumn, TextColumn
17
+
18
+ # --- Internal Modules ---
19
+ from veritensor.core.config import ConfigLoader
20
+ from veritensor.core.types import ScanResult, Severity
21
+ from veritensor.core.cache import HashCache
22
+ from veritensor.engines.hashing.calculator import calculate_sha256
23
+ from veritensor.engines.static.pickle_engine import scan_pickle_stream
24
+ from veritensor.engines.static.keras_engine import scan_keras_file
25
+ from veritensor.integrations.cosign import sign_container, is_cosign_available, generate_key_pair
26
+ from veritensor.integrations.huggingface import HuggingFaceClient
27
+
28
+ # Setup Logging
29
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
30
+ logger = logging.getLogger("veritensor")
31
+
32
+ # Setup Typer & Rich
33
+ app = typer.Typer(help="Veritensor: AI Model Security Scanner & Gatekeeper")
34
+ console = Console()
35
+
36
+ # Supported Extensions
37
+ PICKLE_EXTS = {".pt", ".pth", ".bin", ".pkl", ".ckpt"}
38
+ KERAS_EXTS = {".h5", ".keras"}
39
+ SAFETENSORS_EXTS = {".safetensors"}
40
+ GGUF_EXTS = {".gguf"}
41
+
42
+ @app.command()
43
+ def scan(
44
+ path: Path = typer.Argument(..., help="Path to model file or directory"),
45
+ repo: Optional[str] = typer.Option(None, "--repo", "-r", help="Hugging Face Repo ID (e.g. meta-llama/Llama-2-7b)"),
46
+ image: Optional[str] = typer.Option(None, help="Docker image tag to sign (e.g. myrepo/model:v1)"),
47
+ force: bool = typer.Option(False, "--force", "-f", help="Break-glass: Force approval even if risks found"),
48
+ json_output: bool = typer.Option(False, "--json", help="Output results in JSON format"),
49
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed logs"),
50
+ ):
51
+ """
52
+ Scans a model for malware, verifies integrity against Hugging Face, and optionally signs the container.
53
+ """
54
+ # 1. Load Configuration
55
+ config = ConfigLoader.load()
56
+ if verbose:
57
+ logger.setLevel(logging.DEBUG)
58
+ console.print(f"[dim]Loaded config from {path}[/dim]")
59
+
60
+ if not json_output:
61
+ console.print(Panel.fit(f"🛡️ [bold cyan]Veritensor Security Scanner[/bold cyan] v4.1", border_style="cyan"))
62
+
63
+ # 2. Collect Files
64
+ files_to_scan = []
65
+ if path.is_file():
66
+ files_to_scan.append(path)
67
+ elif path.is_dir():
68
+ files_to_scan.extend([p for p in path.rglob("*") if p.is_file()])
69
+ else:
70
+ console.print(f"[bold red]Error:[/bold red] Path {path} not found.")
71
+ raise typer.Exit(code=1)
72
+
73
+ # 3. Initialize Clients & Cache
74
+ hf_client = None
75
+ if repo:
76
+ hf_client = HuggingFaceClient(token=config.hf_token)
77
+ if not json_output:
78
+ console.print(f"[dim]🔌 Connected to Hugging Face Registry. Verifying against: [bold]{repo}[/bold][/dim]")
79
+
80
+ hash_cache = HashCache()
81
+
82
+ # 4. Execution Loop
83
+ results: List[ScanResult] = []
84
+ has_critical_errors = False
85
+
86
+ with Progress(
87
+ SpinnerColumn(),
88
+ TextColumn("[progress.description]{task.description}"),
89
+ transient=True,
90
+ disable=json_output
91
+ ) as progress:
92
+
93
+ task = progress.add_task(f"Scanning {len(files_to_scan)} files...", total=len(files_to_scan))
94
+
95
+ for file_path in files_to_scan:
96
+ ext = file_path.suffix.lower()
97
+ progress.update(task, description=f"Analyzing {file_path.name}...")
98
+
99
+ # Initialize Result Object
100
+ scan_res = ScanResult(file_path=str(file_path.name))
101
+
102
+ # --- A. Identity (Hashing & Verification) ---
103
+ try:
104
+ # Check local cache first to speed up re-scans
105
+ cached_hash = hash_cache.get(file_path)
106
+ if cached_hash:
107
+ file_hash = cached_hash
108
+ if verbose:
109
+ logger.debug(f"Using cached hash for {file_path.name}")
110
+ else:
111
+ # Calculate SHA256 (handles LFS pointers automatically)
112
+ file_hash = calculate_sha256(file_path)
113
+ hash_cache.set(file_path, file_hash)
114
+
115
+ scan_res.file_hash = file_hash
116
+
117
+ # Verify against Hugging Face API if repo is provided
118
+ if hf_client and repo:
119
+ verification = hf_client.verify_file_hash(repo, file_path.name, file_hash)
120
+
121
+ if verification == "VERIFIED":
122
+ scan_res.identity_verified = True
123
+ elif verification == "MISMATCH":
124
+ scan_res.add_threat(f"CRITICAL: Hash mismatch! File differs from official '{repo}'")
125
+ elif verification == "UNKNOWN":
126
+ scan_res.add_threat(f"WARNING: File not found in remote repo '{repo}'")
127
+
128
+ except Exception as e:
129
+ scan_res.add_threat(f"Hashing Error: {str(e)}")
130
+
131
+ # --- B. Static Analysis ---
132
+ threats = []
133
+
134
+ # 1. Pickle / PyTorch
135
+ if ext in PICKLE_EXTS:
136
+ try:
137
+ with open(file_path, "rb") as f:
138
+ # For MVP simplicity, we read the raw stream.
139
+ # In production, use readers.py to extract pickle from zip if needed.
140
+ content = f.read()
141
+ threats = scan_pickle_stream(content, strict_mode=True)
142
+ except Exception as e:
143
+ threats.append(f"Scan Error: {str(e)}")
144
+
145
+ # 2. Keras / H5
146
+ elif ext in KERAS_EXTS:
147
+ threats = scan_keras_file(file_path)
148
+
149
+ # 3. Safetensors / GGUF (Generally Safe, check metadata)
150
+ elif ext in SAFETENSORS_EXTS or ext in GGUF_EXTS:
151
+ # Future: Check for license violations in metadata via readers.py
152
+ pass
153
+
154
+ # --- C. Policy Check ---
155
+ if threats:
156
+ for t in threats:
157
+ scan_res.add_threat(t)
158
+ has_critical_errors = True
159
+
160
+ # If identity check failed with mismatch, it is critical
161
+ if not scan_res.identity_verified and repo:
162
+ # Check if threats contain the CRITICAL mismatch message
163
+ if any("CRITICAL" in t for t in scan_res.threats):
164
+ has_critical_errors = True
165
+
166
+ results.append(scan_res)
167
+ progress.advance(task)
168
+
169
+ # 5. Reporting
170
+ if json_output:
171
+ # Serialize objects to dicts for JSON output
172
+ results_dicts = [r.__dict__ for r in results]
173
+ console.print_json(json.dumps(results_dicts))
174
+ else:
175
+ _print_table(results)
176
+
177
+ # 6. Decision & Action
178
+ sign_status = "clean"
179
+
180
+ if has_critical_errors:
181
+ if force:
182
+ if not json_output:
183
+ console.print("\n[bold yellow]⚠️ CRITICAL RISKS DETECTED[/bold yellow]")
184
+ console.print(f"[yellow]Break-glass mode enabled (--force). Proceeding with caution.[/yellow]")
185
+ # Add annotation to signature indicating forced approval
186
+ sign_status = "forced_approval"
187
+ else:
188
+ if not json_output:
189
+ console.print("\n[bold red]❌ BLOCKING DEPLOYMENT[/bold red]")
190
+ console.print("Critical threats detected. Use --force to override if authorized.")
191
+ raise typer.Exit(code=1)
192
+ else:
193
+ if not json_output:
194
+ console.print("\n[bold green]✅ Scan Passed. Model is clean.[/bold green]")
195
+
196
+ # 7. Signing (Sprint 4)
197
+ if image:
198
+ _perform_signing(image, sign_status, config)
199
+
200
+
201
+ def _print_table(results: List[ScanResult]):
202
+ """Renders a pretty table of results using Rich."""
203
+ table = Table(title="Scan Results")
204
+ table.add_column("File", style="cyan")
205
+ table.add_column("Status", justify="center")
206
+ table.add_column("Identity", justify="center")
207
+ table.add_column("Threats / Details", style="magenta")
208
+ table.add_column("SHA256 (Short)", style="dim")
209
+
210
+ for res in results:
211
+ status_style = "green" if res.status == "PASS" else "bold red"
212
+ threat_text = "\n".join(res.threats) if res.threats else "None"
213
+ short_hash = res.file_hash[:8] + "..." if res.file_hash else "N/A"
214
+
215
+ # Identity Icon
216
+ if res.identity_verified:
217
+ id_icon = "[green]✔ Verified[/green]"
218
+ elif res.file_hash:
219
+ id_icon = "[dim]Unchecked[/dim]"
220
+ else:
221
+ id_icon = "[red]Error[/red]"
222
+
223
+ table.add_row(
224
+ res.file_path,
225
+ f"[{status_style}]{res.status}[/{status_style}]",
226
+ id_icon,
227
+ threat_text,
228
+ short_hash
229
+ )
230
+ console.print(table)
231
+
232
+
233
+ def _perform_signing(image: str, status: str, config):
234
+ """
235
+ Wrapper for Cosign integration to sign the container image.
236
+ """
237
+ console.print(f"\n🔐 [bold]Signing container:[/bold] {image}")
238
+
239
+ # Determine key path (Config -> Env -> Default)
240
+ key_path = config.private_key_path
241
+ if not key_path and "VERITENSOR_PRIVATE_KEY_PATH" in os.environ:
242
+ key_path = os.environ["VERITENSOR_PRIVATE_KEY_PATH"]
243
+
244
+ if not key_path:
245
+ console.print("[red]Skipping signing: No private key found (set VERITENSOR_PRIVATE_KEY_PATH).[/red]")
246
+ return
247
+
248
+ success = sign_container(
249
+ image_ref=image,
250
+ key_path=key_path,
251
+ annotations={"scanned_by": "veritensor", "status": status}
252
+ )
253
+
254
+ if success:
255
+ console.print(f"[green]✔ Signed successfully with status: {status}[/green]")
256
+ console.print(f"[dim]Artifact pushed to OCI registry.[/dim]")
257
+ else:
258
+ console.print(f"[bold red]Signing Failed.[/bold red] Check logs for details.")
259
+ # We don't fail the build if signing fails in MVP, unless strict mode is added later
260
+
261
+
262
+ @app.command()
263
+ def keygen(output_prefix: str = "veritensor"):
264
+ """
265
+ Generates a generic Cosign key pair for signing.
266
+ """
267
+ console.print(f"[bold]Generating Cosign Key Pair ({output_prefix})...[/bold]")
268
+
269
+ if not is_cosign_available():
270
+ console.print("[bold red]Error:[/bold red] 'cosign' binary not found in PATH.")
271
+ raise typer.Exit(code=1)
272
+
273
+ if generate_key_pair(output_prefix):
274
+ console.print(f"[green]✔ Keys generated: {output_prefix}.key / {output_prefix}.pub[/green]")
275
+ console.print(f"Set [cyan]VERITENSOR_PRIVATE_KEY_PATH={output_prefix}.key[/cyan] to use them.")
276
+ else:
277
+ console.print("[red]Key generation failed.[/red]")
278
+
279
+
280
+ @app.command()
281
+ def version():
282
+ """Show version info."""
283
+ console.print("Veritensor v1.0.0 (Community Edition)")
284
+
285
+
286
+ if __name__ == "__main__":
287
+ app()
@@ -0,0 +1,43 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Optional, Dict
5
+
6
+ CACHE_FILE = Path(".veritensor_cache.json")
7
+
8
+ class HashCache:
9
+ def __init__(self):
10
+ self.cache: Dict[str, Dict] = {}
11
+ if CACHE_FILE.exists():
12
+ try:
13
+ with open(CACHE_FILE, "r") as f:
14
+ self.cache = json.load(f)
15
+ except Exception:
16
+ self.cache = {}
17
+
18
+ def get(self, file_path: Path) -> Optional[str]:
19
+ """Возвращает хэш, если файл не менялся."""
20
+ key = str(file_path.resolve())
21
+ stats = file_path.stat()
22
+
23
+ if key in self.cache:
24
+ entry = self.cache[key]
25
+ # Проверяем, не изменился ли файл (размер + время изменения)
26
+ if entry["size"] == stats.st_size and entry["mtime"] == stats.st_mtime:
27
+ return entry["hash"]
28
+ return None
29
+
30
+ def set(self, file_path: Path, file_hash: str):
31
+ """Сохраняет хэш в кэш."""
32
+ key = str(file_path.resolve())
33
+ stats = file_path.stat()
34
+ self.cache[key] = {
35
+ "hash": file_hash,
36
+ "size": stats.st_size,
37
+ "mtime": stats.st_mtime
38
+ }
39
+ self._save()
40
+
41
+ def _save(self):
42
+ with open(CACHE_FILE, "w") as f:
43
+ json.dump(self.cache, f, indent=2)