feat: add signed client upgrade policies
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-13 07:28:25 +08:00
parent 5780b27e30
commit d42067746c
25 changed files with 2154 additions and 171 deletions

View File

@@ -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)

View File

@@ -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])

View File

@@ -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); }
}

View File

@@ -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)

View File

@@ -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"
}
}
}
}
}
}

View File

@@ -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":"<base64(raw UTF-8 JSON)>","signature":"<unpadded standard base64 DER ECDSA>","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、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。

View File

@@ -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",

View File

@@ -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
}

View File

@@ -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) {

View File

@@ -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}})
}

View File

@@ -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)
}
}
}