# -*- 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", "")