# -*- coding: utf-8 -*- """决策 43:生产公钥落库(spki_sha256 自校验防拷贝损坏)+ .license.json 授权文件导入。 协议红线回归:字段集精确匹配、HTTPS 根地址+允许列表、换实例须显式确认、 导入≠激活(仍走在线激活+公钥验签)、错误话术不回显文件内容。 """ import hashlib import json import os import pytest from cryptography.hazmat.primitives import serialization import license_client.gate as gate from license_client.verify import VerifyError, build_keyring from lic_helpers import IID, IID2, cert_payload, envelope, make_client # noqa: F401 _HERE = os.path.dirname(os.path.abspath(__file__)) PINNED = os.path.join(os.path.dirname(_HERE), "server", "license_client", "pinned_keys.json") # ---------------------------------------------------------------- spki 指纹 def _pem(priv_key): return priv_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("ascii") def _spki(priv_key): der = priv_key.public_key().public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) return hashlib.sha256(der).hexdigest() def test_keyring_spki_match_ok(priv_key): ring = build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key), "spki_sha256": _spki(priv_key), "revoked": False}]) assert "k1" in ring and not ring["k1"]["revoked"] def test_keyring_spki_case_space_tolerant(priv_key): ring = build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key), "spki_sha256": " " + _spki(priv_key).upper() + " "}]) assert "k1" in ring def test_keyring_spki_mismatch_rejected(priv_key): with pytest.raises(VerifyError, match="指纹不符"): build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key), "spki_sha256": "0" * 64}]) def test_keyring_without_spki_still_ok(priv_key): """旧格式(无指纹)向后兼容。""" assert build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key)}]) def test_repo_pinned_keys_prod_key_self_consistent(): """仓库信任根:生产公钥可解析、指纹与 PEM 自洽(拷贝损坏在这里炸)。""" with open(PINNED, encoding="utf-8") as f: keys = json.load(f).get("pinned_keys") assert keys and keys[0]["key_id"] == "prod-22056bfacc8fe8a2" ring = build_keyring(keys) assert ring["prod-22056bfacc8fe8a2"]["revoked"] is False # ---------------------------------------------------------------- 导入校验 GOOD = {"format": "yhy-license-activation", "version": 1, "api_base_url": "https://license.yihuiyong.cn", "instance_id": IID2, "license_key": "LK-1", "secret": "SEC-1"} @pytest.fixture def gate_env(monkeypatch, tmp_path, keyring): assert gate.BUILD is None # 开发库无烧根文件,导入才允许回环 HTTP c = make_client(tmp_path, keyring) # 已配置 IID monkeypatch.setattr(gate, "_client", c) monkeypatch.setattr(gate, "_cfg", {"enforce": True, "api_base": "https://license.yihuiyong.cn"}) return c def _resp(r): assert r["kind"] == "json" and r["code"] == 200 return r["obj"] def test_import_validate_matrix(gate_env): from license_client.gate import _import_validate bad = [ None, # 非对象 {}, # 空对象=缺字段 {**GOOD, "extra": 1}, # 多字段 {k: v for k, v in GOOD.items() if k != "secret"}, # 缺字段 {**GOOD, "format": "yhy-license-activation2"}, {**GOOD, "version": "1"}, {**GOOD, "version": True}, {**GOOD, "instance_id": "not-a-uuid"}, {**GOOD, "secret": "a\r\nb"}, {**GOOD, "license_key": ""}, {**GOOD, "secret": 123}, {**GOOD, "api_base_url": "http://license.yihuiyong.cn"}, # 非回环 http {**GOOD, "api_base_url": "https://evil.example.com"}, # 不在允许列表 {**GOOD, "api_base_url": "https://license.yihuiyong.cn/api/v1"}, # 带路径 {**GOOD, "api_base_url": "https://u:p@license.yihuiyong.cn"}, # 账号信息 {**GOOD, "api_base_url": "https://license.yihuiyong.cn/?x=1"}, # 查询串 {**GOOD, "api_base_url": "ftp://license.yihuiyong.cn"}, ] for b in bad: r = _import_validate(b) assert r["ok"] is False and r["code"] == "IMPORT_INVALID", b assert _import_validate(GOOD)["ok"] is True def test_import_error_never_echoes_content(gate_env): """错误话术不得包含文件内容/secret(协议红线)。""" from license_client.gate import _import_validate leaky = {**GOOD, "secret": "SUPER-SECRET-VALUE", "instance_id": "nope"} for _ in range(1): r = _import_validate(leaky) assert r["ok"] is False assert "SUPER-SECRET-VALUE" not in r["message"] assert "nope" not in r["message"] def test_import_loopback_http_dev_only(monkeypatch): monkeypatch.setattr(gate, "_cfg", {"enforce": True, "api_base": "http://127.0.0.1:8398"}) ok = gate._import_validate({**GOOD, "instance_id": IID, "api_base_url": "http://127.0.0.1:8398"}) assert ok["ok"] is True bad = gate._import_validate({**GOOD, "api_base_url": "http://192.168.1.5:8398"}) assert bad["ok"] is False def test_import_happy_path(priv_key, gate_env): c = gate_env c._tp.script.append((200, {}, {"data": {"instance_id": IID2, "status": "activated", "certificate": envelope( cert_payload(iid=IID2), priv_key, "cert")}})) r = _resp(gate._license_import({"file": GOOD, "replace_confirmed": True})) assert r["ok"] is True and r["data"]["result"]["ok"] is True st = c.state_store.load() assert st["instance_id"] == IID2 and st["status"] == "activated" # 激活请求必须打到文件声明的实例,且带 Idempotency-Key call = c._tp.calls[-1] assert IID2 in call["url"] and call["headers"].get("Idempotency-Key") def test_import_conflict_needs_explicit_confirm(gate_env): c = gate_env r = _resp(gate._license_import({"file": GOOD})) assert r["ok"] is False assert r["data"]["result"]["code"] == "INSTANCE_CONFLICT" assert c.state_store.load()["instance_id"] == IID # 未被动过 # 显式确认后放行(脚本无响应 → 激活 TRANSIENT,但凭据已换写) r2 = _resp(gate._license_import({"file": GOOD, "replace_confirmed": True})) assert r2["data"]["result"]["code"] == "TRANSIENT" assert c.state_store.load()["instance_id"] == IID2 def test_import_same_instance_no_confirm_needed(priv_key, gate_env): c = gate_env same = {**GOOD, "instance_id": IID} c._tp.script.append((200, {}, {"data": {"instance_id": IID, "status": "activated", "certificate": envelope( cert_payload(iid=IID), priv_key, "cert")}})) r = _resp(gate._license_import({"file": same})) assert r["ok"] is True def test_import_high_water_preserved(priv_key, gate_env): """换实例导入不清高水位(协议:切换身份保留时间记录)。""" c = gate_env st = c.state_store.load() st["local_high_water"] = "2026-10-01T00:00:00Z" st["server_high_water"] = "2026-10-01T00:00:00Z" c.state_store.update(lambda s: s.update({"local_high_water": st["local_high_water"], "server_high_water": st["server_high_water"]})) c._tp.script.append((200, {}, {"data": {"instance_id": IID2, "status": "activated", "certificate": envelope( cert_payload(iid=IID2), priv_key, "cert")}})) _resp(gate._license_import({"file": GOOD, "replace_confirmed": True})) st2 = c.state_store.load() assert st2["local_high_water"] == "2026-10-01T00:00:00Z" assert st2["server_high_water"] == "2026-10-01T00:00:00Z"