Files
pricing_review/造价审核/app/server/license_client/gate.py

348 lines
16 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 -*-
"""业务门禁: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