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
+38 -25
View File
@@ -22,7 +22,7 @@ from pathlib import Path
import httpx
from config import settings
from middleware.license_check import license_state
from services.license_state import license_state
from services.license import evaluate, parse_dt, verify_token
ORDER_POLL_INTERVAL = settings.CONNECT_SYNC_INTERVAL_SECONDS
@@ -73,14 +73,26 @@ def _latest_activity(db) -> datetime | None:
def apply_license(now: datetime | None = None) -> None:
"""Re-evaluate the license from the stored signed token (no network)."""
if not settings.SITE_ID or not settings.CLOUD_URL:
return # dev / unregistered / no cloud configured: licensing off, as before KI-006
"""Re-evaluate the license from the stored signed token (no network) and install
the resulting module entitlements (core/modules/entitlements.py).
Called at startup, after every heartbeat and when a business day closes (expiry,
grace and remote locks are deferred to that moment, never mid-service).
LICENSE_MODE=off (dev machines only): every module, no limits.
No SITE_ID / no valid v2 token / expired / inactive / locked: the free tier."""
from core.modules import entitlements
if settings.LICENSE_MODE == "off":
license_state.update({"license_mode": "off", "licensed": True, "license_problem": None,
"entitlement_mode": "dev", "locked": False, "lock_pending": False})
entitlements.set_dev()
return
from database import SessionLocal
from models.business_day import BusinessDay
now = now or utcnow()
payload = verify_token(license_state.get("license_token"), settings.SITE_ID)
payload = verify_token(license_state.get("license_token"), settings.SITE_ID) if settings.SITE_ID else None
db = SessionLocal()
try:
workday_open = db.query(BusinessDay).filter(BusinessDay.status == "open").first() is not None
@@ -91,7 +103,7 @@ def apply_license(now: datetime | None = None) -> None:
floors = [parse_dt(license_state.get("time_high_water")), latest_activity,
parse_dt(payload["issued_at"]) if payload else None]
floor = max((f for f in floors if f), default=None)
result = evaluate(payload, now, floor, workday_open, parse_dt(license_state.get("legacy_ok_at")))
result = evaluate(payload, now, floor, workday_open)
if result["license_problem"] != "clock":
license_state["time_high_water"] = max(floor or now, now).isoformat()
@@ -106,11 +118,17 @@ def apply_license(now: datetime | None = None) -> None:
license_state["lock_pending"] = False
license_state["locked"] = False
ent = entitlements.compute(payload if result["license_problem"] != "clock" else None,
result["licensed"], bool(license_state.get("locked")), now, workday_open,
result["license_problem"])
last_sync = parse_dt(license_state.get("last_sync"))
license_state.update({**result, "offline_days": (now - last_sync).days if last_sync else None})
license_state.update({**result, "license_mode": "enforced", "entitlement_mode": ent.mode,
"offline_days": (now - last_sync).days if last_sync else None})
_persist_state()
entitlements.set_current(ent)
if result["license_problem"]:
logger.warning("License problem: %s (licensed=%s)", result["license_problem"], result["licensed"])
logger.warning("License problem: %s (licensed=%s, entitlements=%s)",
result["license_problem"], result["licensed"], ent.mode)
def _get_local_ip() -> str | None:
@@ -148,22 +166,12 @@ async def _sync_once():
data = resp.json()
token = data.get("license_token")
if token:
if verify_token(token, settings.SITE_ID):
license_state["license_token"] = token
else:
logger.error("Cloud sent a license token that does not verify - keeping the previous one")
if token and verify_token(token, settings.SITE_ID):
license_state["license_token"] = token
elif token:
logger.error("Cloud sent a license token that does not verify (not v2?) - keeping the previous one")
else:
# Cloud without license signing (transition): trust this answer for 72h,
# keep the old immediate lock handling
if data.get("licensed", True):
license_state["legacy_ok_at"] = utcnow().isoformat()
license_state["expires_at"] = data.get("expires_at")
if data.get("locked"):
license_state["lock_pending"] = True
else:
license_state["lock_pending"] = False
license_state["locked"] = False
logger.error("Cloud sent no license token - keeping the previous one")
license_state.update({
"latest_version": data.get("latest_version"),
@@ -400,9 +408,14 @@ async def _pull_pending_orders():
logger.warning("Order pull failed: %s", e)
async def _sync_loop():
def load_license_at_startup() -> None:
"""Decide from the stored license before anything else runs (main.py lifespan,
before the worker supervisor starts), so no module runs a moment longer than allowed."""
_load_persisted_state()
apply_license() # decide from the stored license before the first network attempt
apply_license()
async def _sync_loop():
while True:
await _sync_once()
await asyncio.sleep(SYNC_INTERVAL_SECONDS)
+10 -9
View File
@@ -21,10 +21,12 @@ Rules (evaluate()):
expired: 5-day grace → licensed, warnings in the manager
grace over / site deactivated → unlicensed, but never mid-service:
deferred while a workday is open
no valid token:
old cloud without tokens, heartbeat said licensed < 72h ago → licensed (transition)
otherwise → unlicensed ("unverified")
no valid token → unlicensed ("unverified")
Locks from the cloud (token.locked) keep the existing workday-deferred behaviour.
Platform v2 (D-3, D-21): only `v: 2` tokens are valid, and they must carry a `modules`
map. "Unlicensed" no longer blocks the API; it drops the site to the free tier
(core/modules/entitlements.py), module by module.
"""
import base64
import json
@@ -41,7 +43,6 @@ LICENSE_PUBLIC_KEY = "2oeFHV6hgAlJsx/ZBvG6fqmWYn5tjSW5hURrrPhLoOw="
EXPIRY_GRACE = timedelta(days=5)
CLOCK_TOLERANCE = timedelta(days=1)
LEGACY_UNSIGNED_OK = timedelta(hours=72) # only while the cloud sends no tokens
def _b64url_decode(s: str) -> bytes:
@@ -71,22 +72,22 @@ def verify_token(token: str | None, site_id: str, public_key_b64: str | None = N
payload = json.loads(_b64url_decode(body))
except (InvalidSignature, ValueError, TypeError):
return None
if payload.get("v") != 1 or payload.get("site_id") != site_id:
if payload.get("v") != 2 or payload.get("site_id") != site_id:
return None
if not isinstance(payload.get("modules"), dict):
return None
if not parse_dt(payload.get("expires_at")) or not parse_dt(payload.get("issued_at")):
return None
return payload
def evaluate(payload: dict | None, now: datetime, floor: datetime | None, workday_open: bool,
legacy_ok_at: datetime | None = None) -> dict:
def evaluate(payload: dict | None, now: datetime, floor: datetime | None, workday_open: bool) -> dict:
"""Pure license decision. `floor` = latest time this system has provably seen."""
base = {"license_verified": payload is not None, "license_problem": None, "grace_over": False,
"days_until_expiry": None, "grace_expires_at": None, "grace_days_remaining": None}
if payload is None:
legacy = legacy_ok_at is not None and now - legacy_ok_at <= LEGACY_UNSIGNED_OK
return {**base, "licensed": legacy, "license_problem": None if legacy else "unverified"}
return {**base, "licensed": False, "license_problem": "unverified"}
if floor is not None and now < floor - CLOCK_TOLERANCE:
return {**base, "licensed": False, "license_problem": "clock"}
+33
View File
@@ -0,0 +1,33 @@
"""In-memory license status, shared by cloud_sync (writes), system/business-day routers (read).
Persisted to <data dir>/license_state.json by services/cloud_sync.py. What the site may
USE is decided by core/modules/entitlements.py from the same evaluation; this dict is
the status the manager's license page shows.
Fields:
license_mode "enforced" | "off" (config LICENSE_MODE; "off" only on dev machines)
licensed bool - the global license is valid (expiry/grace/lock deferred to
the end of an open workday). False = the free tier applies.
license_problem None | "unverified" | "expired" | "inactive" | "clock"
entitlement_mode "licensed" | "free" | "dev" (from entitlements.compute)
locked bool - remote lock enforced (applied at workday close)
lock_pending bool - the cloud asked for a lock; waiting for the workday to close
expires_at, days_until_expiry, grace_expires_at, grace_days_remaining, grace_over
license_token the signed token as received (verified on every evaluation)
last_sync, sync_failed, offline_days, time_high_water, latest_version,
waiter_domain, site_numeric_id
"""
license_state: dict = {
"license_mode": "enforced",
"licensed": False,
"license_problem": "unverified",
"entitlement_mode": "free",
"locked": False,
"lock_pending": False,
"expires_at": None,
"days_until_expiry": None,
"grace_expires_at": None,
"last_sync": None,
"sync_failed": False,
"latest_version": None,
}