Files
pricing_review/CostReview/app/server/license_client/client.py
2026-10-11 10:52:01 +08:00

473 lines
23 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""LicenseClient:激活 + 心跳租约 + 本地 can_run 状态机。
协议硬性口径(protocol.md / prompt.md):
- 激活、心跳都必须带 Idempotency-Key;同一次操作的网络重试复用同一键与同一
请求体(心跳复用原 client_time,不得改时间续用原键);新业务操作才换新键。
→ 在途操作键先落盘再发请求,进程重启也能复用。
- 403/409 等确定性拒绝:停止自动重试,转入人工处理(needs_attention)。
- 429:至少等 Retry-After;超时/连接错误/5xx:有界退避,键与请求体不变。
- 仅 active 且授权到期、租约到期都严格晚于 now 才允许业务;租约结束不得晚于
授权结束、不得晚于 server_time + 14 天;本机与服务端时差 ≤ 5 分钟;
本地/服务端两个时间高水位只进不退,落盘原子更新,失败即 fail closed。
- secret 不进 URL、日志、异常文本。网络失败不得延长已接受的租约(can_run
纯本地判定,心跳失败只会让租约自然到期)。
httpx 为可选依赖:只在真正发请求时导入;无网络库时 can_run/状态读取照常工作。
"""
import random
import threading
import time
import uuid as uuid_mod
from datetime import timedelta
try:
from .verify import (VerifyError, verify_certificate, verify_lease,
parse_rfc3339, rfc3339)
from .store import StorageError
except ImportError as _e:
# 只对"相对导入不可用"退裸导入;包内真实依赖缺失(如 cryptography)必须原样抛出,
# 否则真实病因会被掩盖成 "No module named 'verify'" 指错排查方向(2026-10-11 实证踩坑)
if "attempted relative import" not in str(_e):
raise
from verify import (VerifyError, verify_certificate, verify_lease,
parse_rfc3339, rfc3339)
from store import StorageError
DEFAULT_API_BASE = "https://license.yihuiyong.cn"
MIN_HEARTBEAT_SECONDS = 60 # 协议:成功 active 心跳最短间隔 60 秒
MAX_LEASE_DAYS = 14 # 协议:租约最长 14 天
MAX_CLOCK_SKEW = timedelta(minutes=5)
NEED_ATTENTION = ("HTTP_400", "HTTP_401", "HTTP_403", "HTTP_409")
class TransientError(Exception):
"""暂时性网络失败(重试额度用尽)。在途操作键保留,稍后可继续。"""
class LeaseInvalid(VerifyError):
"""租约通过验签但范围非法(租约窗/14 天上限)。"""
class LicenseClient:
def __init__(self, api_base, state_store, secret_store, keyring,
now_fn=None, sleep_fn=time.sleep, transport=None,
max_attempts=4, timeout=15,
expected_product_id=None, cache_ttl=10.0, mono_fn=None):
self.api_base = (api_base or DEFAULT_API_BASE).rstrip("/")
self.state_store = state_store
self.secret_store = secret_store
self.keyring = keyring or {}
self.expected_product_id = expected_product_id # None = 不校验产品线
self.now_fn = now_fn or (lambda: __import__("datetime").datetime.now(
__import__("datetime").timezone.utc))
self.mono_fn = mono_fn or time.monotonic
self.cache_ttl = cache_ttl # can_run 结果缓存(0=关)
self.sleep_fn = sleep_fn
self.max_attempts = max(1, max_attempts)
self.timeout = timeout
self._send_fn = transport or self._httpx_send
self._http = None
self._op_lock = threading.RLock() # 状态读改写串行(心跳线程 × 请求线程)
self._hb_lock = threading.Lock() # 心跳整体串行(循环/自愈/手动 refresh 并发)
self._cr_cache = None # (ok, reason, 过期时刻)——门禁每请求一调,省验签+写盘
# ------------------------------------------------------------ 凭据
def has_credentials(self):
try:
st = self.state_store.load()
return bool(st.get("instance_id") and st.get("license_key")
and self.secret_store.get())
except StorageError:
return False
def configure(self, instance_id, license_key, secret):
"""写入交付凭据:secret → 受保护密钥库;其余 → 状态文件。先密钥库后状态。"""
instance_id = (instance_id or "").strip()
license_key = (license_key or "").strip()
secret = (secret or "").strip()
if not (instance_id and license_key and secret):
raise VerifyError("instance_id / license_key / secret 都必填")
self.secret_store.set(secret)
def mut(st):
st["instance_id"] = instance_id
st["license_key"] = license_key
st.setdefault("status", "unactivated")
st["last_error"] = ""
with self._op_lock:
self.state_store.update(mut)
def _creds(self):
st = self.state_store.load()
iid = st.get("instance_id")
lk = st.get("license_key")
sec = self.secret_store.get() if iid else None
if not (iid and lk and sec):
raise VerifyError("缺少实例凭据(instance_id / license_key / secret)")
return st, iid, lk, sec
# ------------------------------------------------------------ 激活
def activate(self):
"""首次激活。返回 {"ok": bool, ...};网络暂时失败时幂等键已保留,重试复用。"""
st, iid, lk, sec = self._creds()
with self._op_lock:
st = self.state_store.load()
op = st.get("activation_op")
if not op:
op = {"key": str(uuid_mod.uuid4())}
self.state_store.update(lambda s: s.update({"activation_op": op}))
body = {"license_key": lk, "secret": sec}
try:
status, headers, data = self._send_with_retry(
"/api/v1/activation/instances/%s" % iid, body, op["key"])
except TransientError as e:
return {"ok": False, "code": "TRANSIENT",
"message": "网络暂时不可用(激活幂等键已保留,重试会复用同一键):%s" % e}
if status != 200:
self._clear_op("activation_op")
code, msg = _err_body(data)
human = {400: "激活参数被拒绝(%s)" % (msg or code),
401: "license_key 或 secret 不正确,请核对交付凭据",
403: "实例不允许激活(%s)" % (msg or code),
409: "实例状态冲突,不能重复激活(%s),请核对实例状态或联系管理员"
% (msg or code)}.get(status, "激活被拒绝(HTTP %s %s)" % (status, msg or code))
self._set_last_error(human)
return {"ok": False, "code": code or ("HTTP_%d" % status), "message": human}
cert = (data.get("data") or {}).get("certificate")
try:
payload = verify_certificate(cert, iid, self.keyring)
except VerifyError as e:
self._clear_op("activation_op")
human = "激活证书验签失败:%s(请核对 pinned_keys.json 是否为部署环境交付的生产公钥)" % e
self._set_last_error(human)
return {"ok": False, "code": "VERIFY_FAILED", "message": human}
if self.expected_product_id is not None and \
payload.get("product_id") != self.expected_product_id:
self._clear_op("activation_op")
human = ("证书产品线不符(证书 product_id=%s,本软件要求 %s)——"
"多半是凭据发错了产品,请核对交付" % (payload.get("product_id"),
self.expected_product_id))
self._set_last_error(human)
return {"ok": False, "code": "PRODUCT_MISMATCH", "message": human}
def mut(s):
s["certificate"] = payload
s["certificate_envelope"] = cert
s["status"] = "activated"
s.pop("activation_op", None)
s["last_error"] = ""
with self._op_lock:
self.state_store.update(mut)
self._cr_cache = None # 新证书 → 门禁缓存作废
return {"ok": True}
# ------------------------------------------------------------ 心跳
def heartbeat(self):
"""刷新运行租约。成功返回 {"ok":True,"state":...,"next":秒}。
整体串行:心跳循环 / 门禁自愈 / 手动刷新 三方并发时排队,杜绝两个在途操作
互相覆盖 heartbeat_op(幂等键错乱)。"""
with self._hb_lock:
return self._heartbeat_locked()
def _heartbeat_locked(self):
st, iid, _lk, sec = self._creds()
with self._op_lock:
st = self.state_store.load()
op = st.get("heartbeat_op")
if not op:
op = {"key": str(uuid_mod.uuid4()), "client_time": rfc3339(self.now_fn())}
self.state_store.update(lambda s: s.update({"heartbeat_op": op}))
body = {"secret": sec, "client_time": op["client_time"]}
try:
status, headers, data = self._send_with_retry(
"/api/v1/instances/%s/heartbeat" % iid, body, op["key"])
except TransientError as e:
return {"ok": False, "code": "TRANSIENT",
"message": "网络暂时不可用(键与 client_time 已保留,重试复用):%s" % e}
if status != 200:
self._clear_op("heartbeat_op")
code, msg = _err_body(data)
human = {400: "心跳参数被拒绝(%s)" % (msg or code),
401: "实例凭据已被拒(secret 不正确或已重置),需重新交付凭据",
403: "实例被禁止心跳(%s)" % (msg or code),
409: "实例状态冲突(%s),需人工处理" % (msg or code)}.get(
status, "心跳被拒绝(HTTP %s %s)" % (status, msg or code))
if status in (400, 401, 403, 409):
self.state_store.update(lambda s: s.update(
{"status": "needs_attention", "last_error": human}))
return {"ok": False, "code": code or ("HTTP_%d" % status), "message": human}
env = data.get("data")
try:
payload = verify_lease(env, iid, self.keyring)
except VerifyError as e:
self._clear_op("heartbeat_op")
human = "租约验签失败:%s(请核对 pinned_keys.json)" % e
self._set_last_error(human)
return {"ok": False, "code": "VERIFY_FAILED", "message": human}
try:
nxt = self._accept_lease(payload, env)
except VerifyError as e:
self._clear_op("heartbeat_op")
self._set_last_error("租约范围非法:%s" % e)
return {"ok": False, "code": "LEASE_INVALID",
"message": "租约范围非法:%s" % e}
return {"ok": True, "state": payload["state"], "next": nxt}
def _accept_lease(self, payload, envelope):
"""验签通过后先做范围检查,再原子落盘(enabled 随租约状态翻转)。"""
server = parse_rfc3339(payload["server_time"])
ent = parse_rfc3339(payload["entitlement_expires_at"])
le = parse_rfc3339(payload["lease_expires_at"])
if le > ent:
raise LeaseInvalid("租约结束晚于授权结束")
if le > server + timedelta(days=MAX_LEASE_DAYS):
raise LeaseInvalid("租约超过服务端签发时间 + %d 天" % MAX_LEASE_DAYS)
def mut(s):
# 服务端时间高水位:只进不退。回退 = 可疑(重放/旧信封),整体拒绝
hw = s.get("server_high_water")
if hw and server < parse_rfc3339(hw):
raise LeaseInvalid("服务端时间早于已记录的高水位")
s["server_high_water"] = payload["server_time"] if (
not hw or server > parse_rfc3339(hw)) else hw
s["lease"] = payload
s["lease_envelope"] = envelope
s["enabled"] = (payload["state"] == "active")
s["status"] = "activated"
s.pop("heartbeat_op", None)
s["last_heartbeat_at"] = rfc3339(self.now_fn())
s["next_heartbeat_seconds"] = max(MIN_HEARTBEAT_SECONDS,
envelope.get("next_heartbeat_seconds",
MIN_HEARTBEAT_SECONDS))
s["last_error"] = ""
with self._op_lock:
self.state_store.update(mut)
self._cr_cache = None # 新租约 → 门禁缓存作废
return max(MIN_HEARTBEAT_SECONDS, envelope.get("next_heartbeat_seconds",
MIN_HEARTBEAT_SECONDS))
# ------------------------------------------------------------ can_run
def can_run(self, now=None):
"""(True, None) | (False, 原因)。纯本地判定,不发网络请求。
结果缓存 cache_ttl 秒:门禁每个请求都调这里,省掉每次的 ECDSA 验签 +
高水位落盘(约 10 秒粒度的回拨检测延迟,换来磁盘只在一分钟一次量级写)。"""
now = now or self.now_fn()
c = self._cr_cache
if c and self.mono_fn() < c[2]:
return c[0], c[1]
ok, reason = self._can_run_uncached(now)
if self.cache_ttl > 0:
self._cr_cache = (ok, reason, self.mono_fn() + self.cache_ttl)
return ok, reason
def _can_run_uncached(self, now):
now = now or self.now_fn()
st = self.state_store.load()
env = st.get("lease_envelope")
if not env:
if st.get("certificate_envelope"):
return False, "已激活,正在获取运行租约(首次心跳)…"
return False, "尚未激活:请在授权页面完成激活"
try:
payload = verify_lease(env, st.get("instance_id"), self.keyring)
except VerifyError as e:
return False, "本地租约校验失败:%s" % e
try:
lhw = st.get("local_high_water")
if lhw and now < parse_rfc3339(lhw):
return False, ("检测到本机时钟回拨(已记录 %s),为防止绕过授权已锁定,"
"请恢复系统时间后重启软件" % lhw)
shw = st.get("server_high_water")
if shw and parse_rfc3339(payload["server_time"]) < parse_rfc3339(shw):
return False, "服务端时间早于已记录的高水位"
skew = abs(now - parse_rfc3339(payload["server_time"]))
if skew > MAX_CLOCK_SKEW:
return False, "本机时间与服务端时间相差超过 5 分钟,请校准系统时间"
if payload["state"] != "active":
return False, "授权已被服务端置为「%s」,请联系软件提供方" % payload["state"]
ent = parse_rfc3339(payload["entitlement_expires_at"])
le = parse_rfc3339(payload["lease_expires_at"])
if ent <= now:
return False, "授权已于 %s 过期" % payload["entitlement_expires_at"]
if le <= now:
return False, "运行租约已过期(离线过久),请联网后重启软件自动续租"
if le > ent or le > parse_rfc3339(payload["server_time"]) + timedelta(days=MAX_LEASE_DAYS):
return False, "租约时间窗非法"
except VerifyError as e:
return False, str(e)
try:
def mut(s):
# 高水位节流写:只在首记或前进超过 55 秒时落盘(配合 can_run 缓存,
# 磁盘写入降到分钟级;高水位只进不退的语义不变)
w = s.get("local_high_water")
if not w or now > parse_rfc3339(w) + timedelta(seconds=55):
s["local_high_water"] = rfc3339(now)
with self._op_lock:
self.state_store.update(mut)
except StorageError as e:
return False, "授权状态保存失败(fail closed):%s" % e
return True, None
def can_run_safe(self):
"""门禁专用:任何内部异常都折算成 (False, 原因),绝不让门禁 fail open。"""
try:
return self.can_run()
except Exception as e: # 存储损坏等一切意外
return False, "授权子系统异常(fail closed):%s" % e
# ------------------------------------------------------------ 状态视图
def status(self, enforce=True, heartbeat_running=False):
out = {"enforce": enforce, "api_base": self.api_base,
"keyring_ready": bool(self.keyring),
"heartbeat_running": heartbeat_running}
try:
st = self.state_store.load()
except StorageError as e:
out.update({"configured": False, "activated": False, "enabled": False,
"can_run": False, "reason": "授权状态不可读(fail closed):%s" % e,
"status": "error"})
return out
lease = st.get("lease") or {}
cert = st.get("certificate") or {}
ok, reason = self.can_run_safe()
days_left = None
try:
if cert.get("expires_at"):
days_left = (parse_rfc3339(cert["expires_at"]) - self.now_fn()).days
except VerifyError:
pass
out.update({
"configured": bool(st.get("instance_id") and st.get("license_key")),
"instance_id": st.get("instance_id"),
"status": st.get("status") or "unactivated",
"activated": bool(st.get("certificate_envelope")),
"license_id": cert.get("license_id"),
"product_id": cert.get("product_id"),
"expected_product_id": self.expected_product_id,
"days_left": days_left,
"starts_at": cert.get("starts_at"),
"entitlement_expires_at": cert.get("expires_at") or lease.get("entitlement_expires_at"),
"lease_state": lease.get("state"),
"lease_expires_at": lease.get("lease_expires_at"),
"server_time": lease.get("server_time"),
"last_heartbeat_at": st.get("last_heartbeat_at"),
"next_heartbeat_seconds": st.get("next_heartbeat_seconds"),
"last_error": st.get("last_error") or "",
"can_run": ok,
"reason": reason or "授权有效,运行中",
})
return out
# ------------------------------------------------------------ 心跳循环
def run_forever(self, stop_event, log_fn=None):
"""心跳线程:开机立即跳一次,随后按 next_heartbeat_seconds + 正向抖动调度。
403/409/400/401 → 停止自动重试(长休眠直到重启/重新激活);暂时性失败退避。"""
log = log_fn or (lambda *a: None)
backoff = 0
first = True
while not stop_event.wait(0 if first else self._next_wait(backoff, True)):
first = False
try:
r = self.heartbeat()
except (StorageError, VerifyError) as e:
log("license 心跳异常:%s" % e)
r = {"ok": False, "code": "TRANSIENT", "message": str(e)}
if r.get("ok"):
if backoff:
log("license 心跳恢复(state=%s)" % r.get("state"))
backoff = 0
continue
if r.get("code") in NEED_ATTENTION or r.get("code") == "VERIFY_FAILED" \
or r.get("code") == "LEASE_INVALID":
log("license 心跳进入人工处理状态(%s),停止自动重试:%s"
% (r.get("code"), r.get("message")))
while not stop_event.wait(3600):
pass # 停在人工处理状态:不再自动心跳,等重启/重新激活
break
else:
backoff = min(backoff + 1, 6)
log("license 心跳暂时失败(第 %d 次):%s" % (backoff, r.get("message")))
return
def _next_wait(self, backoff, is_loop):
st = self.state_store.load()
base = max(MIN_HEARTBEAT_SECONDS, st.get("next_heartbeat_seconds") or MIN_HEARTBEAT_SECONDS)
if backoff:
base = min(60 * (2 ** backoff), 300)
return base * (1.0 + random.uniform(0, 0.1)) # 少量正向抖动
# ------------------------------------------------------------ HTTP
def _httpx_send(self, method, url, body, headers):
try:
import httpx
except ImportError:
raise TransientError("缺少 httpx 库(pip install httpx),无法联网刷新授权")
if self._http is None:
self._http = httpx.Client(base_url=self.api_base, timeout=self.timeout)
try:
r = self._http.post(url, json=body, headers=headers)
except Exception as e: # 超时/连接错误/重置等一律暂时性
raise TransientError("%s: %s" % (type(e).__name__, e))
return r.status_code, dict(r.headers), _safe_json(r)
def _send_with_retry(self, path, body, idem_key):
"""同一操作:同一请求体 + 同一幂等键,有界重试(429/5xx/网络错误)。
⚠ 请求头不能用返回值覆盖(曾因此重试丢 Idempotency-Key——协议红线)。"""
url = self.api_base + path
req_headers = {"Content-Type": "application/json", "Idempotency-Key": idem_key}
delay = 1.0
last = None
for _ in range(self.max_attempts):
try:
status, resp_headers, data = self._send_fn("POST", url, body, req_headers)
except (TransientError, OSError) as e:
# OSError:ConnectionError/TimeoutError 等原生网络异常(测试/极简传输层)
last = e
self.sleep_fn(delay)
delay = min(delay * 2, 30)
continue
if status < 500 and status != 429:
return status, resp_headers, data
wait = delay
if status == 429:
ra = resp_headers.get("Retry-After") or resp_headers.get("retry-after")
try:
wait = max(float(ra), delay) if ra else delay
except (TypeError, ValueError):
wait = delay
last = TransientError("HTTP %s" % status)
self.sleep_fn(min(wait, 120))
delay = min(delay * 2, 30)
raise TransientError(str(last) if last else "重试额度用尽")
# ------------------------------------------------------------ 小工具
def _clear_op(self, name):
with self._op_lock:
self.state_store.update(lambda s: s.pop(name, None))
def _set_last_error(self, msg):
with self._op_lock:
self.state_store.update(lambda s: s.update({"last_error": msg}))
def _err_body(data):
"""错误响应 → (code, message)。不回显请求内容。"""
err = (data or {}).get("error") if isinstance(data, dict) else None
if isinstance(err, dict):
return str(err.get("code") or ""), str(err.get("message") or "")
return "", ""
def _safe_json(r):
try:
return r.json()
except Exception:
return {}