quantum-safe-py 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. quantum_safe/__init__.py +97 -0
  2. quantum_safe/_internal/__init__.py +2 -0
  3. quantum_safe/_internal/serialization.py +104 -0
  4. quantum_safe/_version.py +5 -0
  5. quantum_safe/audit/__init__.py +50 -0
  6. quantum_safe/audit/auditor.py +292 -0
  7. quantum_safe/audit/cli.py +299 -0
  8. quantum_safe/audit/compliance.py +332 -0
  9. quantum_safe/audit/policy.py +242 -0
  10. quantum_safe/audit/sbom.py +357 -0
  11. quantum_safe/backends/__init__.py +172 -0
  12. quantum_safe/backends/base.py +220 -0
  13. quantum_safe/backends/liboqs.py +439 -0
  14. quantum_safe/backends/rustcrypto.py +187 -0
  15. quantum_safe/exceptions.py +276 -0
  16. quantum_safe/kem/__init__.py +32 -0
  17. quantum_safe/kem/algorithms.py +218 -0
  18. quantum_safe/kem/core.py +196 -0
  19. quantum_safe/kem/hybrid.py +496 -0
  20. quantum_safe/migrate/__init__.py +50 -0
  21. quantum_safe/migrate/cli.py +158 -0
  22. quantum_safe/migrate/scanner.py +707 -0
  23. quantum_safe/migrate/shims.py +251 -0
  24. quantum_safe/migrate/state.py +350 -0
  25. quantum_safe/migrate/upgrader.py +340 -0
  26. quantum_safe/protocols/__init__.py +49 -0
  27. quantum_safe/protocols/envelope.py +354 -0
  28. quantum_safe/protocols/jwt.py +332 -0
  29. quantum_safe/protocols/tls.py +276 -0
  30. quantum_safe/protocols/x509.py +340 -0
  31. quantum_safe/signatures/__init__.py +34 -0
  32. quantum_safe/signatures/algorithms.py +224 -0
  33. quantum_safe/signatures/core.py +369 -0
  34. quantum_safe/signatures/hybrid.py +465 -0
  35. quantum_safe/types/__init__.py +42 -0
  36. quantum_safe/types/kem.py +345 -0
  37. quantum_safe/types/keys.py +789 -0
  38. quantum_safe/types/signatures.py +212 -0
  39. quantum_safe_py-0.1.0.dist-info/METADATA +622 -0
  40. quantum_safe_py-0.1.0.dist-info/RECORD +43 -0
  41. quantum_safe_py-0.1.0.dist-info/WHEEL +4 -0
  42. quantum_safe_py-0.1.0.dist-info/entry_points.txt +3 -0
  43. quantum_safe_py-0.1.0.dist-info/licenses/LICENSE +179 -0
@@ -0,0 +1,97 @@
1
+ """
2
+ quantum_safe
3
+ ~~~~~~~~~~~~
4
+
5
+ Production-grade post-quantum cryptography for Python.
6
+
7
+ Quick start::
8
+
9
+ from quantum_safe import HybridKEM, HybridSign
10
+
11
+ # Key encapsulation (hybrid X25519 + ML-KEM-768 by default)
12
+ kem = HybridKEM()
13
+ kp = kem.generate_keypair()
14
+ ct, shared_secret = kem.encapsulate(kp.public)
15
+ ss2 = kem.decapsulate(kp.secret, ct)
16
+ assert shared_secret == ss2
17
+
18
+ # Digital signatures (hybrid Ed25519 + ML-DSA-65 by default)
19
+ signer = HybridSign()
20
+ sig_kp = signer.generate_keypair()
21
+ sm = signer.sign(b"hello world", sig_kp.secret, context=b"myapp-v1")
22
+ signer.verify(sm, sig_kp.public)
23
+
24
+ See the full documentation at https://quantum-safe.readthedocs.io/
25
+ """
26
+
27
+ from quantum_safe._version import __version__, __version_info__
28
+ from quantum_safe.exceptions import (
29
+ BackendError,
30
+ BackendNotAvailable,
31
+ ClassicalKeyDetected,
32
+ ConfigurationError,
33
+ CryptoError,
34
+ DecapsulationError,
35
+ IncompatibleKeyVersion,
36
+ InsecureOperationError,
37
+ KeyGenerationError,
38
+ KeyParseError,
39
+ MigrationError,
40
+ QuantumSafeError,
41
+ SerializationError,
42
+ UnsupportedAlgorithm,
43
+ VerificationError,
44
+ )
45
+ from quantum_safe.kem import KEM, HybridKEM
46
+ from quantum_safe.signatures import HybridSign, Sign
47
+ from quantum_safe.types import (
48
+ CipherText,
49
+ HybridCipherText,
50
+ KeyPair,
51
+ KeyType,
52
+ MigrationState,
53
+ PublicKey,
54
+ SecretKey,
55
+ SharedSecret,
56
+ SignedMessage,
57
+ generate_nonce,
58
+ )
59
+
60
+ __all__ = [
61
+ # Version
62
+ "__version__",
63
+ "__version_info__",
64
+ # Main classes (most users only need these two)
65
+ "HybridKEM",
66
+ "HybridSign",
67
+ # Single-algorithm variants
68
+ "KEM",
69
+ "Sign",
70
+ # Types
71
+ "PublicKey",
72
+ "SecretKey",
73
+ "KeyPair",
74
+ "KeyType",
75
+ "MigrationState",
76
+ "SharedSecret",
77
+ "CipherText",
78
+ "HybridCipherText",
79
+ "SignedMessage",
80
+ "generate_nonce",
81
+ # Exceptions
82
+ "QuantumSafeError",
83
+ "CryptoError",
84
+ "DecapsulationError",
85
+ "VerificationError",
86
+ "KeyGenerationError",
87
+ "InsecureOperationError",
88
+ "SerializationError",
89
+ "KeyParseError",
90
+ "BackendError",
91
+ "BackendNotAvailable",
92
+ "MigrationError",
93
+ "ClassicalKeyDetected",
94
+ "IncompatibleKeyVersion",
95
+ "ConfigurationError",
96
+ "UnsupportedAlgorithm",
97
+ ]
@@ -0,0 +1,2 @@
1
+ # Internal helpers — not part of the public API.
2
+ # Anything in this package may change without a major version bump.
@@ -0,0 +1,104 @@
1
+ """
2
+ quantum_safe._internal.serialization
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ A thin serialization layer that prefers cbor2 when installed but falls back
6
+ to a JSON+base64 envelope when it isn't.
7
+
8
+ Why not just require cbor2? Because some users (especially those deploying
9
+ to constrained environments like AWS Lambda layers or Heroku slugs) want to
10
+ keep the dependency tree minimal. cbor2 is listed as an optional dependency
11
+ in pyproject.toml; this module handles both cases transparently.
12
+
13
+ The fallback format is a JSON object where bytes fields are base64url-encoded
14
+ strings with a type tag prefix ("b64:"). It is slightly larger than CBOR
15
+ but fully self-describing and human-readable, which has its own value for
16
+ debugging.
17
+
18
+ Callers should never import cbor2 directly — always go through this module.
19
+ The public API mirrors cbor2's: dumps(obj) -> bytes, loads(data) -> obj.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import base64
25
+ import json
26
+ from typing import Any
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Try to use cbor2 first
30
+ # ---------------------------------------------------------------------------
31
+
32
+ # Maximum bytes accepted by loads() — guards against memory-exhaustion
33
+ # attacks via deeply nested or padded CBOR / JSON payloads.
34
+ _MAX_PAYLOAD_BYTES = 10 * 1024 * 1024 # 10 MB
35
+
36
+ try:
37
+ import cbor2 as _cbor2
38
+
39
+ def dumps(obj: Any) -> bytes: # noqa: ANN401
40
+ return _cbor2.dumps(obj)
41
+
42
+ def loads(data: bytes) -> Any: # noqa: ANN401
43
+ if len(data) > _MAX_PAYLOAD_BYTES:
44
+ raise ValueError(
45
+ f"Payload size {len(data)} exceeds maximum allowed "
46
+ f"{_MAX_PAYLOAD_BYTES} bytes"
47
+ )
48
+ return _cbor2.loads(data)
49
+
50
+ BACKEND = "cbor2"
51
+
52
+ except ImportError:
53
+ # ---------------------------------------------------------------------------
54
+ # Fallback: JSON + base64 envelope
55
+ # ---------------------------------------------------------------------------
56
+
57
+ _B64_PREFIX = "b64:"
58
+
59
+ def _encode(obj: Any) -> Any: # noqa: ANN401
60
+ """Recursively encode an object for JSON serialization."""
61
+ if isinstance(obj, (bytes, bytearray, memoryview)):
62
+ raw = bytes(obj)
63
+ return _B64_PREFIX + base64.urlsafe_b64encode(raw).decode("ascii")
64
+ if isinstance(obj, dict):
65
+ return {str(k): _encode(v) for k, v in obj.items()}
66
+ if isinstance(obj, (list, tuple)):
67
+ return [_encode(item) for item in obj]
68
+ # int, float, str, bool, None pass through unchanged
69
+ return obj
70
+
71
+ def _decode(obj: Any) -> Any: # noqa: ANN401
72
+ """Recursively decode a JSON-deserialized object."""
73
+ if isinstance(obj, str) and obj.startswith(_B64_PREFIX):
74
+ b64 = obj[len(_B64_PREFIX):]
75
+ # Restore padding
76
+ padded = b64 + "=" * (-len(b64) % 4)
77
+ return base64.urlsafe_b64decode(padded)
78
+ if isinstance(obj, dict):
79
+ return {k: _decode(v) for k, v in obj.items()}
80
+ if isinstance(obj, list):
81
+ return [_decode(item) for item in obj]
82
+ return obj
83
+
84
+ def dumps(obj: Any) -> bytes: # noqa: ANN401
85
+ """Serialize obj to bytes using JSON+base64 envelope."""
86
+ encoded = _encode(obj)
87
+ # We wrap in a thin envelope so loads() can detect this format
88
+ wrapper = {"_qs_fmt": "json-b64-v1", "d": encoded}
89
+ return json.dumps(wrapper, separators=(",", ":")).encode("utf-8")
90
+
91
+ def loads(data: bytes) -> Any: # noqa: ANN401
92
+ """Deserialize bytes produced by dumps()."""
93
+ if len(data) > _MAX_PAYLOAD_BYTES:
94
+ raise ValueError(
95
+ f"Payload size {len(data)} exceeds maximum allowed "
96
+ f"{_MAX_PAYLOAD_BYTES} bytes"
97
+ )
98
+ wrapper = json.loads(data.decode("utf-8"))
99
+ if isinstance(wrapper, dict) and wrapper.get("_qs_fmt") == "json-b64-v1":
100
+ return _decode(wrapper["d"])
101
+ # Plain JSON (no envelope) — decode as-is, best effort
102
+ return _decode(wrapper)
103
+
104
+ BACKEND = "json-b64"
@@ -0,0 +1,5 @@
1
+ # This file is the single source of truth for the package version.
2
+ # pyproject.toml reads from here via hatch-vcs in release builds;
3
+ # during development we just hardcode it.
4
+ __version__ = "0.1.0"
5
+ __version_info__ = (0, 1, 0)
@@ -0,0 +1,50 @@
1
+ """
2
+ quantum_safe.audit
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Compliance auditing, SBOM enrichment, and CI gate tooling.
6
+
7
+ This module sits above the migrate.scanner — it takes scan results and
8
+ turns them into structured compliance artefacts that security teams,
9
+ auditors, and CI pipelines can consume directly.
10
+
11
+ Submodules
12
+ ----------
13
+ auditor Core Auditor class — orchestrates scanning and report generation
14
+ policy Policy-as-code: configurable rules for what constitutes a failure
15
+ sbom CycloneDX SBOM enrichment with PQC-readiness annotations
16
+ compliance NIST SP 800-208 and FIPS 203/204/205 compliance report generation
17
+ cli qs-audit command-line interface
18
+
19
+ Quick start::
20
+
21
+ from quantum_safe.audit import Auditor, AuditPolicy
22
+
23
+ policy = AuditPolicy(
24
+ min_security_level=3,
25
+ allow_classical_only=False,
26
+ hybrid_required=True,
27
+ fail_on=["HIGH", "CRITICAL"],
28
+ )
29
+ report = Auditor.audit("./src", policy=policy)
30
+
31
+ if report.policy_violations:
32
+ print(report.to_json())
33
+ sys.exit(1)
34
+ """
35
+
36
+ from quantum_safe.audit.auditor import Auditor, AuditReport
37
+ from quantum_safe.audit.compliance import ComplianceReport, NISTComplianceChecker
38
+ from quantum_safe.audit.policy import AuditPolicy, PolicyViolation
39
+ from quantum_safe.audit.sbom import PQCReadiness, SBOMEnricher
40
+
41
+ __all__ = [
42
+ "Auditor",
43
+ "AuditReport",
44
+ "AuditPolicy",
45
+ "PolicyViolation",
46
+ "SBOMEnricher",
47
+ "PQCReadiness",
48
+ "ComplianceReport",
49
+ "NISTComplianceChecker",
50
+ ]
@@ -0,0 +1,292 @@
1
+ """
2
+ quantum_safe.audit.auditor
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ The Auditor class: the single entry point for a full PQC compliance audit.
6
+
7
+ It orchestrates:
8
+ 1. Scanning source code with migrate.Scanner
9
+ 2. Evaluating findings against an AuditPolicy
10
+ 3. Optionally enriching an SBOM with PQC-readiness data
11
+ 4. Producing a structured AuditReport
12
+
13
+ The AuditReport is the primary artefact — it contains everything
14
+ needed for a security review, a CI gate check, or an audit trail.
15
+
16
+ Design choice: Auditor is a class with only classmethods. You don't
17
+ hold state between audits. Each call to Auditor.audit() is independent.
18
+ This makes it safe to call from parallel CI jobs without shared mutable state.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import datetime
24
+ import json
25
+ import uuid
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from quantum_safe.audit.policy import AuditPolicy, PolicyViolation
31
+ from quantum_safe.migrate.scanner import Scanner, ScanReport
32
+
33
+
34
+ @dataclass
35
+ class AuditReport:
36
+ """Complete audit report for a codebase or key store.
37
+
38
+ Attributes:
39
+ audit_id: Unique identifier for this audit run.
40
+ timestamp: ISO 8601 timestamp of when the audit ran.
41
+ target: What was audited (directory path, key store ID, etc.).
42
+ scan_report: The underlying ScanReport from the scanner.
43
+ policy: The AuditPolicy that was evaluated.
44
+ policy_violations: List of policy violations found.
45
+ passed: True if no policy violations exist.
46
+ metadata: Arbitrary key-value pairs (CI job ID, branch, etc.).
47
+ """
48
+
49
+ audit_id: str
50
+ timestamp: str
51
+ target: str
52
+ scan_report: ScanReport
53
+ policy: AuditPolicy
54
+ policy_violations: list[PolicyViolation]
55
+ passed: bool
56
+ metadata: dict[str, Any] = field(default_factory=dict)
57
+
58
+ # ------------------------------------------------------------------
59
+ # Convenience accessors
60
+ # ------------------------------------------------------------------
61
+
62
+ @property
63
+ def critical_count(self) -> int:
64
+ return len(self.scan_report.critical)
65
+
66
+ @property
67
+ def high_count(self) -> int:
68
+ return len(self.scan_report.high)
69
+
70
+ @property
71
+ def medium_count(self) -> int:
72
+ return len(self.scan_report.medium)
73
+
74
+ @property
75
+ def files_scanned(self) -> int:
76
+ return self.scan_report.files_scanned
77
+
78
+ def summary_line(self) -> str:
79
+ """One-line status for logging."""
80
+ status = "PASSED" if self.passed else "FAILED"
81
+ return (
82
+ f"[{status}] Audit {self.audit_id[:8]}... | "
83
+ f"{self.files_scanned} files | "
84
+ f"{self.critical_count}C {self.high_count}H {self.medium_count}M findings | "
85
+ f"{len(self.policy_violations)} violations"
86
+ )
87
+
88
+ # ------------------------------------------------------------------
89
+ # Serialization
90
+ # ------------------------------------------------------------------
91
+
92
+ def to_dict(self) -> dict[str, Any]:
93
+ return {
94
+ "audit_id": self.audit_id,
95
+ "timestamp": self.timestamp,
96
+ "target": self.target,
97
+ "passed": self.passed,
98
+ "files_scanned": self.files_scanned,
99
+ "finding_counts": {
100
+ "critical": self.critical_count,
101
+ "high": self.high_count,
102
+ "medium": self.medium_count,
103
+ "info": len(self.scan_report.info),
104
+ },
105
+ "policy_violations": [v.to_dict() for v in self.policy_violations],
106
+ "policy": self.policy.to_dict(),
107
+ "findings": [f.to_dict() for f in self.scan_report.findings],
108
+ "errors": self.scan_report.errors,
109
+ "metadata": self.metadata,
110
+ }
111
+
112
+ def to_json(self, indent: int = 2) -> str:
113
+ return json.dumps(self.to_dict(), indent=indent)
114
+
115
+ def to_sarif(self) -> dict[str, Any]:
116
+ """Produce SARIF 2.1.0 output (for GitHub Code Scanning)."""
117
+ return self.scan_report.to_sarif()
118
+
119
+ def to_github_summary(self) -> str:
120
+ """Markdown summary suitable for GitHub Actions $GITHUB_STEP_SUMMARY."""
121
+ icon = "✅" if self.passed else "❌"
122
+ lines = [
123
+ f"## {icon} PQC Audit - {'PASSED' if self.passed else 'FAILED'}",
124
+ "",
125
+ "| Metric | Value |",
126
+ "|--------|-------|",
127
+ f"| Files scanned | {self.files_scanned} |",
128
+ f"| Critical findings | {self.critical_count} |",
129
+ f"| High findings | {self.high_count} |",
130
+ f"| Medium findings | {self.medium_count} |",
131
+ f"| Policy violations | {len(self.policy_violations)} |",
132
+ f"| Audit ID | `{self.audit_id[:16]}` |",
133
+ "",
134
+ ]
135
+
136
+ if self.policy_violations:
137
+ lines.append("### Policy violations")
138
+ lines.append("")
139
+ for v in self.policy_violations[:10]: # cap at 10 for readability
140
+ lines.append(f"- **{v.severity.name}**: {v.detail}")
141
+ if len(self.policy_violations) > 10:
142
+ lines.append(f"- ... and {len(self.policy_violations) - 10} more")
143
+ lines.append("")
144
+
145
+ return "\n".join(lines)
146
+
147
+
148
+ class Auditor:
149
+ """Orchestrates PQC compliance auditing.
150
+
151
+ All methods are classmethods — no instantiation needed.
152
+
153
+ Example::
154
+
155
+ from quantum_safe.audit import Auditor, AuditPolicy
156
+
157
+ report = Auditor.audit(
158
+ "./src",
159
+ policy=AuditPolicy.strict(),
160
+ metadata={"branch": "main", "commit": "abc123"},
161
+ )
162
+ print(report.summary_line())
163
+ if not report.passed:
164
+ print(report.to_json())
165
+ sys.exit(1)
166
+ """
167
+
168
+ @classmethod
169
+ def audit(
170
+ cls,
171
+ target: str | Path,
172
+ policy: AuditPolicy | None = None,
173
+ metadata: dict[str, Any] | None = None,
174
+ exclude: list[str] | None = None,
175
+ ) -> AuditReport:
176
+ """Run a full audit on a directory or file.
177
+
178
+ Args:
179
+ target: Directory or file path to audit.
180
+ policy: Compliance policy. Defaults to AuditPolicy() (standard).
181
+ metadata: Arbitrary metadata for the report (CI job ID, etc.).
182
+ exclude: Directory/file patterns to exclude from scanning.
183
+
184
+ Returns:
185
+ AuditReport with all findings and policy evaluation.
186
+ """
187
+ if policy is None:
188
+ policy = AuditPolicy()
189
+
190
+ target = Path(target)
191
+ audit_id = str(uuid.uuid4())
192
+ timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")
193
+
194
+ # Run the scanner
195
+ if target.is_file():
196
+ scan_report = Scanner.scan_file(target)
197
+ else:
198
+ scan_report = Scanner.scan_directory(target, exclude=exclude)
199
+
200
+ # Evaluate policy
201
+ violations = policy.evaluate(scan_report.findings)
202
+ passed = len(violations) == 0
203
+
204
+ return AuditReport(
205
+ audit_id=audit_id,
206
+ timestamp=timestamp,
207
+ target=str(target),
208
+ scan_report=scan_report,
209
+ policy=policy,
210
+ policy_violations=violations,
211
+ passed=passed,
212
+ metadata=metadata or {},
213
+ )
214
+
215
+ @classmethod
216
+ def audit_source(
217
+ cls,
218
+ source: str,
219
+ filename: str = "<string>",
220
+ policy: AuditPolicy | None = None,
221
+ metadata: dict[str, Any] | None = None,
222
+ ) -> AuditReport:
223
+ """Audit a source string directly (useful in tests and CI hooks).
224
+
225
+ Args:
226
+ source: Python source code as a string.
227
+ filename: Virtual filename for error messages.
228
+ policy: Compliance policy. Defaults to AuditPolicy().
229
+
230
+ Returns:
231
+ AuditReport.
232
+ """
233
+ if policy is None:
234
+ policy = AuditPolicy()
235
+
236
+ scan_report = Scanner.scan_source(source, filename=filename)
237
+ violations = policy.evaluate(scan_report.findings)
238
+
239
+ return AuditReport(
240
+ audit_id=str(uuid.uuid4()),
241
+ timestamp=datetime.datetime.now(datetime.timezone.utc)
242
+ .isoformat()
243
+ .replace("+00:00", "Z"),
244
+ target=filename,
245
+ scan_report=scan_report,
246
+ policy=policy,
247
+ policy_violations=violations,
248
+ passed=len(violations) == 0,
249
+ metadata=metadata or {},
250
+ )
251
+
252
+ @classmethod
253
+ def ci_gate(
254
+ cls,
255
+ target: str | Path,
256
+ policy: AuditPolicy | None = None,
257
+ output_sarif: str | None = None,
258
+ output_json: str | None = None,
259
+ metadata: dict[str, Any] | None = None,
260
+ ) -> int:
261
+ """Run audit and return a shell exit code.
262
+
263
+ Designed to be called directly from CI pipeline steps::
264
+
265
+ exit_code = Auditor.ci_gate("./src", output_sarif="audit.sarif")
266
+ sys.exit(exit_code)
267
+
268
+ Args:
269
+ target: Directory or file to audit.
270
+ policy: Compliance policy. Defaults to AuditPolicy().
271
+ output_sarif: If set, write SARIF to this path.
272
+ output_json: If set, write full JSON report to this path.
273
+ metadata: Arbitrary metadata for the report.
274
+
275
+ Returns:
276
+ 0 if all policies pass, 1 if any violations found.
277
+ """
278
+ report = cls.audit(target, policy=policy, metadata=metadata)
279
+
280
+ if output_sarif:
281
+ sarif_path = Path(output_sarif)
282
+ sarif_path.parent.mkdir(parents=True, exist_ok=True)
283
+ sarif_path.write_text(
284
+ json.dumps(report.to_sarif(), indent=2), encoding="utf-8"
285
+ )
286
+
287
+ if output_json:
288
+ json_path = Path(output_json)
289
+ json_path.parent.mkdir(parents=True, exist_ok=True)
290
+ json_path.write_text(report.to_json(), encoding="utf-8")
291
+
292
+ return 0 if report.passed else 1