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:
@@ -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"
|
||||
Reference in New Issue
Block a user