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
+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)