Files
pricing_review/CostReview/app/server/license_client/gate.py

479 lines
23 KiB
Python
Raw Permalink 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 -*-
"""业务门禁: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, UUID_RE
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}}
if method == "POST" and path == "/api/license/import":
return _license_import(body)
return {"kind": "json", "code": 404,
"obj": {"error": {"code": "NOT_FOUND", "message": "未知授权接口"}}}
# ------------------------------------------------- 授权文件导入(.license.json)
#
# 协议口径(接入包「授权文件导入(交付格式 v1)」):文件未签名、不是离线授权,
# 只是一份凭据载体——导入=严格校验后写入受保护存储,仍必须走在线激活+验签。
# 红线:拒绝未知版本/额外字段;api_base_url 只允许 HTTPS 根地址且必须命中预置
# 允许地址;不得覆盖已有不同实例身份(须显式确认);导入错误不得回显文件内容。
IMPORT_FIELDS = {"format", "version", "api_base_url", "instance_id",
"license_key", "secret"}
def _import_invalid(msg):
"""固定话术,绝不回显文件内容/secret。"""
return {"ok": False, "code": "IMPORT_INVALID", "message": msg}
def _import_check_url(url):
"""HTTPS 根地址校验 → (规范化地址, None) | (None, 错误话术)。"""
if not isinstance(url, str) or not url or len(url) > 2048:
return None, "授权文件 api_base_url 非法"
try:
from urllib.parse import urlsplit
u = urlsplit(url)
port = u.port # 非法端口在这里抛 ValueError
except ValueError:
return None, "授权文件 api_base_url 非法"
if u.scheme == "http":
# 本机回环 HTTP 仅限开发版(交付版烧根,一律 HTTPS)
if BUILD is not None or u.hostname not in ("127.0.0.1", "localhost", "::1"):
return None, "授权文件 api_base_url 必须 HTTPS"
elif u.scheme != "https":
return None, "授权文件 api_base_url 必须 HTTPS"
if (u.username or u.password or u.query or u.fragment
or not u.hostname or u.path not in ("", "/")):
return None, "授权文件 api_base_url 只允许根地址(不得带路径/参数/账号信息)"
return url.rstrip("/"), None
def _import_validate(f):
if not isinstance(f, dict) or set(f.keys()) != IMPORT_FIELDS:
return _import_invalid("授权文件格式不符(应为 yhy-license-activation v1,"
"字段缺/多不予接受)")
if f.get("format") != "yhy-license-activation":
return _import_invalid("授权文件 format 不符(需要 yhy-license-activation)")
v = f.get("version")
if isinstance(v, bool) or not isinstance(v, int) or v != 1:
return _import_invalid("授权文件版本不支持(只接受 version=1)")
iid, lk, sec = f.get("instance_id"), f.get("license_key"), f.get("secret")
for name, val in (("instance_id", iid), ("license_key", lk), ("secret", sec)):
if not isinstance(val, str) or not val or len(val) > 512:
return _import_invalid("授权文件 %s 字段非法" % name)
if any(ch in val for ch in ("\r", "\n", "\x00")):
return _import_invalid("授权文件 %s 字段含非法字符" % name)
if not UUID_RE.match(iid):
return _import_invalid("授权文件 instance_id 不是 UUID")
url, err = _import_check_url(f.get("api_base_url"))
if err:
return _import_invalid(err)
allowed = str(_cfg.get("api_base") or "").rstrip("/")
if url.lower() != allowed.lower():
return _import_invalid("授权文件指向的授权中心不在本软件预置允许列表"
"(固定为 %s)" % allowed)
return {"ok": True, "instance_id": iid, "license_key": lk, "secret": sec}
def _license_import(body):
b = body if isinstance(body, dict) else {}
c = _client_for_request()
if c is None:
return _blocked("授权子系统未初始化")
r = _import_validate(b.get("file"))
if not r.get("ok"):
return {"kind": "json", "code": 200, "obj": {"ok": False, "data": {"result": r}}}
iid = r["instance_id"]
cur = status_view().get("instance_id")
if cur and cur.lower() != iid.lower() and not b.get("replace_confirmed"):
return {"kind": "json", "code": 200, "obj": {"ok": False, "data": {"result": {
"ok": False, "code": "INSTANCE_CONFLICT",
"message": "本机已配置其他实例(%s…),更换凭据需界面显式确认" % cur[:8]}}}}
try:
c.configure(iid, r["license_key"], r["secret"])
act = c.activate() # 导入≠激活:仍走在线激活+公钥验签
except (StorageError, VerifyError) as e:
act = {"ok": False, "code": "IMPORT_FAILED", "message": str(e)}
if act.get("ok"):
_restart_heartbeat()
out = status_view()
out["result"] = act
return {"kind": "json", "code": 200, "obj": {"ok": bool(act.get("ok")), "data": out}}
# ---------------------------------------------------------------- 授权页
_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}
.imp{margin-top:14px;font-size:13px}
.imp label{color:#1f4e79;text-decoration:underline;cursor:pointer}
.imp input{display:none}
#impPv button{flex:none;padding:7px 18px;margin-top:8px;font-size:13px}
</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="imp"><label for="impFile">或导入授权文件(.license.json,由软件提供方交付)— 点击选择</label>
<input type="file" id="impFile" accept=".json,application/json" onchange="impPick(this)"></div>
<div class="st" id="impPv" style="display:none;margin-top:12px;margin-bottom:0"></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="网络错误:无法连接本机服务。";});}
function impErr(m){var p=document.getElementById("impPv");p.style.display="";
p.innerHTML="<b>"+esc(m)+"</b>";}
function impPick(inp){var f=inp.files&&inp.files[0];if(!f)return;
if(f.size>16384)return impErr("文件超过 16KiB,不是有效授权文件。");
var r=new FileReader();
r.onload=function(){try{impPreview(JSON.parse(r.value))}catch(e){impErr("文件不是有效 JSON。")}};
r.readAsText(f,"utf-8");
inp.value="";}
function impPreview(o){
if(!o||typeof o!="object"||Array.isArray(o)||o.format!="yhy-license-activation"||
o.version!=1||!o.instance_id||!o.license_key||!o.secret||!o.api_base_url)
return impErr("格式不符:需要 yhy-license-activation v1 授权文件。");
window._imp=o;
fetch("/api/license/status").then(function(r){return r.json()}).then(function(j){
var d=j.data||{},p=document.getElementById("impPv");
var warn=(d.instance_id&&String(d.instance_id).toLowerCase()!=String(o.instance_id).toLowerCase())
?"<b>⚠ 本机已配置其他实例,导入将更换凭据(历史时间记录保留)。</b><br>":"";
p.style.display="";
p.innerHTML=warn+"实例:"+esc(o.instance_id)+"<br>授权中心:"+esc(o.api_base_url)+
"<br><button onclick='impGo()'>确认导入并激活</button>";});}
function impGo(){
var m=document.getElementById("msg");m.className="msg";m.style.display="none";
fetch("/api/license/import",{method:"POST",headers:{"Content-Type":"application/json"},
body:JSON.stringify({file:window._imp,replace_confirmed:true})})
.then(function(r){return r.json()}).then(function(j){
var res=((j.data||{}).result||{});
if(j.ok){m.className="msg ok";m.textContent="导入激活成功,正在进入系统…";
document.getElementById("impPv").style.display="none";setTimeout(load,600);return;}
impErr(res.message||"导入失败,请核对授权文件。");
document.getElementById("st").innerHTML=fmtSt(j.data||{});})
.catch(function(){impErr("网络错误:无法连接本机服务。")});}
load();
</script></body></html>""")
return _PAGE