Platform v2 step 1.10 (APPS_PLATFORM D-16, section 6.5).
- POST /api/auth/support/challenge (public): an 8-character challenge, stored 15 min
(support_challenges, revision 0009; at most 5 open). POST /api/auth/support/verify
{challenge, code}: code = base32(HMAC(SUPPORT_SECRET, site_id + challenge))[:10];
single use, 5 wrong codes burn the challenge. Opens a 4 h support session
(client=support, synthetic superadmin) with a hard end: sessions.expires_at.
- core/support_codes.py (stdlib only) is the derivation; tools/support_code.py
(--init, --site-secret <SITE_ID>, <SITE_ID> <CHALLENGE>) uses it on the builder's
machine with the master key in %USERPROFILE%/.xenia/support_master_key.txt.
- MASTER_USERNAME/MASTER_PASSWORD removed (config, login, docker-compose.yml,
.env.example); SUPPORT_SECRET added; install.sh asks for it.
- e2e: backends get SUPPORT_SECRET from a test master key and log in with challenge
codes (lib/support.mjs, license_e2e.py); install.mjs expects the new prompt.
- Pack rule CS-15.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
276 lines
13 KiB
Python
276 lines
13 KiB
Python
"""License suite (KI-006, platform v2 F-057): a real cloud process + a real site backend process.
|
|
|
|
v2: tokens carry a `modules` map; an unlicensed site runs the free tier (core, catalogue,
|
|
history) instead of refusing every request, so "blocked" checks use an ordering endpoint.
|
|
|
|
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 importlib.util
|
|
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"
|
|
# Support access (D-16): the site gets a SUPPORT_SECRET derived from this test master key,
|
|
# and the suite logs in with a challenge code, the way the builder would.
|
|
SUPPORT_MASTER = "e2e-support-master-key-0000000000"
|
|
_spec = importlib.util.spec_from_file_location("support_codes", BACKEND / "core" / "support_codes.py")
|
|
codes = importlib.util.module_from_spec(_spec)
|
|
_spec.loader.exec_module(codes)
|
|
|
|
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 template.exists() and not _is_v2_db(template):
|
|
print(" seed.db was made by v1 code (no alembic_version) - reseeding")
|
|
template.unlink()
|
|
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 _is_v2_db(path: Path) -> bool:
|
|
conn = sqlite3.connect(path)
|
|
try:
|
|
return conn.execute("select count(*) from sqlite_master where name='alembic_version'").fetchone()[0] == 1
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
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", "LICENSE_MODE": "enforced",
|
|
"SUPPORT_SECRET": codes.site_secret(SUPPORT_MASTER, site_id)}
|
|
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():
|
|
_, ch = call(SITE_URL, "POST", "/api/auth/support/challenge", {})
|
|
code = codes.code_for(codes.site_secret(SUPPORT_MASTER, ch["site_id"]), ch["site_id"], ch["challenge"])
|
|
_, tok = call(SITE_URL, "POST", "/api/auth/support/verify", {"challenge": ch["challenge"], "code": code})
|
|
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/business-day/current", 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"))
|
|
code, body = call(SITE_URL, "GET", "/api/business-day/current", token=tok)
|
|
check("…ordering refused with module.not_licensed", (code, body["error"]["code"]), (402, "module.not_licensed"))
|
|
check("…but the free tier still answers (catalogue)", call(SITE_URL, "GET", "/api/tables/", token=tok)[0], 200)
|
|
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"))
|
|
code, body = call(SITE_URL, "GET", "/api/business-day/current", token=tok)
|
|
check("…free tier: ordering not licensed, login still works", (code, body["error"]["code"]), (402, "module.not_licensed"))
|
|
|
|
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))
|
|
print("── 8. modules edited in the cloud (v2)")
|
|
site_row = cloud_admin("GET", f"/api/sites/{SID}")
|
|
check("cloud got the site's module catalogue", bool(site_row["module_catalog"])
|
|
and any(m["key"] == "kds" for m in site_row["module_catalog"]), True)
|
|
check("kds licensed (default preset)", call(SITE_URL, "GET", "/api/kds/orders", token=tok)[0], 200)
|
|
cloud_admin("PUT", f"/api/sites/{SID}/modules", {"modules": {"ordering": {}, "waiter_app": {},
|
|
"reports": {"limits": {"history_days": 30}}}})
|
|
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
|
code, body = call(SITE_URL, "GET", "/api/kds/orders", token=tok)
|
|
check("kds removed in the cloud → module.not_licensed after the next heartbeat",
|
|
(code, body["error"]["code"]), (402, "module.not_licensed"))
|
|
check("…ordering still licensed", call(SITE_URL, "GET", "/api/business-day/current", token=tok)[0], 200)
|
|
_, mods = call(SITE_URL, "GET", "/api/platform/modules", token=tok)
|
|
rep = next(m for m in mods["modules"] if m["key"] == "reports")
|
|
check("…reports.history_days = 30 from the token", rep["limits"][0]["value"], 30)
|
|
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)
|