feat(license): 接入授权平台客户端门禁(license-v2/lease-v2)并烧入交付版信任根

This commit is contained in:
lianjianwei2024
2026-10-10 18:05:04 +08:00
parent 6de1370ce5
commit d3a805ede0
25 changed files with 3123 additions and 25 deletions

View File

@@ -39,6 +39,7 @@ import price_html as price # 信息价 / 市场价 HTML 解析器
import price_xlsx # 信息价 / 市场价 Excel 解析器(2026-10-06 新增,与上面共用入库口径)
import session_job as sess # 会话库(工作台)
import match # 比对引擎(M4)
import license_client.gate as license_gate # 授权门禁(license-v2/lease-v2,2026-10-10)
# ⚠️ 2026-10-06 删除 `from search_demo import build`:search_demo 的 FTS/x_period 索引只为它
# 自己的演示查询服务,生产比对引擎 match.py 全程用 x_hash_exact/x_hash_semi + LIKE,
# 从不读 bills_fts/lmes_fts;每次导入重建 FTS(约 2 秒)纯属白费。索引由 schema.sql 在
@@ -3541,11 +3542,26 @@ class Handler(SimpleHTTPRequestHandler):
self.end_headers()
self.wfile.write(raw)
def _gate_send(self, r):
"""发送门禁拦截响应:授权页(自包含 HTML)或 JSON 错误。"""
if r.get("kind") == "html":
body = r["text"].encode("utf-8")
self.send_response(r.get("code", 200))
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
return self._json(r["obj"], r.get("code", 200))
def do_GET(self):
if not self._allowed_origin():
return self._json({"error": "forbidden"}, 403)
u = urllib.parse.urlparse(self.path)
p, q = u.path, urllib.parse.parse_qs(u.query)
_g = license_gate.intercept("GET", p) # 授权门禁:未激活/过期只放授权页与 /api/license/*
if _g is not None:
return self._gate_send(_g)
one = {k: v[0] for k, v in q.items()}
try:
if p == "/api/sessions": # 最近审核(会话台账,按源文件去重)
@@ -3702,6 +3718,9 @@ class Handler(SimpleHTTPRequestHandler):
body = {}
if not isinstance(body, dict): # JSON 是数组/字符串/数字时,下面 body.get 会 500,统一按空请求处理
body = {}
_g = license_gate.intercept("POST", u.path, body) # 授权门禁(/api/license/activate 在此放行)
if _g is not None:
return self._gate_send(_g)
try:
if u.path == "/api/admin/import":
with WRITE_LOCK: # 写库串行
@@ -3895,6 +3914,7 @@ def run():
migrate_match_keys() # 决策 27:清单哈希改编码前9位 + 字集键回填(幂等,探针跳过)
ensure_dict_schema() # 数据源字典(首次用库里已有值播种)
backfill_session_batch() # 老会话补 x_batch_id → 工作台才能看到该项目的询价附件
license_gate.init(DATA_DIR) # 授权门禁:读配置/状态,配了凭据则起心跳线程(内部吞异常)
cleanup_sessions() # 启动时清掉超过保留天数的会话(只碰 session.db)
try: # 启动自检:有批次是用旧解析器导入的 → 控制台先报一句
s = stale_batches()

View File

@@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
"""授权平台客户端(license-v2 / lease-v2)。
api_server 只 import license_client.gate 这一个入口:
import license_client.gate as license_gate
license_gate.init(DATA_DIR) # run() 启动时
license_gate.intercept(method, path, body) # do_GET / do_POST 顶部
业务侧判定用 client.can_run_safe()(门禁内部已用,业务代码一般不必再调)。
"""
from .client import LicenseClient, DEFAULT_API_BASE # noqa: F401

View File

@@ -0,0 +1,468 @@
# -*- 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: # 允许把本目录直接加进 sys.path 运行
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 {}

View File

@@ -0,0 +1,347 @@
# -*- coding: utf-8 -*-
"""业务门禁:api_server 唯一挂接点。
run() 时调 init(data_dir):读 data/license/config.json + 随软件分发的
pinned_keys.json + 已存授权状态;配置了凭据且信任根就绪则起心跳线程。
任何初始化异常都不打断服务启动,但门禁 fail closed:
- /api/license/* 永远放行(激活入口本身不能被锁死);
- 其余请求:enforce 且 can_run()=False → GET 一律回授权页(自包含 HTML,
内嵌激活表单),POST/业务 API 回 403 {"error":{"code":"LICENSE_REQUIRED"}}。
本地开发豁免:data/license/config.json 写 "enforce": false(交付/发布环境
不带该文件或 enforce=true,代码默认 true)。
"""
import json
import os
import threading
import time
from .client import LicenseClient, DEFAULT_API_BASE
from .store import JsonFileStore, DpapiSecretStore, StorageError
from .verify import VerifyError, load_keyring_file, build_keyring
try: # 构建时生成(仅交付版有)
from . import license_build_config as BUILD
except ImportError:
BUILD = None
_lock = threading.Lock()
_client = None
_cfg = {"enforce": True, "api_base": DEFAULT_API_BASE, "selfheal_seconds": 300}
_hb_thread = None
_hb_stop = None
_last_selfheal = 0.0 # monotonic:门禁自愈触发节流
# ---------------------------------------------------------------- 初始化
def _load_cfg(lic_dir):
cfg = {"enforce": True,
"api_base": os.environ.get("LICENSE_API_BASE_URL") or DEFAULT_API_BASE}
p = os.path.join(lic_dir, "config.json")
try:
if os.path.exists(p):
with open(p, encoding="utf-8") as f:
user = json.load(f)
if isinstance(user, dict):
if "api_base" in user and not os.environ.get("LICENSE_API_BASE_URL"):
cfg["api_base"] = str(user["api_base"]).rstrip("/")
cfg["enforce"] = bool(user.get("enforce", True))
if user.get("pinned_keys"):
cfg["pinned_keys"] = user["pinned_keys"]
except Exception as e:
print("⚠ license 配置读取失败(按默认 enforce 处理):%s" % e)
return cfg
def init(data_dir):
"""服务启动时调用一次。永不抛异常(授权子系统坏了也不许拖死服务)。
信任根优先级:交付版(license_build_config.py 存在)→ 只信烧进包里的公钥/
平台地址/强制开关,本地 config.json、环境变量、pinned_keys.json 一律不参与
(P0-1:客户改文件/环境变量无法自建信任根)。开发版(无该文件)→ 走
data/license/config.json + pinned_keys.json 的老路径,便于联调。
"""
global _client, _cfg, _hb_thread, _hb_stop
with _lock:
if _client is not None:
return _client
lic_dir = os.environ.get("LICENSE_DATA_DIR") or os.path.join(data_dir, "license")
try:
os.makedirs(lic_dir, exist_ok=True)
expected_product = None
selfheal = 300
if BUILD is not None:
_cfg = {"enforce": bool(BUILD.ENFORCE),
"api_base": str(BUILD.API_BASE).rstrip("/"),
"selfheal_seconds": getattr(BUILD, "SELFHEAL_SECONDS", 300)}
keyring = build_keyring(BUILD.PINNED_KEYS)
expected_product = getattr(BUILD, "PRODUCT_ID", None)
else:
_cfg = _load_cfg(lic_dir)
_cfg.setdefault("selfheal_seconds", 300)
expected_product = _cfg.get("expected_product_id")
keys_path = _cfg.get("pinned_keys") or os.path.join(
os.path.dirname(os.path.abspath(__file__)), "pinned_keys.json")
keyring = load_keyring_file(keys_path)
if not keyring:
print("⚠ license:可信公钥清单为空(%s)——激活/心跳将无法通过验签" % keys_path)
selfheal = max(5, int(_cfg.get("selfheal_seconds") or 300))
_cfg["selfheal_seconds"] = selfheal
client = LicenseClient(
api_base=_cfg["api_base"],
state_store=JsonFileStore(os.path.join(lic_dir, "state.json")),
secret_store=DpapiSecretStore(os.path.join(lic_dir, "secret.bin")),
keyring=keyring,
expected_product_id=expected_product)
_client = client
if client.has_credentials() and keyring:
_start_heartbeat()
elif client.has_credentials():
print("⚠ license:已配置实例凭据但无可信公钥,心跳未启动(补齐 pinned_keys 后重启)")
except Exception as e:
print("⚠ license 子系统初始化失败(门禁按未授权处理):%s" % e)
return _client
def _client_for_request():
"""请求期取客户端;未初始化(如直连 Handler 单测)时懒初始化失败 → None。"""
return _client
def _start_heartbeat():
global _hb_thread, _hb_stop
if _hb_thread and _hb_thread.is_alive():
return
_hb_stop = threading.Event()
_hb_thread = threading.Thread(target=_client.run_forever, args=(_hb_stop,),
name="license-heartbeat", daemon=True)
_hb_thread.start()
def _restart_heartbeat():
"""心跳循环在 403/409 后按协议停在人工处理状态;用户侧动作(手动刷新/
门禁自愈)成功续上租约时,把循环拉起来恢复自动调度。"""
global _hb_thread, _hb_stop
with _lock:
old = _hb_thread
if _hb_stop:
_hb_stop.set()
if old and old is not threading.current_thread():
old.join(timeout=2)
_hb_thread = None
_start_heartbeat()
def _selfheal_maybe(status):
"""授权不可运行时借 /api/license/status 的轮询做后台自愈:
节流期内至多试一次心跳;成功(含从 403 停摆状态救回)即重启心跳循环。"""
global _last_selfheal
if not _cfg.get("enforce", True) or not status.get("configured"):
return
if status.get("can_run"):
return
now = time.monotonic()
if now - _last_selfheal < _cfg.get("selfheal_seconds", 300):
return
_last_selfheal = now
threading.Thread(target=_selfheal_run, name="license-selfheal",
daemon=True).start()
def _selfheal_run():
try:
r = _client.heartbeat()
except Exception:
return
if r.get("ok"):
_restart_heartbeat()
def heartbeat_running():
return bool(_hb_thread and _hb_thread.is_alive())
# ---------------------------------------------------------------- 请求拦截
def intercept(method, path, body=None):
"""None = 放行;否则返回 {"kind":"json"|"html","code":int,...} 由 Handler 发送。"""
if path.startswith("/api/license/"):
return _license_api(method, path, body)
if not _cfg.get("enforce", True):
return None
c = _client_for_request()
if c is None:
return _blocked("授权子系统未初始化")
ok, reason = c.can_run_safe()
if ok:
return None
if method == "GET" and not path.startswith("/api/"):
# 页面/静态资源 → 授权页;/api/* 一律 403 JSON(前端 fetch 不能收到 HTML)
return {"kind": "html", "code": 200, "text": gate_page(reason)}
return _blocked(reason)
def _blocked(reason):
return {"kind": "json", "code": 403,
"obj": {"error": {"code": "LICENSE_REQUIRED", "message": reason}}}
def status_view():
c = _client_for_request()
if c is None:
return {"enforce": _cfg.get("enforce", True), "configured": False,
"activated": False, "can_run": False,
"reason": "授权子系统未初始化", "api_base": _cfg.get("api_base")}
return c.status(enforce=bool(_cfg.get("enforce", True)),
heartbeat_running=heartbeat_running())
def _license_api(method, path, body):
if method == "GET" and path == "/api/license/status":
out = status_view()
_selfheal_maybe(out) # 授权不可运行 → 借轮询节流自愈(后台线程)
return {"kind": "json", "code": 200, "obj": {"ok": True, "data": out}}
if method == "POST" and path == "/api/license/activate":
b = body if isinstance(body, dict) else {}
iid, lk, sec = (b.get("instance_id") or "").strip(), \
(b.get("license_key") or "").strip(), \
(b.get("secret") or "").strip()
if not (iid and lk and sec):
return {"kind": "json", "code": 400,
"obj": {"error": {"code": "BAD_REQUEST",
"message": "instance_id / license_key / secret 都必填"}}}
c = _client_for_request()
if c is None:
return _blocked("授权子系统未初始化")
try:
c.configure(iid, lk, sec)
r = c.activate()
except (StorageError, VerifyError) as e:
r = {"ok": False, "code": "CONFIG_FAILED", "message": str(e)}
if r.get("ok"):
_restart_heartbeat() # 激活成功:新循环(旧循环可能停在人工处理态)
out = status_view()
out["result"] = r
return {"kind": "json", "code": 200, "obj": {"ok": bool(r.get("ok")), "data": out}}
if method == "POST" and path == "/api/license/refresh":
c = _client_for_request()
if c is None:
return _blocked("授权子系统未初始化")
try:
r = c.heartbeat()
except (StorageError, VerifyError) as e:
r = {"ok": False, "code": "ERROR", "message": str(e)}
if r.get("ok"):
_restart_heartbeat() # 手动续上 → 恢复自动心跳调度
out = status_view()
out["result"] = r
return {"kind": "json", "code": 200, "obj": {"ok": bool(r.get("ok")), "data": out}}
return {"kind": "json", "code": 404,
"obj": {"error": {"code": "NOT_FOUND", "message": "未知授权接口"}}}
# ---------------------------------------------------------------- 授权页
_PAGE = None
def gate_page(reason):
"""未授权时替代正常页面的自包含页面:状态 + 激活表单,激活成功自动进系统。"""
global _PAGE
if _PAGE is None:
_PAGE = ("""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>软件授权</title><style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:"Microsoft YaHei",system-ui,sans-serif;background:#f2f4f8;
min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;color:#1c2733}
.card{background:#fff;border-radius:10px;box-shadow:0 6px 24px rgba(16,35,61,.10);
width:520px;max-width:100%;overflow:hidden}
.hd{background:#1f4e79;color:#fff;padding:18px 28px;font-size:19px;font-weight:600}
.hd small{display:block;font-weight:400;font-size:12px;opacity:.75;margin-top:4px}
.bd{padding:24px 28px 28px}
.st{border:1px solid #e3e8ef;border-radius:8px;padding:12px 16px;margin-bottom:20px;
background:#fafbfd;font-size:13px;line-height:1.9}
.st b{color:#b02a2a}
.st .ok{color:#1c7c44}
.row{margin-bottom:14px}
.row label{display:block;font-size:13px;color:#51606f;margin-bottom:5px}
.row input{width:100%;padding:9px 11px;border:1px solid #c8d2dd;border-radius:6px;
font-size:13px;font-family:inherit}
.row input:focus{outline:none;border-color:#1f4e79;box-shadow:0 0 0 2px rgba(31,78,121,.15)}
.btns{display:flex;gap:10px;margin-top:18px}
button{flex:1;padding:10px 0;border:0;border-radius:6px;font-size:14px;cursor:pointer;
font-family:inherit;background:#1f4e79;color:#fff}
button.ghost{background:#fff;color:#1f4e79;border:1px solid #1f4e79}
button:disabled{opacity:.5;cursor:default}
.msg{margin-top:14px;font-size:13px;line-height:1.7;display:none;
padding:10px 12px;border-radius:6px}
.msg.err{display:block;background:#fdf0f0;color:#b02a2a;border:1px solid #f3c8c8}
.msg.ok{display:block;background:#effaf3;color:#1c7c44;border:1px solid #c4e8d0}
.tip{margin-top:16px;font-size:12px;color:#8a97a5;line-height:1.7}
</style></head><body><div class="card">
<div class="hd">造价审核 · 软件授权<small id="sub">正在连接授权状态…</small></div>
<div class="bd">
<div class="st" id="st">加载中…</div>
<div class="row"><label>实例 ID(instance_id)</label>
<input id="iid" placeholder="形如 11111111-2222-3333-4444-555555555555" spellcheck="false"></div>
<div class="row"><label>授权码(license_key)</label>
<input id="lk" placeholder="交付单上提供的授权码" spellcheck="false"></div>
<div class="row"><label>激活密钥(secret,仅输入一次,本机加密保存)</label>
<input id="sec" type="password" placeholder="交付单上提供的一次性 secret"></div>
<div class="btns"><button id="go" onclick="doAct()">激活</button>
<button class="ghost" onclick="load()">刷新状态</button></div>
<div class="msg" id="msg"></div>
<div class="tip">本页面由本机服务(127.0.0.1)提供;激活凭据只保存在本机,不会上传到别处。
激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。</div>
</div></div>
<script>
var TIMER=null;
function esc(s){return String(s==null?"":s).replace(/[&<>"]/g,function(c){
return {"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c];});}
function fmtSt(d){
var h="";
h+="状态:"+(d.can_run?'<span class="ok">已授权,运行中</span>':"<b>"+esc(d.reason||"不可用")+"</b>")+"<br>";
if(d.instance_id)h+="实例:"+esc(d.instance_id)+"<br>";
if(d.entitlement_expires_at)h+="授权到期:"+esc(d.entitlement_expires_at)+"<br>";
if(d.lease_expires_at)h+="租约到期:"+esc(d.lease_expires_at)+"<br>";
if(d.last_heartbeat_at)h+="最后心跳:"+esc(d.last_heartbeat_at)+"<br>";
if(!d.keyring_ready)h+="<b>⚠ 信任根未配置(pinned_keys.json 为空),激活将无法通过验签——请联系软件提供方。</b><br>";
if(d.last_error)h+="最近错误:"+esc(d.last_error);
return h;}
function load(){
fetch("/api/license/status").then(function(r){return r.json()}).then(function(j){
var d=j.data||{};
document.getElementById("st").innerHTML=fmtSt(d);
document.getElementById("sub").textContent="授权服务器:"+(d.api_base||"")+
(d.enforce?"":"(当前为开发模式,未强制校验)");
if(d.can_run&&d.enforce){location.reload();return;}
if(TIMER)clearTimeout(TIMER);
TIMER=setTimeout(load,15000);
}).catch(function(){
document.getElementById("st").innerHTML="<b>无法读取授权状态(本机服务异常?)</b>";
});}
function doAct(){
var b={instance_id:document.getElementById("iid").value.trim(),
license_key:document.getElementById("lk").value.trim(),
secret:document.getElementById("sec").value};
var m=document.getElementById("msg");
if(!b.instance_id||!b.license_key||!b.secret){
m.className="msg err";m.textContent="三项都要填写(见交付单)。";return;}
var btn=document.getElementById("go");btn.disabled=true;
m.className="msg";m.style.display="none";
fetch("/api/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},
body:JSON.stringify(b)}).then(function(r){return r.json()}).then(function(j){
btn.disabled=false;
var d=j.data||{},res=d.result||{};
if(res.ok){document.getElementById("sec").value="";
m.className="msg ok";m.textContent="激活成功,正在进入系统…";setTimeout(load,600);return;}
m.className="msg err";m.textContent=res.message||"激活失败,请核对凭据。";
document.getElementById("st").innerHTML=fmtSt(d);
}).catch(function(){btn.disabled=false;
m.className="msg err";m.textContent="网络错误:无法连接本机服务。";});}
load();
</script></body></html>""")
return _PAGE

View File

@@ -0,0 +1,10 @@
{
"_说明": [
"可信公钥清单(信任根):只随软件/受控部署渠道固定分发,绝不在线发现。",
"上线前由运维(部署环境)交付生产 key_id + 公钥 PEM(SubjectPublicKeyInfo),",
"按 {\"key_id\":..., \"public_key_pem\":\"-----BEGIN PUBLIC KEY-----...\", \"revoked\":false} 追加进 pinned_keys。",
"接入包 test-vectors.json 里的 integration-test-only 测试公钥绝不能加进生产配置。",
"清空 = fail closed:激活/心跳验签一律失败。"
],
"pinned_keys": []
}

View File

@@ -0,0 +1,210 @@
# -*- coding: utf-8 -*-
"""授权状态受保护存储。
- LicenseStateStore:激活证书 / 运行租约 / enabled / 本地与服务端时间高水位的
原子落盘(tmp + fsync + os.replace)。协议要求"先原子保存再启用业务",
保存失败必须让调用方走 fail closed。
- SecretStore 接口 + Windows DPAPI 实现:实例 secret 只进系统级保护存储
(DPAPI CurrentUser),绝不写入源码/日志/普通明文文件;非 Windows 退化为
仅当前用户可读的明文文件(开发环境兜底,交付环境只支持 Windows)。
协议自带声明:一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,
本模块不宣称硬件绑定或防克隆。
"""
import base64
import json
import os
import threading
class StorageError(Exception):
"""状态读写失败(磁盘满/权限等)。调用方必须 fail closed。"""
class LicenseStateStore:
"""接口:load() → dict;save(state) 原子写。"""
def load(self):
raise NotImplementedError
def save(self, state):
raise NotImplementedError
class JsonFileStore(LicenseStateStore):
"""JSON 文件原子存储。进程内加锁;跨进程不做(本应用本就不支持双实例共库)。"""
def __init__(self, path):
self.path = path
self._lock = threading.Lock()
os.makedirs(os.path.dirname(path), exist_ok=True)
def load(self):
with self._lock:
return self._load_unlocked()
def _load_unlocked(self):
try:
with open(self.path, encoding="utf-8") as f:
st = json.load(f)
except FileNotFoundError:
return {}
except Exception as e:
raise StorageError("授权状态读取失败:%s" % e)
return st if isinstance(st, dict) else {}
def save(self, state):
with self._lock:
tmp = self.path + ".tmp"
try:
with open(tmp, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=1)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, self.path)
except Exception as e:
try:
os.unlink(tmp)
except OSError:
pass
raise StorageError("授权状态保存失败:%s" % e)
def update(self, fn):
"""原子读改写:fn(state) → state'(原地改传入 dict 即可),返回新状态。"""
with self._lock:
st = self._load_unlocked()
fn(st)
self._save_unlocked(st)
return st
def _save_unlocked(self, state):
tmp = self.path + ".tmp"
try:
with open(tmp, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=1)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, self.path)
except Exception as e:
try:
os.unlink(tmp)
except OSError:
pass
raise StorageError("授权状态保存失败:%s" % e)
# ---------------------------------------------------------------- secret
class SecretStore:
"""接口:get() → str|None;set(secret);clear()。"""
def get(self):
raise NotImplementedError
def set(self, secret):
raise NotImplementedError
def clear(self):
raise NotImplementedError
if os.name == "nt":
import ctypes
from ctypes import wintypes
class _DATA_BLOB(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD),
("pbData", ctypes.POINTER(ctypes.c_char))]
_CRYPTPROTECT_UI_FORBIDDEN = 0x1
def _dpapi(data, protect):
crypt32 = ctypes.windll.crypt32
k32 = ctypes.windll.kernel32
buf = ctypes.create_string_buffer(data, len(data))
inb = _DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
out = _DATA_BLOB()
if protect:
ok = crypt32.CryptProtectData(
ctypes.byref(inb), "pricing-review-license", None, None, None,
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
else:
ok = crypt32.CryptUnprotectData(
ctypes.byref(inb), None, None, None, None,
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
if not ok:
raise StorageError("DPAPI %s 失败(错误码 %s)"
% ("加密" if protect else "解密", ctypes.GetLastError()))
try:
return ctypes.string_at(out.pbData, out.cbData)
finally:
k32.LocalFree(out.pbData)
class DpapiSecretStore(SecretStore):
"""Windows DPAPI(CurrentUser)加密落盘:换用户/拷走文件都解不开,
源码里没有也不需要任何硬编码密钥。"""
def __init__(self, path):
self.path = path
os.makedirs(os.path.dirname(path), exist_ok=True)
def get(self):
try:
with open(self.path, "rb") as f:
raw = f.read()
except FileNotFoundError:
return None
except OSError as e:
raise StorageError("secret 读取失败:%s" % e)
if not raw:
return None
try:
return _dpapi(base64.b64decode(raw), False).decode("utf-8")
except Exception as e:
raise StorageError("secret 解密失败(可能换了系统用户):%s" % e)
def set(self, secret):
enc = _dpapi(secret.encode("utf-8"), True)
tmp = self.path + ".tmp"
with open(tmp, "wb") as f:
f.write(base64.b64encode(enc))
f.flush()
os.fsync(f.fileno())
os.replace(tmp, self.path)
def clear(self):
try:
os.unlink(self.path)
except FileNotFoundError:
pass
else: # 非 Windows 兜底(开发环境)
class DpapiSecretStore(SecretStore):
"""占位实现:明文落盘(权限收窄到当前用户)。交付环境不支持。"""
def __init__(self, path):
self.path = path
os.makedirs(os.path.dirname(path), exist_ok=True)
def get(self):
try:
with open(self.path, encoding="utf-8") as f:
v = f.read().strip()
except FileNotFoundError:
return None
return base64.b64decode(v).decode("utf-8") if v else None
def set(self, secret):
with open(self.path, "w", encoding="utf-8") as f:
f.write(base64.b64encode(secret.encode("utf-8")).decode("ascii"))
try:
os.chmod(self.path, 0o600)
except OSError:
pass
def clear(self):
try:
os.unlink(self.path)
except FileNotFoundError:
pass

View File

@@ -0,0 +1,223 @@
# -*- coding: utf-8 -*-
"""license-v2 / lease-v2 信封验签(ECDSA P-256 + SHA-256)。
规范要点(license-platform 接入包 protocol.md):
- 规范化串不是 JSON:固定顺序 key=value、单个 LF 连接、无末尾 LF、UTF-8 编码;
整数字段输出正十进制;时间字段用收到的原始字符串(验签前不得格式化/重序列化)。
- signature 是 ASN.1 DER ECDSA 的标准 Base64,不带 = 填充(不是 Base64URL,
也不是固定 64 字节 r||s)。
- canonical_sha256 是规范化字节的 SHA-256 十六进制,仅辅助校验,不能代替公钥验签。
- 拒绝:未知版本、缺字段/多字段、非法类型、含 CR/LF/NUL 的字段、未知或已撤销
key_id、非 P-256 公钥、绑定到其他实例的信封、legacy v1。
信任根:只信随软件/受控渠道固定分发的公钥(pinned_keys.json),绝不在线发现。
"""
import base64
import hashlib
import json
import os
import re
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
LICENSE_V2 = "license-v2"
LEASE_V2 = "lease-v2"
ALGORITHM = "ECDSA-P256-SHA256"
# 固定字段顺序 = canonical 顺序;payload 必须恰好等于这些键,缺一个多一个都拒
FIELDSETS = {
LICENSE_V2: ("version", "instance_id", "license_id", "customer_id",
"product_id", "starts_at", "expires_at", "key_id"),
LEASE_V2: ("version", "instance_id", "state", "server_time",
"entitlement_expires_at", "lease_expires_at", "key_id"),
}
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
re.IGNORECASE)
RFC3339_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
LEASE_STATES = ("active", "frozen", "revoked", "expired", "not_started", "not_activated")
# 两种信封的固定键集合(缺一个多一个都拒)
CERT_ENVELOPE_KEYS = {"version", "payload", "signature", "canonical_sha256"}
LEASE_ENVELOPE_KEYS = {"payload", "signature", "canonical_sha256", "algorithm",
"next_heartbeat_seconds"}
class VerifyError(Exception):
"""验签/结构校验失败。消息只写原因,不含任何凭据。"""
# ---------------------------------------------------------------- 时间工具
def parse_rfc3339(s):
"""RFC3339 → UTC aware datetime。形状不对抛 VerifyError。"""
if not isinstance(s, str) or not RFC3339_RE.match(s):
raise VerifyError("时间格式不是 RFC3339:%r" % (s,))
from datetime import datetime, timezone
v = s.strip()
if v.endswith(("Z", "z")):
v = v[:-1] + "+00:00"
dt = datetime.fromisoformat(v)
if dt.tzinfo is None:
raise VerifyError("时间缺时区:%r" % (s,))
return dt.astimezone(timezone.utc)
def rfc3339(dt):
"""aware datetime → RFC3339 UTC(Z 后缀,秒精度)。"""
from datetime import timezone
dt = dt.astimezone(timezone.utc).replace(microsecond=0)
return dt.isoformat().replace("+00:00", "Z")
# ------------------------------------------------------------- keyring 管理
def build_keyring(entries):
"""[{key_id, public_key_pem, revoked}] → {key_id: {"key": pub, "revoked": bool}}。
pinned 文件本身配置错(非 P-256 / 解不开)要立刻暴露,不能静默当不可信。
"""
ring = {}
for e in entries or []:
kid, pem = e.get("key_id"), e.get("public_key_pem")
if not kid or not pem:
raise VerifyError("pinned_keys 条目缺 key_id/public_key_pem")
key = serialization.load_pem_public_key(pem.encode("utf-8"))
if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1):
raise VerifyError("key_id=%s 的公钥不是 EC P-256" % kid)
ring[kid] = {"key": key, "revoked": bool(e.get("revoked", False))}
return ring
def load_keyring_file(path):
"""读取随软件分发的 pinned_keys.json(不存在/为空 = 未配置信任根,fail closed)。"""
if not os.path.exists(path):
return {}
with open(path, encoding="utf-8") as f:
data = json.load(f)
return build_keyring(data.get("pinned_keys"))
# ---------------------------------------------------------------- 规范化
# 字段类型白名单:ID 三兄弟必须真整数(bool 也拒);时间字段必须合法 RFC3339
_INT_FIELDS = {"license_id", "customer_id", "product_id"}
_TIME_FIELDS = {"starts_at", "expires_at", "server_time",
"entitlement_expires_at", "lease_expires_at"}
def _field_value(payload, name):
v = payload[name]
if isinstance(v, bool) or v is None or isinstance(v, (list, dict, float)):
raise VerifyError("字段 %s 类型非法" % name)
if isinstance(v, int) or name in _INT_FIELDS:
if not isinstance(v, int) or v <= 0:
raise VerifyError("字段 %s 必须是正整数" % name)
return str(v) # ID:正十进制整数
if not isinstance(v, str):
raise VerifyError("字段 %s 类型非法" % name)
if any(c in v for c in ("\r", "\n", "\x00")):
raise VerifyError("字段 %s 含 CR/LF/NUL" % name)
if name in _TIME_FIELDS:
parse_rfc3339(v) # 时间字段必须是合法 RFC3339
elif not v:
raise VerifyError("字段 %s 不能为空" % name)
return v
def canonical_bytes(payload, version):
"""规范化字节串:固定顺序 key=value、LF 连接、无末尾 LF、UTF-8。"""
if version not in FIELDSETS:
raise VerifyError("未知信封版本:%r" % (version,))
out = []
for name in FIELDSETS[version]:
if name not in payload:
raise VerifyError("payload 缺字段 %s" % name)
out.append("%s=%s" % (name, _field_value(payload, name)))
return "\n".join(out).encode("utf-8")
# ---------------------------------------------------------------- 结构校验
def _check_payload(payload, version, expected_instance):
if not isinstance(payload, dict):
raise VerifyError("payload 不是对象")
if set(payload.keys()) != set(FIELDSETS[version]):
raise VerifyError("payload 字段集不符(缺/多字段)")
if payload["version"] != version:
raise VerifyError("payload.version=%r 不是 %s" % (payload["version"], version))
for name in FIELDSETS[version]:
_field_value(payload, name) # 类型/字符白名单
if not UUID_RE.match(str(payload["instance_id"])):
raise VerifyError("instance_id 不是 UUID")
if expected_instance and str(payload["instance_id"]).lower() != str(expected_instance).lower():
raise VerifyError("信封绑定到其他实例")
if version == LICENSE_V2:
parse_rfc3339(payload["starts_at"])
parse_rfc3339(payload["expires_at"])
else:
if payload["state"] not in LEASE_STATES:
raise VerifyError("租约状态非法:%r" % (payload["state"],))
parse_rfc3339(payload["server_time"])
parse_rfc3339(payload["entitlement_expires_at"])
parse_rfc3339(payload["lease_expires_at"])
def _decode_signature(sig):
if not isinstance(sig, str) or not sig:
raise VerifyError("signature 缺失或非法")
if "-" in sig or "_" in sig: # Base64URL 字母表 → 拒
raise VerifyError("signature 疑似 Base64URL 编码")
pad = "=" * (-len(sig) % 4)
try:
return base64.b64decode(sig + pad, validate=True)
except Exception:
raise VerifyError("signature 不是标准 Base64")
def _check_aux_sha(envelope, canonical):
want = envelope.get("canonical_sha256")
if not isinstance(want, str):
raise VerifyError("canonical_sha256 缺失或非法")
got = hashlib.sha256(canonical).hexdigest()
if want.lower() != got:
raise VerifyError("canonical_sha256 不符(载荷与规范化串不一致)")
def _verify_with_keyring(envelope_keys, envelope, version, expected_instance, keyring):
if not isinstance(envelope, dict) or set(envelope.keys()) != envelope_keys:
raise VerifyError("信封字段集不符(缺/多字段)")
payload = envelope.get("payload")
_check_payload(payload, version, expected_instance)
kid = payload["key_id"]
ent = keyring.get(kid) if isinstance(keyring, dict) else None
if ent is None:
raise VerifyError("未知 key_id:%r(不在可信公钥清单)" % (kid,))
if ent["revoked"]:
raise VerifyError("key_id=%s 已撤销" % kid)
canonical = canonical_bytes(payload, version)
_check_aux_sha(envelope, canonical)
der = _decode_signature(envelope.get("signature"))
try:
ent["key"].verify(der, canonical, ec.ECDSA(hashes.SHA256()))
except InvalidSignature:
raise VerifyError("签名无效")
return payload
def verify_certificate(envelope, expected_instance, keyring):
"""激活证书(license-v2):信封含 version 字段。"""
return _verify_with_keyring(CERT_ENVELOPE_KEYS, envelope, LICENSE_V2,
expected_instance, keyring)
def verify_lease(envelope, expected_instance, keyring):
"""运行租约(lease-v2):信封含 algorithm / next_heartbeat_seconds。"""
if envelope.get("algorithm") != ALGORITHM:
raise VerifyError("algorithm=%r 不是 %s" % (envelope.get("algorithm"), ALGORITHM))
nhs = envelope.get("next_heartbeat_seconds")
if isinstance(nhs, bool) or not isinstance(nhs, int) or nhs < 60:
raise VerifyError("next_heartbeat_seconds 必须是 ≥60 的整数")
return _verify_with_keyring(LEASE_ENVELOPE_KEYS, envelope, LEASE_V2,
expected_instance, keyring)