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