from __future__ import annotations import hashlib def test_license_server_api_activates_card(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM db_path = tmp_path / "license.db" service = LicenseService(db_path=db_path, private_key_pem=TEST_PRIVATE_KEY_PEM) card = service.create_cards(days=5, count=1, customer="api-user")[0] client = TestClient(api.create_app(service=service)) health = client.get("/api/v1/health") resp = client.post( "/api/v1/activate", json={"card_key": card.code, "machine_fingerprint": "machine-api"}, ) assert health.status_code == 200 assert health.json()["ok"] is True assert resp.status_code == 200 body = resp.json() assert body["ok"] is True assert body["license"]["payload"]["customer"] == "api-user" assert body["license"]["payload"]["machine_fingerprint"] == "machine-api" assert len(body["license"]["payload"]["card_hash"]) == 64 verify = client.post("/api/v1/verify_license", json={"license": body["license"]}) assert verify.status_code == 200 assert verify.json()["ok"] is True def test_license_server_api_rejects_unknown_card(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service)) resp = client.post( "/api/v1/activate", json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"}, ) assert resp.status_code == 404 assert resp.json()["reason"] == "not_found" def test_license_server_api_verify_license_rejects_revoked_card(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) card = service.create_cards(days=5, count=1, customer="api-user")[0] activated = service.activate(card.code, machine_fingerprint="machine-api") assert activated.license_doc is not None service.revoke(card.code) client = TestClient(api.create_app(service=service)) resp = client.post("/api/v1/verify_license", json={"license": activated.license_doc}) assert resp.status_code == 403 assert resp.json()["reason"] == "revoked" def test_admin_page_requires_token(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) resp = client.get("/admin", follow_redirects=False) assert resp.status_code == 303 assert resp.headers["location"] == "/admin/login" def test_admin_page_can_create_and_revoke_card(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) created = client.post( "/admin/create", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={"csrf_token": "csrf-token", "days": "8", "count": "1", "customer": "web-admin"}, ) card = created.text.split("DG-", 1)[1].split("<", 1)[0] card = "DG-" + card.strip() revoked = client.post( "/admin/revoke", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={"csrf_token": "csrf-token", "card_key": card}, ) assert login.status_code == 303 assert created.status_code == 200 assert "web-admin" in created.text assert card.startswith("DG-") assert revoked.status_code == 200 assert "已禁用" in revoked.text assert service.activate(card, machine_fingerprint="machine-a").reason == "revoked" def test_update_manifest_defaults_to_no_update_with_signature(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) resp = client.get("/api/v1/update/manifest") assert resp.status_code == 200 body = resp.json() assert body["enabled"] is False assert body["version"] == "0.0.0" assert isinstance(body["signature"], str) def test_admin_can_publish_update_and_download_installer(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) payload = b"installer bytes" published = client.post( "/admin/update/publish", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={ "csrf_token": "csrf-token", "version": "3.3.4", "notes": "smoke", "force": "1", }, files={"installer": ("DouyinGuaji-3.3.4-Setup.exe", payload, "application/octet-stream")}, ) manifest = client.get("/api/v1/update/manifest") body = manifest.json() download = client.get("/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe") assert published.status_code == 200 assert "已发布更新 V3.3.4" in published.text assert manifest.status_code == 200 assert body["enabled"] is True assert body["version"] == "3.3.4" assert body["sha256"] assert body["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe") assert isinstance(body["signature"], str) assert download.status_code == 200 assert download.content == payload def test_admin_publish_update_rejects_oversized_upload(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setenv("DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB", "1") service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) payload = b"x" * (1024 * 1024 + 1) published = client.post( "/admin/update/publish", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={ "csrf_token": "csrf-token", "version": "3.3.4", "notes": "oversized", "force": "1", }, files={"installer": ("DouyinGuaji-3.3.4-Setup.exe", payload, "application/octet-stream")}, ) manifest = client.get("/api/v1/update/manifest").json() assert published.status_code == 200 assert "超过大小限制" in published.text assert manifest["enabled"] is False def test_admin_can_publish_delta_update_and_download_zip(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) installer_payload = b"installer bytes" delta_payload = b"zip bytes" client.post( "/admin/update/publish", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={ "csrf_token": "csrf-token", "version": "3.3.6", "notes": "smoke", "force": "1", }, files={"installer": ("DouyinGuaji-3.3.6-Setup.exe", installer_payload, "application/octet-stream")}, ) published_delta = client.post( "/admin/update/publish-delta", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={ "csrf_token": "csrf-token", "from_version": "3.3.5", "to_version": "3.3.6", }, files={"delta_file": ("DouyinGuaji-3.3.5_to_3.3.6_delta.zip", delta_payload, "application/zip")}, ) manifest = client.get("/api/v1/update/manifest").json() download = client.get("/api/v1/update/download/DouyinGuaji-3.3.5_to_3.3.6_delta.zip") assert published_delta.status_code == 200 assert "已发布差量更新 3.3.5 -> 3.3.6" in published_delta.text assert manifest["delta"]["from_version"] == "3.3.5" assert manifest["delta"]["to_version"] == "3.3.6" assert manifest["delta"]["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.5_to_3.3.6_delta.zip") assert manifest["delta"]["sha256"] == hashlib.sha256(delta_payload).hexdigest() assert isinstance(manifest["signature"], str) assert download.status_code == 200 assert download.content == delta_payload def test_admin_can_publish_multiple_cumulative_delta_updates(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) client.post( "/admin/update/publish", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={"csrf_token": "csrf-token", "version": "3.3.9", "notes": "", "force": "1"}, files={"installer": ("DouyinGuaji-3.3.9-Setup.exe", b"installer", "application/octet-stream")}, ) for from_version, payload in [("3.3.7", b"delta37"), ("3.3.8", b"delta38")]: resp = client.post( "/admin/update/publish-delta", cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"}, data={"csrf_token": "csrf-token", "from_version": from_version, "to_version": "3.3.9"}, files={"delta_file": (f"DouyinGuaji-{from_version}_to_3.3.9_delta.zip", payload, "application/zip")}, ) assert resp.status_code == 200 manifest = client.get("/api/v1/update/manifest").json() deltas = manifest["delta"] assert isinstance(deltas, list) assert [item["from_version"] for item in deltas] == ["3.3.7", "3.3.8"] assert deltas[0]["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.7_to_3.3.9_delta.zip") download = client.get("/api/v1/update/download/DouyinGuaji-3.3.7_to_3.3.9_delta.zip") assert download.status_code == 200 assert download.content == b"delta37" def test_license_server_rejects_untrusted_host(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service), base_url="https://evil.example") resp = client.get("/api/v1/health") assert resp.status_code == 400 def test_public_https_base_url_enables_secure_admin_cookies(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setenv("DYGJ_LICENSE_PUBLIC_BASE_URL", "https://dy.absfan.cn") service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient( api.create_app(service=service, admin_token="secret"), base_url="https://dy.absfan.cn", ) login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) assert login.status_code == 303 assert "secure" in login.headers["set-cookie"].lower() def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) active = service.create_cards(days=5, count=1, customer="active-user")[0] revoked = service.create_cards(days=2, count=1, customer="revoked-user")[0] service.activate(active.code, machine_fingerprint="machine-a") service.revoke(revoked.code) client = TestClient(api.create_app(service=service, admin_token="secret")) login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) resp = client.get("/admin") assert login.status_code == 303 assert resp.status_code == 200 body = resp.text assert "总卡密" in body assert "活跃卡密" in body assert "已绑定设备" in body assert "active-user" in body assert "revoked-user" in body assert "最近审计日志" in body assert "activate" in body assert "revoke" in body def test_admin_query_token_is_rejected(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) resp = client.get("/admin?token=secret", follow_redirects=False) assert resp.status_code == 303 assert resp.headers["location"] == "/admin/login" def test_admin_create_requires_csrf(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) resp = client.post( "/admin/create", data={"days": "8", "count": "1", "customer": "web-admin"}, ) assert resp.status_code == 200 assert "CSRF 校验失败" in resp.text def test_admin_login_rejects_wrong_token(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) resp = client.post("/admin/login", data={"admin_token": "wrong"}) assert resp.status_code == 403 assert "管理员 token 不正确" in resp.text def test_admin_login_is_rate_limited(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setattr(api, "ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS", 2) service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) for _ in range(2): assert client.post("/admin/login", data={"admin_token": "wrong"}).status_code == 403 limited = client.post("/admin/login", data={"admin_token": "wrong"}) assert limited.status_code == 429 assert "登录尝试过于频繁" in limited.text def test_license_server_secure_defaults_and_forwarded_for_policy(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setattr(api, "RATE_LIMIT_MAX_REQUESTS", 1) service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) assert client.get("/docs").status_code == 404 first = client.post( "/api/v1/activate", headers={"x-forwarded-for": "198.51.100.1"}, json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"}, ) second = client.post( "/api/v1/activate", headers={"x-forwarded-for": "198.51.100.2"}, json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"}, ) assert first.status_code == 404 assert second.status_code == 429 def test_license_server_can_enable_secure_admin_cookies(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setenv("DYGJ_LICENSE_SECURE_COOKIES", "1") service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient( api.create_app(service=service, admin_token="secret"), base_url="https://testserver", ) login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) csrf = client.get("/admin") assert "secure" in login.headers["set-cookie"].lower() assert "secure" in csrf.headers["set-cookie"].lower() def test_admin_logout_clears_session(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service, admin_token="secret")) client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False) assert client.get("/admin").status_code == 200 logout = client.post("/admin/logout", follow_redirects=False) after = client.get("/admin", follow_redirects=False) assert logout.status_code == 303 assert after.status_code == 303 assert after.headers["location"] == "/admin/login" def test_api_rate_limits_repeated_failed_activation(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setattr(api, "RATE_LIMIT_MAX_REQUESTS", 2) service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service)) for _ in range(2): assert client.post( "/api/v1/activate", json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"}, ).status_code == 404 limited = client.post( "/api/v1/activate", json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"}, ) assert limited.status_code == 429 assert limited.json()["reason"] == "rate_limited" def test_external_redeem_create_requires_bearer_token(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient( api.create_app(service=service, external_api_token="external-secret"), base_url="https://dy.absfan.cn", ) resp = client.post( "/api/v1/redeem/external/create", json={ "platform": "xianyu", "external_order_id": "ORDER-1", "customer": "buyer-a", "days": 30, "max_devices": 1, }, ) assert resp.status_code == 403 assert resp.json()["reason"] == "forbidden" def test_external_redeem_create_returns_claim_url_without_card_key(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient( api.create_app(service=service, external_api_token="external-secret"), base_url="https://dy.absfan.cn", ) resp = client.post( "/api/v1/redeem/external/create", headers={"authorization": "Bearer external-secret"}, json={ "platform": "xianyu", "external_order_id": "ORDER-1", "customer": "buyer-a", "days": 30, "max_devices": 1, }, ) body = resp.json() assert resp.status_code == 200 assert body["ok"] is True assert body["claim_url"].startswith("https://dy.absfan.cn/redeem#") assert "card_key" not in body assert service.stats()["total"] == 0 def test_redeem_claim_exchanges_token_for_card_once(tmp_path): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) token = service.create_redeem_token( days=30, max_devices=1, customer="buyer-a", platform="xianyu", external_order_id="ORDER-1", ) client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn") first = client.post("/api/v1/redeem/claim", json={"token": token.token}) second = client.post("/api/v1/redeem/claim", json={"token": token.token}) assert first.status_code == 200 assert first.json()["ok"] is True assert first.json()["card_key"].startswith("DG-") assert second.status_code == 409 assert second.json()["reason"] == "already_redeemed" def test_redeem_claim_is_rate_limited(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setattr(api, "REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS", 2) service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn") for _ in range(2): assert client.post("/api/v1/redeem/claim", json={"token": "missing"}).status_code == 404 limited = client.post("/api/v1/redeem/claim", json={"token": "missing"}) assert limited.status_code == 429 assert limited.json()["reason"] == "rate_limited" def test_external_redeem_auth_failures_are_rate_limited(tmp_path, monkeypatch): from fastapi.testclient import TestClient from license_server import api from license_server.core import LicenseService from tests.license_test_keys import TEST_PRIVATE_KEY_PEM monkeypatch.setattr(api, "EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS", 2) service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM) client = TestClient( api.create_app(service=service, external_api_token="external-secret"), base_url="https://dy.absfan.cn", ) for _ in range(2): assert client.post( "/api/v1/redeem/external/create", json={"days": 1}, ).status_code == 403 limited = client.post( "/api/v1/redeem/external/create", json={"days": 1}, ) assert limited.status_code == 429 assert limited.json()["reason"] == "rate_limited"