From d42067746c7c7992079d7255b0987a3765abee40 Mon Sep 17 00:00:00 2001 From: xiewenjun <88080888@163.com> Date: Tue, 13 Oct 2026 07:28:25 +0800 Subject: [PATCH] feat: add signed client upgrade policies Co-Authored-By: Craft Agent --- backend/internal/httpapi/business.go | 3 + .../internal/httpapi/integration_archive.go | 20 +- .../integration_assets/client/update-sdk.mjs | 73 ++ .../integration_assets/client/update_sdk.py | 182 ++++ .../httpapi/integration_assets/openapi.json | 800 +++++++++++++++++- .../httpapi/integration_assets/upgrade.md | 84 +- backend/internal/httpapi/integration_kit.go | 5 +- .../internal/httpapi/integration_kit_test.go | 10 +- backend/internal/httpapi/readiness.go | 2 +- backend/internal/httpapi/updates.go | 314 +++++++ backend/internal/httpapi/updates_test.go | 67 ++ .../000012_update_policies.down.sql | 1 + .../migrations/000012_update_policies.up.sql | 18 + backend/migrations/README.md | 2 + client/test-update-sdk.mjs | 37 + client/test_update_sdk.py | 72 ++ client/update-sdk.mjs | 73 ++ client/update_sdk.py | 182 ++++ client/upgrade-sdk-testing.md | 14 + docs/client-integration-center.md | 57 +- frontend/src/date-format.ts | 22 + frontend/src/releases-api.test.ts | 39 + frontend/src/releases-api.ts | 35 + frontend/src/views/ReleasesPanel.test.ts | 109 ++- frontend/src/views/ReleasesPanel.vue | 104 ++- 25 files changed, 2154 insertions(+), 171 deletions(-) create mode 100644 backend/internal/httpapi/integration_assets/client/update-sdk.mjs create mode 100644 backend/internal/httpapi/integration_assets/client/update_sdk.py create mode 100644 backend/internal/httpapi/updates.go create mode 100644 backend/internal/httpapi/updates_test.go create mode 100644 backend/migrations/000012_update_policies.down.sql create mode 100644 backend/migrations/000012_update_policies.up.sql create mode 100644 client/test-update-sdk.mjs create mode 100644 client/test_update_sdk.py create mode 100644 client/update-sdk.mjs create mode 100644 client/update_sdk.py create mode 100644 client/upgrade-sdk-testing.md create mode 100644 frontend/src/releases-api.test.ts create mode 100644 frontend/src/releases-api.ts diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go index 746edab..743a81a 100644 --- a/backend/internal/httpapi/business.go +++ b/backend/internal/httpapi/business.go @@ -60,6 +60,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { c.JSON(200, gin.H{"data": a.keyring}) }) api.POST("/instances/:instance_id/heartbeat", a.heartbeat) + api.POST("/instances/:instance_id/updates/check", a.checkUpdate) api.POST("/auth/logout", a.authenticated, a.logout) secured := api.Group("", a.authenticated) secured.GET("/me", a.me) @@ -98,6 +99,8 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { secured.POST("/products/:id/releases", a.createRelease) secured.GET("/products/:id/releases", a.listReleases) secured.GET("/releases", a.listReleases) + secured.GET("/products/:id/update-policies", a.listUpdatePolicies) + secured.PUT("/products/:id/update-policies", a.saveUpdatePolicy) api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease) secured.POST("/instances/:instance_id/freeze", a.freezeInstance) secured.POST("/licenses", a.issueLicense) diff --git a/backend/internal/httpapi/integration_archive.go b/backend/internal/httpapi/integration_archive.go index 8e481cd..d0bc9c8 100644 --- a/backend/internal/httpapi/integration_archive.go +++ b/backend/internal/httpapi/integration_archive.go @@ -17,6 +17,14 @@ import ( "github.com/gin-gonic/gin" ) +func mustReadClientAsset(name string) []byte { + content, err := integrationAssets.ReadFile("integration_assets/" + name) + if err != nil { + panic(err) + } + return content +} + func languageRequirements(language string) string { return map[string]string{ "python": "Python:使用 cryptography 的 ECDSA(SHA256) 和 httpx;base64 补齐填充后解码 DER;pytest 覆盖验签与状态机。密钥库通过可注入接口实现,禁止以硬编码加密密钥充当保护。", @@ -77,10 +85,12 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) { return } files := map[string][]byte{ - "README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json,将 prompt.md 提供给实现工程师。verification-keys.md 包含当前部署验签公钥,经可信渠道核对指纹后预置;test-vectors.json 使用随机测试密钥,绝不能导入生产。upgrade.md 说明当前可用下载能力和自动升级待建设的契约;当前支持实例门户版本查询与授权下载,尚无签名升级清单;按 upgrade.md 实现 UpdateClient 与安装适配器。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"), - "verification-keys.md": []byte(keys), - "prompt.md": []byte(kit.Prompt), - "test-vectors.json": vectors, + "README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json。client/update_sdk.py 和 client/update-sdk.mjs 是可运行的参考 SDK,覆盖 update-v1 验签、TTL、策略回滚、禁止重定向下载、长度/摘要校验和注入式安装器;不执行任意命令。prompt.md 可提供给实现工程师。verification-keys.md 包含当前部署验签公钥,经可信渠道核对指纹后预置;test-vectors.json 使用随机测试密钥,绝不能导入生产。\n"), + "verification-keys.md": []byte(keys), + "prompt.md": []byte(kit.Prompt), + "test-vectors.json": vectors, + "client/update_sdk.py": mustReadClientAsset("client/update_sdk.py"), + "client/update-sdk.mjs": mustReadClientAsset("client/update-sdk.mjs"), } for _, name := range []string{"protocol.md", "upgrade.md", "openapi.json"} { content, err := integrationAsset(name) @@ -92,7 +102,7 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) { } var buffer bytes.Buffer archive := zip.NewWriter(&buffer) - for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "verification-keys.md", "test-vectors.json"} { + for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "verification-keys.md", "test-vectors.json", "client/update_sdk.py", "client/update-sdk.mjs"} { file, err := archive.Create(name) if err == nil { _, err = file.Write(files[name]) diff --git a/backend/internal/httpapi/integration_assets/client/update-sdk.mjs b/backend/internal/httpapi/integration_assets/client/update-sdk.mjs new file mode 100644 index 0000000..b8e1101 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/client/update-sdk.mjs @@ -0,0 +1,73 @@ +import { createHash, createPublicKey, randomUUID, verify } from 'node:crypto'; +import { mkdir, rename, open, rm } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +export class UpdateError extends Error {} +const MAX_PACKAGE_BYTES = 64 * 1024 * 1024; +const REQUIRED = new Set(['version','instance_id','product_id','customer_id','current_version','platform','arch','channel','server_time','expires_at','policy_revision','policy_enabled','recommended_version','minimum_supported_version','enforce_after','mandatory','required_now','update_available','download_allowed','release_id','sha256','size_bytes','message']); +const instant = value => { if (typeof value !== 'string' || !value.endsWith('Z')) throw new UpdateError('invalid_time'); const n = Date.parse(value); if (!Number.isFinite(n)) throw new UpdateError('invalid_time'); return n; }; +const decode = value => { if (typeof value !== 'string' || !value || !/^[A-Za-z0-9+/]+$/.test(value)) throw new UpdateError('invalid_signature'); return Buffer.from(value, 'base64'); }; + +export function verifyCheck(envelope, publicKeys, expectedInstance, { now = Date.now(), previous = null, expectedPlatform = null, expectedArch = null, expectedChannel = null, expectedCurrentVersion = null } = {}) { + if (!envelope || typeof envelope.payload !== 'string' || typeof envelope.key_id !== 'string') throw new UpdateError('invalid_payload'); + let raw, p; try { raw = decode(envelope.payload); p = JSON.parse(raw.toString('utf8')); } catch { throw new UpdateError('invalid_payload'); } + if (!p || p.version !== 'update-v1' || p.instance_id !== expectedInstance || (expectedPlatform !== null && p.platform !== expectedPlatform) || (expectedArch !== null && p.arch !== expectedArch) || (expectedChannel !== null && p.channel !== expectedChannel) || (expectedCurrentVersion !== null && p.current_version !== expectedCurrentVersion) || REQUIRED.size !== Object.keys(p).length || [...REQUIRED].some(k => !(k in p))) throw new UpdateError('invalid_context'); + const pem = publicKeys[envelope.key_id]; if (!pem) throw new UpdateError('unknown_key'); + const key = createPublicKey(pem); if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') throw new UpdateError('invalid_key'); + if (!verify('sha256', raw, key, decode(envelope.signature))) throw new UpdateError('invalid_signature'); + const server = instant(p.server_time), expiry = instant(p.expires_at); + if (expiry <= now || expiry - server > 900000 || Math.abs(server - now) > 300000) throw new UpdateError('expired_or_clock_skew'); + if (!Number.isSafeInteger(p.policy_revision) || p.policy_revision < 0 || (previous && p.policy_revision < previous.policy_revision)) throw new UpdateError('policy_rollback'); + if (!Number.isSafeInteger(p.size_bytes) || p.size_bytes < 0 || !Number.isSafeInteger(p.release_id) || p.release_id < 0) throw new UpdateError('invalid_release'); + return { payload: p, signature: decode(envelope.signature) }; +} + +export class UpdateClient { + constructor({ baseUrl, instanceId, secret, publicKeys, state = null, fetchImpl = fetch, clock = () => Date.now() }) { + const u = new URL(baseUrl); if (u.protocol !== 'https:' || u.pathname !== '/' || u.search || u.hash) throw new Error('base_url_must_be_https_origin'); + this.baseUrl = u; this.instanceId = instanceId; this.secret = secret; this.publicKeys = publicKeys; this.state = state; this.fetch = fetchImpl; this.clock = clock; + } + scope(platform, arch, channel) { return JSON.stringify([this.instanceId, platform, arch, channel]); } + previous(platform, arch, channel) { + const stored = this.state?.load?.(); if (!stored) return null; + const key = this.scope(platform, arch, channel); + if (stored.scope === key) return stored; + return stored.scopes?.[key] ?? null; + } + async check(currentVersion, platform, arch, channel) { + const response = await this.fetch(new URL(`api/v1/instances/${this.instanceId}/updates/check`, this.baseUrl), { method: 'POST', redirect: 'error', headers: {'content-type':'application/json'}, body: JSON.stringify({secret:this.secret,current_version:currentVersion,platform,arch,channel}) }); + if (!response.ok) throw new UpdateError(`check_http_${response.status}`); + const result = verifyCheck((await response.json()).data, this.publicKeys, this.instanceId, { now: this.clock(), previous: this.previous(platform, arch, channel), expectedPlatform: platform, expectedArch: arch, expectedChannel: channel, expectedCurrentVersion: currentVersion }); + if (this.state) { + const scope = this.scope(platform, arch, channel); const stored = this.state.load?.() ?? {}; const scopes = { ...(stored.scopes ?? {}) }; + const entry = { scope, instance_id:this.instanceId, policy_revision:result.payload.policy_revision, server_time:result.payload.server_time, accepted_at:this.clock() }; + scopes[scope] = entry; this.state.saveAtomic?.({ ...entry, scopes }); + } + return result; + } + async download(result, destination, { signal = null, timeoutMs = 30000 } = {}) { + const p = result.payload; if (!p.download_allowed || !p.update_available || !p.release_id) throw new UpdateError('download_not_allowed'); + const controller = new AbortController(); const timer = setTimeout(() => controller.abort(new UpdateError('download_timeout')), timeoutMs); + const abort = () => controller.abort(signal.reason); if (signal) { if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once:true }); } + let response = null; + let tmp = null; + try { + if (!Number.isSafeInteger(p.size_bytes) || p.size_bytes < 0 || p.size_bytes > MAX_PACKAGE_BYTES) throw new UpdateError('package_too_large'); + response = await this.fetch(new URL(`api/v1/customers/${p.customer_id}/releases/${p.release_id}/download`, this.baseUrl), { method:'POST', redirect:'error', signal:controller.signal, headers:{'content-type':'application/json'}, body:JSON.stringify({instance_id:this.instanceId,secret:this.secret}) }); + if (response.status !== 200) throw new UpdateError(`download_http_${response.status}`); + await mkdir(dirname(destination), { recursive:true }); tmp = `${destination}.tmp-${randomUUID()}`; let total = 0; const hash = createHash('sha256'); + const file = await open(tmp, 'wx'); + try { + for await (const chunk of response.body) { total += chunk.length; if (total > p.size_bytes || total > MAX_PACKAGE_BYTES) throw new UpdateError('package_too_large'); hash.update(chunk); await file.write(chunk); } + } finally { await file.close(); } + if (total !== p.size_bytes || hash.digest('hex').toLowerCase() !== p.sha256.toLowerCase()) throw new UpdateError('package_integrity_failed'); + await rename(tmp, destination); tmp = null; return destination; + } catch (error) { + controller.abort(); + try { await response?.body?.cancel?.(); } catch {} + if (tmp) await rm(tmp, { force:true }); + throw error; + } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); } + } + install(packagePath, installer) { return installer(packagePath); } +} diff --git a/backend/internal/httpapi/integration_assets/client/update_sdk.py b/backend/internal/httpapi/integration_assets/client/update_sdk.py new file mode 100644 index 0000000..7007808 --- /dev/null +++ b/backend/internal/httpapi/integration_assets/client/update_sdk.py @@ -0,0 +1,182 @@ +"""Reference client for the signed update-v1 contract. + +Requires Python 3.11 and the ``cryptography`` package. No installer is executed +by this module; callers inject an installer after verification. +""" +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import tempfile +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Callable, Mapping, Protocol +from urllib.parse import urljoin, urlparse + +import httpx +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature + + +class UpdateError(Exception): + pass + + +MAX_PACKAGE_BYTES = 64 * 1024 * 1024 + + +class StateStore(Protocol): + def load(self) -> Mapping[str, object] | None: ... + def save_atomic(self, state: Mapping[str, object]) -> None: ... + + +@dataclass(frozen=True) +class UpdateResult: + payload: dict + signature: bytes + + +def _time(value: str) -> float: + if not isinstance(value, str) or not value.endswith("Z"): + raise UpdateError("invalid_time") + try: + return datetime.fromisoformat(value[:-1] + "+00:00").timestamp() + except ValueError as exc: + raise UpdateError("invalid_time") from exc + + +def _b64(value: object) -> bytes: + if not isinstance(value, str) or not value or any(c not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" for c in value) or ("=" in value and not value.endswith("=" * (len(value) - len(value.rstrip("="))))): + raise UpdateError("invalid_signature") + try: + return base64.b64decode(value + "=" * (-len(value) % 4), validate=True) + except ValueError as exc: + raise UpdateError("invalid_signature") from exc + + +def verify_check(envelope: Mapping[str, object], public_keys: Mapping[str, str], expected_instance: str, + now: float | None = None, previous: Mapping[str, object] | None = None, + expected_platform: str | None = None, expected_arch: str | None = None, + expected_channel: str | None = None, expected_current_version: str | None = None) -> UpdateResult: + encoded = envelope.get("payload") + raw = _b64(encoded) + try: + payload = raw.decode("utf-8") + data = json.loads(payload) + except (UnicodeError, json.JSONDecodeError) as exc: + raise UpdateError("invalid_payload") from exc + if not isinstance(data, dict) or data.get("version") != "update-v1": + raise UpdateError("unsupported_payload") + required = {"version", "instance_id", "product_id", "customer_id", "current_version", "platform", "arch", "channel", "server_time", "expires_at", "policy_revision", "policy_enabled", "recommended_version", "minimum_supported_version", "enforce_after", "mandatory", "required_now", "update_available", "download_allowed", "release_id", "sha256", "size_bytes", "message"} + if set(data) != required or data["instance_id"] != expected_instance or (expected_platform is not None and data["platform"] != expected_platform) or (expected_arch is not None and data["arch"] != expected_arch) or (expected_channel is not None and data["channel"] != expected_channel) or (expected_current_version is not None and data["current_version"] != expected_current_version): + raise UpdateError("invalid_context") + key_id = envelope.get("key_id") + if not isinstance(key_id, str) or key_id not in public_keys: + raise UpdateError("unknown_key") + signature = _b64(envelope.get("signature")) + try: + key = serialization.load_pem_public_key(public_keys[key_id].encode()) + if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1): + raise ValueError + key.verify(signature, raw, ec.ECDSA(hashes.SHA256())) + except Exception as exc: + raise UpdateError("invalid_signature") from exc + current = time.time() if now is None else now + server, expires = _time(data["server_time"]), _time(data["expires_at"]) + if expires <= current or expires - server > 900 or server - current > 300 or current - server > 300: + raise UpdateError("expired_or_clock_skew") + if not isinstance(data["policy_revision"], int) or data["policy_revision"] < 0: + raise UpdateError("invalid_revision") + if previous and data["policy_revision"] < int(previous.get("policy_revision", 0)): + raise UpdateError("policy_rollback") + if data["size_bytes"] < 0 or (data["release_id"] == 0 and data["update_available"]): + raise UpdateError("invalid_release") + return UpdateResult(data, signature) + + +class UpdateClient: + def __init__(self, base_url: str, instance_id: str, secret: str, public_keys: Mapping[str, str], + state: StateStore | None = None, client: httpx.Client | None = None): + parsed = urlparse(base_url) + if parsed.scheme != "https" or parsed.query or parsed.fragment or parsed.path.rstrip("/"): + raise ValueError("base_url_must_be_https_origin") + self.base_url, self.instance_id, self.secret, self.public_keys = base_url.rstrip("/") + "/", instance_id, secret, public_keys + self.state, self.client = state, client or httpx.Client(follow_redirects=False, timeout=30) + + def _scope(self, platform: str, arch: str, channel: str) -> str: + return json.dumps([self.instance_id, platform, arch, channel], separators=(",", ":")) + + def _scoped_previous(self, platform: str, arch: str, channel: str) -> Mapping[str, object] | None: + if not self.state: + return None + stored = self.state.load() + if not stored: + return None + if stored.get("scope") == self._scope(platform, arch, channel): + return stored + scopes = stored.get("scopes") + if isinstance(scopes, Mapping): + value = scopes.get(self._scope(platform, arch, channel)) + return value if isinstance(value, Mapping) else None + return None + + def check(self, current_version: str, platform: str, arch: str, channel: str) -> UpdateResult: + response = self.client.post(urljoin(self.base_url, f"api/v1/instances/{self.instance_id}/updates/check"), json={"secret": self.secret, "current_version": current_version, "platform": platform, "arch": arch, "channel": channel}, follow_redirects=False, timeout=30) + if response.status_code != 200: + raise UpdateError(f"check_http_{response.status_code}") + envelope = response.json().get("data") + if not isinstance(envelope, dict): + raise UpdateError("invalid_response") + previous = self._scoped_previous(platform, arch, channel) + result = verify_check(envelope, self.public_keys, self.instance_id, previous=previous, expected_platform=platform, expected_arch=arch, expected_channel=channel, expected_current_version=current_version) + if self.state: + scope = self._scope(platform, arch, channel) + stored = self.state.load() or {} + scopes = dict(stored.get("scopes", {})) if isinstance(stored.get("scopes"), Mapping) else {} + scopes[scope] = {"scope": scope, "instance_id": self.instance_id, "policy_revision": result.payload["policy_revision"], "server_time": result.payload["server_time"], "accepted_at": time.time()} + self.state.save_atomic({"scope": scope, "instance_id": self.instance_id, "policy_revision": result.payload["policy_revision"], "server_time": result.payload["server_time"], "accepted_at": time.time(), "scopes": scopes}) + return result + + def download(self, result: UpdateResult, destination: str | os.PathLike[str]) -> Path: + p = result.payload + if not p["download_allowed"] or not p["update_available"] or not p["release_id"]: + raise UpdateError("download_not_allowed") + url = urljoin(self.base_url, f"api/v1/customers/{p['customer_id']}/releases/{p['release_id']}/download") + expected = int(p["size_bytes"]) + if expected < 0 or expected > MAX_PACKAGE_BYTES: + raise UpdateError("package_too_large") + target = Path(destination) + target.parent.mkdir(parents=True, exist_ok=True) + temp = None + total = 0 + digest = hashlib.sha256() + try: + with self.client.stream("POST", url, json={"instance_id": self.instance_id, "secret": self.secret}, follow_redirects=False, timeout=httpx.Timeout(30, read=30)) as response: + if response.status_code != 200: + raise UpdateError(f"download_http_{response.status_code}") + with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + ".", delete=False) as tmp: + temp = Path(tmp.name) + for chunk in response.iter_bytes(): + if not chunk: + continue + total += len(chunk) + if total > expected or total > MAX_PACKAGE_BYTES: + raise UpdateError("package_too_large") + digest.update(chunk) + tmp.write(chunk) + if total != expected or digest.hexdigest().lower() != p["sha256"].lower(): + raise UpdateError("package_integrity_failed") + temp.replace(target) + return target + except Exception: + if temp is not None: + temp.unlink(missing_ok=True) + raise + + def install(self, package: Path, installer: Callable[[Path], object]) -> object: + return installer(package) diff --git a/backend/internal/httpapi/integration_assets/openapi.json b/backend/internal/httpapi/integration_assets/openapi.json index e256969..28061c6 100644 --- a/backend/internal/httpapi/integration_assets/openapi.json +++ b/backend/internal/httpapi/integration_assets/openapi.json @@ -1,44 +1,778 @@ { "openapi": "3.0.3", - "info": {"title": "License Platform Client API", "version": "1.0.0", "description": "Client-facing endpoints. Admin session is not a client credential. See protocol.md for canonical signature and trust-root rules."}, - "servers": [{"url": "https://license.example.com", "description": "Replace with deployed HTTPS origin"}], + "info": { + "title": "License Platform Client API", + "version": "1.1.0", + "description": "Client-facing instance APIs. Update checks return signed update-v1 metadata; admin sessions are never client credentials. See protocol.md for canonical signature and trust-root rules." + }, + "servers": [ + { + "url": "https://license.yihuiyong.cn", + "description": "Deployed HTTPS origin" + } + ], "paths": { - "/api/v1/portal/snapshot": {"post": {"summary": "实例凭据查询已发布版本与下载权限", "parameters": [{"in": "query", "name": "page", "schema": {"type": "integer", "minimum": 1}}, {"in": "query", "name": "page_size", "schema": {"type": "integer", "minimum": 1, "maximum": 100}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["instance_id", "secret"], "properties": {"instance_id": {"type": "string", "format": "uuid"}, "secret": {"type": "string"}}}}}}, "responses": {"200": {"description": "data 含 customer/product/license/instance/lease/releases,meta 为分页;版本项含 id/version/sha256/size_bytes/download_allowed,不是签名升级清单。"}, "403": {"description": "实例凭据无效"}, "503": {"description": "门户不可用"}}}}, - "/api/v1/activation/instances/{instance_id}": {"post": { - "operationId": "activateInstance", "summary": "Activate pre-provisioned instance", - "parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}], - "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["license_key", "secret"], "properties": {"license_key": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}}, - "responses": {"200": {"description": "Activation certificate; verify data.certificate before accepting", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"instance_id": {"type": "string"}, "status": {"type": "string", "enum": ["activated"]}, "certificate": {"$ref": "#/components/schemas/Certificate"}}}, "idempotent_replay": {"type": "boolean"}}}}}}, "default": {"$ref": "#/components/responses/Error"}} - }}, - "/api/v1/instances/{instance_id}/heartbeat": {"post": { - "operationId": "heartbeat", "summary": "Refresh signed runtime lease", - "parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}], - "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["secret", "client_time"], "properties": {"secret": {"type": "string", "format": "password"}, "client_time": {"type": "string", "format": "date-time"}}}}}}, - "responses": {"200": {"description": "Signed lease; HTTP 200 does not imply active state", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Lease"}}}}}}, "429": {"description": "Rate limited; respect Retry-After", "headers": {"Retry-After": {"schema": {"type": "string"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "default": {"$ref": "#/components/responses/Error"}} - }}, - "/api/v1/customers/{customer_id}/releases/{id}/download": {"post": { - "operationId": "downloadRelease", "summary": "Download entitled release; repeat credentials for Range retries", - "parameters": [{"name": "customer_id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "Range", "in": "header", "schema": {"type": "string"}}], - "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["instance_id", "secret"], "properties": {"instance_id": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}}, - "responses": {"200": {"description": "Full file (through configured download gateway)", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "206": {"description": "Partial file", "headers": {"Content-Range": {"schema": {"type": "string"}}}, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "416": {"description": "Unsatisfiable Range"}, "default": {"$ref": "#/components/responses/Error"}} - }}, - "/api/v1/activation/keyring": {"get": { - "operationId": "discoverKeyring", "summary": "Discovery only, NOT a trust-root bootstrap", - "responses": {"200": {"description": "Configured verification keys", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"current_key_id": {"type": "string"}, "keys": {"type": "array", "items": {"type": "object", "properties": {"key_id": {"type": "string"}, "public_key_pem": {"type": "string"}, "revoked": {"type": "boolean"}}}}}}}}}}}, "default": {"$ref": "#/components/responses/Error"}} - }} + "/api/v1/portal/snapshot": { + "post": { + "summary": "实例凭据查询已发布版本与下载权限", + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "in": "query", + "name": "page_size", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "instance_id", + "secret" + ], + "properties": { + "instance_id": { + "type": "string", + "format": "uuid" + }, + "secret": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "data 含 customer/product/license/instance/lease/releases,meta 为分页;版本项含 id/version/sha256/size_bytes/download_allowed,不是签名升级清单。" + }, + "403": { + "description": "实例凭据无效" + }, + "503": { + "description": "门户不可用" + } + } + } + }, + "/api/v1/activation/instances/{instance_id}": { + "post": { + "operationId": "activateInstance", + "summary": "Activate pre-provisioned instance", + "parameters": [ + { + "$ref": "#/components/parameters/InstanceID" + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "license_key", + "secret" + ], + "properties": { + "license_key": { + "type": "string" + }, + "secret": { + "type": "string", + "format": "password" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Activation certificate; verify data.certificate before accepting", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "instance_id": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "activated" + ] + }, + "certificate": { + "$ref": "#/components/schemas/Certificate" + } + } + }, + "idempotent_replay": { + "type": "boolean" + } + } + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + }, + "/api/v1/instances/{instance_id}/heartbeat": { + "post": { + "operationId": "heartbeat", + "summary": "Refresh signed runtime lease", + "parameters": [ + { + "$ref": "#/components/parameters/InstanceID" + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "secret", + "client_time" + ], + "properties": { + "secret": { + "type": "string", + "format": "password" + }, + "client_time": { + "type": "string", + "format": "date-time" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Signed lease; HTTP 200 does not imply active state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Lease" + } + } + } + } + } + }, + "429": { + "description": "Rate limited; respect Retry-After", + "headers": { + "Retry-After": { + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + }, + "/api/v1/customers/{customer_id}/releases/{id}/download": { + "post": { + "operationId": "downloadRelease", + "summary": "Download entitled release; repeat credentials for Range retries", + "parameters": [ + { + "name": "customer_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "Range", + "in": "header", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "instance_id", + "secret" + ], + "properties": { + "instance_id": { + "type": "string" + }, + "secret": { + "type": "string", + "format": "password" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Full file (through configured download gateway)", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "206": { + "description": "Partial file", + "headers": { + "Content-Range": { + "schema": { + "type": "string" + } + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "416": { + "description": "Unsatisfiable Range" + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + }, + "/api/v1/activation/keyring": { + "get": { + "operationId": "discoverKeyring", + "summary": "Discovery only, NOT a trust-root bootstrap", + "responses": { + "200": { + "description": "Configured verification keys", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "current_key_id": { + "type": "string" + }, + "keys": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key_id": { + "type": "string" + }, + "public_key_pem": { + "type": "string" + }, + "revoked": { + "type": "boolean" + } + } + } + } + } + } + } + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + }, + "/api/v1/instances/{instance_id}/updates/check": { + "post": { + "operationId": "checkForUpdate", + "summary": "返回实例绑定的签名 update-v1 策略与发布元数据", + "parameters": [ + { + "$ref": "#/components/parameters/InstanceID" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateCheckRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Signed envelope; verify raw decoded payload before use", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateCheckResponse" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + } }, "components": { "parameters": { - "InstanceID": {"name": "instance_id", "in": "path", "required": true, "schema": {"type": "string"}}, - "IdempotencyKey": {"name": "Idempotency-Key", "in": "header", "required": true, "schema": {"type": "string"}, "description": "Same key and unchanged body for retries of one operation; new key for a new operation"} + "InstanceID": { + "name": "instance_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + "IdempotencyKey": { + "name": "Idempotency-Key", + "in": "header", + "required": true, + "schema": { + "type": "string" + }, + "description": "Same key and unchanged body for retries of one operation; new key for a new operation" + } + }, + "responses": { + "Error": { + "description": "See error.code and HTTP status; never blindly retry conflicts", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } }, - "responses": {"Error": {"description": "See error.code and HTTP status; never blindly retry conflicts", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}, "schemas": { - "Error": {"type": "object", "properties": {"error": {"type": "object", "properties": {"code": {"type": "string"}, "message": {"type": "string"}}}}}, - "Certificate": {"type": "object", "required": ["version", "payload", "signature", "canonical_sha256"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "payload": {"$ref": "#/components/schemas/CertificatePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}}}, - "CertificatePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "license_id", "customer_id", "product_id", "starts_at", "expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "instance_id": {"type": "string"}, "license_id": {"type": "integer", "minimum": 1}, "customer_id": {"type": "integer", "minimum": 1}, "product_id": {"type": "integer", "minimum": 1}, "starts_at": {"type": "string", "format": "date-time"}, "expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}}, - "Lease": {"type": "object", "required": ["payload", "signature", "canonical_sha256", "algorithm", "next_heartbeat_seconds"], "properties": {"payload": {"$ref": "#/components/schemas/LeasePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}, "algorithm": {"type": "string", "enum": ["ECDSA-P256-SHA256"]}, "next_heartbeat_seconds": {"type": "integer", "minimum": 60}}}, - "LeasePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "state", "server_time", "entitlement_expires_at", "lease_expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["lease-v2"]}, "instance_id": {"type": "string"}, "state": {"type": "string", "enum": ["active", "frozen", "revoked", "expired", "not_started", "not_activated"]}, "server_time": {"type": "string", "format": "date-time"}, "entitlement_expires_at": {"type": "string", "format": "date-time"}, "lease_expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}} + "Error": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + } + }, + "Certificate": { + "type": "object", + "required": [ + "version", + "payload", + "signature", + "canonical_sha256" + ], + "properties": { + "version": { + "type": "string", + "enum": [ + "license-v2" + ] + }, + "payload": { + "$ref": "#/components/schemas/CertificatePayload" + }, + "signature": { + "type": "string", + "description": "ASN.1 DER ECDSA, unpadded standard Base64" + }, + "canonical_sha256": { + "type": "string" + } + } + }, + "CertificatePayload": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "instance_id", + "license_id", + "customer_id", + "product_id", + "starts_at", + "expires_at", + "key_id" + ], + "properties": { + "version": { + "type": "string", + "enum": [ + "license-v2" + ] + }, + "instance_id": { + "type": "string" + }, + "license_id": { + "type": "integer", + "minimum": 1 + }, + "customer_id": { + "type": "integer", + "minimum": 1 + }, + "product_id": { + "type": "integer", + "minimum": 1 + }, + "starts_at": { + "type": "string", + "format": "date-time" + }, + "expires_at": { + "type": "string", + "format": "date-time" + }, + "key_id": { + "type": "string" + } + } + }, + "Lease": { + "type": "object", + "required": [ + "payload", + "signature", + "canonical_sha256", + "algorithm", + "next_heartbeat_seconds" + ], + "properties": { + "payload": { + "$ref": "#/components/schemas/LeasePayload" + }, + "signature": { + "type": "string", + "description": "ASN.1 DER ECDSA, unpadded standard Base64" + }, + "canonical_sha256": { + "type": "string" + }, + "algorithm": { + "type": "string", + "enum": [ + "ECDSA-P256-SHA256" + ] + }, + "next_heartbeat_seconds": { + "type": "integer", + "minimum": 60 + } + } + }, + "LeasePayload": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "instance_id", + "state", + "server_time", + "entitlement_expires_at", + "lease_expires_at", + "key_id" + ], + "properties": { + "version": { + "type": "string", + "enum": [ + "lease-v2" + ] + }, + "instance_id": { + "type": "string" + }, + "state": { + "type": "string", + "enum": [ + "active", + "frozen", + "revoked", + "expired", + "not_started", + "not_activated" + ] + }, + "server_time": { + "type": "string", + "format": "date-time" + }, + "entitlement_expires_at": { + "type": "string", + "format": "date-time" + }, + "lease_expires_at": { + "type": "string", + "format": "date-time" + }, + "key_id": { + "type": "string" + } + } + }, + "UpdateCheckRequest": { + "type": "object", + "required": [ + "secret", + "current_version", + "platform", + "arch", + "channel" + ], + "properties": { + "secret": { + "type": "string", + "format": "password" + }, + "current_version": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "arch": { + "type": "string" + }, + "channel": { + "type": "string" + } + } + }, + "UpdateCheckResponse": { + "type": "object", + "required": [ + "data" + ], + "properties": { + "data": { + "$ref": "#/components/schemas/UpdateEnvelope" + } + } + }, + "UpdateEnvelope": { + "type": "object", + "required": [ + "payload", + "signature", + "key_id" + ], + "properties": { + "payload": { + "type": "string", + "description": "Standard Base64 of raw UTF-8 JSON update-v1 payload" + }, + "signature": { + "type": "string", + "description": "Unpadded standard Base64 DER ECDSA P-256 SHA-256 over decoded payload" + }, + "key_id": { + "type": "string" + } + } + }, + "UpdatePayload": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "instance_id", + "product_id", + "customer_id", + "current_version", + "platform", + "arch", + "channel", + "server_time", + "expires_at", + "policy_revision", + "policy_enabled", + "recommended_version", + "minimum_supported_version", + "enforce_after", + "mandatory", + "required_now", + "update_available", + "download_allowed", + "release_id", + "sha256", + "size_bytes", + "message" + ], + "properties": { + "version": { + "type": "string", + "enum": [ + "update-v1" + ] + }, + "instance_id": { + "type": "string" + }, + "product_id": { + "type": "integer" + }, + "customer_id": { + "type": "integer" + }, + "current_version": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "arch": { + "type": "string" + }, + "channel": { + "type": "string" + }, + "server_time": { + "type": "string", + "format": "date-time" + }, + "expires_at": { + "type": "string", + "format": "date-time" + }, + "policy_revision": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "policy_enabled": { + "type": "boolean" + }, + "recommended_version": { + "type": "string" + }, + "minimum_supported_version": { + "type": "string" + }, + "enforce_after": { + "type": "string", + "format": "date-time" + }, + "mandatory": { + "type": "boolean" + }, + "required_now": { + "type": "boolean" + }, + "update_available": { + "type": "boolean" + }, + "download_allowed": { + "type": "boolean" + }, + "release_id": { + "type": "integer", + "minimum": 0 + }, + "sha256": { + "type": "string" + }, + "size_bytes": { + "type": "integer", + "minimum": 0 + }, + "message": { + "type": "string" + } + } + } } } } diff --git a/backend/internal/httpapi/integration_assets/upgrade.md b/backend/internal/httpapi/integration_assets/upgrade.md index 5bff04d..db1abc4 100644 --- a/backend/internal/httpapi/integration_assets/upgrade.md +++ b/backend/internal/httpapi/integration_assets/upgrade.md @@ -1,85 +1,33 @@ -# 客户端升级方案 +# 客户端升级契约(update-v1) ## 当前能力与实施边界 -默认平台根地址:https://license.example.com,可由 LICENSE_API_BASE_URL 覆盖。 +服务端提供签名升级检查、授权下载和策略决定;客户端仍须集成业务授权、安装器、健康检查和回滚。SDK 不执行任意命令,也不把升级结果当作业务许可。 -当前可用:后台按产品发布版本包,记录 version、sha256、size_bytes;客户端通过 POST /api/v1/customers/{customer_id}/releases/{release_id}/download,JSON 提交 instance_id、secret,获得当前有权访问的包。下载时检查实例归属、产品、客户、授权有效期及冻结/撤销状态,并写入下载审计。发布包当前上限 64 MiB。 +默认平台根地址:`https://license.yihuiyong.cn`,可由 `LICENSE_API_BASE_URL` 覆盖。客户端只使用实例凭据;管理员接口、管理员会话和 keyring 发现接口不得进入客户端。 -尚未实现:自动目标版本选择、签名升级清单、平台/架构/渠道匹配、灰度及强制升级策略、安装器、健康检查及升级结果回报。GET /api/v1/products/{id}/releases 是管理员接口,客户端不能使用管理员账号或会话调用它。release_id 不代表版本大小顺序,现有版本字符串不保证符合 SemVer。 +## 检查更新 -下载授权不等于代码可信。当前 X-Package-SHA256 可检测字节损坏,但它与包来自同一服务,不能替代独立签名。license-v2 / lease-v2 签名只证明授权和运行状态,不是升级包签名。当前实现不能宣称已支持安全无人值守自动升级。 +`POST /api/v1/instances/{instance_id}/updates/check` -## SDK 快速接入:版本查询与下载(现有接口) +请求 JSON:`{"secret":"...","current_version":"1.2.3","platform":"windows","arch":"amd64","channel":"stable"}`。 -SDK 复用已激活实例的受保护凭据,不使用管理员会话。Python、Go、Java、.NET 和 Node.js 接入提示词均要求实现以下流程。 +响应 `200` 的 `data` 是签名 envelope:`{"payload":"","signature":"","key_id":"current"}`。使用受控渠道预置的 P-256 公钥,验证 ECDSA SHA-256 对解码后的 raw bytes 签名。不得把服务端返回的 key 当作信任根。解码 JSON 必须严格包含 `version`、`instance_id`、`product_id`、`customer_id`、`current_version`、`platform`、`arch`、`channel`、`server_time`、`expires_at`、`policy_revision`、`policy_enabled`、`recommended_version`、`minimum_supported_version`、`enforce_after`、`mandatory`、`required_now`、`update_available`、`download_allowed`、`release_id`、`sha256`、`size_bytes`、`message`。 -1. `POST /api/v1/portal/snapshot?page=1&page_size=20`,JSON:`{"instance_id":"实例 UUID","secret":"实例密钥"}`。读取 `data.customer.id`、`data.product`、`data.releases` 和 `meta.total/page/page_size`。按分页查询,不能只检查第一页。版本项含 `id`、`version`、`sha256`、`size_bytes`、`download_allowed`。 -2. 按产品约定比较本地版本;只有明确约定 SemVer 时使用 SemVer。列表按记录 ID 倒序,ID 不代表版本优先级。目前无 OS/架构/渠道字段,多平台包需通过受控发布说明或用户选择匹配目标。 -3. 用户确认目标后,`POST /api/v1/customers/{data.customer.id}/releases/{release.id}/download`,提交相同 JSON 凭据。`download_allowed` 仅为快照,下载会重新鉴权。 -4. 同源 HTTPS 流式下载至临时文件,校验实际长度、SHA-256 和独立可信发布签名/平台代码签名。HTTP 200 不代表包完整;凭据不放 URL,不跨域转发。门户摘要不能单独建立发布信任。 -5. 独立安装器安装并验证实际版本与业务健康,失败回退;保留 instance_id、secret、证书和租约,不能覆盖授权状态目录。 +客户端必须核对实例上下文、服务端时间与当前时间偏差不超过 5 分钟、`expires_at` 未过期且不超过 `server_time + 15min`,并持久化拒绝 `policy_revision` 回退。`required_now` 只在签名验证、策略有效且本地版本比较确认低于最低支持版本后生效;`mandatory` 不能绕过用户/维护窗口、下载或包校验。`enforce_after` 为空表示无截止时间。 -SDK 建议接口(客户端约定,不是新增服务端 URL): +无策略或策略关闭时,服务端返回 `policy_enabled=false` 且 release 元数据为空/不可下载。`canRun` 不得把升级检查通过、`download_allowed` 或 active entitlement 当成授权许可;业务运行仍由独立、已验证的 license-v2/lease-v2 状态决定。 -- `UpdateClient.listReleases(page)`:返回分页版本、客户/产品信息与下载权限。 -- `UpdateClient.selectUpdate(currentVersion, releases, policy)`:可注入版本比较、平台选择与用户确认策略。 -- `UpdateClient.downloadRelease(release, destination)`:同源下载、超时、取消、文件大小限制,返回完整临时文件。 -- `UpdateClient.verifyPackage(file, release, trustedVerifier)`:校验长度、哈希与独立发布真实性。 -- `Installer.install(stagedPackage)`:注入桌面/服务/容器安装与回退适配器。未配置可信验证器或安装器时,只查询并提示,不自动执行。 +## 下载与安装边界 -交付业务调用示例,并覆盖分页、无更新、权限拒绝、损坏包、取消、安装失败回退及授权状态保留。客户端 SDK 源码和安装器仍需在目标工程实现;接入包提供可复用契约、协议和工程提示词。 +仅当签名 payload 的 `download_allowed=true`、`update_available=true` 且 `release_id>0` 时,调用 `POST /api/v1/customers/{customer_id}/releases/{release_id}/download`。正文包含 `instance_id` 和 `secret`。SDK 必须使用同源 HTTPS、禁止自动重定向,不把 secret 放 URL;流式写入同卷临时文件,验证实际长度等于 `size_bytes`、SHA-256 等于 payload `sha256`,再原子替换暂存目标。包 digest 是可信元数据绑定,但不是独立包签名;部署应再验证 Authenticode、代码签名、镜像签名或发布签名。 -## 第一阶段:受控人工升级(可复用现有下载接口) +SDK 只提供 check、download、摘要校验和注入式 Installer。安装器必须由应用提供,SDK 不执行 shell、脚本、包内命令或任意路径。安装前应锁定并发更新、检查磁盘和归档路径,失败保留旧版本并由应用健康检查/回滚。容器由 CI/CD 或受控部署代理升级,不覆盖自身程序。 -发布负责人通过受控渠道向客户端交付目标 release_id、产品、版本、OS/架构、包长度和 SHA-256,并提供独立可信的包签名或平台代码签名校验方式。客户端使用已有实例身份下载,管理员凭据不得进入客户端。没有独立可信的签名/摘要时,仅允许管理员人工验证来源后安装,不启用自动执行。 +## 离线、错误与 rollout 限制 -下载必须经过配置了 X-Accel-Redirect internal 文件路由的 Nginx。直接调用 Go API 可能只有授权响应头而没有包体,不能将 HTTP 200 当成下载成功。校验实际长度与可信摘要;下载路由是带 JSON 凭据的 POST,不是公开 GET URL。禁止跟随跨域重定向转发 secret。 +离线不能刷新检查结果或延长 15 分钟 envelope TTL;不能因检查失败伪造强制升级。有效 license lease 的离线运行按既有租约策略执行,过期或回拨必须 fail closed。网络错误、401/403、409、429 和 5xx 只允许有限重试,不把 HTTP 错误解释成策略。灰度由服务端策略决定,客户端不得自行伪造命中;当前协议不提供升级回报接口。策略 revision 是单调高水位,检测到回退立即拒绝。 -Range 续传依赖部署网关验证。每次续传仍发送 POST JSON 凭据;只有 206、Content-Range 起止与已下载偏移一致且总长度吻合时才能追加。若返回 200,截断临时文件重新下载,禁止追加完整响应。416 重新检查临时文件与目标版本。禁止让完整文件中的 HTTP 错误页进入安装流程。当前服务没有实现断点上传,下载续传能力须在实际网关验收。 +## 参考实现 -## 第二阶段:自动升级所需服务端契约(设计,尚未实现) - -建议新增实例认证的 POST /api/v1/instances/{instance_id}/updates/check。请求含 secret、product_id、current_version、current_release_sequence、platform、arch、channel、updater_version;服务端以实例关联产品为准,不信任客户端 product_id。返回无更新或已签名更新元数据。不得把这个设计地址当作现有接口调用,也不在当前 OpenAPI 中将其标记为可用。 - -签名元数据至少绑定 schema_version、product_id、release_id、release_sequence(产品/平台/架构/渠道范围内单调递增)、version、platform、arch、channel、package_format、size_bytes、sha256、published_at、expires_at、minimum_updater_version、minimum_supported_version、rollout_policy_version、mandatory、key_id 和 relative_download_path。relative_download_path 只能命中同源已有下载路由,不能是任意 URL。先验证签名、有效期、目标匹配、序号高水位和本地策略,再下载。 - -升级签名使用独立发布信任根与发布权限,不能直接复用授权签名私钥。优先采用成熟 TUF 实现,覆盖 root/targets/snapshot/timestamp、阈值签名、密钥轮换、元数据过期和版本一致性;平台代码签名作为额外校验。若另行实现简化签名,必须先冻结规范化字节、算法、key_id、信任根更新规则和跨语言向量,不能对 JSON 序列化输出随意签名。 - -升级清单中的 mandatory 只在完成真实性校验后才生效。离线时不因无法检查更新而立即阻断业务;运行权限仍由已验证授权租约决定。需要安全强制升级时,明确经过签名的最低支持版本、执行宽限期、离线策略和应急恢复流程。HTTP 错误不能被解释为可信的强制升级命令。 - -发布数据需要新增平台/架构/渠道、单调发布序号、签名清单、发布状态及灰度策略。稳定灰度分桶使用实例 ID 与服务端活动盐计算哈希,不使用每次随机命中。检查结果不能仅用时间戳或字符串比较决定版本,SemVer 要定义预发布版本与构建号规则。升级回报建议新增实例认证 POST /api/v1/instances/{instance_id}/updates/report,包含 attempt_id、from/to、阶段、结果和脱敏错误码,重复回报幂等;不能伪造尚未采集的成功率。 - -## 客户端状态机 - -空闲 → 检查 → 验证清单 → 等待批准/维护窗口 → 下载到临时目录 → 校验长度/哈希/签名 → 暂存 → 停止业务并安装 → 启动与健康检查 → 确认成功。 - -失败时保留可运行旧版本,记录失败版本和原因并进入退避,避免反复安装同一坏版本。为每次升级生成 attempt_id;使用跨进程锁防止多个更新器同时安装。网络重试不等于安装重试。持久化阶段日志,重启后能识别下载中、切换中、待确认和回滚状态。 - -健康失败触发回滚:停止新版本,切回最近一次已验证的健康版本,恢复兼容配置并重新启动。防回滚高水位仍保留,不接受远端下发更旧版本;本地故障回退只允许事务中保留的上一健康版本。服务端紧急恢复应发布更高序号的恢复版本,不能悄悄降低序号。 - -安装前检查磁盘(新包、解压、旧版本和备份所需空间)、权限、进程占用和路径。解压拒绝绝对路径、..、符号链接/硬链接越界及解压炸弹,设置文件数和解压总量上限。跨卷 rename 不保证原子,暂存与目标放在同卷;文件替换、目录切换和日志持久化必须按 OS 验证断电恢复。实例 ID、secret、授权证书与租约存于独立受保护状态目录,升级不可重新初始化或随包覆盖。 - -数据库迁移采用先兼容旧版本的 expand,再切换代码,最后在回退窗口结束后 contract。不能回滚数据库的升级禁止宣称一键自动回退;先备份并验证恢复方案。新程序健康检查包括启动、版本确认、关键业务和本地状态可读,不能只验证进程存活。 - -## 桌面客户端 - -使用独立更新器或安装器,主程序完成下载校验后提示用户保存工作,退出并等待进程结束,再由更新器安装。Windows 文件占用时不能让程序直接覆盖自己的 EXE;验证 Authenticode/安装包签名,并限制提权。macOS 验证 Developer ID、代码签名及公证,Linux 验证发布签名。启动新版本并握手确认实际运行版本与健康状态;失败恢复旧版本。自动下载和自动安装分别由用户策略控制。 - -## 常驻服务 - -由独立 supervisor、systemd 或 Windows Service 管理更新。使用版本目录与可恢复的入口切换,先摘流量、等待在途任务结束,再停止、切换、启动、探活。集群滚动更新限制并发与不可用实例数;严格约定任务幂等及共享存储兼容性。更新器权限最小化,维护窗口决定安装时机。安装失败优先恢复旧实例提供服务。 - -## 容器部署 - -容器内应用不得下载包覆盖自身程序,不挂载 Docker socket 给业务容器。升级由 CI/CD、Kubernetes 或受控部署代理执行;固定镜像 digest,验镜像签名/来源并使用 registry 凭据。先 readiness 再滚动替换,保留旧 digest、配置及持久化状态以便回退。现有二进制下载接口不是容器镜像仓库;镜像发布、灰度与部署回报是另行建设的能力。实例身份与 secret 由独立卷/Secret 注入,副本身份规则需要显式定义。 - -## 错误和重试策略 - -403:无下载权限,暂停此次升级并检查授权,不自动删除已验证运行租约。409:检查状态冲突,人工或业务决策后再尝试。429:遵守 Retry-After。网络/5xx:有限次数指数退避加抖动,不泄露 secret。签名、长度、哈希、架构或发布序号失败:立即丢弃暂存包并禁止安装;当前健康版本继续按照授权租约规则运行。取消和超时不覆盖当前版本。 - -## 验收清单 - -覆盖:完整升级;无更新;错误产品/OS/架构/渠道;损坏包与签名篡改;未知/撤销发布密钥;过期元数据;旧序号重放;网络中断及 200/206/416 续传;无 Nginx 包体;磁盘不足;恶意解压路径;并发更新锁;进程占用;安装中断电恢复;新版本探活失败与本地回退;数据库不兼容阻止安装;升级后 instance_id/secret/租约保留;冻结/撤销阻止新下载;回报幂等与日志脱敏。容器另验固定 digest、验签、滚动健康与恢复旧 digest。 - -接入团队交付 UpdateClient、受控包验证器、独立安装器/部署适配器、持久化升级状态及跨进程锁、健康与回退策略、上述负向测试。第一阶段只对现有下载接口实现适配;第二阶段契约完成前,版本发现和签名元数据通过可注入接口模拟,明确标记待接平台,不得伪装成生产可调用 API。 +仓库提供 `client/update_sdk.py`(Python 3.11 + cryptography)和 `client/update-sdk.mjs`(Node.js 20+,内置 crypto/fetch),包含验签、上下文/TTL/回滚检查、禁止重定向的下载、长度与摘要校验及注入安装器。其它语言应按同一 raw payload、DER ECDSA、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。 diff --git a/backend/internal/httpapi/integration_kit.go b/backend/internal/httpapi/integration_kit.go index d63b8b4..d9ca19c 100644 --- a/backend/internal/httpapi/integration_kit.go +++ b/backend/internal/httpapi/integration_kit.go @@ -86,6 +86,7 @@ func buildIntegrationKit(language, mode string) integrationKitResponse { Mode: mode, ModeLabel: modeLabel, Endpoints: []kitAPI{ + {Method: "POST", Path: "/api/v1/instances/{instance_id}/updates/check", Purpose: "提交 secret、current_version、platform、arch、channel,验证签名 update-v1 策略"}, {Method: "POST", Path: "/api/v1/portal/snapshot", Purpose: "提交 instance_id、secret,查询已发布版本、客户 ID 与下载权限"}, {Method: "POST", Path: "/api/v1/activation/instances/{instance_id}", Purpose: "首次激活,提交 license_key、secret 和 Idempotency-Key"}, {Method: "POST", Path: "/api/v1/instances/{instance_id}/heartbeat", Purpose: "刷新已签名运行租约,提交 secret、client_time 和 Idempotency-Key"}, @@ -95,13 +96,13 @@ func buildIntegrationKit(language, mode string) integrationKitResponse { "仅信任随软件或受控部署渠道固定分发的 P-256 公钥;不得将 keyring 发现接口作为信任根。", "secret 只可放在系统密钥库、Vault、Docker/Kubernetes Secret 或受限加密文件中;不得进入 URL、日志、镜像、源码或浏览器 LocalStorage。", "每次网络重试复用同一 Idempotency-Key;新的业务操作必须生成新的键。", - "验签后核对 version、key_id、instance_id、state、授权到期和租约到期;仅 active 且未到期时可执行业务。", + "验签后核对 version、key_id、instance_id、策略 revision、server_time/expires_at 和本地版本;required_now 仍须按可信时间/过期及本地版本再次判断。", "保存服务端时间与本地时间高水位,拒绝显著回拨;正常心跳最短 60 秒,租约最长 14 天。", "403/409 进入不可用或人工处理状态;429 遵循 Retry-After;不得无限自动重试。", }, Protocol: string(protocol), Upgrade: string(upgrade), - Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md、upgrade.md 与 openapi.json。签名规范化不是 JSON:固定顺序 key=value、LF 连接、UTF-8、无末尾换行;签名是 DER ECDSA 的无填充标准 Base64。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。\n\n客户端升级:实现 UpdateClient.listReleases(page)、selectUpdate、downloadRelease、verifyPackage 和可注入 Installer。通过 POST /api/v1/portal/snapshot 提交 instance_id、secret,读取 data.customer.id、data.releases 与 meta 分页,再调用实例认证下载接口。按 upgrade.md 完成版本比较、用户确认、同源流式下载、长度/摘要/独立签名验证、安装与失败回退,保留授权状态。门户不是签名升级清单;平台/架构匹配、灰度及回报未实现,禁止伪造 API 或自动执行未验证包。", + Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md、upgrade.md 与 openapi.json。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。\n\n客户端升级:优先调用 POST /api/v1/instances/{instance_id}/updates/check,解码 payload Base64 原始 JSON 并验证 update-v1 签名、上下文、15 分钟 TTL、策略 revision 回滚和 required_now 的可信时间/本地版本条件,再调用同源实例下载接口校验长度与 SHA-256。使用可注入 Installer,不执行任意命令;disabled 或检查成功不得替代 canRun 的 license-v2/lease-v2 授权判断。参考源码为 client/update_sdk.py 与 client/update-sdk.mjs,按 upgrade.md 覆盖篡改、上下文、deadline、hash、离线和回退。", TestVector: kitVector{ Version: "lease-v2", InstanceID: "11111111-2222-3333-4444-555555555555", State: "active", ServerTime: "2026-10-09T03:00:00Z", EntitlementExpiresAt: "2027-10-09T03:00:00Z", LeaseExpiresAt: "2026-10-23T03:00:00Z", diff --git a/backend/internal/httpapi/integration_kit_test.go b/backend/internal/httpapi/integration_kit_test.go index 6299128..2fbf489 100644 --- a/backend/internal/httpapi/integration_kit_test.go +++ b/backend/internal/httpapi/integration_kit_test.go @@ -40,7 +40,7 @@ func TestIntegrationInputs(t *testing.T) { } for language := range integrationLanguages { kit := buildIntegrationKit(language, "service") - if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") || !strings.Contains(kit.Upgrade, "当前能力与实施边界") || !strings.Contains(kit.Prompt, "UpdateClient.listReleases") || !strings.Contains(kit.Upgrade, "/api/v1/portal/snapshot") { + if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") || !strings.Contains(kit.Prompt, "update-v1") || !strings.Contains(kit.Upgrade, "required_now") { t.Fatal("incomplete kit") } } @@ -63,7 +63,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) { mc, _ := gin.CreateTestContext(md) mc.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil) a.downloadIntegrationKit(mc) - if !strings.Contains(md.Body.String(), "SDK 快速接入") || !strings.Contains(md.Body.String(), "UpdateClient.listReleases") || md.Code != 200 || !strings.Contains(md.Body.String(), public) || !strings.Contains(md.Body.String(), "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562") || strings.Contains(md.Body.String(), "retired") || md.Header().Get("Cache-Control") != "no-store" { + if !strings.Contains(md.Body.String(), "update-v1") || !strings.Contains(md.Body.String(), "required_now") || md.Code != 200 || !strings.Contains(md.Body.String(), public) || !strings.Contains(md.Body.String(), "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562") || strings.Contains(md.Body.String(), "retired") || md.Header().Get("Cache-Control") != "no-store" { t.Fatal("markdown lacks trusted deployment key") } w := httptest.NewRecorder() @@ -77,7 +77,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) { if err != nil { t.Fatal(err) } - if len(archive.File) != 7 { + if len(archive.File) != 9 { t.Fatal("missing files") } for _, file := range archive.File { @@ -96,9 +96,11 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) { if file.Name == "verification-keys.md" && (!strings.Contains(string(content), public) || strings.Contains(string(content), "retired")) { t.Fatal("incorrect deployment key in archive") } - if file.Name == "upgrade.md" && !strings.Contains(string(content), "自动升级所需服务端契约") { + if file.Name == "upgrade.md" && (!strings.Contains(string(content), "update-v1") || !strings.Contains(string(content), "required_now")) { t.Fatal("missing upgrade plan") } + if file.Name == "client/update_sdk.py" && !strings.Contains(string(content), "def verify_check") { t.Fatal("missing Python SDK") } + if file.Name == "client/update-sdk.mjs" && !strings.Contains(string(content), "verifyCheck") { t.Fatal("missing Node SDK") } if file.Name != "test-vectors.json" { continue } diff --git a/backend/internal/httpapi/readiness.go b/backend/internal/httpapi/readiness.go index bf7880c..40343a3 100644 --- a/backend/internal/httpapi/readiness.go +++ b/backend/internal/httpapi/readiness.go @@ -9,7 +9,7 @@ import ( "github.com/gin-gonic/gin" ) -const RequiredSchemaVersion = 11 +const RequiredSchemaVersion = 12 func RegisterReadiness(r *gin.Engine, db *sql.DB) { r.GET("/api/v1/health/ready", func(c *gin.Context) { diff --git a/backend/internal/httpapi/updates.go b/backend/internal/httpapi/updates.go new file mode 100644 index 0000000..7f54bd9 --- /dev/null +++ b/backend/internal/httpapi/updates.go @@ -0,0 +1,314 @@ +package httpapi + +import ( + "crypto/ecdsa" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/gin-gonic/gin" +) + +// Stable SemVer only. Existing arbitrary release labels remain valid for manual downloads. +var stableVersion = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`) + +func compareUpdateVersions(a, b string) (int, error) { + if len(a) > 64 || len(b) > 64 || !stableVersion.MatchString(a) || !stableVersion.MatchString(b) { + return 0, errors.New("version must be stable SemVer") + } + aa, bb := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < 3; i++ { + if len(aa[i]) < len(bb[i]) { + return -1, nil + } + if len(aa[i]) > len(bb[i]) { + return 1, nil + } + if aa[i] < bb[i] { + return -1, nil + } + if aa[i] > bb[i] { + return 1, nil + } + } + return 0, nil +} + +type UpdatePolicy struct { + ProductID uint64 `json:"product_id"` + Platform string `json:"platform"` + Arch string `json:"arch"` + Channel string `json:"channel"` + Enabled bool `json:"enabled"` + ReleaseID uint64 `json:"release_id"` + RecommendedVersion string `json:"recommended_version"` + MinimumSupportedVersion string `json:"minimum_supported_version"` + EnforceAfter string `json:"enforce_after"` + Message string `json:"message"` + Revision uint64 `json:"revision"` +} + +func updateScopeValid(platform, arch, channel string) bool { + return (platform == "windows" || platform == "linux" || platform == "macos") && (arch == "x64" || arch == "arm64") && (channel == "stable" || channel == "beta") +} + +const policySelect = `SELECT u.product_id,u.platform,u.arch,u.channel,u.enabled,u.release_id,r.version,u.minimum_supported_version,u.enforce_after,u.message,u.revision,r.sha256,r.size_bytes,r.published FROM product_update_policies u JOIN product_releases r ON r.id=u.release_id AND r.product_id=u.product_id` + +func scanUpdatePolicy(row interface{ Scan(...any) error }) (UpdatePolicy, string, uint64, bool, error) { + var p UpdatePolicy + var deadline sql.NullTime + var digest string + var size uint64 + var published bool + err := row.Scan(&p.ProductID, &p.Platform, &p.Arch, &p.Channel, &p.Enabled, &p.ReleaseID, &p.RecommendedVersion, &p.MinimumSupportedVersion, &deadline, &p.Message, &p.Revision, &digest, &size, &published) + if deadline.Valid { + p.EnforceAfter = deadline.Time.UTC().Format(time.RFC3339Nano) + } + return p, digest, size, published, err +} +func (a *BusinessAPI) listUpdatePolicies(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + apiError(c, 400, "invalid_request", "产品无效") + return + } + rows, err := a.db.QueryContext(c, policySelect+" WHERE u.product_id=? ORDER BY u.platform,u.arch,u.channel", id) + if err != nil { + apiError(c, 503, "updates_unavailable", "升级策略不可用") + return + } + defer rows.Close() + out := []UpdatePolicy{} + for rows.Next() { + p, _, _, _, err := scanUpdatePolicy(rows) + if err != nil { + apiError(c, 503, "updates_unavailable", "升级策略不可用") + return + } + out = append(out, p) + } + if rows.Err() != nil { + apiError(c, 503, "updates_unavailable", "升级策略不可用") + return + } + c.JSON(200, gin.H{"data": out}) +} +func (a *BusinessAPI) saveUpdatePolicy(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 8192) + var p UpdatePolicy + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 || c.ShouldBindJSON(&p) != nil || !updateScopeValid(p.Platform, p.Arch, p.Channel) || p.ReleaseID == 0 || utf8.RuneCountInString(p.Message) > 2000 { + apiError(c, 400, "invalid_request", "升级策略参数无效") + return + } + p.ProductID = id + var deadline any + if p.MinimumSupportedVersion != "" { + if _, err = compareUpdateVersions(p.MinimumSupportedVersion, p.MinimumSupportedVersion); err != nil { + apiError(c, 400, "invalid_version", "最低版本必须为 x.y.z") + return + } + t, e := time.Parse(time.RFC3339Nano, p.EnforceAfter) + if e != nil { + apiError(c, 400, "invalid_request", "强制升级必须设置生效时间") + return + } + deadline = t.UTC() + p.EnforceAfter = t.UTC().Format(time.RFC3339Nano) + } else if p.EnforceAfter != "" { + apiError(c, 400, "invalid_request", "没有最低版本时不能设置强制时间") + return + } + tx, err := a.db.BeginTx(c, nil) + if err != nil { + apiError(c, 503, "updates_unavailable", "保存失败") + return + } + defer tx.Rollback() + // Product lock serializes scope inserts and revision changes. + var locked uint64 + if err = tx.QueryRowContext(c, "SELECT id FROM products WHERE id=? FOR UPDATE", id).Scan(&locked); err != nil { + apiError(c, 404, "not_found", "产品不存在") + return + } + var published bool + if err = tx.QueryRowContext(c, "SELECT version,published FROM product_releases WHERE id=? AND product_id=? FOR UPDATE", p.ReleaseID, id).Scan(&p.RecommendedVersion, &published); err != nil || !published { + apiError(c, 400, "invalid_release", "请选择该产品已发布版本") + return + } + if _, err = compareUpdateVersions(p.RecommendedVersion, p.RecommendedVersion); err != nil { + apiError(c, 400, "invalid_version", "目标版本必须为 x.y.z") + return + } + if p.MinimumSupportedVersion != "" { + cmp, _ := compareUpdateVersions(p.MinimumSupportedVersion, p.RecommendedVersion) + if cmp > 0 { + apiError(c, 400, "invalid_version", "最低支持版本不能高于目标版本") + return + } + } + _, err = tx.ExecContext(c, `INSERT INTO product_update_policies(product_id,platform,arch,channel,enabled,release_id,minimum_supported_version,enforce_after,message,updated_by) VALUES(?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE enabled=VALUES(enabled),release_id=VALUES(release_id),minimum_supported_version=VALUES(minimum_supported_version),enforce_after=VALUES(enforce_after),message=VALUES(message),updated_by=VALUES(updated_by),revision=revision+1`, id, p.Platform, p.Arch, p.Channel, p.Enabled, p.ReleaseID, p.MinimumSupportedVersion, deadline, p.Message, c.GetUint64("admin_id")) + if err != nil { + apiError(c, 503, "updates_unavailable", "保存失败") + return + } + if err = tx.QueryRowContext(c, "SELECT revision FROM product_update_policies WHERE product_id=? AND platform=? AND arch=? AND channel=?", id, p.Platform, p.Arch, p.Channel).Scan(&p.Revision); err != nil { + apiError(c, 503, "updates_unavailable", "保存失败") + return + } + details, _ := json.Marshal(p) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'update_policy.saved','product',?,?)", c.GetUint64("admin_id"), id, details); err != nil { + apiError(c, 503, "audit_unavailable", "审计失败,策略未保存") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 503, "updates_unavailable", "保存失败") + return + } + c.JSON(200, gin.H{"data": p}) +} + +type UpdatePayload struct { + Version string `json:"version"` + InstanceID string `json:"instance_id"` + ProductID uint64 `json:"product_id"` + CustomerID uint64 `json:"customer_id"` + CurrentVersion string `json:"current_version"` + Platform string `json:"platform"` + Arch string `json:"arch"` + Channel string `json:"channel"` + ServerTime string `json:"server_time"` + ExpiresAt string `json:"expires_at"` + PolicyRevision uint64 `json:"policy_revision"` + PolicyEnabled bool `json:"policy_enabled"` + RecommendedVersion string `json:"recommended_version"` + MinimumSupportedVersion string `json:"minimum_supported_version"` + EnforceAfter string `json:"enforce_after"` + Mandatory bool `json:"mandatory"` + RequiredNow bool `json:"required_now"` + UpdateAvailable bool `json:"update_available"` + DownloadAllowed bool `json:"download_allowed"` + ReleaseID uint64 `json:"release_id"` + SHA256 string `json:"sha256"` + SizeBytes uint64 `json:"size_bytes"` + Message string `json:"message"` +} + +func evaluateUpdate(p UpdatePolicy, current string, now time.Time) (available, mandatory, required bool) { + if !p.Enabled { + return + } + cmp, err := compareUpdateVersions(current, p.RecommendedVersion) + available = err == nil && cmp < 0 + if p.MinimumSupportedVersion != "" { + cmp, err = compareUpdateVersions(current, p.MinimumSupportedVersion) + mandatory = err == nil && cmp < 0 + t, e := time.Parse(time.RFC3339Nano, p.EnforceAfter) + required = mandatory && e == nil && !now.Before(t) + } + return +} +func (a *BusinessAPI) checkUpdate(c *gin.Context) { + c.Header("Cache-Control", "private, no-store") + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096) + var in struct { + Secret string `json:"secret"` + CurrentVersion string `json:"current_version"` + Platform string `json:"platform"` + Arch string `json:"arch"` + Channel string `json:"channel"` + } + instance := c.Param("instance_id") + if len(instance) != 36 || c.ShouldBindJSON(&in) != nil || len(in.Secret) > 128 || !updateScopeValid(in.Platform, in.Arch, in.Channel) { + apiError(c, 400, "invalid_request", "升级检查参数无效") + return + } + if _, err := compareUpdateVersions(in.CurrentVersion, in.CurrentVersion); err != nil { + apiError(c, 400, "invalid_version", "当前版本必须为 x.y.z") + return + } + raw, err := base64.RawURLEncoding.DecodeString(in.Secret) + if err != nil || len(raw) != 32 { + apiError(c, 403, "forbidden", "实例凭据无效") + return + } + sum := sha256.Sum256(raw) + if a.keyring == nil { + apiError(c, 503, "keyring_unavailable", "升级签名不可用") + return + } + key, err := readSigningKey(a.signingPrivateKeyPEM) + if err != nil || a.keyring.Current == "" { + apiError(c, 503, "keyring_unavailable", "升级签名不可用") + return + } + tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead}) + if err != nil { + apiError(c, 503, "updates_unavailable", "升级检查不可用") + return + } + defer tx.Rollback() + var rowID, actor, owner, product uint64 + var stored []byte + var istate, freeze, lstate, cstate string + var active bool + var starts, ends, now time.Time + err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.secret_hash,i.status,i.freeze_state,l.status,c.status,p.active,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id AND l.customer_id=i.customer_id AND l.product_id=i.product_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=?`, instance).Scan(&rowID, &actor, &owner, &product, &stored, &istate, &freeze, &lstate, &cstate, &active, &starts, &ends) + if err == sql.ErrNoRows || (err == nil && !bytesEqual(stored, sum[:])) { + apiError(c, 403, "forbidden", "实例凭据无效") + return + } + if err != nil { + apiError(c, 503, "updates_unavailable", "升级检查不可用") + return + } + if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil { + apiError(c, 503, "updates_unavailable", "升级检查不可用") + return + } + p, digest, size, published, err := scanUpdatePolicy(tx.QueryRowContext(c, policySelect+" WHERE u.product_id=? AND u.platform=? AND u.arch=? AND u.channel=?", product, in.Platform, in.Arch, in.Channel)) + if err != nil && err != sql.ErrNoRows { + apiError(c, 503, "updates_unavailable", "升级检查不可用") + return + } + if err == sql.ErrNoRows { + p = UpdatePolicy{} + } + // Never disable an enabled mandatory policy silently when its target is unavailable. + if p.Enabled && !published { + apiError(c, 503, "update_target_unavailable", "升级目标不可用,请联系管理员") + return + } + available, mandatory, required := evaluateUpdate(p, in.CurrentVersion, now) + payload := UpdatePayload{Version: "update-v1", InstanceID: instance, ProductID: product, CustomerID: owner, CurrentVersion: in.CurrentVersion, Platform: in.Platform, Arch: in.Arch, Channel: in.Channel, ServerTime: now.UTC().Format(time.RFC3339Nano), ExpiresAt: now.Add(15 * time.Minute).UTC().Format(time.RFC3339Nano), PolicyRevision: p.Revision, PolicyEnabled: p.Enabled, RecommendedVersion: p.RecommendedVersion, MinimumSupportedVersion: p.MinimumSupportedVersion, EnforceAfter: p.EnforceAfter, Mandatory: mandatory, RequiredNow: required, UpdateAvailable: available, DownloadAllowed: leaseState(istate, freeze, lstate, cstate, active, starts, ends, now) == "active" && p.Enabled, ReleaseID: p.ReleaseID, SHA256: digest, SizeBytes: size, Message: p.Message} + bytes, err := json.Marshal(payload) + if err != nil { + apiError(c, 503, "updates_unavailable", "升级检查不可用") + return + } + hash := sha256.Sum256(bytes) + signature, err := ecdsa.SignASN1(rand.Reader, key, hash[:]) + if err != nil { + apiError(c, 503, "updates_unavailable", "升级签名不可用") + return + } + details, _ := json.Marshal(gin.H{"client_actor": "instance", "current_version": in.CurrentVersion, "policy_revision": p.Revision, "required_now": required, "platform": in.Platform, "arch": in.Arch, "channel": in.Channel}) + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'update.checked','license_instance',?,?)", actor, rowID, details); err != nil { + apiError(c, 503, "audit_unavailable", "审计失败") + return + } + if err = tx.Commit(); err != nil { + apiError(c, 503, "updates_unavailable", "升级检查不可用") + return + } + c.JSON(200, gin.H{"data": gin.H{"payload": base64.RawStdEncoding.EncodeToString(bytes), "signature": base64.RawStdEncoding.EncodeToString(signature), "key_id": a.keyring.Current}}) +} diff --git a/backend/internal/httpapi/updates_test.go b/backend/internal/httpapi/updates_test.go new file mode 100644 index 0000000..3918e02 --- /dev/null +++ b/backend/internal/httpapi/updates_test.go @@ -0,0 +1,67 @@ +package httpapi + +import ( + "github.com/gin-gonic/gin" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestUpdateVersionComparison(t *testing.T) { + for _, tc := range []struct { + a, b string + want int + }{{"1.10.0", "1.9.0", 1}, {"2.0.0", "2.0.0", 0}, {"1.99.99", "2.0.0", -1}, {"99999999999999999999999.0.0", "100000000000000000000000.0.0", -1}} { + got, err := compareUpdateVersions(tc.a, tc.b) + if err != nil || got != tc.want { + t.Fatalf("%s vs %s: %d %v", tc.a, tc.b, got, err) + } + } + for _, s := range []string{"v2.0", "1.0", "01.0.0", "1.0.0-beta", "1.0.0+build", "-1.0.0", "1.2.3\n"} { + if _, err := compareUpdateVersions(s, "1.0.0"); err == nil { + t.Fatalf("accepted %q", s) + } + } +} +func TestUpdateDeadline(t *testing.T) { + deadline := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + p := UpdatePolicy{Enabled: true, RecommendedVersion: "2.0.0", MinimumSupportedVersion: "1.5.0", EnforceAfter: deadline.Format(time.RFC3339)} + for _, tc := range []struct { + current string + now time.Time + available, mandatory, required bool + }{{"1.0.0", deadline.Add(-time.Second), true, true, false}, {"1.0.0", deadline, true, true, true}, {"1.5.0", deadline, true, false, false}, {"2.0.0", deadline, false, false, false}, {"2.1.0", deadline, false, false, false}} { + a, m, r := evaluateUpdate(p, tc.current, tc.now) + if a != tc.available || m != tc.mandatory || r != tc.required { + t.Fatalf("%+v: %v %v %v", tc, a, m, r) + } + } + p.Enabled = false + a, m, r := evaluateUpdate(p, "1.0.0", deadline) + if a || m || r { + t.Fatal("disabled policy enforced") + } +} +func TestUpdateInvalidRequests(t *testing.T) { + for _, body := range []string{`{"platform":"windows","arch":"x64","channel":"stable","release_id":1,"minimum_supported_version":"2.0.0"}`, `{"platform":"windows","arch":"x64","channel":"stable","release_id":1,"enforce_after":"2026-11-01T00:00:00Z"}`, `{"platform":"other","arch":"x64","channel":"stable","release_id":1}`} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Params = gin.Params{{Key: "id", Value: "1"}} + c.Request = httptest.NewRequest("PUT", "/", strings.NewReader(body)) + (&BusinessAPI{}).saveUpdatePolicy(c) + if w.Code != 400 { + t.Fatalf("%s: %d %s", body, w.Code, w.Body) + } + } + for _, body := range []string{`{"current_version":"v1.0","platform":"windows","arch":"x64","channel":"stable"}`, `{"current_version":"1.0.0","platform":"windows","arch":"x64","channel":"stable","secret":"invalid"}`} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Params = gin.Params{{Key: "instance_id", Value: "11111111-2222-3333-4444-555555555555"}} + c.Request = httptest.NewRequest("POST", "/", strings.NewReader(body)) + (&BusinessAPI{}).checkUpdate(c) + if w.Code != 400 && w.Code != 403 { + t.Fatalf("%s: %d", body, w.Code) + } + } +} diff --git a/backend/migrations/000012_update_policies.down.sql b/backend/migrations/000012_update_policies.down.sql new file mode 100644 index 0000000..b249fa6 --- /dev/null +++ b/backend/migrations/000012_update_policies.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS product_update_policies; diff --git a/backend/migrations/000012_update_policies.up.sql b/backend/migrations/000012_update_policies.up.sql new file mode 100644 index 0000000..bbf7fc5 --- /dev/null +++ b/backend/migrations/000012_update_policies.up.sql @@ -0,0 +1,18 @@ +CREATE TABLE product_update_policies ( + product_id BIGINT UNSIGNED NOT NULL, + platform VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + arch VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT FALSE, + release_id BIGINT UNSIGNED NOT NULL, + minimum_supported_version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', + enforce_after TIMESTAMP(6) NULL, + message TEXT NOT NULL, + revision BIGINT UNSIGNED NOT NULL DEFAULT 1, + updated_by BIGINT UNSIGNED NOT NULL, + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (product_id,platform,arch,channel), + CONSTRAINT fk_update_policy_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE, + CONSTRAINT fk_update_policy_release FOREIGN KEY (release_id) REFERENCES product_releases(id), + CONSTRAINT fk_update_policy_admin FOREIGN KEY (updated_by) REFERENCES admins(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/backend/migrations/README.md b/backend/migrations/README.md index 010bd3d..1f27a2c 100644 --- a/backend/migrations/README.md +++ b/backend/migrations/README.md @@ -29,3 +29,5 @@ On 2026-09-30, a dedicated MySQL 8.0 container was used to verify an empty datab Schema 10 adds unique administrator usernames. Existing accounts become `admin-{id}` and retain their passwords; login requests must send `username` instead of `email`. Run migrations before starting the current server or `admin-init`. Schema 11 adds nullable `license_instances.secret_encrypted`. Apply before API startup. Configure `LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE` as an absolute path to an independent 32-byte raw random key. Mount read-only, back up securely with the database, and never commit it. Missing key preserves first-return-only creation. Existing hashes cannot recover secrets. Losing/changing the key makes ciphertext unreadable; rotation is not implemented. Down migration deletes retained ciphertext and requires backup and confirmation. + +Schema 12 adds `product_update_policies`, one policy per product/platform/architecture/channel. Apply before enabling the update-policy administrator UI or `/instances/:instance_id/updates/check`. Only published stable-SemVer releases can be policy targets; the minimum supported version cannot exceed the target. The update response is signed with the configured current P-256 key and expires after 15 minutes. Down migration deletes policy rows and requires an operator-reviewed backup/confirmation. Existing portal snapshot and download APIs remain compatible. diff --git a/client/test-update-sdk.mjs b/client/test-update-sdk.mjs new file mode 100644 index 0000000..3e47103 --- /dev/null +++ b/client/test-update-sdk.mjs @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import { createHash, generateKeyPairSync, sign } from 'node:crypto'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Readable } from 'node:stream'; +import { UpdateClient, UpdateError, verifyCheck } from './update-sdk.mjs'; + +const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); +const now = Date.now(); +const payload = {version:'update-v1',instance_id:'i1',product_id:1,customer_id:2,current_version:'1.0',platform:'linux',arch:'x64',channel:'stable',server_time:new Date(now).toISOString().replace('.000Z','Z'),expires_at:new Date(now+600000).toISOString().replace('.000Z','Z'),policy_revision:3,policy_enabled:true,recommended_version:'2.0',minimum_supported_version:'1.0',enforce_after:null,mandatory:false,required_now:false,update_available:true,download_allowed:true,release_id:7,sha256:createHash('sha256').update('good').digest('hex'),size_bytes:4,message:''}; +function envelope(p = payload) { const raw = Buffer.from(JSON.stringify(p)); return {payload:raw.toString('base64').replace(/=+$/,''),signature:sign('sha256',raw,privateKey).toString('base64').replace(/=+$/,''),key_id:'k1'}; } +const keys = {k1:publicKey.export({type:'spki',format:'pem'})}; +const signed = envelope(); +verifyCheck(signed, keys, 'i1', {now,expectedPlatform:'linux',expectedArch:'x64',expectedChannel:'stable',expectedCurrentVersion:'1.0'}); +const tampered = {...signed, payload:Buffer.from('{"version":"update-v1"}').toString('base64').replace(/=+$/,'')}; +assert.throws(() => verifyCheck(tampered, keys, 'i1', {now}), UpdateError); +assert.throws(() => verifyCheck(signed, keys, 'wrong', {now}), UpdateError); +assert.throws(() => verifyCheck(signed, keys, 'i1', {now:now+600001}), UpdateError); +assert.throws(() => verifyCheck(signed, keys, 'i1', {now,previous:{policy_revision:4}}), UpdateError); +assert.throws(() => verifyCheck(signed, keys, 'i1', {now,expectedCurrentVersion:'0.9'}), UpdateError); + +for (const [status, chunks, expected] of [[200,['good-extra'],'package_too_large'],[206,['good'],'download_http_206'],[302,[],'download_http_302'],[500,[],'download_http_500'],[200,['evil'],'package_integrity_failed']]) { + const dir = await mkdtemp(join(tmpdir(),'update-sdk-')); const target = join(dir,'pkg.bin'); + const fetchImpl = async () => new Response(Readable.toWeb(Readable.from(chunks.map(x => Buffer.from(x)))), {status,headers: status===302?{location:'https://evil.invalid'}:{}}); + const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,fetchImpl}); + await assert.rejects(client.download({payload},target), e => e instanceof UpdateError && e.message.includes(expected)); + assert.deepEqual(await readdir(dir), []); await rm(dir,{recursive:true,force:true}); +} + +let persisted; +const state = {load:()=>persisted,saveAtomic:value=>{persisted=value;}}; +const fetchImpl = async () => Response.json({data:signed}); +const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,state,fetchImpl,clock:()=>now}); +persisted={scope:JSON.stringify(['i1','windows','x64','stable']),policy_revision:99}; +assert.equal((await client.check('1.0','linux','x64','stable')).payload.policy_revision,3); +console.log('Node update SDK negative tests passed'); diff --git a/client/test_update_sdk.py b/client/test_update_sdk.py new file mode 100644 index 0000000..dcee1bc --- /dev/null +++ b/client/test_update_sdk.py @@ -0,0 +1,72 @@ +import base64 +import hashlib +import json +import tempfile +import unittest +from pathlib import Path +from datetime import datetime, timezone + +import httpx +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from update_sdk import UpdateClient, UpdateError, verify_check + + +class MemoryState: + def __init__(self, value=None): self.value = value + def load(self): return self.value + def save_atomic(self, state): self.value = state + + +class SDKTests(unittest.TestCase): + def setUp(self): + self.private = ec.generate_private_key(ec.SECP256R1()) + self.public = self.private.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode() + self.now = __import__('time').time() + stamp = datetime.fromtimestamp(self.now, timezone.utc).isoformat().replace('+00:00', 'Z') + self.payload = {"version":"update-v1","instance_id":"i1","product_id":1,"customer_id":2,"current_version":"1.0","platform":"linux","arch":"x64","channel":"stable","server_time":stamp,"expires_at":datetime.fromtimestamp(self.now+600, timezone.utc).isoformat().replace('+00:00','Z'),"policy_revision":3,"policy_enabled":True,"recommended_version":"2.0","minimum_supported_version":"1.0","enforce_after":None,"mandatory":False,"required_now":False,"update_available":True,"download_allowed":True,"release_id":7,"sha256":hashlib.sha256(b'good').hexdigest(),"size_bytes":4,"message":""} + self.envelope = self.sign(self.payload) + + def sign(self, payload): + raw = json.dumps(payload, separators=(',', ':')).encode() + sig = self.private.sign(raw, ec.ECDSA(hashes.SHA256())) + return {"payload":base64.b64encode(raw).decode().rstrip('='),"signature":base64.b64encode(sig).decode().rstrip('='),"key_id":"k1"} + + def test_signature_context_expiry_and_rollback(self): + verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_platform="linux", expected_arch="x64", expected_channel="stable", expected_current_version="1.0") + tampered = dict(self.envelope); tampered["payload"] = base64.b64encode(b'{"version":"update-v1"}').decode().rstrip('=') + with self.assertRaises(UpdateError): verify_check(tampered, {"k1":self.public}, "i1", now=self.now) + with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "wrong", now=self.now) + with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now+601) + with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, previous={"policy_revision":4}) + with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_current_version="0.9") + + def client(self, handler, state=None): + transport = httpx.MockTransport(handler) + client = httpx.Client(transport=transport, follow_redirects=False) + return UpdateClient('https://license.example', 'i1', 'secret', {"k1":self.public}, state=state, client=client) + + def test_stream_download_bounds_redirect_and_cleanup(self): + cases = [ + (lambda req: httpx.Response(200, content=b'good-extra'), 'package_too_large'), + (lambda req: httpx.Response(302, headers={"location":"https://evil.invalid"}), 'download_http_302'), + (lambda req: httpx.Response(200, content=b'evil'), 'package_integrity_failed'), + ] + for handler, expected_error in cases: + with self.subTest(error=expected_error), tempfile.TemporaryDirectory() as directory: + target = Path(directory) / 'pkg.bin' + sdk = self.client(handler) + with self.assertRaises(UpdateError) as caught: sdk.download(type('R', (), {"payload":self.payload})(), target) + self.assertIn(expected_error, str(caught.exception)) + self.assertFalse(target.exists()) + self.assertEqual(list(Path(directory).iterdir()), []) + + def test_scoped_revision_does_not_leak_between_platforms(self): + state = MemoryState({"scope": '["i1","windows","x64","stable"]', "policy_revision":99}) + sdk = self.client(lambda req: httpx.Response(200, json={"data":self.envelope}), state) + result = sdk.check('1.0','linux','x64','stable') + self.assertEqual(result.payload['policy_revision'], 3) + + +if __name__ == '__main__': unittest.main() diff --git a/client/update-sdk.mjs b/client/update-sdk.mjs new file mode 100644 index 0000000..b8e1101 --- /dev/null +++ b/client/update-sdk.mjs @@ -0,0 +1,73 @@ +import { createHash, createPublicKey, randomUUID, verify } from 'node:crypto'; +import { mkdir, rename, open, rm } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +export class UpdateError extends Error {} +const MAX_PACKAGE_BYTES = 64 * 1024 * 1024; +const REQUIRED = new Set(['version','instance_id','product_id','customer_id','current_version','platform','arch','channel','server_time','expires_at','policy_revision','policy_enabled','recommended_version','minimum_supported_version','enforce_after','mandatory','required_now','update_available','download_allowed','release_id','sha256','size_bytes','message']); +const instant = value => { if (typeof value !== 'string' || !value.endsWith('Z')) throw new UpdateError('invalid_time'); const n = Date.parse(value); if (!Number.isFinite(n)) throw new UpdateError('invalid_time'); return n; }; +const decode = value => { if (typeof value !== 'string' || !value || !/^[A-Za-z0-9+/]+$/.test(value)) throw new UpdateError('invalid_signature'); return Buffer.from(value, 'base64'); }; + +export function verifyCheck(envelope, publicKeys, expectedInstance, { now = Date.now(), previous = null, expectedPlatform = null, expectedArch = null, expectedChannel = null, expectedCurrentVersion = null } = {}) { + if (!envelope || typeof envelope.payload !== 'string' || typeof envelope.key_id !== 'string') throw new UpdateError('invalid_payload'); + let raw, p; try { raw = decode(envelope.payload); p = JSON.parse(raw.toString('utf8')); } catch { throw new UpdateError('invalid_payload'); } + if (!p || p.version !== 'update-v1' || p.instance_id !== expectedInstance || (expectedPlatform !== null && p.platform !== expectedPlatform) || (expectedArch !== null && p.arch !== expectedArch) || (expectedChannel !== null && p.channel !== expectedChannel) || (expectedCurrentVersion !== null && p.current_version !== expectedCurrentVersion) || REQUIRED.size !== Object.keys(p).length || [...REQUIRED].some(k => !(k in p))) throw new UpdateError('invalid_context'); + const pem = publicKeys[envelope.key_id]; if (!pem) throw new UpdateError('unknown_key'); + const key = createPublicKey(pem); if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') throw new UpdateError('invalid_key'); + if (!verify('sha256', raw, key, decode(envelope.signature))) throw new UpdateError('invalid_signature'); + const server = instant(p.server_time), expiry = instant(p.expires_at); + if (expiry <= now || expiry - server > 900000 || Math.abs(server - now) > 300000) throw new UpdateError('expired_or_clock_skew'); + if (!Number.isSafeInteger(p.policy_revision) || p.policy_revision < 0 || (previous && p.policy_revision < previous.policy_revision)) throw new UpdateError('policy_rollback'); + if (!Number.isSafeInteger(p.size_bytes) || p.size_bytes < 0 || !Number.isSafeInteger(p.release_id) || p.release_id < 0) throw new UpdateError('invalid_release'); + return { payload: p, signature: decode(envelope.signature) }; +} + +export class UpdateClient { + constructor({ baseUrl, instanceId, secret, publicKeys, state = null, fetchImpl = fetch, clock = () => Date.now() }) { + const u = new URL(baseUrl); if (u.protocol !== 'https:' || u.pathname !== '/' || u.search || u.hash) throw new Error('base_url_must_be_https_origin'); + this.baseUrl = u; this.instanceId = instanceId; this.secret = secret; this.publicKeys = publicKeys; this.state = state; this.fetch = fetchImpl; this.clock = clock; + } + scope(platform, arch, channel) { return JSON.stringify([this.instanceId, platform, arch, channel]); } + previous(platform, arch, channel) { + const stored = this.state?.load?.(); if (!stored) return null; + const key = this.scope(platform, arch, channel); + if (stored.scope === key) return stored; + return stored.scopes?.[key] ?? null; + } + async check(currentVersion, platform, arch, channel) { + const response = await this.fetch(new URL(`api/v1/instances/${this.instanceId}/updates/check`, this.baseUrl), { method: 'POST', redirect: 'error', headers: {'content-type':'application/json'}, body: JSON.stringify({secret:this.secret,current_version:currentVersion,platform,arch,channel}) }); + if (!response.ok) throw new UpdateError(`check_http_${response.status}`); + const result = verifyCheck((await response.json()).data, this.publicKeys, this.instanceId, { now: this.clock(), previous: this.previous(platform, arch, channel), expectedPlatform: platform, expectedArch: arch, expectedChannel: channel, expectedCurrentVersion: currentVersion }); + if (this.state) { + const scope = this.scope(platform, arch, channel); const stored = this.state.load?.() ?? {}; const scopes = { ...(stored.scopes ?? {}) }; + const entry = { scope, instance_id:this.instanceId, policy_revision:result.payload.policy_revision, server_time:result.payload.server_time, accepted_at:this.clock() }; + scopes[scope] = entry; this.state.saveAtomic?.({ ...entry, scopes }); + } + return result; + } + async download(result, destination, { signal = null, timeoutMs = 30000 } = {}) { + const p = result.payload; if (!p.download_allowed || !p.update_available || !p.release_id) throw new UpdateError('download_not_allowed'); + const controller = new AbortController(); const timer = setTimeout(() => controller.abort(new UpdateError('download_timeout')), timeoutMs); + const abort = () => controller.abort(signal.reason); if (signal) { if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once:true }); } + let response = null; + let tmp = null; + try { + if (!Number.isSafeInteger(p.size_bytes) || p.size_bytes < 0 || p.size_bytes > MAX_PACKAGE_BYTES) throw new UpdateError('package_too_large'); + response = await this.fetch(new URL(`api/v1/customers/${p.customer_id}/releases/${p.release_id}/download`, this.baseUrl), { method:'POST', redirect:'error', signal:controller.signal, headers:{'content-type':'application/json'}, body:JSON.stringify({instance_id:this.instanceId,secret:this.secret}) }); + if (response.status !== 200) throw new UpdateError(`download_http_${response.status}`); + await mkdir(dirname(destination), { recursive:true }); tmp = `${destination}.tmp-${randomUUID()}`; let total = 0; const hash = createHash('sha256'); + const file = await open(tmp, 'wx'); + try { + for await (const chunk of response.body) { total += chunk.length; if (total > p.size_bytes || total > MAX_PACKAGE_BYTES) throw new UpdateError('package_too_large'); hash.update(chunk); await file.write(chunk); } + } finally { await file.close(); } + if (total !== p.size_bytes || hash.digest('hex').toLowerCase() !== p.sha256.toLowerCase()) throw new UpdateError('package_integrity_failed'); + await rename(tmp, destination); tmp = null; return destination; + } catch (error) { + controller.abort(); + try { await response?.body?.cancel?.(); } catch {} + if (tmp) await rm(tmp, { force:true }); + throw error; + } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); } + } + install(packagePath, installer) { return installer(packagePath); } +} diff --git a/client/update_sdk.py b/client/update_sdk.py new file mode 100644 index 0000000..7007808 --- /dev/null +++ b/client/update_sdk.py @@ -0,0 +1,182 @@ +"""Reference client for the signed update-v1 contract. + +Requires Python 3.11 and the ``cryptography`` package. No installer is executed +by this module; callers inject an installer after verification. +""" +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import tempfile +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Callable, Mapping, Protocol +from urllib.parse import urljoin, urlparse + +import httpx +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature + + +class UpdateError(Exception): + pass + + +MAX_PACKAGE_BYTES = 64 * 1024 * 1024 + + +class StateStore(Protocol): + def load(self) -> Mapping[str, object] | None: ... + def save_atomic(self, state: Mapping[str, object]) -> None: ... + + +@dataclass(frozen=True) +class UpdateResult: + payload: dict + signature: bytes + + +def _time(value: str) -> float: + if not isinstance(value, str) or not value.endswith("Z"): + raise UpdateError("invalid_time") + try: + return datetime.fromisoformat(value[:-1] + "+00:00").timestamp() + except ValueError as exc: + raise UpdateError("invalid_time") from exc + + +def _b64(value: object) -> bytes: + if not isinstance(value, str) or not value or any(c not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" for c in value) or ("=" in value and not value.endswith("=" * (len(value) - len(value.rstrip("="))))): + raise UpdateError("invalid_signature") + try: + return base64.b64decode(value + "=" * (-len(value) % 4), validate=True) + except ValueError as exc: + raise UpdateError("invalid_signature") from exc + + +def verify_check(envelope: Mapping[str, object], public_keys: Mapping[str, str], expected_instance: str, + now: float | None = None, previous: Mapping[str, object] | None = None, + expected_platform: str | None = None, expected_arch: str | None = None, + expected_channel: str | None = None, expected_current_version: str | None = None) -> UpdateResult: + encoded = envelope.get("payload") + raw = _b64(encoded) + try: + payload = raw.decode("utf-8") + data = json.loads(payload) + except (UnicodeError, json.JSONDecodeError) as exc: + raise UpdateError("invalid_payload") from exc + if not isinstance(data, dict) or data.get("version") != "update-v1": + raise UpdateError("unsupported_payload") + required = {"version", "instance_id", "product_id", "customer_id", "current_version", "platform", "arch", "channel", "server_time", "expires_at", "policy_revision", "policy_enabled", "recommended_version", "minimum_supported_version", "enforce_after", "mandatory", "required_now", "update_available", "download_allowed", "release_id", "sha256", "size_bytes", "message"} + if set(data) != required or data["instance_id"] != expected_instance or (expected_platform is not None and data["platform"] != expected_platform) or (expected_arch is not None and data["arch"] != expected_arch) or (expected_channel is not None and data["channel"] != expected_channel) or (expected_current_version is not None and data["current_version"] != expected_current_version): + raise UpdateError("invalid_context") + key_id = envelope.get("key_id") + if not isinstance(key_id, str) or key_id not in public_keys: + raise UpdateError("unknown_key") + signature = _b64(envelope.get("signature")) + try: + key = serialization.load_pem_public_key(public_keys[key_id].encode()) + if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1): + raise ValueError + key.verify(signature, raw, ec.ECDSA(hashes.SHA256())) + except Exception as exc: + raise UpdateError("invalid_signature") from exc + current = time.time() if now is None else now + server, expires = _time(data["server_time"]), _time(data["expires_at"]) + if expires <= current or expires - server > 900 or server - current > 300 or current - server > 300: + raise UpdateError("expired_or_clock_skew") + if not isinstance(data["policy_revision"], int) or data["policy_revision"] < 0: + raise UpdateError("invalid_revision") + if previous and data["policy_revision"] < int(previous.get("policy_revision", 0)): + raise UpdateError("policy_rollback") + if data["size_bytes"] < 0 or (data["release_id"] == 0 and data["update_available"]): + raise UpdateError("invalid_release") + return UpdateResult(data, signature) + + +class UpdateClient: + def __init__(self, base_url: str, instance_id: str, secret: str, public_keys: Mapping[str, str], + state: StateStore | None = None, client: httpx.Client | None = None): + parsed = urlparse(base_url) + if parsed.scheme != "https" or parsed.query or parsed.fragment or parsed.path.rstrip("/"): + raise ValueError("base_url_must_be_https_origin") + self.base_url, self.instance_id, self.secret, self.public_keys = base_url.rstrip("/") + "/", instance_id, secret, public_keys + self.state, self.client = state, client or httpx.Client(follow_redirects=False, timeout=30) + + def _scope(self, platform: str, arch: str, channel: str) -> str: + return json.dumps([self.instance_id, platform, arch, channel], separators=(",", ":")) + + def _scoped_previous(self, platform: str, arch: str, channel: str) -> Mapping[str, object] | None: + if not self.state: + return None + stored = self.state.load() + if not stored: + return None + if stored.get("scope") == self._scope(platform, arch, channel): + return stored + scopes = stored.get("scopes") + if isinstance(scopes, Mapping): + value = scopes.get(self._scope(platform, arch, channel)) + return value if isinstance(value, Mapping) else None + return None + + def check(self, current_version: str, platform: str, arch: str, channel: str) -> UpdateResult: + response = self.client.post(urljoin(self.base_url, f"api/v1/instances/{self.instance_id}/updates/check"), json={"secret": self.secret, "current_version": current_version, "platform": platform, "arch": arch, "channel": channel}, follow_redirects=False, timeout=30) + if response.status_code != 200: + raise UpdateError(f"check_http_{response.status_code}") + envelope = response.json().get("data") + if not isinstance(envelope, dict): + raise UpdateError("invalid_response") + previous = self._scoped_previous(platform, arch, channel) + result = verify_check(envelope, self.public_keys, self.instance_id, previous=previous, expected_platform=platform, expected_arch=arch, expected_channel=channel, expected_current_version=current_version) + if self.state: + scope = self._scope(platform, arch, channel) + stored = self.state.load() or {} + scopes = dict(stored.get("scopes", {})) if isinstance(stored.get("scopes"), Mapping) else {} + scopes[scope] = {"scope": scope, "instance_id": self.instance_id, "policy_revision": result.payload["policy_revision"], "server_time": result.payload["server_time"], "accepted_at": time.time()} + self.state.save_atomic({"scope": scope, "instance_id": self.instance_id, "policy_revision": result.payload["policy_revision"], "server_time": result.payload["server_time"], "accepted_at": time.time(), "scopes": scopes}) + return result + + def download(self, result: UpdateResult, destination: str | os.PathLike[str]) -> Path: + p = result.payload + if not p["download_allowed"] or not p["update_available"] or not p["release_id"]: + raise UpdateError("download_not_allowed") + url = urljoin(self.base_url, f"api/v1/customers/{p['customer_id']}/releases/{p['release_id']}/download") + expected = int(p["size_bytes"]) + if expected < 0 or expected > MAX_PACKAGE_BYTES: + raise UpdateError("package_too_large") + target = Path(destination) + target.parent.mkdir(parents=True, exist_ok=True) + temp = None + total = 0 + digest = hashlib.sha256() + try: + with self.client.stream("POST", url, json={"instance_id": self.instance_id, "secret": self.secret}, follow_redirects=False, timeout=httpx.Timeout(30, read=30)) as response: + if response.status_code != 200: + raise UpdateError(f"download_http_{response.status_code}") + with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + ".", delete=False) as tmp: + temp = Path(tmp.name) + for chunk in response.iter_bytes(): + if not chunk: + continue + total += len(chunk) + if total > expected or total > MAX_PACKAGE_BYTES: + raise UpdateError("package_too_large") + digest.update(chunk) + tmp.write(chunk) + if total != expected or digest.hexdigest().lower() != p["sha256"].lower(): + raise UpdateError("package_integrity_failed") + temp.replace(target) + return target + except Exception: + if temp is not None: + temp.unlink(missing_ok=True) + raise + + def install(self, package: Path, installer: Callable[[Path], object]) -> object: + return installer(package) diff --git a/client/upgrade-sdk-testing.md b/client/upgrade-sdk-testing.md new file mode 100644 index 0000000..7b0cd4a --- /dev/null +++ b/client/upgrade-sdk-testing.md @@ -0,0 +1,14 @@ +# Upgrade SDK tests + +Run the Python test from the client directory so the module import resolves: + +```sh +cd client +python -m unittest test_update_sdk -v +``` + +Run the Node.js negative tests from the repository root: + +```sh +node client/test-update-sdk.mjs +``` diff --git a/docs/client-integration-center.md b/docs/client-integration-center.md index 38612a0..8b64453 100644 --- a/docs/client-integration-center.md +++ b/docs/client-integration-center.md @@ -1,58 +1,33 @@ # 客户端接入中心 -管理员登录后进入 `/integration`,选择 Python、Go、Java、.NET 或 Node.js,以及桌面、常驻服务或容器模式。页面提供接口清单、可复制工程提示词、完整协议、安全约束、字段示例和 ZIP/Markdown 下载。首版交付生成资料,不包含五种语言已经实现并完成生产验收的 SDK。 +管理员登录后进入 `/integration`,选择 Python、Go、Java、.NET 或 Node.js,以及桌面、常驻服务或容器模式。页面提供接口清单、工程提示词、协议、安全约束、字段示例和 ZIP/Markdown 下载。ZIP 现在包含可运行的 Python 与 Node.js 升级参考 SDK;其余语言提供同契约实现要求,不能把参考 SDK 宣称为五种语言均已生产验收。 -SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权平台根地址;部署可以通过 `LICENSE_API_BASE_URL` 覆盖。该值必须是根地址,不能附加 `/api/v1`。协议、OpenAPI、Markdown 与 ZIP 内的资料都使用相同默认值。 +SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权平台根地址;部署可以通过 `LICENSE_API_BASE_URL` 覆盖,但必须是 HTTPS 根地址,不能附加 `/api/v1`。 -## 管理员接口 - -以下 GET 路由使用现有管理员会话保护,不属于外部客户端运行 API: +## 集成资产 - `/api/v1/integration-kit?language=python&mode=service`:JSON 资料。 -- `/api/v1/integration-kit/download?language=python&mode=service`:UTF-8 Markdown,包含选定提示词、协议、字段示例和当前部署验签公钥(key ID、SPKI SHA-256 指纹及 PEM)。 -- `/api/v1/integration-kit/archive?language=python&mode=service`:ZIP,包含 README.md、protocol.md、upgrade.md、openapi.json、prompt.md、verification-keys.md、test-vectors.json。公钥必须经可信渠道核对后预置,不能把服务端发现结果自动变成信任根。 +- `/api/v1/integration-kit/download?...`:UTF-8 Markdown,包含选定提示词、协议、update-v1 升级契约和当前部署验签公钥。 +- `/api/v1/integration-kit/archive?...`:ZIP,包含 README、protocol、upgrade、OpenAPI、prompt、部署公钥、测试向量,以及 `client/update_sdk.py`、`client/update-sdk.mjs`。 -省略参数默认 python/service。未知语言或模式返回 400,不接受文件路径参数。下载使用 no-store,文件名按受控语言/模式生成。无需新数据库表,不包含任何真实实例 secret、数据库凭据或生产私钥。 +公钥必须经可信渠道核对指纹后预置,不能把服务端发现结果自动变成信任根。ZIP 中测试向量使用随机测试密钥,绝不能导入生产。 -每次 ZIP 下载为测试向量生成独立随机 P-256 密钥,返回公钥及 license-v2/lease-v2 的有效 DER ECDSA 签名、固定规范化内容及 SHA-256。私钥仅在生成时的内存中使用,不输出,不落盘。向量使用固定历史时间,时间相关测试必须使用给定固定 now;生产不得信任测试公钥。 +## update-v1 客户端契约 -## 协议维护 +客户端调用 `POST /api/v1/instances/{instance_id}/updates/check`,提交 `secret`、`current_version`、`platform`、`arch`、`channel`。响应 payload 是 raw UTF-8 JSON 的标准 Base64,签名是无填充标准 Base64 的 DER ECDSA P-256 SHA-256。客户端必须验证固定字段、实例上下文、可信 key_id、服务端时间/过期时间、15 分钟 TTL 和策略 revision 单调性。 -协议源文件在 `backend/internal/httpapi/integration_assets/protocol.md`,OpenAPI 3.0.3 在同目录 `openapi.json`,由 Go embed 嵌入二进制。修改接口实现时必须同时核对这两个文件,重新构建后端后生效。`client/verify.mjs` 提供 v2 验签与运行状态算法参考。 +`required_now` 是服务端根据 deadline 计算的提示,客户端仍必须使用可信时间、TTL/过期检查和本地版本比较再次判断;`mandatory` 不能绕过用户确认、维护窗口、下载授权或包完整性校验。策略关闭返回 disabled/空 release 元数据。升级检查成功、`download_allowed` 或 active entitlement 都不能实现业务 `canRun`,业务许可仍由独立验签的 license-v2/lease-v2 决定。 -选择语言会加入对应加密库、HTTP/取消/状态存储/测试要求;运行模式在提示词中明确,完整协议包括桌面/服务/容器的身份和持久化约束。页面请求使用序列号忽略旧请求返回,避免快速切换后显示过期资料。 +只有签名 payload 允许下载时,客户端才调用现有实例认证下载接口。必须同源 HTTPS、禁止重定向、不把 secret 放 URL,验证长度和 SHA-256 后才暂存/交给应用安装器。SDK 不执行 shell、脚本或包内任意命令;安装器、健康检查和回滚由应用注入。 -部署方须确认 keyring 已配置并通过受控渠道交付公钥;legacy v1 默认部署不满足本资料要求。keyring 发现不是信任引导。14 天离线租约意味着冻结/撤销最多可延迟 14 天生效,不能宣传立即离线撤销或硬件防克隆。Kubernetes 集群代理、移动设备、CI 临时身份、完全离线授权需要额外方案。 +## 参考 SDK 与限制 -## 验证记录 +`client/update_sdk.py` 需要 Python 3.11 与 `cryptography`,`client/update-sdk.mjs` 需要 Node.js 20+。两者覆盖验签、篡改/上下文/TTL/策略回滚拒绝、禁止重定向下载、长度与摘要校验、原子暂存和注入安装器。调用方应增加跨进程锁、持久化防回拨钩子和本地版本比较测试。 -- 后端 `go test ./...` 与 `go vet ./...` 通过。新增测试检查三个管理员接口未认证均为 401、非法选择 400、五种语言提示、OpenAPI JSON、ZIP 五文件及两类签名/篡改失败。 -- 前端类型检查、12 个测试文件共 33 项测试、生产构建通过。新增面板测试检查加载/失败/选择更新及下载参数,路由测试包括 `/integration`。 -- 使用隔离数据库 `license_platform_local_261009` 的真实管理员会话:JSON 与 ZIP 下载均 200,ZIP 包内容与 no-store 响应头已核对。 -- 浏览器实际切换 .NET:专属 DER 格式提示与下载 URL 更新。390×844 窄屏无整体横向溢出,控制台 0 error。 +离线不能刷新或延长 update-v1 TTL,网络错误不可伪造强制升级;有效 lease 的离线行为仍按既有租约,过期或时钟回拨必须 fail closed。灰度由服务端决定,当前不提供升级回报接口;容器应由受控 CI/CD 或部署代理升级。完全离线、移动端、CI 临时身份和 Kubernetes 多副本需要额外身份方案。 -未迁移或修改原业务数据库,未提交或推送代码。现有大包构建提示与旧测试的组件 stub 警告仍存在。全仓 `git diff --check` 的两项旧文档末尾空行不在本次功能范围内。 +## 授权与信任交付 -## 首次激活交付与客户端字段 +管理员创建实例并交付 `instance_id`、`license_key`、`secret`。secret 仅保存于系统密钥库、Vault、Secret 或受限加密文件,不能写 URL、日志、镜像或浏览器 LocalStorage。生产公钥通过受控渠道预置,keyring 发现接口不是信任引导。激活和心跳仍使用原有 license-v2/lease-v2 流程,冻结/撤销的离线残留时间受既有租约限制。 -管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。配置凭据加密密钥后,新实例同时保存密文与验证哈希,管理员可重复查看和下载 JSON;旧实例或未配置时仅存哈希,无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。 - -## 授权文件导出与导入 - -实例创建成功后,在当前凭据窗口填写实际授权中心根地址,点击“导出授权文件”,下载 `license-{instance_id}.license.json`。默认地址为 `https://license.yihuiyong.cn`。文件是 UTF-8 JSON,包含 `format: yhy-license-activation`、`version: 1`、`api_base_url`、`instance_id`、`license_key`、`secret`。前端仅从当前内存凭据生成下载,不新增接口或数据库表,不写浏览器持久化存储。文件含明文密钥,需安全交付;关闭窗口后不能重新取得 secret 或补导出。 - -客户端需按 protocol.md 的“授权文件导入”实现导入入口。接入中心生成的工程提示已包含这一要求,但目前不提供各语言已实现的导入 SDK。客户端应限制文件大小、校验字段及版本、核对受控授权中心允许列表并让用户确认,随后安全保存凭据、在线激活、验签证书和心跳租约。导入不能清空既有时间高水位或静默切换实例。文件本身未签名,不包含可信公钥,不构成离线运行凭证。 - -升级方案随 JSON、Markdown 和 ZIP 导出,ZIP 包含 upgrade.md 与 verification-keys.md(共七个文件)。实例创建响应设置 Cache-Control: no-store;前端不将 secret 写入日志或浏览器持久化存储。 - -## 开发到生产快速交付 - -接入中心展示当前部署公钥环、当前 key_id、撤销标记和 SHA-256(SPKI DER)指纹,支持复制/下载未撤销 PEM。需要管理员会话,公钥接口为 GET /api/v1/integration-trust;未配置 v2 keyring 返回 503。 - -授权实例页可导出 yhy-license-trust v1 JSON:api_base_url、protocol_versions、signature_algorithm、current_key_id、未撤销 keys(含 PEM/指纹)、instance_id、customer_id、product_id。不含 secret;激活凭据另行导出。地址必须由管理员确认,HTTPS 根地址或本机 HTTP 回环地址;本机 API 使用 18081,而非前端 15173。 - -客户端需实现此新格式的严格导入与受保护存储。导入公钥须经过受控渠道确认,不能把发现接口当作信任根;验证签名、key_id、实例/客户/产品绑定、时间及状态。生产切换必须从生产后台重新交付地址、信任和凭据。导出不是证书,不会激活客户端,也不替代后续撤销策略。各语言 SDK 尚未在本仓库实现。 - -### 升级接入 - -ZIP、Markdown、接口清单及五种语言工程提示词包含 UpdateClient 查询、目标选择、授权下载、包验证和安装适配器契约。通过 POST /api/v1/portal/snapshot 查询分页已发布版本,再使用实例凭据下载。SDK 源码与安装器需在目标客户端工程实现;签名升级清单、平台自动匹配、灰度及回报尚未实现。 +协议源文件为 `backend/internal/httpapi/integration_assets/protocol.md`,OpenAPI 为同目录 `openapi.json`,升级契约为 `upgrade.md`。修改接口时必须同步核对三者和 ZIP 内容。未提交或部署代码由维护流程另行处理。 diff --git a/frontend/src/date-format.ts b/frontend/src/date-format.ts index b7f7b4f..3083999 100644 --- a/frontend/src/date-format.ts +++ b/frontend/src/date-format.ts @@ -1,3 +1,25 @@ +// Element Plus datetime pickers use local Date fields. Map those fields to UTC explicitly. +export function utcPickerToISO(value: Date | null): string { + if (!value || !Number.isFinite(value.getTime())) return '' + const utc = new Date(0) + utc.setUTCFullYear(value.getFullYear(), value.getMonth(), value.getDate()) + utc.setUTCHours(value.getHours(), value.getMinutes(), value.getSeconds(), 0) + return utc.toISOString() +} +export function isoToUTCPicker(value: string): Date | null { + if (!value) return null + const utc = new Date(value) + if (!Number.isFinite(utc.getTime())) return null + const local = new Date(0) + local.setFullYear(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()) + local.setHours(utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds(), 0) + return local +} +export function formatUTCDateTime(value: string): string { + const date = new Date(value) + return value && Number.isFinite(date.getTime()) ? `${date.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '')} UTC` : '—' +} + const formatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', diff --git a/frontend/src/releases-api.test.ts b/frontend/src/releases-api.test.ts new file mode 100644 index 0000000..74f97b4 --- /dev/null +++ b/frontend/src/releases-api.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { compareStableVersions, isStableSemVer, validateUpdatePolicy, type Release, type UpdatePolicy } from './releases-api' +import { formatUTCDateTime, isoToUTCPicker, utcPickerToISO } from './date-format' +const target:Release = {id:9, product_id:7, version:'2.10.0', published:true, sha256:'hash', size_bytes:1, product_name:'甲', product_code:'a'} +const policy:UpdatePolicy = {platform:'windows', arch:'x64', channel:'stable', enabled:false, release_id:9, minimum_supported_version:'', enforce_after:'', message:''} +describe('update policy validation', () => { + it('accepts stable SemVer only and compares numerically without precision loss', () => { + for (const value of ['01.2.3','1.02.3','1.2.03','1.2','v1.2.3','1.2.3-beta','1.2.3+build']) expect(isStableSemVer(value)).toBe(false) + expect(isStableSemVer('0.0.0')).toBe(true) + expect(compareStableVersions('2.9.0','2.10.0')).toBe(-1) + expect(compareStableVersions('99999999999999999999.0.0','99999999999999999998.0.0')).toBe(1) + }) + it('requires a published target of the same product', () => { + expect(validateUpdatePolicy(policy,target,7)).toBe('') + expect(validateUpdatePolicy(policy,undefined,7)).toContain('已发布') + expect(validateUpdatePolicy(policy,{...target,published:false},7)).toContain('已发布') + expect(validateUpdatePolicy(policy,target,8)).toContain('当前产品') + }) + it('enforces minimum version, dependent date and message limits', () => { + expect(validateUpdatePolicy({...policy,minimum_supported_version:'2.11.0'},target,7)).toContain('不能高于') + expect(validateUpdatePolicy({...policy,minimum_supported_version:'1.0.0'},target,7)).toContain('UTC') + expect(validateUpdatePolicy({...policy,minimum_supported_version:'1.0.0',enforce_after:'invalid'},target,7)).toContain('UTC') + expect(validateUpdatePolicy({...policy,enforce_after:'2026-10-12T15:00:00Z'},target,7)).toContain('清空') + expect(validateUpdatePolicy({...policy,minimum_supported_version:'2.10.0',enforce_after:'2026-10-12T15:00:00Z'},target,7)).toBe('') + expect(validateUpdatePolicy({...policy,message:'😀'.repeat(2000)},target,7)).toBe('') + expect(validateUpdatePolicy({...policy,message:'😀'.repeat(2001)},target,7)).toContain('2000') + }) + it('maps UTC picker fields without applying the browser timezone twice', () => { + const picker = new Date(2026,9,12,22,49,5) + expect(utcPickerToISO(picker)).toBe('2026-10-12T22:49:05.000Z') + const restored = isoToUTCPicker('2026-10-12T22:49:05Z')! + expect(restored.getHours()).toBe(22) + expect(restored.getDate()).toBe(12) + expect(utcPickerToISO(restored)).toBe('2026-10-12T22:49:05.000Z') + expect(formatUTCDateTime('2026-10-12T22:49:05Z')).toBe('2026-10-12 22:49:05 UTC') + expect(isoToUTCPicker('')).toBeNull() + expect(utcPickerToISO(null)).toBe('') + }) +}) diff --git a/frontend/src/releases-api.ts b/frontend/src/releases-api.ts new file mode 100644 index 0000000..d04f8eb --- /dev/null +++ b/frontend/src/releases-api.ts @@ -0,0 +1,35 @@ +export type Release = { id:number; product_id:number; version:string; sha256:string; size_bytes:number; published:boolean; product_name:string; product_code:string } +export type UpdatePolicy = { + platform:'windows'|'linux'|'macos'; arch:'x64'|'arm64'; channel:'stable'|'beta'; enabled:boolean + release_id:number; minimum_supported_version:string; enforce_after:string; message:string +} +export type SavedUpdatePolicy = UpdatePolicy & { product_id:number; revision:number; recommended_version:string } +export async function releaseResponse(response:Response) { + const body = await response.json() + if (!response.ok) throw new Error(body.error?.message || '请求失败') + return body +} +export async function listUpdatePolicies(productID:number):Promise { + const body = await releaseResponse(await fetch(`/api/v1/products/${productID}/update-policies`, {credentials:'include'})) + return body.data +} +export async function saveUpdatePolicy(productID:number, policy:UpdatePolicy):Promise { + const body = await releaseResponse(await fetch(`/api/v1/products/${productID}/update-policies`, {method:'PUT', credentials:'include', headers:{'Content-Type':'application/json'}, body:JSON.stringify(policy)})) + return body.data +} +export function isStableSemVer(value:string):boolean { return /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) } +export function compareStableVersions(left:string, right:string):number { + const a = left.split('.').map(BigInt), b = right.split('.').map(BigInt) + for (let i = 0; i < 3; i++) { if (a[i]! < b[i]!) return -1; if (a[i]! > b[i]!) return 1 } + return 0 +} +export function validateUpdatePolicy(policy:UpdatePolicy, target:Release|undefined, productID:number):string { + if (!target || target.product_id !== productID || !target.published || !isStableSemVer(target.version)) return '请选择当前产品已发布的正式 SemVer 版本' + if (policy.minimum_supported_version) { + if (!isStableSemVer(policy.minimum_supported_version)) return '最低支持版本须为正式 SemVer(x.y.z,不含前导零)' + if (compareStableVersions(policy.minimum_supported_version, target.version) > 0) return '最低支持版本不能高于目标版本' + if (!policy.enforce_after || !Number.isFinite(Date.parse(policy.enforce_after))) return '设置最低支持版本时必须选择 UTC 生效时间' + } else if (policy.enforce_after) return '未设置最低支持版本时请清空生效时间' + if (Array.from(policy.message).length > 2000) return '更新说明最多 2000 个字符' + return '' +} diff --git a/frontend/src/views/ReleasesPanel.test.ts b/frontend/src/views/ReleasesPanel.test.ts index 93ecdee..2645929 100644 --- a/frontend/src/views/ReleasesPanel.test.ts +++ b/frontend/src/views/ReleasesPanel.test.ts @@ -1,23 +1,104 @@ import { mount, flushPromises } from '@vue/test-utils' import { afterEach, describe, expect, it, vi } from 'vitest' +import { ElMessageBox } from 'element-plus' +import type { Product } from '../api' +import type { SavedUpdatePolicy } from '../releases-api' import ReleasesPanel from './ReleasesPanel.vue' - -describe('ReleasesPanel', () => { - afterEach(() => vi.unstubAllGlobals()) - it('loads all products by default', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], meta: { total: 0 } }) }) - vi.stubGlobal('fetch', fetchMock) - const wrapper = mount(ReleasesPanel, { props: { products: [] }, global: { stubs: { ElButton: true, ElSelect: true, ElOption: true, ElInput: true, ElTable: { template: '
' }, ElTableColumn: true, ElPagination: true }, directives: { loading: () => {} } } }) - await flushPromises() - expect(fetchMock).toHaveBeenCalledWith('/api/v1/releases?page=1', { credentials: 'include' }) - expect(wrapper.findAll('el-table-column-stub').map(c => c.attributes('label'))).toContain('产品') +const stubs = { + ElButton: {template:'', props:['disabled']}, + ElSelect: {template:'
', props:['modelValue']}, ElOption:true, + ElInput: {template:'', props:['modelValue']}, + ElDatePicker: {template:'', props:['modelValue']}, ElSwitch: {template:'', props:['modelValue']}, + ElTable:{template:'
',props:['data']}, ElTableColumn:true, ElPagination:true, +} +const products = [{id:7,name:'产品甲',code:'a',active:true},{id:8,name:'产品乙',code:'b',active:true}] as Product[] +const saved:SavedUpdatePolicy = {product_id:7,revision:3,platform:'windows',arch:'x64',channel:'stable',enabled:true,release_id:9,minimum_supported_version:'1.0.0',enforce_after:'2026-10-12T15:00:00Z',message:'请更新',recommended_version:'2.0.0'} +const target = {id:9,product_id:7,version:'2.0.0',published:true,sha256:'hash',size_bytes:1,product_name:'产品甲',product_code:'a'} +const response = (body:unknown, ok = true) => ({ok,json:async()=>body}) +function setup(policyList:SavedUpdatePolicy[] = [saved]) { + const fetchMock = vi.fn(async (url:string, options?:RequestInit) => { + if (options?.method === 'PUT') return response({data:{...JSON.parse(options.body as string),product_id:7,revision:4,recommended_version:'2.0.0'}}) + if (url.includes('update-policies')) return response({data:policyList}) + if (url.includes('product_id=7')) return url.includes('page=2') ? response({data:[target],meta:{total:2}}) : response({data:[{...target,id:10,version:'2.1.0-beta'}],meta:{total:2}}) + return response({data:[],meta:{total:0}}) }) - it('shows validation error without sending an invalid publication', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], meta: { total: 0 } }) })) - const wrapper = mount(ReleasesPanel, { props: { products: [] }, global: { stubs: { ElButton: { template: '' }, ElSelect: true, ElOption: true, ElInput: true, ElTable: { template: '
' }, ElTableColumn: true, ElPagination: true }, directives: { loading: () => {} } } }) - expect(wrapper.find('[role="alert"]').exists()).toBe(false) + vi.stubGlobal('fetch',fetchMock) + const wrapper = mount(ReleasesPanel,{props:{products},global:{stubs,directives:{loading:()=>{}}}}) + return {wrapper,fetchMock} +} +describe('ReleasesPanel',()=>{ + afterEach(()=>{vi.unstubAllGlobals();vi.restoreAllMocks()}) + it('loads all products by default and preserves publication validation',async()=>{ + const {wrapper,fetchMock} = setup() + await flushPromises() + expect(fetchMock).toHaveBeenCalledWith('/api/v1/releases?page=1',{credentials:'include'}) + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(wrapper.findAll('el-table-column-stub').map(c=>c.attributes('label'))).toContain('产品') await wrapper.findAll('button')[1]!.trigger('click') expect(wrapper.find('[role="alert"]').text()).toContain('请选择产品') expect(wrapper.find('input[type="file"]').attributes('aria-label')).toBe('版本文件') + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + it('loads scope, paginates targets and excludes unpublished/prerelease versions',async()=>{ + const {wrapper,fetchMock} = setup() + wrapper.findComponent('[aria-label="策略产品"]').vm.$emit('update:modelValue',7) + await flushPromises() + expect(fetchMock).toHaveBeenCalledWith('/api/v1/releases?page=2&product_id=7',{credentials:'include'}) + const options = wrapper.findComponent('[aria-label="策略目标版本"]').findAll('el-option-stub') + expect(options).toHaveLength(1) + expect(options[0]!.attributes('label')).toBe('2.0.0') + expect(wrapper.find('[aria-label="最低支持版本"]').element).toHaveProperty('value','1.0.0') + expect(wrapper.text()).toContain('修订 3') + expect(wrapper.findAllComponents(stubs.ElTable)[0]!.props('data')).toEqual([saved]) + wrapper.findComponent('[aria-label="策略架构"]').vm.$emit('update:modelValue','arm64') + await flushPromises() + expect(wrapper.find('[aria-label="最低支持版本"]').element).toHaveProperty('value','') + expect(wrapper.text()).toContain('windows / arm64 / stable') + wrapper.findComponent('[aria-label="策略架构"]').vm.$emit('update:modelValue','x64') + await flushPromises() + expect(wrapper.find('[aria-label="最低支持版本"]').element).toHaveProperty('value','1.0.0') + }) + it('confirms mandatory enable, cancels without PUT, saves UTC and displays server errors',async()=>{ + const {wrapper,fetchMock} = setup() + const confirm = vi.spyOn(ElMessageBox,'confirm').mockRejectedValueOnce('cancel') + wrapper.findComponent('[aria-label="策略产品"]').vm.$emit('update:modelValue',7) + await flushPromises() + const button = () => wrapper.findAll('button').find(item=>item.text()==='保存更新策略')! + await button().trigger('click'); await flushPromises() + expect(confirm).toHaveBeenCalledWith(expect.stringContaining('2026-10-12 15:00:00 UTC'),'启用强制更新策略',expect.any(Object)) + expect(fetchMock.mock.calls.some(([,options])=>options?.method==='PUT')).toBe(false) + confirm.mockResolvedValue('confirm' as Awaited>) + await button().trigger('click'); await flushPromises() + expect(fetchMock).toHaveBeenCalledWith('/api/v1/products/7/update-policies',expect.objectContaining({method:'PUT',credentials:'include',body:JSON.stringify({...saved,product_id:undefined,revision:undefined,recommended_version:undefined,enforce_after:'2026-10-12T15:00:00.000Z'})})) + expect(wrapper.find('[role="status"]').text()).toContain('修订 4') + fetchMock.mockResolvedValueOnce(response({error:{message:'目标版本已撤回'}},false)) + await button().trigger('click'); await flushPromises() + expect(wrapper.find('[role="alert"]').text()).toContain('目标版本已撤回') + }) + it('saves optional disabled scope without mandatory confirmation and keeps version filter independent',async()=>{ + const {wrapper,fetchMock} = setup([]) + const confirm = vi.spyOn(ElMessageBox,'confirm') + wrapper.findComponent('[aria-label="策略产品"]').vm.$emit('update:modelValue',7) + await flushPromises() + wrapper.findComponent('[aria-label="策略目标版本"]').vm.$emit('update:modelValue',9) + await wrapper.findAll('button').find(item=>item.text()==='保存更新策略')!.trigger('click') + await flushPromises() + expect(confirm).not.toHaveBeenCalled() + const put = fetchMock.mock.calls.find(([,options])=>options?.method==='PUT')! + expect(JSON.parse(put[1]!.body as string)).toMatchObject({enabled:false,minimum_supported_version:'',enforce_after:'',release_id:9}) + expect(fetchMock.mock.calls.filter(([url])=>url==='/api/v1/releases?page=1')).toHaveLength(1) + }) + it('shows load failures and ignores stale product responses',async()=>{ + const {wrapper,fetchMock} = setup() + let resolveOld!:(value:ReturnType)=>void + fetchMock.mockImplementationOnce(()=>new Promise(resolve=>{resolveOld=resolve})) + wrapper.findComponent('[aria-label="策略产品"]').vm.$emit('update:modelValue',7) + await flushPromises() + fetchMock.mockResolvedValueOnce(response({error:{message:'策略加载失败'}},false)) + wrapper.findComponent('[aria-label="策略产品"]').vm.$emit('update:modelValue',8) + await flushPromises() + expect(wrapper.find('[role="alert"]').text()).toContain('策略加载失败') + resolveOld(response({data:[saved]})); await flushPromises() + expect(wrapper.text()).not.toContain('修订 3') }) }) diff --git a/frontend/src/views/ReleasesPanel.vue b/frontend/src/views/ReleasesPanel.vue index 1e33f6e..da04257 100644 --- a/frontend/src/views/ReleasesPanel.vue +++ b/frontend/src/views/ReleasesPanel.vue @@ -1,10 +1,73 @@