From e128cc37ec3b78da16050e0d7d2fa28c8a9bf4fa Mon Sep 17 00:00:00 2001 From: bonamin Date: Thu, 12 Nov 2026 19:28:20 +0200 Subject: [PATCH] feat(backend): heartbeat v2 sends the module catalogue; license e2e on v2 Platform v2 step 1.7, site side (APPS_PLATFORM D-20, D-21; contract C-1 v2). - cloud_sync heartbeat body is {version, local_ip, module_catalog}; the catalogue (key, kind, name, depends, limits) comes from the manifests and drives the sysadmin module editor - license_e2e.py runs against the v2 cloud: free-tier checks use an ordering endpoint (the catalogue stays available), new section 8 edits the site's modules in the cloud and checks kds becomes module.not_licensed and reports.history_days = 30 after the next heartbeat (25/25 pass) - e2e seed templates made by v1 code (no alembic_version) are detected and reseeded automatically (license_e2e.py and lib/proc.mjs) Co-Authored-By: Claude Opus 5.5 --- local_backend/services/cloud_sync.py | 12 +++++++- tests/e2e/lib/proc.mjs | 5 ++++ tests/e2e/license_e2e.py | 41 +++++++++++++++++++++++++--- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 8f9d2a5..cd7e6e6 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -147,6 +147,16 @@ def _get_local_ip() -> str | None: db.close() +def module_catalog() -> list[dict]: + """What this site's code can run (heartbeat C-1, D-20): the cloud's module editor is + built from it, so the sysadmin can only license modules the site knows.""" + from core.modules.registry import registry + return [{"key": m.key, "kind": m.kind, "name": m.name, "depends": list(m.depends), + "limits": [{"key": lim.key, "description": lim.description, "free": lim.free, + "licensed_default": lim.licensed_default} for lim in m.limits]} + for m in registry().values()] + + async def _sync_once(): if not settings.SITE_ID or not settings.CLOUD_URL: logger.debug("No SITE_ID/CLOUD_URL configured — skipping cloud sync") @@ -161,7 +171,7 @@ async def _sync_once(): "X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY, }, - json={"version": settings.VERSION, "uptime_seconds": 0, "local_ip": local_ip}, + json={"version": settings.VERSION, "local_ip": local_ip, "module_catalog": module_catalog()}, ) resp.raise_for_status() data = resp.json() diff --git a/tests/e2e/lib/proc.mjs b/tests/e2e/lib/proc.mjs index 50e8dab..6db9430 100644 --- a/tests/e2e/lib/proc.mjs +++ b/tests/e2e/lib/proc.mjs @@ -32,6 +32,11 @@ export async function waitHttp(url, up = true, timeoutMs = 60_000) { */ export function seededDataDir(label = 'data') { const template = path.join(OUT, 'seed.db') + // A template seeded by v1 code has no alembic_version: v2 refuses it (CS-1), so reseed + if (existsSync(template)) { + const v2 = execFileSync(PYTHON, ['-c', 'import sqlite3, sys; print(sqlite3.connect(sys.argv[1]).execute("select count(*) from sqlite_master where name=?", ("alembic_version",)).fetchone()[0])', template], { encoding: 'utf8' }) + if (!Number(v2)) { console.log(' seed.db was made by v1 code - reseeding'); rmSync(template, { force: true }) } + } if (!existsSync(template)) { console.log(' seeding a demo database (once)…') const partial = `${template}.partial` diff --git a/tests/e2e/license_e2e.py b/tests/e2e/license_e2e.py index 0023cfa..38dccc4 100644 --- a/tests/e2e/license_e2e.py +++ b/tests/e2e/license_e2e.py @@ -1,4 +1,7 @@ -"""License suite (KI-006): a real cloud process + a real site backend process. +"""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 @@ -45,6 +48,9 @@ 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" @@ -61,6 +67,14 @@ def seed_db(target: Path): 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 @@ -101,7 +115,7 @@ def start_cloud(): 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", + "SITE_ID": site_id, "SITE_KEY": site_key, "SECRET_KEY": "e2e-site", "LICENSE_MODE": "enforced", "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)") @@ -159,7 +173,7 @@ try: 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) + check("…and fully usable", call(SITE_URL, "GET", "/api/business-day/current", token=tok)[0], 200) print("── 3. tampered license file") stop("site") @@ -174,7 +188,9 @@ try: 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) + 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)) @@ -206,6 +222,8 @@ try: 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()}) @@ -226,6 +244,21 @@ try: 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)