Yuchen Yuan Claude Opus 4.7 (1M context) commited on
Commit
d06bf19
·
1 Parent(s): e66189d

Plugin protocol Phase 5: final audit fixes + polish

Browse files

Defence-in-depth fixes from the security/UX/scientific audits:

Backend safety:
- Reject `\` and absolute paths in zip entry names (defensive even on
Linux containers).
- Cap stdin payload at 50 MB in the subprocess wrapper before parsing.
- Drop the full `/tmp/quda_plugins/<user>/<kind>/` path from the
"handler.py missing" error message — user already knows their kind.

Frontend UX:
- QNode now renders a red-bordered tombstone card with a "?" badge and
a "plugin not installed" hint when a referenced plugin has been
deleted, instead of silently disappearing.
- App.tsx listens for `storage` events on `quda.*` keys to refresh the
plugin list across tabs.
- UploadPluginModal title now reads "Upload your own block" with a
one-line explanation of what plugins do.
- TrySlide adds a "Upload your own block" tip alongside the Export .py
one so new users discover the plugin workflow.

Docs:
- README.md gains a User plugins section pointing to PLUGIN_SDK.md.
- PLUGIN_SDK.md adds a "Things to watch when returning a new circuit"
callout (qubit count, classical regs, parametric assumptions, custom
gates) and warns about silent expansion that breaks downstream
metrics like QuBound/Qshot.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

PLUGIN_SDK.md CHANGED
@@ -190,6 +190,29 @@ treats plugins like built-in blocks: they participate in the per-
190
  node intermediate cache, the auto-connect family-order chain, and
191
  the SSE step-by-step result stream.
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  ## Where plugins live
194
 
195
  Plugins are stored under `/tmp/quda_plugins/<your_user_id>/<kind>/`
 
190
  node intermediate cache, the auto-connect family-order chain, and
191
  the SSE step-by-step result stream.
192
 
193
+ ### Things to watch when returning a new `circuit_qpy_bytes`
194
+
195
+ A few downstream blocks have hard expectations about circuit shape;
196
+ violating them surfaces as a confusing error several steps later.
197
+
198
+ - **Qubit count** — QuBound and Qshot were trained on 5–8 qubit
199
+ circuits. Returning a circuit with a wildly different qubit count
200
+ works (they handle it gracefully), but the metric values may be
201
+ outside the model's confident range. Don't silently expand qubits
202
+ just to satisfy a downstream block.
203
+ - **Classical bits** — keep at least the classical registers needed
204
+ for measurement; if you drop them, downstream `Output` will report
205
+ empty counts.
206
+ - **Parameterized circuits** — CompressVQC assumes parametric RX/RY/RZ
207
+ rotations. If your block fully binds the parameters into static
208
+ numeric gates, CompressVQC will return zero compression.
209
+ - **Custom gates** — avoid `qc.append` of user-defined `Gate`
210
+ subclasses unless you also include a decomposition; QPY may fail
211
+ to deserialize them on the other end.
212
+
213
+ When in doubt, return the upstream circuit untouched plus your
214
+ result in `scalars` — that always composes safely.
215
+
216
  ## Where plugins live
217
 
218
  Plugins are stored under `/tmp/quda_plugins/<your_user_id>/<kind>/`
README.md CHANGED
@@ -45,6 +45,19 @@ cache, so the demo returns instantly on first click. A cold QuBound run
45
  the shared HF CPU takes 1–3 min; QuCAD and CompressVQC are sub-second
46
  on small circuits.
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  ## Stack
49
 
50
  - **Backend**: FastAPI + Qiskit 2.3 + qiskit-aer + qiskit-optimization +
 
45
  the shared HF CPU takes 1–3 min; QuCAD and CompressVQC are sub-second
46
  on small circuits.
47
 
48
+ ## User plugins
49
+
50
+ Drop a `.zip` (manifest.json + handler.py) onto the **Upload** button
51
+ next to "Add blocks" to add your own source / backend / algorithm /
52
+ metric / sink block to the catalog. Plugins are per-browser (anonymous
53
+ UUID in `localStorage`), run in an isolated subprocess with a 10-min
54
+ wall-clock cap and 1 GB RAM cap, and never see `IBM_QUANTUM_TOKEN`.
55
+ Each browser is capped at 5 active plugins.
56
+
57
+ See [`PLUGIN_SDK.md`](./PLUGIN_SDK.md) for the manifest schema, the
58
+ `run(inputs, params)` contract, per-family conventions, and the
59
+ limits table. Worked examples live in `example_plugins/`.
60
+
61
  ## Stack
62
 
63
  - **Backend**: FastAPI + Qiskit 2.3 + qiskit-aer + qiskit-optimization +
backend/app/services/_plugin_subprocess.py CHANGED
@@ -58,12 +58,25 @@ def main() -> int:
58
  handler_path = Path(sys.argv[1])
59
 
60
  # Read the whole stdin payload before doing anything else so the
61
- # parent can close its end.
 
 
 
62
  try:
63
- raw = sys.stdin.read()
64
  except Exception as exc:
65
  _emit_error(f"reading stdin failed: {exc}")
66
  return 1
 
 
 
 
 
 
 
 
 
 
67
  try:
68
  payload = json.loads(raw)
69
  except json.JSONDecodeError as exc:
 
58
  handler_path = Path(sys.argv[1])
59
 
60
  # Read the whole stdin payload before doing anything else so the
61
+ # parent can close its end. Hard cap at 50 MB so a runaway parent
62
+ # (shouldn't happen, but defence in depth) can't exhaust memory
63
+ # before the OS-level rlimit kicks in.
64
+ MAX_STDIN_BYTES = 50 * 1024 * 1024
65
  try:
66
+ raw = sys.stdin.buffer.read(MAX_STDIN_BYTES + 1)
67
  except Exception as exc:
68
  _emit_error(f"reading stdin failed: {exc}")
69
  return 1
70
+ if len(raw) > MAX_STDIN_BYTES:
71
+ _emit_error(
72
+ f"stdin payload exceeded {MAX_STDIN_BYTES} bytes; refusing to load."
73
+ )
74
+ return 1
75
+ try:
76
+ raw = raw.decode("utf-8")
77
+ except UnicodeDecodeError as exc:
78
+ _emit_error(f"stdin is not valid UTF-8: {exc}")
79
+ return 1
80
  try:
81
  payload = json.loads(raw)
82
  except json.JSONDecodeError as exc:
backend/app/services/plugin_runner.py CHANGED
@@ -85,7 +85,9 @@ def run_plugin(
85
  """
86
  handler_py = handler_dir / "handler.py"
87
  if not handler_py.exists():
88
- raise PluginRunError(f"Plugin handler not found at {handler_py}.")
 
 
89
 
90
  wrapper = Path(__file__).resolve().parent / "_plugin_subprocess.py"
91
  if not wrapper.exists():
 
85
  """
86
  handler_py = handler_dir / "handler.py"
87
  if not handler_py.exists():
88
+ # Don't leak the full /tmp/quda_plugins/<user>/<kind>/ path —
89
+ # the user already knows their plugin kind, that's enough.
90
+ raise PluginRunError("Plugin handler.py is missing.")
91
 
92
  wrapper = Path(__file__).resolve().parent / "_plugin_subprocess.py"
93
  if not wrapper.exists():
backend/app/services/plugin_service.py CHANGED
@@ -257,7 +257,18 @@ def install_plugin_zip(user_id: str, zip_bytes: bytes) -> PluginManifest:
257
  if m.is_dir():
258
  continue
259
  name = m.filename
260
- if name.startswith("/") or ".." in Path(name).parts:
 
 
 
 
 
 
 
 
 
 
 
261
  raise PluginError(f"Suspicious zip entry path: {name!r}.")
262
  # Reject extensions outside the allowlist.
263
  ext = Path(name).suffix.lower()
 
257
  if m.is_dir():
258
  continue
259
  name = m.filename
260
+ # Defence-in-depth: reject path-traversal in multiple flavours.
261
+ # On Linux the .. check below is sufficient, but we also reject
262
+ # backslash separators (Windows-style) and leading dots so a
263
+ # crafted zip can't end up writing to unexpected paths if this
264
+ # codebase is ever deployed on another OS.
265
+ if (
266
+ name.startswith("/")
267
+ or name.startswith("\\")
268
+ or "\\" in name
269
+ or ".." in Path(name).parts
270
+ or Path(name).is_absolute()
271
+ ):
272
  raise PluginError(f"Suspicious zip entry path: {name!r}.")
273
  # Reject extensions outside the allowlist.
274
  ext = Path(name).suffix.lower()
frontend/src/App.tsx CHANGED
@@ -208,14 +208,25 @@ export default function App() {
208
  // Fetch this browser's plugin manifests (anonymous user_id stored
209
  // in localStorage). Silent on failure — the user just won't see
210
  // their previously-uploaded plugins until they re-upload.
211
- import("./lib/userId").then(({ getUserId }) => {
212
- api
213
- .listPlugins(getUserId())
214
- .then(setPlugins)
215
- .catch(() => {
216
- /* ignore */
217
- });
218
- });
 
 
 
 
 
 
 
 
 
 
 
219
  }, [setHealth, setPlugins]);
220
 
221
  const leftWidth = leftCollapsed ? COLLAPSED_W : leftW;
 
208
  // Fetch this browser's plugin manifests (anonymous user_id stored
209
  // in localStorage). Silent on failure — the user just won't see
210
  // their previously-uploaded plugins until they re-upload.
211
+ const refreshPlugins = () => {
212
+ import("./lib/userId").then(({ getUserId }) => {
213
+ api
214
+ .listPlugins(getUserId())
215
+ .then(setPlugins)
216
+ .catch(() => {
217
+ /* ignore */
218
+ });
219
+ });
220
+ };
221
+ refreshPlugins();
222
+ // Multi-tab sync: if the user uploads/deletes a plugin in another
223
+ // tab the storage event lets this tab pick the change up. We
224
+ // listen for any quda.* key to be safe.
225
+ const onStorage = (e: StorageEvent) => {
226
+ if (!e.key || e.key.startsWith("quda.")) refreshPlugins();
227
+ };
228
+ window.addEventListener("storage", onStorage);
229
+ return () => window.removeEventListener("storage", onStorage);
230
  }, [setHealth, setPlugins]);
231
 
232
  const leftWidth = leftCollapsed ? COLLAPSED_W : leftW;
frontend/src/components/QNode.tsx CHANGED
@@ -73,7 +73,45 @@ export function QNode({ id, data, selected }: NodeProps) {
73
  // state, not in node-data, because it's UI affordance only — we
74
  // don't want it serialised into share-links or auto-connect graphs.
75
  const [paramsOpen, setParamsOpen] = useState(false);
76
- if (!spec) return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  const Icon = spec.icon;
78
 
79
  /** Patch this node's `data.params` and propagate to React Flow state. */
 
73
  // state, not in node-data, because it's UI affordance only — we
74
  // don't want it serialised into share-links or auto-connect graphs.
75
  const [paramsOpen, setParamsOpen] = useState(false);
76
+ if (!spec) {
77
+ // Plugin was deleted (or never installed in this browser) while a
78
+ // node referencing its kind is still on the canvas — show a
79
+ // tombstone so the user knows what happened instead of an
80
+ // invisible-but-runnable block.
81
+ return (
82
+ <div className="node-card group relative border-danger/40 bg-danger/5">
83
+ <button
84
+ type="button"
85
+ aria-label="Delete this block"
86
+ title="Delete this orphaned block"
87
+ className="nodrag absolute -top-2 -right-2 w-5 h-5 rounded-full bg-surface border border-edge text-mute hover:text-danger hover:border-danger/60 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10"
88
+ onClick={(e) => {
89
+ e.stopPropagation();
90
+ deleteElements({ nodes: [{ id }] });
91
+ }}
92
+ >
93
+ <X className="w-3 h-3" strokeWidth={2.5} />
94
+ </button>
95
+ <div className="flex items-center gap-2">
96
+ <span className="w-7 h-7 rounded-md flex items-center justify-center text-[10px] font-bold text-white bg-danger/60 shrink-0">
97
+ ?
98
+ </span>
99
+ <div className="min-w-0 flex-1">
100
+ <div className="font-medium text-ink text-sm truncate">
101
+ {d.kind}
102
+ </div>
103
+ <div className="text-[10px] text-danger uppercase tracking-wider">
104
+ plugin not installed
105
+ </div>
106
+ </div>
107
+ </div>
108
+ <div className="mt-1.5 text-[10px] text-mute leading-snug">
109
+ Re-upload this plugin to make the block work, or hover and
110
+ click × to remove it.
111
+ </div>
112
+ </div>
113
+ );
114
+ }
115
  const Icon = spec.icon;
116
 
117
  /** Patch this node's `data.params` and propagate to React Flow state. */
frontend/src/components/UploadPluginModal.tsx CHANGED
@@ -103,9 +103,12 @@ export function UploadPluginModal({
103
  >
104
  <div className="px-4 py-3 border-b border-edge flex items-center justify-between">
105
  <div>
106
- <div className="text-sm font-semibold text-ink">Upload plugin</div>
 
 
107
  <div className="text-[11px] text-mute">
108
- Drop a .zip that contains manifest.json + handler.py.
 
109
  </div>
110
  </div>
111
  <button
 
103
  >
104
  <div className="px-4 py-3 border-b border-edge flex items-center justify-between">
105
  <div>
106
+ <div className="text-sm font-semibold text-ink">
107
+ Upload your own block
108
+ </div>
109
  <div className="text-[11px] text-mute">
110
+ Add a custom source/algorithm/metric/sink to your catalog. Only
111
+ you see it.
112
  </div>
113
  </div>
114
  <button
frontend/src/components/tour/TrySlide.tsx CHANGED
@@ -10,6 +10,7 @@ import {
10
  Atom,
11
  CircleDot,
12
  Code2,
 
13
  Play,
14
  Sparkles,
15
  } from "lucide-react";
@@ -134,14 +135,29 @@ export function TrySlide({ onClose }: { onClose?: () => void } = {}) {
134
  <div className="text-[10px] uppercase tracking-widest text-mute mb-2">
135
  Once you've got results
136
  </div>
137
- <div className="flex items-start gap-2 text-[12px]">
138
- <Code2 className="w-3.5 h-3.5 mt-0.5 text-accent shrink-0" />
139
- <span className="text-mute leading-relaxed">
140
- <span className="text-ink font-medium">Export .py</span> —
141
- download the current pipeline as a runnable Python script for
142
- your own Jupyter / slurm setup. Tweak parameters and re-run
143
- inside QuDA to compare a few values side by side.
144
- </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  </div>
146
  </div>
147
 
 
10
  Atom,
11
  CircleDot,
12
  Code2,
13
+ Package,
14
  Play,
15
  Sparkles,
16
  } from "lucide-react";
 
135
  <div className="text-[10px] uppercase tracking-widest text-mute mb-2">
136
  Once you've got results
137
  </div>
138
+ <div className="space-y-2">
139
+ <div className="flex items-start gap-2 text-[12px]">
140
+ <Code2 className="w-3.5 h-3.5 mt-0.5 text-accent shrink-0" />
141
+ <span className="text-mute leading-relaxed">
142
+ <span className="text-ink font-medium">Export .py</span> —
143
+ download the current pipeline as a runnable Python script for
144
+ your own Jupyter / slurm setup. Tweak parameters and re-run
145
+ inside QuDA to compare a few values side by side.
146
+ </span>
147
+ </div>
148
+ <div className="flex items-start gap-2 text-[12px]">
149
+ <Package className="w-3.5 h-3.5 mt-0.5 text-accent2 shrink-0" />
150
+ <span className="text-mute leading-relaxed">
151
+ <span className="text-ink font-medium">Upload your own block</span>{" "}
152
+ — drop a .zip with{" "}
153
+ <span className="font-mono text-ink">manifest.json</span> +{" "}
154
+ <span className="font-mono text-ink">handler.py</span> next to
155
+ "Add blocks". Your block shows up in the catalog beside the
156
+ built-ins, visible only to your browser. See{" "}
157
+ <span className="font-mono text-ink">PLUGIN_SDK.md</span> in the
158
+ repo for the spec.
159
+ </span>
160
+ </div>
161
  </div>
162
  </div>
163