Spaces:
Sleeping
Sleeping
Harden: fail-closed+const-time auth, id validation, FILES_DIR reaper+trim, server size cap, copy-outside-lock, api_poll .get(), no analytics
Browse filesFiles changed (2)
20 unmodified lines2122232425269 unmodified lines3637383940414243444513 unmodified lines59606162636465663 unmodified lines70717273747514 unmodified lines909192939495969715 unmodified lines1131141151161171183 unmodified lines1221231241251261271285 unmodified lines1341351361371381394 unmodified lines1441451461471481492 unmodified lines15215315415515615715815916016116216316416516633 unmodified lines20020120220320420520620720820921021121 unmodified lines23323423523623723823912 unmodified lines25225325425525625725871 unmodified lines33033133233333433533684 unmodified lines42142242342442542642720 unmodified lines"""import osimport timeimport uuidimport shutil9 unmodified linesMAX_OUTPUT_CHARS = 200_000 # cap stored output per commandMAX_HISTORY_PER_CLIENT = 200 # ring-buffer of commandsMAX_FILE_BYTES = 100 * 1024 * 1024 # 100 MB cap on transfersFILES_DIR = pathlib.Path(tempfile.gettempdir()) / "relay_files"FILES_DIR.mkdir(exist_ok=True)LOCK = threading.Lock()CLIENTS: dict[str, dict] = {} # cid -> {last_seen, meta}COMMANDS: dict[str, dict] = {} # command_id -> record13 unmodified linesdef _check(secret: str):if SECRET and secret != SECRET:raise gr.Error("bad secret")def _touch_client(cid: str, meta: str = ""):3 unmodified linesc["meta"] = meta# --------------------------------------------------------------------------- ## Machine API (called by the daemon via gradio_client) ## --------------------------------------------------------------------------- #14 unmodified linesout = []with LOCK:_touch_client(client_id)for cmd_id in BY_CLIENT[client_id]:rec = COMMANDS[cmd_id]if rec["status"] == "pending":rec["status"] = "acknowledged"rec["acknowledged_at"] = _now()15 unmodified linesdef api_result(command_id: str, client_id: str, secret: str,exit_code: float, stdout: str, session: str):_check(secret)with LOCK:rec = COMMANDS.get(command_id)if rec is None:3 unmodified lines"command": "(unknown — relay restarted)", "created": _now(),"status": "pending",}BY_CLIENT[client_id].append(command_id)rec["status"] = "done"rec["finished_at"] = _now()rec["exit_code"] = int(exit_code)5 unmodified linesdef api_fetch_file(file_id: str, secret: str):"""Daemon calls this to download a server->client (push) payload."""_check(secret)info = PUT_FILES.get(file_id)if not info or not os.path.isfile(info["path"]):raise gr.Error("unknown or expired file_id")4 unmodified lines"""Daemon calls this to post the result of a client->server (pull) request.`fileobj` is the uploaded file path on success, or None when `error` is set."""_check(secret)with LOCK:rec = COMMANDS.get(command_id)if rec is None: # relay restarted — keep the file anyway2 unmodified lines"type": "get", "command": "(file fetch — relay restarted)","created": _now(), "status": "pending",}BY_CLIENT[client_id].append(command_id)rec["status"] = "done"rec["finished_at"] = _now()_touch_client(client_id)if fileobj:fname = os.path.basename(fileobj)saved = FILES_DIR / f"{command_id}__{fname}"shutil.copy(fileobj, saved)sz = saved.stat().st_sizerec.update(stored_path=str(saved), filename=fname, size=sz,exit_code=0, stdout=f"fetched {fname} ({_human(sz)})")else:33 unmodified lines"command": command, "timeout": int(timeout),"status": "pending", "created": _now(),}hist = BY_CLIENT[cid]hist.append(cmd_id)# trim ring bufferwhile len(hist) > MAX_HISTORY_PER_CLIENT:old = hist.pop(0)COMMANDS.pop(old, None)return f"➡️ sent to `{cid}` [{session}]", ""21 unmodified lines"command": f"📤 send {fname} ({_human(sz)}) → {dest}","timeout": 300, "status": "pending", "created": _now(),}BY_CLIENT[cid].append(cmd_id)return f"➡️ sending `{fname}` to `{cid}`:`{dest}`", None12 unmodified lines"remote_path": remote_path, "command": f"📥 fetch {remote_path}","timeout": 300, "status": "pending", "created": _now(),}BY_CLIENT[cid].append(cmd_id)return f"➡️ requested `{remote_path}` from `{cid}`"71 unmodified lines# --------------------------------------------------------------------------- ## Layout ## --------------------------------------------------------------------------- #with gr.Blocks(title="NII Relay") as demo:gr.Markdown("# 🛰️ NII Relay\n""Send shell commands to no-SSH containers via a polling daemon. "84 unmodified linesa_out, api_name="upload_result")if __name__ == "__main__":demo.queue(default_concurrency_limit=16).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)),theme=gr.themes.Soft(), max_file_size="150mb",20 unmodified lines21222324252627289 unmodified lines383940414243444546474849505152535413 unmodified lines686970717273747576773 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613714 unmodified lines15215315415515615715815916016115 unmodified lines1771781791801811821831843 unmodified lines1881891901911921931945 unmodified lines2002012022032042052062074 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352 unmodified lines23823924024124224324424524624724824925025133 unmodified lines28528628728828929029121 unmodified lines31331431531631731831912 unmodified lines33233333433533633733871 unmodified lines41041141241341441541684 unmodified lines50150250350450550650750850951051151220 unmodified lines"""import osimport reimport hmacimport timeimport uuidimport shutil9 unmodified linesMAX_OUTPUT_CHARS = 200_000 # cap stored output per commandMAX_HISTORY_PER_CLIENT = 200 # ring-buffer of commandsMAX_FILE_BYTES = 100 * 1024 * 1024 # 100 MB cap on transfersFILE_TTL = 3600 # delete stored files older than 1hFILES_DIR = pathlib.Path(tempfile.gettempdir()) / "relay_files"FILES_DIR.mkdir(exist_ok=True)_HEX32 = re.compile(r"\A[0-9a-f]{32}\Z")def _valid_id(s) -> bool:return isinstance(s, str) and bool(_HEX32.match(s))LOCK = threading.Lock()CLIENTS: dict[str, dict] = {} # cid -> {last_seen, meta}COMMANDS: dict[str, dict] = {} # command_id -> record13 unmodified linesdef _check(secret: str):# Fail closed: an empty/unset RELAY_SECRET rejects everything (no silent# auth-off). Constant-time compare to avoid a timing oracle on the secret.if not SECRET or not hmac.compare_digest(secret or "", SECRET):raise gr.Error("unauthorized")def _touch_client(cid: str, meta: str = ""):3 unmodified linesc["meta"] = metadef _unlink(path: str):try:os.unlink(path)except OSError:passdef _drop_command(cmd_id: str):"""Remove a command record and any file it owns on disk. Call under LOCK."""rec = COMMANDS.pop(cmd_id, None)if not rec:returnif rec.get("stored_path"):_unlink(rec["stored_path"])fid = rec.get("file_id")if fid:info = PUT_FILES.pop(fid, None)if info:_unlink(info["path"])def _append_and_trim(cid: str, cmd_id: str):"""Append to a client's history and ring-buffer it, deleting evicted files.Call under LOCK. Used by every append site so growth is bounded uniformly."""hist = BY_CLIENT[cid]hist.append(cmd_id)while len(hist) > MAX_HISTORY_PER_CLIENT:_drop_command(hist.pop(0))def _file_reaper():"""Backstop against disk growth on the ephemeral Space: delete stored filesolder than FILE_TTL and prune PUT_FILES whose file is gone."""while True:time.sleep(600)cutoff = _now() - FILE_TTLtry:for p in FILES_DIR.iterdir():try:if p.is_file() and p.stat().st_mtime < cutoff:p.unlink()except OSError:passexcept OSError:passwith LOCK:for fid in list(PUT_FILES):if not os.path.isfile(PUT_FILES[fid]["path"]):PUT_FILES.pop(fid, None)# --------------------------------------------------------------------------- ## Machine API (called by the daemon via gradio_client) ## --------------------------------------------------------------------------- #14 unmodified linesout = []with LOCK:_touch_client(client_id)for cmd_id in list(BY_CLIENT.get(client_id, [])):rec = COMMANDS.get(cmd_id)if rec is None:continueif rec["status"] == "pending":rec["status"] = "acknowledged"rec["acknowledged_at"] = _now()15 unmodified linesdef api_result(command_id: str, client_id: str, secret: str,exit_code: float, stdout: str, session: str):_check(secret)if not _valid_id(command_id):raise gr.Error("bad command id")with LOCK:rec = COMMANDS.get(command_id)if rec is None:3 unmodified lines"command": "(unknown — relay restarted)", "created": _now(),"status": "pending",}_append_and_trim(client_id, command_id)rec["status"] = "done"rec["finished_at"] = _now()rec["exit_code"] = int(exit_code)5 unmodified linesdef api_fetch_file(file_id: str, secret: str):"""Daemon calls this to download a server->client (push) payload."""_check(secret)if not _valid_id(file_id):raise gr.Error("bad file id")info = PUT_FILES.get(file_id)if not info or not os.path.isfile(info["path"]):raise gr.Error("unknown or expired file_id")4 unmodified lines"""Daemon calls this to post the result of a client->server (pull) request.`fileobj` is the uploaded file path on success, or None when `error` is set."""_check(secret)if not _valid_id(command_id):raise gr.Error("bad command id")# Do filesystem work BEFORE taking the lock (a 100 MB copy must not stall# every concurrent poll/UI handler). Enforce the size cap server-side too —# don't trust the client.saved = Nonefname = sz = Nonetoo_big = Falseif fileobj:sz = os.path.getsize(fileobj)if sz > MAX_FILE_BYTES:too_big = Trueelse:fname = os.path.basename(fileobj)saved = FILES_DIR / f"{command_id}__{fname}"shutil.copy(fileobj, saved)with LOCK:rec = COMMANDS.get(command_id)if rec is None: # relay restarted — keep the file anyway2 unmodified lines"type": "get", "command": "(file fetch — relay restarted)","created": _now(), "status": "pending",}_append_and_trim(client_id, command_id)rec["status"] = "done"rec["finished_at"] = _now()_touch_client(client_id)if too_big:rec.update(exit_code=1,stdout=f"file exceeds the {_human(MAX_FILE_BYTES)} limit")elif saved is not None:rec.update(stored_path=str(saved), filename=fname, size=sz,exit_code=0, stdout=f"fetched {fname} ({_human(sz)})")else:33 unmodified lines"command": command, "timeout": int(timeout),"status": "pending", "created": _now(),}_append_and_trim(cid, cmd_id)return f"➡️ sent to `{cid}` [{session}]", ""21 unmodified lines"command": f"📤 send {fname} ({_human(sz)}) → {dest}","timeout": 300, "status": "pending", "created": _now(),}_append_and_trim(cid, cmd_id)return f"➡️ sending `{fname}` to `{cid}`:`{dest}`", None12 unmodified lines"remote_path": remote_path, "command": f"📥 fetch {remote_path}","timeout": 300, "status": "pending", "created": _now(),}_append_and_trim(cid, cmd_id)return f"➡️ requested `{remote_path}` from `{cid}`"71 unmodified lines# --------------------------------------------------------------------------- ## Layout ## --------------------------------------------------------------------------- #with gr.Blocks(title="NII Relay", analytics_enabled=False) as demo:gr.Markdown("# 🛰️ NII Relay\n""Send shell commands to no-SSH containers via a polling daemon. "84 unmodified linesa_out, api_name="upload_result")threading.Thread(target=_file_reaper, daemon=True).start()if __name__ == "__main__":if not SECRET:print("WARNING: RELAY_SECRET is empty — all daemon API calls will be rejected ""(fail-closed). Set it as a Space secret.", flush=True)demo.queue(default_concurrency_limit=16).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)),theme=gr.themes.Soft(), max_file_size="150mb",
__pycache__/app.cpython-311.pyc
app.py+105-20