feat(backend): license entitlements, enforced limits, free tier

Platform v2 step 1.4 (APPS_PLATFORM D-3..D-6, D-21, §5).
- core/modules/entitlements.py: compute() turns the evaluated license into
  per-module grants: the v2 token's `modules` map (own `exp` with the 5-day
  grace, never cut mid-service) + the free tier; no/invalid token, expired
  after grace, inactive, locked or clock tampering -> free tier only; core
  always. limit(module, name) with token value -> manifest licensed_default ->
  free value; None = unlimited. LICENSE_MODE=off (dev/test only) = everything
- module gating says why: module.not_licensed (402, the first unlicensed
  module in the dependency chain) before module.disabled (403)
- services/license.py accepts only v2 tokens with a modules map; the v1
  "legacy unsigned 72h" path is gone
- apply_license() always installs entitlements (startup before workers,
  every heartbeat, workday close); workers follow license changes
- the global license middleware is deleted (no more whole-API 402/423);
  license_state moved to services/license_state.py
- history_days enforced in every report/history endpoint: lower date bounds
  clamped (also when no "from" is given), and business days older than the
  limit refused by id (license.history_limited); data is never deleted
- bootstrap/modules API show license mode, entitlement source and limit values
- LICENSE_MODE=off in docker-compose.dev.yml and the e2e launchers; sites
  default to enforced
- tests: entitlement rules, limits, the three done-when checks, signed-token
  apply_license path; license tests moved to v2 tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 18:32:57 +02:00
co-authored by Claude Opus 5.5
parent 231a97c186
commit 0d43e6a111
21 changed files with 628 additions and 172 deletions
+10 -4
View File
@@ -70,12 +70,17 @@ def pytest_collection_modifyitems(config, items):
@pytest.fixture(autouse=True)
def _venue_time():
"""Every test runs in Europe/Athens with rollover 06:00 (D-11) and venue language "en"
(D-12), without reading settings from a database. Tests may call configure(...) to change them."""
"""Every test runs in Europe/Athens with rollover 06:00 (D-11), venue language "en"
(D-12) and every module entitled without limits (D-3), without reading anything from a
database. Tests may call configure(...) / entitlements.set_current(...) to change them."""
from core import i18n, timeutil
from core.modules import entitlements
timeutil.configure(tz="Europe/Athens", rollover_hour=6)
i18n.configure(venue_language="en")
# Every module, no limits (like LICENSE_MODE=off). License tests install their own.
entitlements.set_current(entitlements.dev(), notify=False)
yield
entitlements.reset()
timeutil.invalidate()
i18n.invalidate()
from core.modules import state as module_state
@@ -128,11 +133,12 @@ def client(db):
"""FastAPI TestClient on the real app, using the test session.
The lifespan is NOT run (no cloud sync, print-retry thread or TLS work);
the schema comes from `_engine`. The license middleware is forced open."""
the schema comes from `_engine`. Entitlements are "dev" (every module, no limits)
via the autouse `_venue_time` fixture; license tests install their own."""
from fastapi.testclient import TestClient
import main
from database import get_db
from middleware.license_check import license_state
from services.license_state import license_state
saved = dict(license_state)
license_state.update(licensed=True, locked=False)
+206
View File
@@ -0,0 +1,206 @@
"""Entitlements, limits, free tier (plan step 1.4, APPS_PLATFORM D-3..D-6, §5)."""
from datetime import datetime, timedelta, timezone
import pytest
from core.modules import entitlements as E
from core.modules.free_tier import FREE_TIER
NOW = datetime(2026, 11, 12, 12, tzinfo=timezone.utc)
def payload(**modules):
return {"v": 2, "site_id": "site-A", "modules": modules}
def ent(mods, licensed=True, locked=False, workday_open=False, now=NOW):
return E.compute(payload(**mods), licensed, locked, now, workday_open)
# ── compute ──────────────────────────────────────────────────────────────────
def test_token_modules_plus_core_plus_free():
e = ent({"ordering": {}, "kds": {"limits": {"devices": 2}}})
assert e.mode == "licensed"
assert {"core", "catalog", "ordering", "kds", "history"} <= set(e.grants)
assert "tabs" not in e.grants and "waiter_app" not in e.grants
assert e.grants["kds"].source == "license" and e.grants["history"].source == "free"
@pytest.mark.parametrize("licensed,locked,reason", [(False, False, "expired"), (True, True, "locked")])
def test_not_licensed_or_locked_gives_free_tier(licensed, locked, reason):
e = ent({"ordering": {}, "kds": {}}, licensed=licensed, locked=locked)
assert e.mode == "free" and e.reason == reason
assert set(e.grants) == {"core", "catalog"} | set(FREE_TIER)
def test_no_token_gives_free_tier():
e = E.compute(None, False, False, NOW, False, problem="unverified")
assert e.mode == "free" and e.reason == "unverified" and "ordering" not in e.grants
def test_module_exp_with_grace_and_workday():
exp = (NOW - timedelta(days=3)).isoformat()
assert "caller_id" in ent({"caller_id": {"exp": exp}}).grants # within 5-day grace
old = (NOW - timedelta(days=6)).isoformat()
assert "caller_id" not in ent({"caller_id": {"exp": old}}).grants # grace over
kept = ent({"caller_id": {"exp": old}}, workday_open=True).grants["caller_id"]
assert kept.exp_deferred is True # never mid-service
def test_unknown_module_in_token_is_ignored():
assert "teleporter" not in ent({"teleporter": {}, "ordering": {}}).grants
# ── limits ───────────────────────────────────────────────────────────────────
def test_limits_token_value_default_and_unlimited():
e = ent({"kds": {"limits": {"devices": 2}}, "pos_counter": {}, "reports": {}})
assert e.limit("kds", "devices") == 2 # from the token
assert e.limit("pos_counter", "devices") == 1 # manifest licensed_default
assert e.limit("reports", "history_days") is None # licensed_default None = unlimited
assert e.limit("signage", "devices") == 0 # not entitled
def test_free_tier_limits():
e = E.compute(None, False, False, NOW, False)
assert e.limit("history", "history_days") == FREE_TIER["history"]["limits"]["history_days"]
licensed_history = ent({"history": {}})
assert licensed_history.limit("history", "history_days") is None
def test_dev_mode_has_everything_unlimited():
e = E.dev()
assert e.mode == "dev" and e.limit("kds", "devices") is None and e.entitled("fiscal")
# ── API: done-when checks ────────────────────────────────────────────────────
def install(mods, **kw):
E.set_current(ent(mods, **kw), notify=False)
def test_token_without_kds_blocks_kds_api(client, make_user, login): # "done when" 1
install({"ordering": {}})
r = client.get("/api/kds/orders", headers=login(make_user(role="superadmin")))
assert r.status_code == 402
assert r.json()["error"] == {"code": "module.not_licensed", "params": {"module": "kds"},
"message": "This site's license doesn't include kds."}
def test_dependency_not_licensed_reports_the_dependency(client, make_user, login):
install({"kds": {}}) # kds without ordering
r = client.get("/api/kds/orders", headers=login(make_user(role="superadmin")))
assert r.json()["error"]["params"] == {"module": "ordering"}
def _orders_at(db, user, days_ago_list):
from models.order import Order, OrderItem
from models.product import Category, Product
cat = Category(name="C")
db.add(cat)
db.flush()
prod = Product(name="P", base_price=5.0, category_id=cat.id)
db.add(prod)
db.flush()
for d in days_ago_list:
when = datetime.now(timezone.utc) - timedelta(days=d) # noqa: test data
o = Order(opened_by=user.id, status="closed", opened_at=when, closed_at=when)
db.add(o)
db.flush()
db.add(OrderItem(order_id=o.id, product_id=prod.id, added_by=user.id, quantity=1,
unit_price=5.0, status="paid", added_at=when, paid_at=when))
db.commit()
def test_history_days_clamps_a_90_day_report(client, db, make_user, login): # "done when" 2
admin = make_user(role="superadmin")
_orders_at(db, admin, [10, 60, 85])
since = (datetime.now(timezone.utc) - timedelta(days=90)).date().isoformat()
install({"ordering": {}, "reports": {"limits": {"history_days": 30}}})
r = client.get("/api/reports/revenue/trends", params={"from": since, "granularity": "monthly"}, headers=login(admin))
assert r.status_code == 200, r.text
rows = r.json() if isinstance(r.json(), list) else next(v for v in r.json().values() if isinstance(v, list))
assert sum(row["orders"] for row in rows) == 1 # only the 10-day-old order is visible
install({"ordering": {}, "reports": {}}) # unlimited again: data was never deleted
r = client.get("/api/reports/revenue/trends", params={"from": since, "granularity": "monthly"}, headers=login(admin))
rows = r.json() if isinstance(r.json(), list) else next(v for v in r.json().values() if isinstance(v, list))
assert sum(row["orders"] for row in rows) == 3
def test_history_limit_also_applies_without_from(client, db, make_user, login):
admin = make_user(role="superadmin")
_orders_at(db, admin, [5, 200])
install({"ordering": {}, "reports": {"limits": {"history_days": 30}}})
r = client.get("/api/reports/traffic", headers=login(admin))
assert sum(b["orders"] for b in r.json()["by_hour"]) == 1
def test_old_business_day_refused_by_id(client, db, make_user, login):
from models.business_day import BusinessDay
from core.timeutil import business_date_of
admin = make_user(role="superadmin")
opened = datetime.now(timezone.utc) - timedelta(days=60)
bd = BusinessDay(opened_by_id=admin.id, opened_at=opened, business_date=business_date_of(opened),
status="closed", closed_at=opened + timedelta(hours=10))
db.add(bd)
db.commit()
install({"ordering": {}, "reports": {"limits": {"history_days": 30}}})
r = client.get("/api/reports/traffic", params={"business_day_id": bd.id}, headers=login(admin))
assert r.status_code == 402 and r.json()["error"]["code"] == "license.history_limited"
assert r.json()["error"]["params"] == {"module": "reports", "days": 30}
def test_free_tier_history_is_capped_and_reports_blocked(client, db, make_user, login):
admin = make_user(role="superadmin")
E.set_current(E.compute(None, False, False, NOW, False), notify=False)
assert client.get("/api/reports/orders/history", headers=login(admin)).status_code == 200
assert client.get("/api/reports/traffic", headers=login(admin)).json()["error"]["code"] == "module.not_licensed"
def test_expired_site_can_log_in_and_see_license_page_but_not_order(client, make_user): # "done when" 3
from conftest import TEST_PASSWORD
E.set_current(E.compute(None, False, False, NOW, False, problem="expired"), notify=False)
m = make_user(role="store_manager")
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
assert r.status_code == 200
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
assert client.get("/api/system/status", headers=h).status_code == 200
assert client.get("/api/setup/security-config").status_code == 200
boot = client.get("/api/platform/bootstrap", headers=h).json()
assert boot["license"] == {"mode": "free", "reason": "expired"}
assert "ordering" not in {x["key"] for x in boot["modules"]}
assert client.get("/api/business-day/current", headers=h).json()["error"]["code"] == "module.not_licensed"
def test_catalogue_shows_entitlement_and_limit_values(client, make_user, login):
install({"ordering": {}, "kds": {"limits": {"devices": 3}}})
mods = {m["key"]: m for m in client.get("/api/platform/modules",
headers=login(make_user(role="superadmin"))).json()["modules"]}
assert mods["kds"]["entitled"] and mods["kds"]["entitlement"]["source"] == "license"
assert mods["kds"]["limits"][0]["value"] == 3
assert mods["signage"]["entitled"] is False and mods["signage"]["effective"] is False
# ── apply_license end to end (signed token, real code path) ─────────────────
def test_apply_license_installs_entitlements_from_a_signed_token(monkeypatch):
from tests.test_license import PUB, make_token
import services.license as L
from config import settings
from services import cloud_sync
from services.license_state import license_state
monkeypatch.setattr(L, "LICENSE_PUBLIC_KEY", PUB)
monkeypatch.setattr(settings, "SITE_ID", "site-A")
monkeypatch.setattr(settings, "LICENSE_MODE", "enforced")
monkeypatch.setitem(license_state, "license_token", make_token(modules={"ordering": {}, "reports": {}}))
monkeypatch.setitem(license_state, "time_high_water", None)
cloud_sync.apply_license(now=datetime(2027, 1, 1, tzinfo=timezone.utc))
e = E.current()
assert e.mode == "licensed" and e.entitled("reports") and not e.entitled("kds")
assert license_state["entitlement_mode"] == "licensed" and license_state["licensed"] is True
monkeypatch.setattr(settings, "LICENSE_MODE", "off")
cloud_sync.apply_license()
assert E.current().mode == "dev" and license_state["license_mode"] == "off"
+12 -13
View File
@@ -1,4 +1,4 @@
"""Offline-capable licensing rules (services/license.py, KI-006).
"""Offline-capable licensing rules (services/license.py, KI-006; v2 tokens, D-21).
Tokens are signed with a throwaway key here — the production signing key is
never needed; verify_token() takes the public key as a parameter.
@@ -24,8 +24,9 @@ def b64(data: bytes) -> str:
def make_token(signer=KEY, **overrides) -> str:
payload = {"v": 1, "site_id": "site-A", "active": True, "locked": False, "lock_reason": None,
"expires_at": EXPIRES.isoformat(), "issued_at": ISSUED.isoformat(), **overrides}
payload = {"v": 2, "site_id": "site-A", "active": True, "locked": False, "lock_reason": None,
"expires_at": EXPIRES.isoformat(), "issued_at": ISSUED.isoformat(),
"modules": {"ordering": {}}, **overrides}
body = b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
return f"{body}.{b64(signer.sign(body.encode()))}"
@@ -48,6 +49,14 @@ def test_edited_expiry_rejected(payload):
assert verify_token(f"{forged}.{sig}", "site-A", PUB) is None
def test_v1_token_rejected(): # D-21: v2 sites accept only v2 tokens
assert verify_token(make_token(v=1), "site-A", PUB) is None
def test_v2_token_without_modules_rejected():
assert verify_token(make_token(modules=None), "site-A", PUB) is None
def test_token_for_another_site_rejected():
assert verify_token(make_token(site_id="site-B"), "site-A", PUB) is None
@@ -115,16 +124,6 @@ def test_clock_before_signed_issue_time_blocks(payload):
# ── evaluate: no genuine token ───────────────────────────────────────────────
def test_transition_old_cloud_recent_ok():
r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=10))
assert (r["licensed"], r["license_problem"]) == (True, None)
def test_transition_old_cloud_stale():
r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=80))
assert (r["licensed"], r["license_problem"]) == (False, "unverified")
def test_never_licensed_blocks():
r = evaluate(None, ISSUED, None, False)
assert (r["licensed"], r["license_problem"]) == (False, "unverified")