feat: add signed client upgrade policies
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -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); }
|
||||
}
|
||||
182
backend/internal/httpapi/integration_assets/client/update_sdk.py
Normal file
182
backend/internal/httpapi/integration_assets/client/update_sdk.py
Normal 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)
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。
|
||||
|
||||
Reference in New Issue
Block a user