重新按英文命名,修改成相对路径

This commit is contained in:
lianjianwei2024
2026-10-11 10:52:01 +08:00
parent eea5d511dc
commit 9bb23ac13b
64 changed files with 913 additions and 1427 deletions

View File

@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
"""把 lic_helpers 里的 fixtures 暴露给 pytest(fixtures 必须在 conftest 命名空间)。"""
from lic_helpers import client, keyring, priv_key # noqa: F401

View File

@@ -0,0 +1,171 @@
# -*- coding: utf-8 -*-
"""license_client 测试辅助:本地生成 P-256 测试密钥、签名信封、假传输层。
⚠ 测试只用本地随机生成的密钥 / 包内 test-vectors 的 integration-test-only 公钥,
绝不进入生产 pinned_keys.json。
"""
import base64
import hashlib
import json
import os
import sys
from datetime import datetime, timedelta, timezone
import pytest
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
HERE = os.path.dirname(os.path.abspath(__file__))
SERVER_DIR = os.path.join(os.path.dirname(HERE), "server")
if SERVER_DIR not in sys.path:
sys.path.insert(0, SERVER_DIR)
from license_client.client import LicenseClient # noqa: E402
from license_client.store import JsonFileStore, SecretStore # noqa: E402
from license_client.verify import (FIELDSETS, LICENSE_V2, LEASE_V2, # noqa: E402
build_keyring)
IID = "11111111-2222-3333-4444-555555555555"
IID2 = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
NOW = datetime(2026, 10, 9, 3, 0, 0, tzinfo=timezone.utc)
Z = "%04d-%02d-%02dT%02d:%02d:%02dZ"
def z(dt):
return Z % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
def rfc(dt):
return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
# ---------------------------------------------------------------- 信封构造
def canonical(payload, version):
def val(v):
if isinstance(v, bool):
raise TypeError("bool 不允许")
return str(v) if isinstance(v, int) else v
return "\n".join("%s=%s" % (k, val(payload[k])) for k in FIELDSETS[version]).encode("utf-8")
def sign_b64(key, data):
der = key.sign(data, ec.ECDSA(hashes.SHA256()))
return base64.b64encode(der).decode("ascii").rstrip("=")
def cert_payload(key_id="integration-test-only", iid=IID, **over):
p = {"version": LICENSE_V2, "instance_id": iid, "license_id": 1, "customer_id": 2,
"product_id": 3, "starts_at": z(NOW), "expires_at": z(NOW + timedelta(days=365)),
"key_id": key_id}
p.update(over)
return p
def lease_payload(key_id="integration-test-only", iid=IID,
state="active", server=None, ent=None, le=None, **over):
p = {"version": LEASE_V2, "instance_id": iid, "state": state,
"server_time": z(server or NOW),
"entitlement_expires_at": z(ent or NOW + timedelta(days=365)),
"lease_expires_at": z(le or (server or NOW) + timedelta(days=7)),
"key_id": key_id}
p.update(over)
return p
def envelope(payload, key, kind, next_hb=60, sha=None):
"""kind="cert" → license-v2 信封;"lease" → lease-v2 信封。sha 传 "bad" 可篡改辅助校验。"""
version = LICENSE_V2 if kind == "cert" else LEASE_V2
data = canonical(payload, version)
env = {"payload": payload,
"signature": sign_b64(key, data),
"canonical_sha256": sha or hashlib.sha256(data).hexdigest()}
if kind == "cert":
env = {"version": version, **env}
else:
env = {"algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": next_hb, **env}
return env
# ---------------------------------------------------------------- 假设施
class MemSecret(SecretStore):
def __init__(self):
self.v = None
def get(self):
return self.v
def set(self, s):
self.v = s
def clear(self):
self.v = None
class FakeTransport:
"""脚本化传输层:依次消费 script(异常 / (status, headers, data));记录全部调用。"""
def __init__(self, script):
self.script = list(script)
self.calls = []
def __call__(self, method, url, body, headers):
self.calls.append({"method": method, "url": url, "body": dict(body),
"headers": dict(headers)})
item = self.script.pop(0) if self.script else (500, {}, {"error": {"code": "X", "message": "脚本耗尽"}})
if isinstance(item, Exception):
raise item
status, headers, data = item
return status, dict(headers), data
def keys(self):
return [c["headers"].get("Idempotency-Key") for c in self.calls]
def make_keyring(priv_key, key_id="integration-test-only", revoked=False):
pem = priv_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
return build_keyring([{"key_id": key_id, "public_key_pem": pem.decode("ascii"),
"revoked": revoked}])
@pytest.fixture
def priv_key():
return ec.generate_private_key(ec.SECP256R1())
@pytest.fixture
def keyring(priv_key):
return make_keyring(priv_key)
@pytest.fixture
def client(tmp_path, keyring):
"""已配置凭据的客户端:now 冻结在 NOW,sleep 记录不真等。"""
return make_client(tmp_path, keyring)
def make_client(tmp_path, keyring, transport=None, now_fn=None, max_attempts=4):
sleeps = []
tp = transport or FakeTransport([])
c = LicenseClient(
api_base="https://license.test",
state_store=JsonFileStore(str(tmp_path / "state.json")),
secret_store=MemSecret(),
keyring=keyring,
now_fn=now_fn or (lambda: NOW),
sleep_fn=lambda s: sleeps.append(s),
transport=tp,
max_attempts=max_attempts)
c._sleeps = sleeps
c._tp = tp
c.configure(IID, "LK-TEST-1", "SECRET-DO-NOT-LOG")
return c
def load_vectors():
p = os.path.join(HERE, "testdata", "license_test_vectors.json")
with open(p, encoding="utf-8") as f:
return json.load(f)

View File

@@ -0,0 +1,277 @@
# -*- coding: utf-8 -*-
"""网络/时钟回拨/过期租约负向测试 + 幂等/429/掉线/存储失败(协议交付验收清单)。"""
import json
from datetime import timedelta
import pytest
from lic_helpers import (IID, NOW, FakeTransport, MemSecret, cert_payload,
envelope, lease_payload, make_client, make_keyring, rfc, z)
from license_client.client import LicenseClient
from license_client.store import JsonFileStore, StorageError
from license_client.verify import VerifyError
def ok_lease(priv_key, server=NOW, le=None, state="active", iid=IID, next_hb=60):
return 200, {}, {"data": envelope(
lease_payload(server=server, le=le, state=state, iid=iid),
priv_key, "lease", next_hb=next_hb)}
def ok_cert(priv_key, iid=IID):
return 200, {}, {"data": {"instance_id": iid, "status": "activated",
"certificate": envelope(cert_payload(iid=iid), priv_key, "cert")},
"idempotent_replay": False}
# ------------------------------------------------------------ 激活
def test_activate_happy_path(priv_key, client):
client._tp.script.append(ok_cert(priv_key))
r = client.activate()
assert r["ok"] is True
st = client.state_store.load()
assert st["status"] == "activated"
assert st["certificate"]["version"] == "license-v2"
assert "activation_op" not in st
assert client._tp.calls[0]["url"].endswith("/api/v1/activation/instances/" + IID)
assert client._tp.calls[0]["headers"]["Idempotency-Key"]
def test_activate_retry_reuses_key_and_body(priv_key, tmp_path, keyring):
"""网络失败重试:同一 Idempotency-Key + 同一请求体(含 secret 字段不变)。"""
tp = FakeTransport([ConnectionError("断网"), ok_cert(priv_key)])
c = make_client(tmp_path, keyring, transport=tp)
r = c.activate()
assert r["ok"] is True
assert len(tp.calls) == 2
assert tp.keys()[0] == tp.keys()[1]
assert tp.calls[0]["body"] == tp.calls[1]["body"]
def test_activate_rejects_stop_retrying(priv_key, client):
client._tp.script.append((401, {}, {"error": {"code": "BAD_CREDENTIALS",
"message": "nope"}}))
r = client.activate()
assert r["ok"] is False and r["code"] == "BAD_CREDENTIALS"
assert len(client._tp.calls) == 1 # 401 不重试
st = client.state_store.load()
assert "activation_op" not in st
assert st["last_error"]
def test_activate_verify_failure_fails_closed(priv_key, client, keyring):
"""证书绑定别的实例 → 拒收,状态不得进入 activated。"""
client._tp.script.append(ok_cert(priv_key, iid="bbbbbbbb-cccc-dddd-eeee-ffffffffffff"))
r = client.activate()
assert r["ok"] is False and r["code"] == "VERIFY_FAILED"
assert client.state_store.load().get("status") != "activated"
def test_activate_persisted_key_survives_restart(priv_key, tmp_path, keyring):
"""激活中途进程重启:新客户端从状态文件找回在途幂等键继续用。"""
tp = FakeTransport([ConnectionError("断网")])
c1 = make_client(tmp_path, keyring, transport=tp, max_attempts=1)
c1.activate() # 瞬时失败,键已落盘
saved_key = c1.state_store.load()["activation_op"]["key"]
tp2 = FakeTransport([ok_cert(priv_key)])
c2 = make_client(tmp_path, keyring, transport=tp2)
c2.activate()
assert tp2.calls[0]["headers"]["Idempotency-Key"] == saved_key
# ------------------------------------------------------------ 心跳与租约状态机
def test_heartbeat_accepts_active_lease(priv_key, client):
client._tp.script.append(ok_lease(priv_key))
r = client.heartbeat()
assert r["ok"] and r["state"] == "active"
st = client.state_store.load()
assert st["enabled"] is True
assert st["server_high_water"] == z(NOW)
assert st["next_heartbeat_seconds"] == 60
assert "heartbeat_op" not in st
ok, reason = client.can_run()
assert ok is True and reason is None
@pytest.mark.parametrize("state", ["frozen", "revoked", "expired", "not_started", "not_activated"])
def test_non_active_lease_disables_business(priv_key, client, state):
"""HTTP 200 不代表授权有效:签名租约非 active 必须关闭业务。"""
client._tp.script.append(ok_lease(priv_key, state=state))
r = client.heartbeat()
assert r["ok"] is True
st = client.state_store.load()
assert st["enabled"] is False
ok, reason = client.can_run()
assert ok is False and state in reason
def test_lease_expired(priv_key, client):
client._tp.script.append(ok_lease(priv_key, le=NOW - timedelta(seconds=1)))
client.heartbeat()
ok, reason = client.can_run()
assert ok is False and "租约已过期" in reason
def test_entitlement_expired(priv_key, client):
env = envelope(lease_payload(ent=NOW - timedelta(days=1),
le=NOW - timedelta(days=2)), priv_key, "lease")
client._tp.script.append((200, {}, {"data": env}))
client.heartbeat()
ok, reason = client.can_run()
assert ok is False and "过期" in reason
def test_lease_longer_than_entitlement_rejected(priv_key, client):
env = envelope(lease_payload(ent=NOW + timedelta(days=3),
le=NOW + timedelta(days=10)), priv_key, "lease")
client._tp.script.append((200, {}, {"data": env}))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "LEASE_INVALID"
assert client.state_store.load().get("lease") is None # 不得接受
def test_lease_over_14_days_rejected(priv_key, client):
env = envelope(lease_payload(server=NOW, le=NOW + timedelta(days=14, seconds=1)),
priv_key, "lease")
client._tp.script.append((200, {}, {"data": env}))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "LEASE_INVALID"
def test_server_time_rollback_rejected(priv_key, client):
"""第二份租约 server_time 早于已存高水位 → 拒收且保留新租约。"""
client._tp.script.append(ok_lease(priv_key, server=NOW))
client.heartbeat()
old = client.state_store.load()["lease"]
client._tp.script.append(ok_lease(priv_key, server=NOW - timedelta(hours=1)))
r = client.heartbeat()
assert r["ok"] is False
assert client.state_store.load()["lease"] == old
def test_next_heartbeat_honored_with_min_60(priv_key, client):
client._tp.script.append(ok_lease(priv_key, next_hb=120))
r = client.heartbeat()
assert r["next"] == 120
client._tp.script.append(ok_lease(priv_key, next_hb=30)) # 服务端违反 schema(min 60)→ 拒收
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "VERIFY_FAILED"
assert client.state_store.load()["next_heartbeat_seconds"] == 120 # 旧值保留
# ------------------------------------------------------------ 时钟
def test_local_clock_rollback_locks(priv_key, client):
client.cache_ttl = 0 # 回拨检测专用测试:关掉结果缓存
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
ok, _ = client.can_run()
assert ok
class T:
t = NOW - timedelta(seconds=90) # 把本机时钟往回拨
client.now_fn = lambda: T.t
ok, reason = client.can_run()
assert ok is False and "回拨" in reason
def test_clock_skew_over_5min_rejected(priv_key, client):
client._tp.script.append(ok_lease(priv_key, server=NOW - timedelta(minutes=10)))
client.heartbeat()
ok, reason = client.can_run()
assert ok is False and "5 分钟" in reason
# ------------------------------------------------------------ 掉线与离线宽限
def test_offline_grace_not_extended(priv_key, client):
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
before = client.state_store.load()["lease"]["lease_expires_at"]
client._tp.script.append(ConnectionError("断网"))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "TRANSIENT"
st = client.state_store.load()
assert st["lease"]["lease_expires_at"] == before # 网络失败不得延长租约
assert "heartbeat_op" in st # 在途操作保留(键+client_time 复用)
ok, _ = client.can_run()
assert ok is True # 有效租约内允许继续(离线宽限)
def test_restart_keeps_lease_without_network(priv_key, tmp_path, keyring):
"""重启不得清除高水位/租约:新客户端不联网即可继续运行。"""
tp = FakeTransport([ok_lease(priv_key)])
c1 = make_client(tmp_path, keyring, transport=tp)
c1.heartbeat()
secret = c1.secret_store.get()
tp2 = FakeTransport([]) # 一旦联网即测试失败
c2 = LicenseClient(api_base="https://license.test",
state_store=c1.state_store, secret_store=c1.secret_store,
keyring=keyring, now_fn=lambda: NOW,
sleep_fn=lambda s: None, transport=tp2)
ok, reason = c2.can_run()
assert ok is True and tp2.calls == []
def test_tampered_local_lease_fails_closed(priv_key, client):
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
p = client.state_store.path
st = json.load(open(p, encoding="utf-8"))
st["lease_envelope"]["payload"]["entitlement_expires_at"] = "2099-01-01T00:00:00Z"
json.dump(st, open(p, "w", encoding="utf-8"), ensure_ascii=False)
ok, reason = client.can_run()
assert ok is False and "校验失败" in reason
def test_storage_save_failure_fail_closed(priv_key, client):
"""原子存储失败:can_run 必须 fail closed,不得放行业务。"""
client._tp.script.append(ok_lease(priv_key))
client.heartbeat()
class Broken(JsonFileStore):
def update(self, fn):
raise StorageError("磁盘已满")
client.state_store = Broken(client.state_store.path)
ok, reason = client.can_run()
assert ok is False and "fail closed" in reason
# ------------------------------------------------------------ 429 / 5xx
def test_429_respects_retry_after(priv_key, client):
client._tp.script.append((429, {"Retry-After": "7"}, {}))
client._tp.script.append(ok_lease(priv_key))
r = client.heartbeat()
assert r["ok"] is True
assert any(s >= 7 for s in client._sleeps)
assert client._tp.keys()[0] == client._tp.keys()[1] # 同键重试
def test_5xx_bounded_retry_then_transient(priv_key, client):
for _ in range(4):
client._tp.script.append((503, {}, {}))
r = client.heartbeat()
assert r["ok"] is False and r["code"] == "TRANSIENT"
assert len(client._tp.calls) == 4 # 有界
assert len(set(client._tp.keys())) == 1 # 同键同体
assert client._tp.calls[0]["body"] == client._tp.calls[-1]["body"]
def test_403_parks_heartbeat_no_auto_retry(priv_key, client):
client._tp.script.append((403, {}, {"error": {"code": "INSTANCE_DISABLED",
"message": "x"}}))
r = client.heartbeat()
assert r["ok"] is False and len(client._tp.calls) == 1
st = client.state_store.load()
assert st["status"] == "needs_attention"
assert "SECRET-DO-NOT-LOG" not in json.dumps(st) # secret 不进状态文件
for c in client._tp.calls:
assert "SECRET-DO-NOT-LOG" not in c["url"] # secret 不进 URL
assert c["body"].get("secret") == "SECRET-DO-NOT-LOG" # 只在请求体里
def test_secret_never_in_error_messages(priv_key, client):
client._tp.script.append(ConnectionError("boom"))
r = client.heartbeat()
assert "SECRET-DO-NOT-LOG" not in r.get("message", "")

View File

@@ -0,0 +1,117 @@
# -*- coding: utf-8 -*-
"""决策 31 加固项:can_run 结果缓存、高水位节流写、product_id 绑定、心跳并发串行、
缓存失效(心跳接受新租约后门禁立即看到)。"""
import json
import threading
import time
from datetime import timedelta
from lic_helpers import (NOW, FakeTransport, envelope, lease_payload,
make_client, cert_payload, z)
def active_env(priv_key, server=NOW):
return (200, {}, {"data": envelope(lease_payload(server=server), priv_key, "lease")})
def test_can_run_cache_within_ttl(priv_key, client):
client.cache_ttl = 600
client.mono_fn = (lambda: 1000.0)
client._tp.script.append(active_env(priv_key))
client.heartbeat()
assert client.can_run()[0] is True
# TTL 内就算本地租约被篡改,也吃到缓存(这正是缓存的意义:不每请求验签)
p = client.state_store.path
st = json.load(open(p, encoding="utf-8"))
st["lease_envelope"]["payload"]["state"] = "frozen"
json.dump(st, open(p, "w", encoding="utf-8"), ensure_ascii=False)
client.mono_fn = (lambda: 1001.0)
assert client.can_run()[0] is True # 缓存命中
client.mono_fn = (lambda: 1000.0 + 601) # TTL 过 → 重新验签发现篡改
ok, reason = client.can_run()
assert ok is False and "校验失败" in reason
def test_cache_invalidated_by_new_lease(priv_key, client):
client.cache_ttl = 600
client.mono_fn = (lambda: 1000.0)
client._tp.script.append((200, {}, {"data": envelope(lease_payload(state="frozen"),
priv_key, "lease")}))
client.heartbeat()
assert client.can_run()[0] is False # 负结果也进缓存
client._tp.script.append(active_env(priv_key))
client.heartbeat() # 新租约必须作废缓存
assert client.can_run()[0] is True
def test_high_water_throttled_write(priv_key, client):
"""55 秒内不重复落盘高水位;跨过阈值才前进;回拨检测不受影响。"""
client.cache_ttl = 0 # 关缓存,专测节流
t = {"now": NOW}
client.now_fn = lambda: t["now"]
client._tp.script.append(active_env(priv_key))
client.heartbeat()
assert client.can_run()[0] is True
assert client.state_store.load()["local_high_water"] == z(NOW)
t["now"] = NOW + timedelta(seconds=30)
assert client.can_run()[0] is True
assert client.state_store.load()["local_high_water"] == z(NOW) # 未落盘
t["now"] = NOW + timedelta(seconds=60)
assert client.can_run()[0] is True
assert client.state_store.load()["local_high_water"] == z(NOW + timedelta(seconds=60))
t["now"] = NOW + timedelta(seconds=20) # 回拨 40 秒:立即锁
ok, reason = client.can_run()
assert ok is False and "回拨" in reason
def test_product_binding(priv_key, tmp_path, keyring):
c = make_client(tmp_path, keyring)
c.expected_product_id = 3
c._tp.script.append((200, {}, {"data": {"instance_id": c.state_store.load()["instance_id"],
"status": "activated",
"certificate": envelope(
cert_payload(product_id=9), priv_key, "cert")}}))
r = c.activate()
assert r["ok"] is False and r["code"] == "PRODUCT_MISMATCH"
assert c.state_store.load().get("status") != "activated"
c._tp.script.append((200, {}, {"data": {"instance_id": c.state_store.load()["instance_id"],
"status": "activated",
"certificate": envelope(
cert_payload(product_id=3), priv_key, "cert")}}))
assert c.activate()["ok"] is True
assert c.status()["product_id"] == 3
def test_concurrent_heartbeats_serialized(priv_key, client):
"""循环/自愈/手动三方并发:必须串行(各自完整操作、键不互踩、状态不撕)。"""
base = client._tp.__call__
def slow(method, url, body, headers):
time.sleep(0.05)
return base(method, url, body, headers)
client._send_fn = slow
client._tp.script.append(active_env(priv_key))
client._tp.script.append(active_env(priv_key))
rs = []
def beat():
rs.append(client.heartbeat())
ts = [threading.Thread(target=beat) for _ in range(2)]
[t.start() for t in ts]
[t.join() for t in ts]
assert all(r["ok"] for r in rs)
keys = [c["headers"].get("Idempotency-Key") for c in client._tp.calls]
assert len(keys) == 2 and len(set(keys)) == 2 # 两个独立操作、两把键
st = client.state_store.load()
assert st["enabled"] is True and "heartbeat_op" not in st
def test_gate_can_run_safe_uses_cache(priv_key, client):
"""门禁入口 can_run_safe 走同一缓存:TTL 内重复调用不再触发落盘。"""
client.cache_ttl = 600
client.mono_fn = (lambda: 1000.0)
client._tp.script.append(active_env(priv_key))
client.heartbeat()
a = client.can_run_safe()
b = client.can_run_safe()
assert a[0] is True and b[0] is True

View File

@@ -0,0 +1,189 @@
# -*- coding: utf-8 -*-
"""验签单元测试:包内向量 + 全套负向(篡改/未知密钥/撤销/实例不匹配/v1/额外字段/
非法类型/CR-LF-NUL/Base64URL/canonical_sha256 不符/非 P-256 公钥)。"""
import hashlib
from datetime import timedelta
import pytest
from cryptography.hazmat.primitives.asymmetric import ec
from lic_helpers import (IID, IID2, NOW, canonical, cert_payload, envelope,
lease_payload, load_vectors, sign_b64)
from license_client.verify import (LICENSE_V2, LEASE_V2, VerifyError,
build_keyring, canonical_bytes,
verify_certificate, verify_lease)
# ------------------------------------------------------------ 包内随机测试向量
def test_package_vectors_canonical_matches():
"""先验规范化串本身:我们拼的字节必须和接入包给的 canonical 逐字节一致。"""
v = load_vectors()
for kind, version in (("license", LICENSE_V2), ("lease", LEASE_V2)):
assert canonical_bytes(v[kind]["payload"], version) == v[kind]["canonical"].encode("utf-8")
assert hashlib.sha256(v[kind]["canonical"].encode("utf-8")).hexdigest() \
== v[kind]["canonical_sha256"]
def test_package_vectors_verify():
"""用包内随机测试公钥过 license-v2 / lease-v2 验签(接入包要求的先行动作)。"""
v = load_vectors()
ring = build_keyring(v["pinned_keys"])
lic = {"version": LICENSE_V2,
"payload": v["license"]["payload"],
"signature": v["license"]["signature"],
"canonical_sha256": v["license"]["canonical_sha256"]}
assert verify_certificate(lic, IID, ring)["version"] == LICENSE_V2
lease = {"payload": v["lease"]["payload"],
"signature": v["lease"]["signature"],
"canonical_sha256": v["lease"]["canonical_sha256"],
"algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": 60}
assert verify_lease(lease, IID, ring)["state"] == "active"
# ------------------------------------------------------------ 正常路径
def test_roundtrip_cert_and_lease(priv_key, keyring):
p = cert_payload()
assert verify_certificate(envelope(p, priv_key, "cert"), IID, keyring) == p
p2 = lease_payload()
assert verify_lease(envelope(p2, priv_key, "lease"), IID, keyring) == p2
# ------------------------------------------------------------ 篡改与伪造
def test_tampered_payload_field(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env["payload"]["state"] = "frozen" # 换状态不换签名
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_tampered_signature(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
sig = env["signature"]
env["signature"] = ("A" if sig[0] != "A" else "B") + sig[1:]
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_signed_by_foreign_key(keyring):
evil = ec.generate_private_key(ec.SECP256R1())
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(), evil, "lease"), IID, keyring)
def test_unknown_key_id(priv_key):
ring = build_keyring([]) # 空信任根
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(), priv_key, "lease"), IID, ring)
def test_revoked_key(priv_key):
from lic_helpers import make_keyring
ring = make_keyring(priv_key, revoked=True)
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(), priv_key, "lease"), IID, ring)
def test_instance_mismatch(priv_key, keyring):
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(iid=IID2), priv_key, "lease"), IID, keyring)
# ------------------------------------------------------------ 结构拒绝
def test_v1_rejected(priv_key, keyring):
p = lease_payload(version="lease-v1")
with pytest.raises(VerifyError):
verify_lease(envelope(p, priv_key, "lease"), IID, keyring)
def test_missing_field(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env["payload"].pop("key_id") # 先签名再抠字段:canonical 与字段集必须双双拒
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_extra_field(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env["payload"]["extra"] = "x"
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_wrong_types(priv_key, keyring):
def bad_cert(mut):
env = envelope(cert_payload(), priv_key, "cert")
mut(env["payload"])
return env
with pytest.raises(VerifyError): # ID 变字符串
verify_certificate(bad_cert(lambda p: p.update(license_id="1")), IID, keyring)
with pytest.raises(VerifyError): # ID 非正数
verify_certificate(bad_cert(lambda p: p.update(license_id=0)), IID, keyring)
with pytest.raises(VerifyError): # bool 冒充整数
verify_certificate(bad_cert(lambda p: p.update(license_id=True)), IID, keyring)
with pytest.raises(VerifyError): # 非法状态枚举
verify_lease(bad_cert(lambda p: p.update(state="睡了的")), IID, keyring)
with pytest.raises(VerifyError): # 时间格式坏
verify_lease(bad_cert(lambda p: p.update(server_time="2026/10/09 03:00:00")),
IID, keyring)
with pytest.raises(VerifyError): # instance_id 非 UUID
verify_certificate(bad_cert(lambda p: p.update(instance_id="not-a-uuid")),
IID, keyring)
def test_cr_lf_nul_in_fields(priv_key, keyring):
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(key_id="k\nid"), priv_key, "lease"), IID, keyring)
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(key_id="k\r"), priv_key, "lease"), IID, keyring)
with pytest.raises(VerifyError):
verify_lease(envelope(lease_payload(key_id="k\x00"), priv_key, "lease"), IID, keyring)
def test_base64url_signature_rejected(priv_key, keyring):
"""Base64URL 字母表(-/_)不是标准 Base64:出现即拒,不猜填充。"""
env = envelope(lease_payload(), priv_key, "lease")
env["signature"] = "-" + env["signature"][1:]
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
env2 = envelope(lease_payload(), priv_key, "lease")
env2["signature"] = "_" + env2["signature"][1:]
with pytest.raises(VerifyError):
verify_lease(env2, IID, keyring)
def test_canonical_sha_mismatch(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease", sha="0" * 64)
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
def test_non_p256_key_rejected_at_ring_build():
p384 = ec.generate_private_key(ec.SECP384R1())
from cryptography.hazmat.primitives import serialization
pem = p384.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("ascii")
with pytest.raises(VerifyError):
build_keyring([{"key_id": "k", "public_key_pem": pem}])
def test_lease_envelope_requires_algorithm_and_next(priv_key, keyring):
env = envelope(lease_payload(), priv_key, "lease")
env.pop("algorithm")
with pytest.raises(VerifyError):
verify_lease(env, IID, keyring)
env2 = envelope(lease_payload(), priv_key, "lease", next_hb=30) # < 60 拒
with pytest.raises(VerifyError):
verify_lease(env2, IID, keyring)
def test_cert_envelope_missing_version(priv_key, keyring):
env = envelope(cert_payload(), priv_key, "cert")
env.pop("version")
with pytest.raises(VerifyError):
verify_certificate(env, IID, keyring)

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
"""wipe 清场防回归(2026-10-10)。
背景:wipe 手工枚举清表清单两次漏表(2026-09-30 s_sections、2026-10-10 s_lme_res),
每次漏表 = 「重新解析」不断叠加脏数据(台班组成曾叠到 13 份)。
改造后 wipe 按 sqlite_master 动态发现 s_ 表,本测试钉死两条防线:
① 未来新建任何带 session_id 的 s_ 表(即使谁都不记得它),wipe 必然清它;
② WIPE_KEEP 里的表(s_remarks/s_settings)任何情况下不被清。
"""
import sqlite3
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "core"))
import session_job # noqa: E402
def _mk_db():
con = sqlite3.connect(":memory:")
c = con.cursor()
# 业务表形状(简化自 schema,只保留 wipe 相关列)
c.execute("CREATE TABLE s_bills (id INTEGER PRIMARY KEY, session_id INT)")
c.execute("CREATE TABLE s_norms (id INTEGER PRIMARY KEY, bill_id INT)") # 无 session_id
c.execute("CREATE TABLE s_norm_res (id INTEGER PRIMARY KEY, norm_id INT)") # 无 session_id
# ⭐ 模拟「未来新表」:带 session_id 的普通数据表,谁都不用记得登记
c.execute("CREATE TABLE s_future_thing (id INTEGER PRIMARY KEY, session_id INT)")
# 保留清单里的表
c.execute("CREATE TABLE s_remarks (id INTEGER PRIMARY KEY, session_id INT)")
c.execute("CREATE TABLE s_settings (id INTEGER PRIMARY KEY, session_id INT)")
# sessions 表(s_ 前缀误匹配检查:'sessions' 不应以通配方式被清/被当数据表)
c.execute("CREATE TABLE sessions (id INTEGER PRIMARY KEY)")
# 数据
c.execute("INSERT INTO sessions VALUES (58)")
c.execute("INSERT INTO s_bills (session_id) VALUES (58)")
c.execute("INSERT INTO s_norms (bill_id) VALUES (1)")
c.execute("INSERT INTO s_norms (bill_id) VALUES (NULL)") # 孤儿定额
c.execute("INSERT INTO s_norm_res (norm_id) VALUES (1)")
c.execute("INSERT INTO s_norm_res (norm_id) VALUES (NULL)") # 孤儿消耗量
c.execute("INSERT INTO s_future_thing (session_id) VALUES (58)")
c.execute("INSERT INTO s_remarks (session_id) VALUES (58)")
c.execute("INSERT INTO s_settings (session_id) VALUES (58)")
con.commit()
return con
def test_wipe_clears_future_tables():
"""⭐ 核心防线:未来加的新表(带 session_id)即使没人同步 wipe 也必被清。"""
con = _mk_db()
session_job.wipe(con, 58)
assert con.execute("SELECT COUNT(*) FROM s_future_thing").fetchone()[0] == 0
def test_wipe_clears_known_tables():
con = _mk_db()
session_job.wipe(con, 58)
for t in ("s_bills",):
assert con.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] == 0, t
# 定额按 bill_id 绕层清 + 孤儿全清
assert con.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0] == 0
assert con.execute("SELECT COUNT(*) FROM s_norm_res").fetchone()[0] == 0
def test_wipe_keeps_remarks_and_settings():
"""保留清单:备注与设置跨重新解析存活。"""
con = _mk_db()
session_job.wipe(con, 58)
assert con.execute("SELECT COUNT(*) FROM s_remarks").fetchone()[0] == 1
assert con.execute("SELECT COUNT(*) FROM s_settings").fetchone()[0] == 1
def test_wipe_scoped_to_session_and_keeps_sessions_row():
con = _mk_db()
c = con.cursor()
c.execute("INSERT INTO s_bills (session_id) VALUES (99)") # 别的会话
c.execute("INSERT INTO s_remarks (session_id) VALUES (99)")
con.commit()
session_job.wipe(con, 58)
assert c.execute("SELECT COUNT(*) FROM s_bills WHERE session_id=99").fetchone()[0] == 1
assert c.execute("SELECT COUNT(*) FROM sessions WHERE id=58").fetchone()[0] == 1
def test_wipe_keep_list_has_documented_members():
"""保留清单必须精确等于这两张表 —— 多了会漏清数据,少了会丢用户数据。"""
assert session_job.WIPE_KEEP == {"s_remarks", "s_settings"}

View File

@@ -0,0 +1,39 @@
{
"lease": {
"canonical": "version=lease-v2\ninstance_id=11111111-2222-3333-4444-555555555555\nstate=active\nserver_time=2026-10-09T03:00:00Z\nentitlement_expires_at=2027-10-09T03:00:00Z\nlease_expires_at=2026-10-23T03:00:00Z\nkey_id=integration-test-only",
"canonical_sha256": "da433cd2ec57a9ebf1f6a47e30521682e205f397ce5988b05785511a3e428aac",
"payload": {
"entitlement_expires_at": "2027-10-09T03:00:00Z",
"instance_id": "11111111-2222-3333-4444-555555555555",
"key_id": "integration-test-only",
"lease_expires_at": "2026-10-23T03:00:00Z",
"server_time": "2026-10-09T03:00:00Z",
"state": "active",
"version": "lease-v2"
},
"signature": "MEUCIC7K5MBrMw2M+mTnI8V14qUbgsqafewS+iFxnW2t7g68AiEAkBpVMJWsZ8T8szdvZHbR24PSiZbXHIWrNedh/+X/g2I"
},
"license": {
"canonical": "version=license-v2\ninstance_id=11111111-2222-3333-4444-555555555555\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-10-09T03:00:00Z\nexpires_at=2027-10-09T03:00:00Z\nkey_id=integration-test-only",
"canonical_sha256": "81d4930737bf289e752f5f37f43f9a0dfa0c0692075b2dba3d4d643ec1602355",
"payload": {
"customer_id": 2,
"expires_at": "2027-10-09T03:00:00Z",
"instance_id": "11111111-2222-3333-4444-555555555555",
"key_id": "integration-test-only",
"license_id": 1,
"product_id": 3,
"starts_at": "2026-10-09T03:00:00Z",
"version": "license-v2"
},
"signature": "MEUCIQDGb8FCV0JWvdE6UrMoscU9ZaidDajGGecslbI8A5xNkgIgVmI7IHlQQi5qhaulYNM9u27INVmXgPrNwNYLQsJrTJw"
},
"pinned_keys": [
{
"key_id": "integration-test-only",
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhrrB+tsg5H7cPScLrwZh/2q6fPx7\nSfzrQwmlKlJV74r0j0r5qPINY59icRBa42fEQTDI6hd9faWGifSW8Fb+jw==\n-----END PUBLIC KEY-----\n",
"revoked": false
}
],
"warning": "TEST ONLY: never trust this key in production; use frozen now=2026-10-09T03:00:00Z for state tests"
}