qshield 1.2.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 (77) hide show
  1. qshield/__init__.py +31 -0
  2. qshield/ai.py +201 -0
  3. qshield/ci/__init__.py +3 -0
  4. qshield/cli/__init__.py +1 -0
  5. qshield/cli/main.py +910 -0
  6. qshield/core/__init__.py +35 -0
  7. qshield/core/circuit_ir.py +270 -0
  8. qshield/core/config.py +198 -0
  9. qshield/core/exporters.py +204 -0
  10. qshield/core/gate_database.py +518 -0
  11. qshield/core/parsers/__init__.py +79 -0
  12. qshield/core/parsers/expressions.py +149 -0
  13. qshield/core/parsers/framework_parsers.py +333 -0
  14. qshield/core/parsers/qasm_parser.py +702 -0
  15. qshield/core/qasm_emitter.py +87 -0
  16. qshield/db/__init__.py +3 -0
  17. qshield/dynamic/__init__.py +33 -0
  18. qshield/dynamic/differential_tester.py +153 -0
  19. qshield/dynamic/quantum_fuzzer.py +327 -0
  20. qshield/dynamic/sandbox_executor.py +239 -0
  21. qshield/dynamic/statistical_tests.py +246 -0
  22. qshield/evasion/__init__.py +27 -0
  23. qshield/evasion/attacks.py +221 -0
  24. qshield/evasion/hardening.py +66 -0
  25. qshield/formal/__init__.py +14 -0
  26. qshield/formal/equivalence_checker.py +85 -0
  27. qshield/formal/property_verifier.py +25 -0
  28. qshield/formal/zx_calculus.py +131 -0
  29. qshield/ml/__init__.py +49 -0
  30. qshield/ml/classifier.py +199 -0
  31. qshield/ml/dataset.py +67 -0
  32. qshield/ml/detector.py +239 -0
  33. qshield/ml/gnn.py +129 -0
  34. qshield/ml/graph.py +88 -0
  35. qshield/policy.py +328 -0
  36. qshield/py.typed +0 -0
  37. qshield/redteam.py +111 -0
  38. qshield/reporting/__init__.py +17 -0
  39. qshield/reporting/finding.py +70 -0
  40. qshield/reporting/html_exporter.py +25 -0
  41. qshield/reporting/json_exporter.py +10 -0
  42. qshield/reporting/sarif_exporter.py +95 -0
  43. qshield/reporting/templates/report.html.jinja2 +87 -0
  44. qshield/runtime/__init__.py +66 -0
  45. qshield/runtime/adapters.py +219 -0
  46. qshield/runtime/alerting.py +113 -0
  47. qshield/runtime/integrity.py +107 -0
  48. qshield/runtime/proxy.py +432 -0
  49. qshield/runtime/validation.py +154 -0
  50. qshield/scanner.py +490 -0
  51. qshield/signatures/__init__.py +31 -0
  52. qshield/signatures/builtin/ancilla_leakage.yaml +21 -0
  53. qshield/signatures/builtin/identity_pairs.yaml +23 -0
  54. qshield/signatures/builtin/known_trojans.yaml +22 -0
  55. qshield/signatures/builtin/measurement_manipulation.yaml +20 -0
  56. qshield/signatures/builtin/parameter_encoding.yaml +22 -0
  57. qshield/signatures/community/CONTRIBUTING.md +90 -0
  58. qshield/signatures/community/manifest.json +7 -0
  59. qshield/signatures/community.py +87 -0
  60. qshield/signatures/loader.py +133 -0
  61. qshield/signatures/matcher.py +237 -0
  62. qshield/signatures/updater.py +282 -0
  63. qshield/static/__init__.py +23 -0
  64. qshield/static/dependency_scanner.py +275 -0
  65. qshield/static/randomized_equivalence.py +146 -0
  66. qshield/static/rules/__init__.py +3 -0
  67. qshield/static/structural_analyzer.py +540 -0
  68. qshield/static/unitary_verifier.py +254 -0
  69. qshield/ui/__init__.py +5 -0
  70. qshield/ui/page.py +642 -0
  71. qshield/ui/server.py +314 -0
  72. qshield-1.2.0.dist-info/METADATA +163 -0
  73. qshield-1.2.0.dist-info/RECORD +77 -0
  74. qshield-1.2.0.dist-info/WHEEL +5 -0
  75. qshield-1.2.0.dist-info/entry_points.txt +2 -0
  76. qshield-1.2.0.dist-info/licenses/LICENSE +201 -0
  77. qshield-1.2.0.dist-info/top_level.txt +1 -0
qshield/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """QSHIELD: Quantum Software Supply Chain Security Framework.
2
+
3
+ Detects, analyzes and prevents security vulnerabilities in quantum
4
+ software supply chains: backdoor gates, trojan unitaries, covert
5
+ channels and malicious circuit modifications.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ __version__ = "1.2.0"
11
+ __all__ = [
12
+ "CircuitIR",
13
+ "CircuitLocation",
14
+ "Evidence",
15
+ "Finding",
16
+ "GateNode",
17
+ "GateType",
18
+ "ScanResults",
19
+ "ScanSummary",
20
+ "Scanner",
21
+ "ThreatLevel",
22
+ "UnsupportedGateError",
23
+ "__version__",
24
+ "scan",
25
+ "to_qiskit",
26
+ ]
27
+
28
+ from qshield.core.circuit_ir import CircuitIR, GateNode, GateType, ThreatLevel
29
+ from qshield.core.exporters import UnsupportedGateError, to_qiskit
30
+ from qshield.reporting.finding import CircuitLocation, Evidence, Finding
31
+ from qshield.scanner import Scanner, ScanResults, ScanSummary, scan
qshield/ai.py ADDED
@@ -0,0 +1,201 @@
1
+ """Optional AI assistance via Sarvam AI (cloud) — ADVISORY ONLY.
2
+
3
+ NOT part of the offline core: nothing in this module runs unless you invoke
4
+ `qshield ai ...` explicitly. Findings (not the raw circuit source) are sent to
5
+ Sarvam AI's cloud API. LLM output is a lead for a human auditor — never a
6
+ verdict, never proof that a circuit is honest.
7
+
8
+ Requires: pip install sarvamai and SARVAM_API_KEY in the environment or a
9
+ gitignored .env file.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+
18
+ CHAT_MODEL = "sarvam-105b-conversations"
19
+ STT_MODEL = "saaras:v4"
20
+ TTS_MODEL = "bulbul:v4-flash"
21
+ TRANSLATE_MODEL = "sarvam-translate:v1"
22
+ DEFAULT_SPEAKER = "simran_en_customer"
23
+
24
+ _DISCLAIMER = "AI-advisory (Sarvam AI, cloud) — verify against the evidence. LLM output is not a verdict."
25
+
26
+
27
+ class SarvamUnavailable(RuntimeError):
28
+ pass
29
+
30
+
31
+ def _load_dotenv(path: Path) -> None:
32
+ if not path.exists():
33
+ return
34
+ for raw in path.read_text().splitlines():
35
+ line = raw.strip()
36
+ if not line or line.startswith("#") or "=" not in line:
37
+ continue
38
+ k, v = line.split("=", 1)
39
+ os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
40
+
41
+
42
+ def _client():
43
+ repo_root = Path(__file__).resolve().parents[2]
44
+ _load_dotenv(Path.cwd() / ".env")
45
+ _load_dotenv(repo_root / ".env")
46
+ key = os.environ.get("SARVAM_API_KEY")
47
+ if not key:
48
+ raise SarvamUnavailable(
49
+ "SARVAM_API_KEY is not set. Add it to .env (gitignored) or export it. "
50
+ "Get a key at https://indus.sarvam.ai/key-management"
51
+ )
52
+ try:
53
+ from sarvamai import SarvamAI
54
+ except ImportError as exc:
55
+ raise SarvamUnavailable("The 'sarvamai' package is required: pip install sarvamai") from exc
56
+ return SarvamAI(api_subscription_key=key)
57
+
58
+
59
+ def _payload(results, circuit_name: str) -> dict:
60
+ findings = []
61
+ for f in results.findings:
62
+ findings.append(
63
+ {
64
+ "id": f.finding_id,
65
+ "severity": f.severity,
66
+ "threat_type": f.threat_type,
67
+ "title": f.title,
68
+ "description": f.description,
69
+ "confidence": round(f.confidence, 3),
70
+ "false_positive_probability": round(f.false_positive_probability, 3),
71
+ "gate_indices": list(f.location.gate_indices),
72
+ "qubit_indices": list(f.location.qubit_indices),
73
+ "remediation": f.remediation,
74
+ }
75
+ )
76
+ s = results.summary
77
+ return {
78
+ "circuit": circuit_name,
79
+ "summary": {
80
+ "total": s.total,
81
+ "critical": s.critical,
82
+ "high": s.high,
83
+ "medium": s.medium,
84
+ "low": s.low,
85
+ "info": s.info,
86
+ },
87
+ "findings": findings,
88
+ }
89
+
90
+
91
+ def scan_findings(path: Path) -> dict:
92
+ """Run the local static + supply-chain analyzer and return a compact payload."""
93
+ from qshield.scanner import Scanner
94
+
95
+ sc = Scanner(config="default")
96
+ sc.add_circuit(str(path), name=path.stem)
97
+ results = sc.run(analyses=["static", "supply_chain"])
98
+ return _payload(results, path.name)
99
+
100
+
101
+ def scan_findings_ir(ir, name: str = "workbench") -> dict:
102
+ """Same payload, from an already-parsed CircuitIR (e.g. in-memory Workbench uploads)."""
103
+ from qshield.scanner import Scanner
104
+
105
+ sc = Scanner(config="default", parallel=False)
106
+ sc.add_circuit(ir)
107
+ results = sc.run(analyses=["static"])
108
+ return _payload(results, name)
109
+
110
+
111
+ def configured() -> bool:
112
+ """True if a SARVAM_API_KEY is discoverable (env or gitignored .env). Never reveals it."""
113
+ repo_root = Path(__file__).resolve().parents[2]
114
+ _load_dotenv(Path.cwd() / ".env")
115
+ _load_dotenv(repo_root / ".env")
116
+ return bool(os.environ.get("SARVAM_API_KEY"))
117
+
118
+
119
+ def disclaimer() -> str:
120
+ return _DISCLAIMER
121
+
122
+
123
+ def triage(payload: dict) -> str:
124
+ client = _client()
125
+ system = (
126
+ "You are an auditor's assistant for quantum-circuit supply-chain security. "
127
+ "You receive structured static-analysis findings (not the raw circuit). "
128
+ "For each finding give: (1) what it means in plain English, "
129
+ "(2) whether it is likely a true positive or deserves a second look — and why, "
130
+ "(3) priority order for remediation. Then give one overall disposition: "
131
+ "BLOCK / REVIEW / TRACK. Be explicit about uncertainty. Never claim the circuit "
132
+ "is 'safe' or 'secure'; your output is advisory leads, not a verdict."
133
+ )
134
+ response = client.chat.completions(
135
+ model=CHAT_MODEL,
136
+ messages=[
137
+ {"role": "system", "content": system},
138
+ {"role": "user", "content": json.dumps(payload, indent=2)},
139
+ ],
140
+ )
141
+ return response.choices[0].message.content
142
+
143
+
144
+ def tts_bytes(text: str, language_code: str = "hi-IN", speaker: str = DEFAULT_SPEAKER) -> bytes:
145
+ """Synthesize speech in memory; returns audio bytes."""
146
+ import base64
147
+
148
+ client = _client()
149
+ audio = client.text_to_speech.convert(
150
+ text=text, language_code=language_code, model=TTS_MODEL, speaker=speaker
151
+ )
152
+ data = getattr(audio, "audios", None)
153
+ if not data:
154
+ raise SarvamUnavailable("Sarvam TTS returned no audio payload")
155
+ return base64.b64decode("".join(data))
156
+
157
+
158
+ def stt_bytes(data: bytes, mode: str = "transcribe") -> str:
159
+ """Transcribe audio bytes; no temp files."""
160
+ import io
161
+
162
+ client = _client()
163
+ response = client.speech_to_text.transcribe(file=io.BytesIO(data), model=STT_MODEL, mode=mode)
164
+ return response.transcript
165
+
166
+
167
+ def speak(text: str, out: Path, language_code: str = "hi-IN", speaker: str = DEFAULT_SPEAKER) -> Path:
168
+ out.write_bytes(tts_bytes(text, language_code=language_code, speaker=speaker))
169
+ return out
170
+
171
+
172
+ def listen(path: Path, mode: str = "transcribe") -> str:
173
+ return stt_bytes(path.read_bytes(), mode=mode)
174
+
175
+
176
+ def translate(text: str, target_language_code: str, source_language_code: str = "en-IN") -> str:
177
+ client = _client()
178
+ response = client.text.translate(
179
+ input=text,
180
+ source_language_code=source_language_code,
181
+ target_language_code=target_language_code,
182
+ model=TRANSLATE_MODEL,
183
+ mode="formal",
184
+ )
185
+ return getattr(response, "translated_text", None) or getattr(response, "translation", None) or str(response)
186
+
187
+
188
+ def english_report(payload: dict) -> str:
189
+ s = payload["summary"]
190
+ lines = [
191
+ f"QSHIELD audit report for {payload['circuit']}.",
192
+ f"Findings: {s['total']} total — {s['critical']} critical, {s['high']} high, "
193
+ f"{s['medium']} medium, {s['low']} low, {s['info']} info.",
194
+ ]
195
+ for f in payload["findings"][:10]:
196
+ lines.append(
197
+ f"[{f['severity'].upper()}] {f['threat_type']} — {f['title']} (confidence {f['confidence']:.2f}). "
198
+ f"Remediation: {f['remediation']}"
199
+ )
200
+ lines.append("Evidence from static analysis — not a proof of honesty. Human review recommended.")
201
+ return "\n".join(lines)
qshield/ci/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """CI/CD integration. GitHub Actions annotations are emitted inline by the CLI
2
+ (--github-actions). Dedicated GitHub/GitLab/Jenkins plugins are Phase 4 roadmap.
3
+ """
@@ -0,0 +1 @@
1
+ """Command-line interface."""