test: end-to-end suites (install.sh, licensing, browser, Android emulator) + runner
tests/e2e (see its README): - install.mjs: real install.sh in a Debian container - VPN-safe HOST_IP detection on simulated hosts, fresh/upgrade/re-run, and the proxy config byte-identical to nginx-proxy/nginx.conf (guards rule CS-5) - license_e2e.py: real cloud + site processes with a throwaway signing key - 400 days offline, tampered file, clock rollback, expiry deferred to workday close, renewal, remote lock - browser.mjs: web delivery modes (same-origin, plain HTTP by LAN IP, venue mode) and the install dialog on Android/iPhone/desktop/no-APK - android.mjs basics|rediscovery|stacks: pairing, venues, camera, back button, restart; IP change / server down / cold start; TLS pinning (wrong-key QR, impostor, upgrade, renewal, rediscovery) and UI bundles (apply, staged, tampered, APK too old, rollback, two venues) on isolated compose stacks built from the repo - lib/: env (paths, LAN IP autodetect, settings), proc (seeded throwaway DBs via demo_seed.py, backends, nginx, Vite, compose stacks), android (adb + WebView DevTools, boots the AVD), cdp - run-all.mjs runs everything fastest-first with a summary Nothing machine-specific is hard-coded; developer stacks/DBs are never touched. Results on this machine: install 9/9, license 17/17, browser 22/22, android basics 19/19, rediscovery 10/10, stacks 21/21. Pack README: Testing section + rule CS-11 (tests follow the code; run run-all before a release). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
"""License suite (KI-006): a real cloud process + a real site backend process.
|
||||
|
||||
Self-contained: a throwaway Ed25519 keypair signs the licenses — the cloud gets
|
||||
the private key via its normal LICENSE_SIGNING_KEY setting, the site gets the
|
||||
public key patched in-process by its launcher (never through configuration).
|
||||
Starts the cloud on :8101 and the site on :8055, on throwaway databases.
|
||||
|
||||
python license_e2e.py
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
|
||||
E2E = Path(__file__).resolve().parent
|
||||
CS = E2E.parents[1]
|
||||
BACKEND = CS / "local_backend"
|
||||
CLOUD = Path(os.environ.get("CLOUD_DIR", CS.parent / "cloud-service" / "cloud_backend"))
|
||||
OUT = E2E / "out"
|
||||
CLOUD_URL, SITE_URL = "http://127.0.0.1:8101", "http://127.0.0.1:8055"
|
||||
MASTER = {"username": "e2e", "password": "e2e-pass-123"}
|
||||
|
||||
key = Ed25519PrivateKey.generate()
|
||||
PRIV = base64.b64encode(key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())).decode()
|
||||
PUB = base64.b64encode(key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
|
||||
|
||||
OUT.mkdir(exist_ok=True)
|
||||
tmp = Path(tempfile.mkdtemp(prefix="license-", dir=OUT))
|
||||
(tmp / "data").mkdir()
|
||||
STATE = tmp / "data" / "license_state.json"
|
||||
fails = 0
|
||||
|
||||
|
||||
def seed_db(target: Path):
|
||||
template = OUT / "seed.db"
|
||||
if not template.exists():
|
||||
print(" seeding a demo database (once)…")
|
||||
partial = OUT / "seed.db.partial"
|
||||
partial.unlink(missing_ok=True)
|
||||
subprocess.run([sys.executable, "demo_seed.py"], cwd=BACKEND, check=True, stdout=subprocess.DEVNULL,
|
||||
env={**os.environ, "DATABASE_URL": f"sqlite:///{partial.as_posix()}", "PYTHONIOENCODING": "utf-8"})
|
||||
# Only a database that really holds the demo data becomes the template
|
||||
conn = sqlite3.connect(partial)
|
||||
orders = conn.execute("select count(*) from orders").fetchone()[0]
|
||||
conn.close() # Windows: the file can't be renamed while open
|
||||
if not orders:
|
||||
raise SystemExit("demo_seed.py produced no orders")
|
||||
partial.replace(template)
|
||||
shutil.copy(template, target)
|
||||
|
||||
|
||||
def check(name, got, want):
|
||||
global fails
|
||||
ok = got == want
|
||||
fails += not ok
|
||||
print(f"{'PASS' if ok else 'FAIL'} {name}: {got!r}" + ("" if ok else f" (want {want!r})"))
|
||||
|
||||
|
||||
def call(base, method, path, body=None, token=None, headers=None):
|
||||
req = urllib.request.Request(base + path, method=method, data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {token}"} if token else {}), **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status, json.loads(r.read() or b"null")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read() or b"null")
|
||||
|
||||
|
||||
def wait_up(url):
|
||||
for _ in range(120):
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=2)
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
raise SystemExit(f"{url} did not start")
|
||||
|
||||
|
||||
procs = {}
|
||||
|
||||
|
||||
def start_cloud():
|
||||
env = {**os.environ, "DATABASE_URL": f"sqlite:///{(tmp / 'cloud.db').as_posix()}", "ADMIN_USERNAME": "e2eadmin",
|
||||
"ADMIN_PASSWORD": "e2e-admin-pass", "SECRET_KEY": "e2e", "LICENSE_SIGNING_KEY": PRIV}
|
||||
procs["cloud"] = subprocess.Popen([sys.executable, "-m", "uvicorn", "main:app", "--port", "8101"], cwd=CLOUD, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=open(tmp / "cloud.log", "a"))
|
||||
wait_up(f"{CLOUD_URL}/docs")
|
||||
|
||||
|
||||
def start_site(site_id, site_key):
|
||||
env = {**os.environ, "DATABASE_URL": f"sqlite:///{(tmp / 'data' / 'pos.db').as_posix()}", "CLOUD_URL": CLOUD_URL,
|
||||
"SITE_ID": site_id, "SITE_KEY": site_key, "SECRET_KEY": "e2e-site",
|
||||
"MASTER_USERNAME": MASTER["username"], "MASTER_PASSWORD": MASTER["password"]}
|
||||
launcher = (f"import services.license as L; L.LICENSE_PUBLIC_KEY = {PUB!r}; "
|
||||
"import uvicorn; uvicorn.run('main:app', host='127.0.0.1', port=8055)")
|
||||
procs["site"] = subprocess.Popen([sys.executable, "-c", launcher], cwd=BACKEND, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=open(tmp / "site.log", "a"))
|
||||
wait_up(f"{SITE_URL}/api/system/health")
|
||||
time.sleep(2) # first heartbeat attempt + apply_license
|
||||
|
||||
|
||||
def stop(name):
|
||||
p = procs.pop(name, None)
|
||||
if p:
|
||||
p.terminate()
|
||||
p.wait(10)
|
||||
|
||||
|
||||
def status():
|
||||
_, tok = call(SITE_URL, "POST", "/api/auth/login", MASTER)
|
||||
return call(SITE_URL, "GET", "/api/system/status", token=tok["access_token"])[1], tok["access_token"]
|
||||
|
||||
|
||||
def edit_state(fn):
|
||||
s = json.loads(STATE.read_text())
|
||||
fn(s)
|
||||
STATE.write_text(json.dumps(s))
|
||||
|
||||
|
||||
try:
|
||||
seed_db(tmp / "data" / "pos.db")
|
||||
start_cloud()
|
||||
_, admin = call(CLOUD_URL, "POST", "/api/auth/login", {"username": "e2eadmin", "password": "e2e-admin-pass"})
|
||||
A = admin["access_token"]
|
||||
|
||||
def cloud_admin(method, path, body=None):
|
||||
code, out = call(CLOUD_URL, method, path, body, token=A)
|
||||
assert code == 200, f"cloud {method} {path} -> {code} {out}"
|
||||
return out
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
_, site = call(CLOUD_URL, "POST", "/api/sites/", {"name": "E2E Taverna", "owner_name": "x", "contact_email": "x@x.gr",
|
||||
"license_expires_at": (now + timedelta(days=730)).isoformat()}, token=A)
|
||||
SID, SKEY = site["site_id"], site["secret_key"]
|
||||
_, hb = call(CLOUD_URL, "POST", "/api/heartbeat/", {"version": "e2e"}, headers={"X-Site-ID": SID, "X-Site-Key": SKEY})
|
||||
check("cloud: heartbeat carries a signed license token", bool(hb.get("license_token")) and hb["license_token"].count(".") == 1, True)
|
||||
|
||||
print("── 1. online")
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("verified signed license, licensed", (st["license_verified"], st["licensed"], st["lock_reason"]), (True, True, None))
|
||||
check("state file in the data dir holds the token", STATE.exists() and bool(json.loads(STATE.read_text()).get("license_token")), True)
|
||||
|
||||
print("── 2. cloud gone, 400 days since last contact")
|
||||
stop("cloud"); stop("site")
|
||||
edit_state(lambda s: s.update(last_sync=(now - timedelta(days=400)).isoformat()))
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("still licensed (no 72h rule)", (st["licensed"], st["sync_failed"], st["offline_days"] >= 399), (True, True, True))
|
||||
check("…and fully usable", call(SITE_URL, "GET", "/api/tables/", token=tok)[0], 200)
|
||||
|
||||
print("── 3. tampered license file")
|
||||
stop("site")
|
||||
good = json.loads(STATE.read_text())["license_token"]
|
||||
|
||||
def tamper(s):
|
||||
body, sig = s["license_token"].split(".")
|
||||
p = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
|
||||
p["expires_at"] = "2099-01-01T00:00:00+00:00"
|
||||
s["license_token"] = base64.urlsafe_b64encode(json.dumps(p).encode()).rstrip(b"=").decode() + "." + sig
|
||||
edit_state(tamper)
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("edited file → not licensed, 'unverified'", (st["licensed"], st["lock_reason"]), (False, "unverified"))
|
||||
check("…requests refused (402)", call(SITE_URL, "GET", "/api/tables/", token=tok)[0], 402)
|
||||
stop("site")
|
||||
edit_state(lambda s: s.update(license_token=good))
|
||||
|
||||
print("── 4. clock set back (newest order 30 days in the 'future')")
|
||||
db = sqlite3.connect(tmp / "data" / "pos.db")
|
||||
row = db.execute("SELECT id, opened_at FROM orders ORDER BY id DESC LIMIT 1").fetchone()
|
||||
db.execute("UPDATE orders SET opened_at=? WHERE id=?", ((now + timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S"), row[0]))
|
||||
db.commit()
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("blocked, reason 'clock'", (st["licensed"], st["lock_reason"]), (False, "clock"))
|
||||
stop("site")
|
||||
db.execute("UPDATE orders SET opened_at=? WHERE id=?", (row[1], row[0]))
|
||||
db.commit()
|
||||
db.close()
|
||||
edit_state(lambda s: s.update(time_high_water=None))
|
||||
|
||||
print("── 5. expired past grace while a workday is open")
|
||||
start_cloud()
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("licensed again after restore", st["licensed"], True)
|
||||
code, _ = call(SITE_URL, "POST", "/api/business-day/open", {}, token=tok)
|
||||
check("workday opened", code in (200, 201), True)
|
||||
cloud_admin("PUT", f"/api/sites/{SID}", {"license_expires_at": (now - timedelta(days=10)).isoformat()})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("grace over, workday open → keeps running", (st["licensed"], st["grace_over"]), (True, True))
|
||||
check("workday closed", call(SITE_URL, "POST", "/api/business-day/close", {"force": True}, token=tok)[0], 200)
|
||||
st, tok = status()
|
||||
check("after closing → blocked, 'expired'", (st["licensed"], st["lock_reason"]), (False, "expired"))
|
||||
|
||||
print("── 6. renewal")
|
||||
cloud_admin("PUT", f"/api/sites/{SID}", {"license_expires_at": (now - timedelta(days=2)).isoformat()})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("expired 2 days ago → grace, 3 days left", (st["licensed"], st["grace_days_remaining"]), (True, 3))
|
||||
cloud_admin("PUT", f"/api/sites/{SID}", {"license_expires_at": (now + timedelta(days=365)).isoformat()})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("renewed for a year", (st["licensed"], st["days_until_expiry"] in (363, 364)), (True, True))
|
||||
|
||||
print("── 7. remote lock")
|
||||
cloud_admin("POST", f"/api/sites/{SID}/lock", {"reason": "e2e"})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("cloud lock (no workday) → locked", (st["locked"], st["lock_reason"]), (True, "admin"))
|
||||
cloud_admin("POST", f"/api/sites/{SID}/unlock", None)
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("cloud unlock → running again", (st["locked"], st["licensed"]), (False, True))
|
||||
finally:
|
||||
for n in list(procs):
|
||||
stop(n)
|
||||
|
||||
print(f"\n{'✗' if fails else '✓'} license: {fails} failure(s) | logs: {tmp}")
|
||||
sys.exit(1 if fails else 0)
|
||||
Reference in New Issue
Block a user