nomadro/scripts/security_selftest_com.py
Eric 9b7ffb24dc Ship social-first admin console, soft trials, and safer join gates.
Rebuild admin.nomadro.com around community ops, add configurable free peeks instead of nav locks, humanize user copy, and harden UGC/liveness admin APIs with backup/self-test scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 23:47:04 +08:00

211 lines
6.4 KiB
Python

# -*- coding: utf-8 -*-
"""Security self-test for nomadro.com — no PII dumps, fail-closed checks.
Checks:
1) Public API does not leak join leads / liveness / roster PII without auth
2) Admin UGC / switches require auth (401/403)
3) Chat trial gate returns 402 when exhausted (when probe guest has history)
4) Remote-config public snapshot has no secrets (no api keys / passwords)
5) Sensitive collections not listable anonymously via PocketBase if exposed
Exit 0 = all critical pass; 1 = fail.
"""
from __future__ import annotations
import json
import sys
import urllib.error
import urllib.request
BASE = "https://nomadro.com"
API = f"{BASE}/api"
PB = f"{BASE}/api" # PocketBase often under same host; adjust if separate
CRITICAL_FAIL = 0
WARN = 0
def http(
method: str,
url: str,
*,
headers: dict[str, str] | None = None,
body: bytes | None = None,
timeout: int = 25,
) -> tuple[int, str, dict[str, str]]:
req = urllib.request.Request(url, data=body, method=method)
for k, v in (headers or {}).items():
req.add_header(k, v)
if body is not None and "Content-Type" not in (headers or {}):
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8", "replace")
return resp.status, raw, dict(resp.headers)
except urllib.error.HTTPError as e:
raw = e.read().decode("utf-8", "replace") if e.fp else ""
return int(e.code), raw, dict(e.headers or {})
except Exception as e:
return 0, str(e), {}
def fail(msg: str) -> None:
global CRITICAL_FAIL
CRITICAL_FAIL += 1
print(f"[FAIL] {msg}")
def warn(msg: str) -> None:
global WARN
WARN += 1
print(f"[WARN] {msg}")
def ok(msg: str) -> None:
print(f"[OK] {msg}")
SECRET_NEEDLES = (
"password",
"secret",
"api_key",
"apikey",
"private_key",
"sk_live",
"sk_test",
"xorpay",
"offer_key",
"appkey",
"app_key",
)
def check_public_config() -> None:
code, body, _ = http("GET", f"{API}/config")
if code not in (200, 304) and code != 200:
# try alternate public path
code, body, _ = http("GET", f"{API}/public/v1/config")
if code != 200:
code2, body2, _ = http("GET", f"{BASE}/api/config")
code, body = code2, body2
if code != 200:
warn(f"public config HTTP {code} — skip secret scan")
return
low = body.lower()
leaked = [n for n in SECRET_NEEDLES if n in low and f'"{n}"' in low]
# Heuristic: long base64-looking secrets in JSON values are rare; flag raw key names with non-empty strings
try:
data = json.loads(body)
except Exception:
fail("public config is not JSON")
return
blob = json.dumps(data)
for n in ("sk_live", "sk_test", "BEGIN PRIVATE"):
if n in blob:
fail(f"public config contains secret marker {n}")
return
ok("public config reachable; no obvious secret markers")
def check_admin_guard() -> None:
paths = [
f"{API}/admin/weapp/switches",
f"{API}/admin/social/ugc/messages",
f"{API}/admin/social/ugc/join-leads",
f"{API}/admin/social/ugc/roster",
f"{API}/admin/social/ugc/liveness",
]
for url in paths:
code, body, _ = http("GET", url)
if code in (401, 403, 404):
ok(f"admin guarded {url.split('/admin')[-1]} → {code}")
elif code == 200:
# Must not return PII lists anonymously
low = body.lower()
if any(k in low for k in ("email", "guest", "avatar", "video")):
fail(f"UNAUTH admin returned data: {url} ({len(body)} bytes)")
else:
warn(f"admin {url} returned 200 without obvious PII — verify auth")
elif code == 0:
warn(f"admin unreachable {url}: {body[:80]}")
else:
ok(f"admin {url.split('/admin')[-1]} → {code} (not open)")
def check_join_leads_leak() -> None:
# Social public endpoints must not list leads
probes = [
f"{API}/social/v1/join-leads",
f"{API}/social/v1/admin/join-leads",
f"{API}/v1/social/join-leads",
f"{BASE}/api/social/v1/liveness",
]
for url in probes:
code, body, _ = http("GET", url)
if code == 200 and ("@" in body or "email" in body.lower()):
fail(f"possible join/PII leak at {url}")
elif code in (401, 403, 404, 405, 422):
ok(f"no open leads at {url.split('/')[-1]} → {code}")
elif code == 0:
warn(f"probe fail {url}: {body[:60]}")
else:
ok(f"leads probe {url.split('/')[-1]} → {code}")
def check_chat_trial_header() -> None:
# Missing guest id must fail closed
url = f"{API}/social/v1/channels/lobby/messages"
code, body, _ = http(
"POST",
url,
body=json.dumps({"author": "probe", "text": "security-selftest"}).encode(),
)
if code in (400, 401, 403, 404, 422):
ok(f"chat without guest fails closed → {code}")
elif code == 200:
fail("chat accepted message without X-Social-Guest-Id")
else:
ok(f"chat probe → {code}")
def check_roster_enumeration() -> None:
url = f"{API}/social/v1/roster"
code, body, _ = http("GET", url)
if code == 200:
try:
data = json.loads(body)
except Exception:
warn("roster 200 non-JSON")
return
# Public discovery may exist — ensure no emails / phone / liveness URLs
blob = json.dumps(data).lower()
bad = []
if "@" in blob and "email" in blob:
bad.append("email")
for n in ("liveness_video", "livenessvideo", "front_url", "turn_url"):
if n in blob:
bad.append(n)
if bad:
fail(f"roster public payload may leak {bad}")
else:
ok("roster public payload has no obvious private URLs/emails")
elif code in (401, 403, 404):
ok(f"roster not anonymously open → {code}")
else:
ok(f"roster → {code}")
def main() -> int:
print(f"== security self-test {BASE} ==")
check_public_config()
check_admin_guard()
check_join_leads_leak()
check_chat_trial_header()
check_roster_enumeration()
print(f"\nsummary: fail={CRITICAL_FAIL} warn={WARN}")
return 1 if CRITICAL_FAIL else 0
if __name__ == "__main__":
raise SystemExit(main())