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
@@ -12,7 +12,7 @@ Agent notes:
adds per-user grants; superadmin gets every key (D-7).
- Access: PUT uses require_settings_manager until step 1.5 switches it to
require("core.modules.manage").
- `entitled` is True for every module until step 1.4.
- `entitled`/`entitlement`/limit `value` come from core/modules/entitlements.py (step 1.4).
"""
from __future__ import annotations
@@ -24,7 +24,7 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from core import i18n, timeutil
from core.modules import state
from core.modules import entitlements, state
from core.modules.registry import all_permissions, registry
from database import get_db
from routers.deps import get_current_user, require_settings_manager
@@ -48,16 +48,21 @@ def _setting(db: Session, key: str, default: str) -> str:
def _module_out(m, enabled: dict, effective: frozenset) -> dict:
ent = entitlements.current()
grant = ent.grants.get(m.key)
return {
"key": m.key, "kind": m.kind, "name": m.name, "description": m.description,
"depends": list(m.depends),
"entitled": True,
"entitled": grant is not None,
"entitlement": ({"source": grant.source, "exp": grant.exp, "exp_deferred": grant.exp_deferred}
if grant else None),
"enabled": enabled.get(m.key, True),
"effective": m.key in effective,
"can_disable": m.can_disable,
"permissions": [{"key": p.key, "description": p.description, "roles": list(p.roles)} for p in m.permissions],
"limits": [{"key": lim.key, "description": lim.description, "free": lim.free,
"licensed_default": lim.licensed_default} for lim in m.limits],
"licensed_default": lim.licensed_default,
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
for sd in m.settings],
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
@@ -87,6 +92,7 @@ def bootstrap(
"business_day_rollover_hour": timeutil.rollover_hour(),
},
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
"license": {"mode": entitlements.current().mode, "reason": entitlements.current().reason},
"languages": list(i18n.SUPPORTED_LANGUAGES),
"user": None,
"language": i18n.venue_language(),
+178
View File
@@ -0,0 +1,178 @@
"""Which modules this site may use, and with which limits (APPS_PLATFORM D-3..D-6, §5.1).
effective = (entitled ∪ free tier) ∩ enabled (state.py adds "enabled" and deps)
Sources, decided by compute():
- LICENSE_MODE=off (config; dev and test machines only): every module, no limits.
- a valid v2 token and the global license says "licensed" (services/license.py::evaluate,
which already defers expiry/lock to the end of an open workday): the token's
`modules` map. A module with its own `exp` gets the same 5-day grace and is never
cut off while a workday is open. Plus the free tier for modules the token lacks.
- anything else (no token, bad token, expired after grace, inactive, locked, clock
tampering): the free tier only (core/modules/free_tier.py).
Core modules are always entitled.
Limits (D-6): limit(module, name) -> int | None (None = unlimited).
module from the token: token's limits[name], else the manifest's licensed_default
module only from the free tier: FREE_TIER[module]["limits"][name], else Limit.free
Limits restrict what is shown or used, never what is stored.
The current result is held in memory (set by cloud_sync.apply_license at startup, after
every heartbeat and at workday close). Tests call set_current(compute(...)) or set_dev().
"""
from __future__ import annotations
import logging
import threading
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from core.modules.free_tier import FREE_TIER
from core.timeutil import utcnow
from core.modules.registry import registry
logger = logging.getLogger("xenia.license")
MODULE_EXPIRY_GRACE = timedelta(days=5) # same as services/license.py EXPIRY_GRACE
@dataclass(frozen=True)
class Grant:
source: str # "license" | "free" | "dev" | "core"
limits: dict = field(default_factory=dict)
exp: str | None = None
exp_deferred: bool = False # past exp + grace, kept until the open workday closes
@dataclass(frozen=True)
class Entitlements:
mode: str # "dev" | "licensed" | "free"
grants: dict # {module key: Grant}
reason: str | None = None # why "free": unverified | expired | inactive | locked | clock
def entitled(self, key: str) -> bool:
return key in self.grants
def limit(self, module: str, name: str) -> int | None:
g = self.grants.get(module)
m = registry().get(module)
decl = next((lim for lim in m.limits if lim.key == name), None) if m else None
if g is None:
return 0
if g.source == "dev":
return None
if name in g.limits:
return g.limits[name]
if decl is None:
return None
return decl.free if g.source == "free" else decl.licensed_default
def _parse(dt):
from services.license import parse_dt
return parse_dt(dt)
def compute(payload: dict | None, licensed: bool, locked: bool, now: datetime, workday_open: bool,
problem: str | None = None) -> Entitlements:
reg = registry()
grants: dict[str, Grant] = {k: Grant("core") for k, m in reg.items() if m.kind == "core"}
def add_free():
for k, spec in FREE_TIER.items():
if k in reg and k not in grants:
grants[k] = Grant("free", dict(spec.get("limits", {})))
if payload is None or not licensed or locked:
add_free()
reason = "locked" if locked else (problem or ("unverified" if payload is None else "expired"))
return Entitlements("free", grants, reason)
for k, spec in (payload.get("modules") or {}).items():
if k not in reg:
logger.info("license.unknown_module key=%s (newer cloud catalogue?)", k)
continue
spec = spec or {}
exp = _parse(spec.get("exp"))
deferred = False
if exp is not None and now > exp + MODULE_EXPIRY_GRACE:
if not workday_open:
continue # this module's own license ran out
deferred = True # never cut off mid-service
if reg[k].kind == "core":
grants[k] = Grant("core", dict(spec.get("limits") or {}))
continue
grants[k] = Grant("license", dict(spec.get("limits") or {}),
exp.isoformat() if exp else None, deferred)
add_free()
return Entitlements("licensed", grants)
def dev() -> Entitlements:
return Entitlements("dev", {k: Grant("dev") for k in registry()})
# ── current state ────────────────────────────────────────────────────────────
_lock = threading.Lock()
_current: Entitlements | None = None
def current() -> Entitlements:
with _lock:
cur = _current
if cur is None:
# Before the first apply_license(): dev mode if configured, else the free tier.
from config import settings
cur = dev() if settings.LICENSE_MODE == "off" else compute(None, False, False, utcnow(), False)
return cur
def set_current(ent: Entitlements, notify: bool = True) -> None:
"""Install a new result; modules and workers follow at once if anything changed.
notify=False is for tests that have no database to re-read."""
global _current
with _lock:
changed = _current is None or _current.grants != ent.grants
_current = ent
if changed and notify:
logger.info("license.entitlements mode=%s modules=%d reason=%s", ent.mode, len(ent.grants), ent.reason)
from core.modules import state
state.notify()
def set_dev() -> None:
set_current(dev())
def reset() -> None:
global _current
with _lock:
_current = None
def limit(module: str, name: str) -> int | None:
return current().limit(module, name)
def history_floor(module: str) -> datetime | None:
"""Earliest moment `module` may show, from its `history_days` limit (D-6). None = no limit."""
days = limit(module, "history_days")
if days is None:
return None
return utcnow() - timedelta(days=days)
def clamp_start(start: datetime | None, module: str) -> datetime | None:
"""A lower time bound moved forward to the module's history floor (D-6)."""
floor = history_floor(module)
if floor is None:
return start
return floor if start is None or start < floor else start
def history_since(value, module: str) -> datetime | None:
"""API "from" value -> UTC lower bound, never older than the module allows (D-6).
No value and no limit -> None (no bound)."""
from core.timeutil import parse_api_datetime
return clamp_start(parse_api_datetime(value) if value else None, module)
+33 -3
View File
@@ -13,7 +13,8 @@ module_required(key) is the FastAPI dependency main.py adds to each non-core rou
Agent notes:
- Always change enablement through set_enabled(), never by writing SiteModule rows,
or the cache and the workers won't follow.
- Step 1.4 replaces `_entitled()` with the license evaluation (entitled ∪ free tier).
- Entitlement comes from core/modules/entitlements.py (license ∪ free tier, step 1.4).
A blocked request says why: module.not_licensed (402) before module.disabled (403).
"""
from __future__ import annotations
@@ -73,7 +74,19 @@ def enabled_map(db: Session | None = None) -> dict[str, bool]:
def _entitled(key: str) -> bool:
return True # >>> step 1.4: license entitlements ∪ free tier
from core.modules import entitlements
return entitlements.current().entitled(key)
def notify() -> None:
"""Tell listeners (the worker supervisor) the effective set may have changed,
e.g. after the license was re-evaluated."""
eff = effective_set()
for fn in list(_listeners):
try:
fn(eff)
except Exception:
logger.exception("module listener failed")
def effective_set(db: Session | None = None) -> frozenset[str]:
@@ -122,6 +135,23 @@ def set_enabled(db: Session, key: str, enabled: bool, user_id: int | None = None
return eff
def blocked_error(key: str, db: Session | None = None) -> XeniaError:
"""Why `key` isn't effective: not licensed (itself or a dependency) beats turned off."""
reg = registry()
seen, stack = set(), [key]
while stack:
k = stack.pop()
if k in seen:
continue
seen.add(k)
if not _entitled(k):
return XeniaError("module.not_licensed", module=k)
stack.extend(reg[k].depends)
enabled = enabled_map(db)
off = next((k for k in [key, *sorted(seen - {key})] if not enabled.get(k, True)), key)
return XeniaError("module.disabled", module=off)
def module_required(key: str):
"""FastAPI dependency: the endpoint answers `module.disabled` unless the module is effective."""
if key not in registry():
@@ -129,7 +159,7 @@ def module_required(key: str):
def _check(db: Session = Depends(get_db)) -> None:
if not is_effective(key, db):
raise XeniaError("module.disabled", module=key)
raise blocked_error(key, db)
_check.__name__ = f"module_required_{key}"
return _check