feat(cloud): Alembic, license token v2 with modules, plan presets, module editor
Platform v2 step 1.7 (APPS_PLATFORM D-3, D-20, D-21, D-22, §5.2).
- Alembic replaces create_all + _run_migrations. 0001_cloud_baseline is
exactly the v1 production schema (incl. the dead menu_hours_en/_gr), checked
against a frozen fixture; schema.py refuses an unstamped v1 DB, so prod is
stamped once at cutover (DEPLOYMENT_GUIDE Part 6)
- 0002_v2_licensing: sites.modules (JSON), sites.module_catalog(_at),
plan_presets; existing sites get every module v1 had (KDS unlimited); the
same map is seeded as preset "Everything (v1 sites)"; dead columns dropped
- license token v: 2 with a normalized `modules` map
- heartbeat v2: request {version, local_ip, module_catalog} (catalogue stored
per site); response {license_token, latest_version, waiter_domain,
site_numeric_id} - the unsigned v1 license fields are gone
- sites API: create with a preset, PUT /{id}/modules (validated),
POST /{id}/apply-preset/{preset}; /api/presets CRUD
- sysadmin panel: Licensed modules card per site (built from the reported
catalogue, fallback list), preset picker on register, Presets page
- .dockerignore: local *.db, .env and tests no longer baked into the image
- tests (new): baseline = v1, unstamped refused, stamp+upgrade of a v1 DB,
drift, token v2 shape/signature, module edits, presets; CL-2/CL-7 rules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
"""Cloud backend tests. Run from cloud_backend/: python -m pytest tests -q
|
||||
|
||||
Before anything imports config/database, DATABASE_URL points at a fresh temp file and a
|
||||
throwaway LICENSE_SIGNING_KEY is set, so tests never touch a real cloud DB or key.
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
|
||||
_TMP = Path(tempfile.mkdtemp(prefix="xenia-cloud-tests-"))
|
||||
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'cloud.db').as_posix()}"
|
||||
TEST_KEY = Ed25519PrivateKey.generate()
|
||||
os.environ["LICENSE_SIGNING_KEY"] = base64.b64encode(
|
||||
TEST_KEY.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw,
|
||||
serialization.NoEncryption())).decode()
|
||||
TEST_PUB = base64.b64encode(TEST_KEY.public_key().public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
|
||||
os.environ["ADMIN_USERNAME"] = "sysadmin"
|
||||
os.environ["ADMIN_PASSWORD"] = "test-admin-pw"
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import pytest # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client():
|
||||
from fastapi.testclient import TestClient
|
||||
import main
|
||||
with TestClient(main.app) as c: # runs the lifespan: Alembic upgrade + default admin
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def admin_h(client):
|
||||
r = client.post("/api/auth/login", json={"username": "sysadmin", "password": "test-admin-pw"})
|
||||
assert r.status_code == 200, r.text
|
||||
return {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
-- The v1 production cloud schema (create_all + _run_migrations on main, 2026-11-12).
|
||||
-- Frozen fixture for tests/test_schema.py: the v2 baseline must equal it, and a DB
|
||||
-- in this shape must stamp + upgrade cleanly (APPS_PLATFORM D-22). Never edit.
|
||||
|
||||
CREATE TABLE admins (
|
||||
id INTEGER NOT NULL,
|
||||
username VARCHAR NOT NULL,
|
||||
password_hash VARCHAR NOT NULL,
|
||||
role VARCHAR,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE (username)
|
||||
);
|
||||
CREATE TABLE manager_accounts (
|
||||
id INTEGER NOT NULL,
|
||||
email VARCHAR NOT NULL,
|
||||
password_hash VARCHAR NOT NULL,
|
||||
full_name VARCHAR,
|
||||
is_active INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
CREATE TABLE manager_site_access (
|
||||
manager_id INTEGER NOT NULL,
|
||||
site_id INTEGER NOT NULL,
|
||||
PRIMARY KEY (manager_id, site_id),
|
||||
FOREIGN KEY(manager_id) REFERENCES manager_accounts (id),
|
||||
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||
);
|
||||
CREATE TABLE menu_snapshots (
|
||||
id INTEGER NOT NULL,
|
||||
site_id INTEGER NOT NULL,
|
||||
snapshot_json TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||
);
|
||||
CREATE TABLE online_orders (
|
||||
id INTEGER NOT NULL,
|
||||
site_id INTEGER NOT NULL,
|
||||
public_ref VARCHAR NOT NULL,
|
||||
order_type VARCHAR NOT NULL,
|
||||
customer_name VARCHAR NOT NULL,
|
||||
customer_phone VARCHAR,
|
||||
customer_address TEXT,
|
||||
customer_notes TEXT,
|
||||
items_json TEXT NOT NULL,
|
||||
subtotal FLOAT NOT NULL,
|
||||
delivery_fee FLOAT NOT NULL,
|
||||
total FLOAT NOT NULL,
|
||||
status VARCHAR NOT NULL,
|
||||
rejection_reason VARCHAR,
|
||||
synced_to_local INTEGER NOT NULL,
|
||||
local_order_id INTEGER,
|
||||
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(site_id) REFERENCES sites (id),
|
||||
UNIQUE (public_ref)
|
||||
);
|
||||
CREATE TABLE product_images (
|
||||
id INTEGER NOT NULL,
|
||||
site_id INTEGER NOT NULL,
|
||||
product_id INTEGER NOT NULL,
|
||||
image_url VARCHAR NOT NULL,
|
||||
image_hash VARCHAR NOT NULL,
|
||||
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uq_product_images_site_product UNIQUE (site_id, product_id),
|
||||
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||
);
|
||||
CREATE TABLE sites (
|
||||
id INTEGER NOT NULL,
|
||||
site_id VARCHAR NOT NULL,
|
||||
name VARCHAR NOT NULL,
|
||||
owner_name VARCHAR NOT NULL,
|
||||
contact_email VARCHAR NOT NULL,
|
||||
secret_key_hash VARCHAR NOT NULL,
|
||||
is_active BOOLEAN,
|
||||
is_locked BOOLEAN,
|
||||
lock_reason VARCHAR,
|
||||
license_expires_at DATETIME NOT NULL,
|
||||
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
last_seen_at DATETIME,
|
||||
last_seen_ip VARCHAR,
|
||||
last_seen_local_ip VARCHAR,
|
||||
waiter_domain VARCHAR,
|
||||
order_counter INTEGER NOT NULL,
|
||||
menu_mode VARCHAR NOT NULL,
|
||||
menu_display_name VARCHAR,
|
||||
menu_tagline_en VARCHAR,
|
||||
menu_tagline_gr VARCHAR,
|
||||
menu_blurb_en VARCHAR,
|
||||
menu_blurb_gr VARCHAR,
|
||||
menu_hours VARCHAR,
|
||||
menu_header_image_url VARCHAR, menu_hours_en VARCHAR, menu_hours_gr VARCHAR,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
CREATE TABLE stats_snapshots (
|
||||
id INTEGER NOT NULL,
|
||||
site_id INTEGER NOT NULL,
|
||||
snapshot_json TEXT NOT NULL,
|
||||
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE (site_id),
|
||||
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||
);
|
||||
CREATE INDEX ix_admins_id ON admins (id);
|
||||
CREATE UNIQUE INDEX ix_manager_accounts_email ON manager_accounts (email);
|
||||
CREATE INDEX ix_manager_accounts_id ON manager_accounts (id);
|
||||
CREATE INDEX ix_menu_snapshots_id ON menu_snapshots (id);
|
||||
CREATE UNIQUE INDEX ix_menu_snapshots_site_id ON menu_snapshots (site_id);
|
||||
CREATE INDEX ix_online_orders_id ON online_orders (id);
|
||||
CREATE INDEX ix_online_orders_site_id ON online_orders (site_id);
|
||||
CREATE INDEX ix_online_orders_status ON online_orders (status);
|
||||
CREATE INDEX ix_product_images_id ON product_images (id);
|
||||
CREATE INDEX ix_product_images_site_id ON product_images (site_id);
|
||||
CREATE INDEX ix_sites_id ON sites (id);
|
||||
CREATE UNIQUE INDEX ix_sites_site_id ON sites (site_id);
|
||||
@@ -0,0 +1,101 @@
|
||||
"""License token v2, site modules, presets, heartbeat catalogue (plan step 1.7, D-3, D-20, D-21)."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
|
||||
from conftest import TEST_PUB
|
||||
|
||||
|
||||
def _decode(token):
|
||||
body, sig = token.split(".")
|
||||
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
|
||||
Ed25519PublicKey.from_public_bytes(base64.b64decode(TEST_PUB)).verify(
|
||||
base64.urlsafe_b64decode(pad(sig)), body.encode()) # raises if the signature is wrong
|
||||
return json.loads(base64.urlsafe_b64decode(pad(body)))
|
||||
|
||||
|
||||
def _new_site(client, admin_h, **extra):
|
||||
r = client.post("/api/sites/", headers=admin_h, json={
|
||||
"name": "Test", "owner_name": "O", "contact_email": "o@example.com",
|
||||
"license_expires_at": "2027-06-01T00:00:00+00:00", **extra})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _heartbeat(client, site, catalog=()):
|
||||
r = client.post("/api/heartbeat/", headers={"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]},
|
||||
json={"version": "2.0.0", "local_ip": "192.168.1.10", "module_catalog": list(catalog)})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_normalize_modules():
|
||||
from services.license_token import normalize_modules
|
||||
assert normalize_modules({"kds": {"limits": {"devices": "2"}, "junk": 1}, "tabs": None}) == \
|
||||
{"kds": {"limits": {"devices": 2}}, "tabs": {}}
|
||||
|
||||
|
||||
def test_new_site_gets_default_preset_and_v2_token(client, admin_h):
|
||||
site = _new_site(client, admin_h)
|
||||
assert "ordering" in site["modules"]
|
||||
hb = _heartbeat(client, site)
|
||||
assert set(hb) == {"license_token", "latest_version", "waiter_domain", "site_numeric_id"}
|
||||
p = _decode(hb["license_token"])
|
||||
assert p["v"] == 2 and p["site_id"] == site["site_id"] and p["modules"]["kds"] == {"limits": {"devices": None}}
|
||||
assert {"active", "locked", "expires_at", "issued_at"} <= set(p)
|
||||
|
||||
|
||||
def test_site_without_preset_licenses_nothing(client, admin_h):
|
||||
site = _new_site(client, admin_h, preset=None)
|
||||
assert _decode(_heartbeat(client, site)["license_token"])["modules"] == {}
|
||||
|
||||
|
||||
def test_editing_modules_changes_the_next_token(client, admin_h):
|
||||
site = _new_site(client, admin_h)
|
||||
r = client.put(f"/api/sites/{site['site_id']}/modules", headers=admin_h,
|
||||
json={"modules": {"ordering": {}, "kds": {"limits": {"devices": 2}},
|
||||
"caller_id": {"exp": "2027-01-31T00:00:00+00:00"}}})
|
||||
assert r.status_code == 200, r.text
|
||||
mods = _decode(_heartbeat(client, site)["license_token"])["modules"]
|
||||
assert mods == {"ordering": {}, "kds": {"limits": {"devices": 2}},
|
||||
"caller_id": {"exp": "2027-01-31T00:00:00+00:00"}}
|
||||
|
||||
|
||||
def test_bad_module_maps_are_refused(client, admin_h):
|
||||
site = _new_site(client, admin_h)
|
||||
for bad in ({"kds": {"limits": {"devices": -1}}}, {"kds": {"limits": {"devices": "x"}}},
|
||||
{"caller_id": {"exp": "tomorrow"}}):
|
||||
assert client.put(f"/api/sites/{site['site_id']}/modules", headers=admin_h, json={"modules": bad}).status_code == 422
|
||||
|
||||
|
||||
def test_heartbeat_stores_the_module_catalogue(client, admin_h):
|
||||
site = _new_site(client, admin_h)
|
||||
catalog = [{"key": "kds", "kind": "app", "name": "Kitchen display", "depends": ["ordering"],
|
||||
"limits": [{"key": "devices", "free": 0, "licensed_default": 1}]}]
|
||||
_heartbeat(client, site, catalog)
|
||||
got = client.get(f"/api/sites/{site['site_id']}", headers=admin_h).json()
|
||||
assert got["module_catalog"] == catalog and got["module_catalog_at"]
|
||||
|
||||
|
||||
def test_presets_crud_and_apply(client, admin_h):
|
||||
r = client.post("/api/presets/", headers=admin_h, json={"name": "Cafe basic", "description": "POS + KDS",
|
||||
"modules": {"ordering": {}, "kds": {"limits": {"devices": 1}}}})
|
||||
assert r.status_code == 201, r.text
|
||||
preset = r.json()
|
||||
names = [p["name"] for p in client.get("/api/presets/", headers=admin_h).json()]
|
||||
assert "Cafe basic" in names and "Everything (v1 sites)" in names
|
||||
site = _new_site(client, admin_h, preset="Cafe basic")
|
||||
assert set(site["modules"]) == {"ordering", "kds"}
|
||||
site2 = _new_site(client, admin_h)
|
||||
applied = client.post(f"/api/sites/{site2['site_id']}/apply-preset/{preset['id']}", headers=admin_h).json()
|
||||
assert applied["modules"] == {"ordering": {}, "kds": {"limits": {"devices": 1}}}
|
||||
assert client.post("/api/presets/", headers=admin_h, json={"name": "Cafe basic", "modules": {}}).status_code == 409
|
||||
assert client.delete(f"/api/presets/{preset['id']}", headers=admin_h).status_code == 204
|
||||
|
||||
|
||||
def test_unknown_preset_on_create(client, admin_h):
|
||||
r = client.post("/api/sites/", headers=admin_h, json={
|
||||
"name": "T", "owner_name": "O", "contact_email": "o@x", "license_expires_at": "2027-06-01T00:00:00+00:00",
|
||||
"preset": "Nope"})
|
||||
assert r.status_code == 400
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Cloud schema guard (APPS_PLATFORM D-22): Alembic only, baseline = v1 production, no drift."""
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from schema import BASELINE, UnstampedDatabaseError, stamp_baseline, upgrade_to_head
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
V1_SQL = (HERE / "fixtures" / "v1_cloud_schema.sql").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _v1_db(path: Path):
|
||||
con = sqlite3.connect(path)
|
||||
con.executescript(V1_SQL)
|
||||
con.execute("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
|
||||
"is_locked, license_expires_at, order_counter, menu_mode, menu_hours_en) values "
|
||||
"(1, 'site-1', 'Kopse', 'O', 'o@x', 'h', 1, 0, '2027-05-01 00:00:00', 7, 'order', 'old')")
|
||||
con.commit()
|
||||
con.close()
|
||||
return create_engine(f"sqlite:///{path.as_posix()}")
|
||||
|
||||
|
||||
def _shape(path):
|
||||
con = sqlite3.connect(path)
|
||||
tables = {t: sorted((r[1], r[2].upper(), r[3]) for r in con.execute(f'pragma table_info("{t}")'))
|
||||
for (t,) in con.execute("select name from sqlite_master where type='table' "
|
||||
"and name not in ('alembic_version', 'sqlite_sequence')")}
|
||||
idx = sorted(r[0] for r in con.execute("select name from sqlite_master where type='index' and name not like 'sqlite_%'"))
|
||||
con.close()
|
||||
return tables, idx
|
||||
|
||||
|
||||
def test_baseline_equals_v1_production_schema(tmp_path):
|
||||
from schema import alembic_config
|
||||
from alembic import command
|
||||
eng = create_engine(f"sqlite:///{(tmp_path / 'b.db').as_posix()}")
|
||||
with eng.begin() as conn:
|
||||
command.upgrade(alembic_config(conn), BASELINE)
|
||||
eng.dispose()
|
||||
con = sqlite3.connect(tmp_path / "v1.db")
|
||||
con.executescript(V1_SQL)
|
||||
con.close()
|
||||
assert _shape(tmp_path / "b.db") == _shape(tmp_path / "v1.db")
|
||||
|
||||
|
||||
def test_unstamped_v1_db_is_refused(tmp_path):
|
||||
eng = _v1_db(tmp_path / "prod.db")
|
||||
with pytest.raises(UnstampedDatabaseError):
|
||||
upgrade_to_head(eng)
|
||||
|
||||
|
||||
def test_stamp_then_upgrade_a_v1_db(tmp_path): # the cutover procedure
|
||||
eng = _v1_db(tmp_path / "prod.db")
|
||||
stamp_baseline(eng)
|
||||
upgrade_to_head(eng)
|
||||
with eng.connect() as conn:
|
||||
site = conn.execute(text("select site_id, order_counter, modules from sites")).one()
|
||||
presets = conn.execute(text("select name from plan_presets")).scalars().all()
|
||||
cols = [r[1] for r in conn.execute(text("pragma table_info(sites)"))]
|
||||
eng.dispose()
|
||||
assert site[0] == "site-1" and site[1] == 7 # data kept
|
||||
mods = json.loads(site[2])
|
||||
assert {"ordering", "waiter_app", "kds", "connect_menu"} <= set(mods)
|
||||
assert mods["kds"] == {"limits": {"devices": None}} # v1 had no KDS limit
|
||||
assert presets == ["Everything (v1 sites)"]
|
||||
assert "menu_hours_en" not in cols
|
||||
|
||||
|
||||
def test_no_drift_between_models_and_migrations(tmp_path):
|
||||
from database import Base
|
||||
import models.all # noqa: F401
|
||||
eng = create_engine(f"sqlite:///{(tmp_path / 'd.db').as_posix()}")
|
||||
upgrade_to_head(eng)
|
||||
with eng.connect() as conn:
|
||||
diff = compare_metadata(MigrationContext.configure(conn, opts={"compare_type": True}), Base.metadata)
|
||||
eng.dispose()
|
||||
assert diff == [], "\n".join(map(str, diff))
|
||||
|
||||
|
||||
def test_nothing_calls_create_all():
|
||||
root = HERE.parent
|
||||
bad = [p.relative_to(root).as_posix() for p in root.rglob("*.py")
|
||||
if not p.relative_to(root).as_posix().startswith(("tests/", "migrations/"))
|
||||
and re.search(r"\.create_all\(", p.read_text(encoding="utf-8", errors="ignore"))]
|
||||
assert bad == []
|
||||
Reference in New Issue
Block a user