fix: make client integration kit self-contained and clarify capabilities
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 15:22:09 +08:00
parent d42067746c
commit 5353a4a128
15 changed files with 198 additions and 32 deletions

View File

@@ -0,0 +1,2 @@
cryptography>=41
httpx>=0.25,<1

View File

@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
import { mkdtemp, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { UpdateClient, UpdateError, verifyCheck } from './update-sdk.mjs';
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const now = Date.now();
const payload = {version:'update-v1',instance_id:'i1',product_id:1,customer_id:2,current_version:'1.0.0',platform:'linux',arch:'x64',channel:'stable',server_time:new Date(now).toISOString().replace('.000Z','Z'),expires_at:new Date(now+600000).toISOString().replace('.000Z','Z'),policy_revision:3,policy_enabled:true,recommended_version:'2.0.0',minimum_supported_version:'1.0.0',enforce_after:'',mandatory:false,required_now:false,update_available:true,download_allowed:true,release_id:7,sha256:createHash('sha256').update('good').digest('hex'),size_bytes:4,message:''};
function envelope(p = payload) { const raw = Buffer.from(JSON.stringify(p)); return {payload:raw.toString('base64').replace(/=+$/,''),signature:sign('sha256',raw,privateKey).toString('base64').replace(/=+$/,''),key_id:'k1'}; }
const keys = {k1:publicKey.export({type:'spki',format:'pem'})};
const signed = envelope();
verifyCheck(signed, keys, 'i1', {now,expectedPlatform:'linux',expectedArch:'x64',expectedChannel:'stable',expectedCurrentVersion:'1.0.0'});
const tampered = {...signed, payload:Buffer.from('{"version":"update-v1"}').toString('base64').replace(/=+$/,'')};
assert.throws(() => verifyCheck(tampered, keys, 'i1', {now}), UpdateError);
assert.throws(() => verifyCheck(signed, keys, 'wrong', {now}), UpdateError);
assert.throws(() => verifyCheck(signed, keys, 'i1', {now:now+600001}), UpdateError);
assert.throws(() => verifyCheck(signed, keys, 'i1', {now,previous:{policy_revision:4}}), UpdateError);
assert.throws(() => verifyCheck(signed, keys, 'i1', {now,expectedCurrentVersion:'0.9'}), UpdateError);
for (const [status, chunks, expected] of [[200,['good-extra'],'package_too_large'],[206,['good'],'download_http_206'],[302,[],'download_http_302'],[500,[],'download_http_500'],[200,['evil'],'package_integrity_failed']]) {
const dir = await mkdtemp(join(tmpdir(),'update-sdk-')); const target = join(dir,'pkg.bin');
const fetchImpl = async () => new Response(Readable.toWeb(Readable.from(chunks.map(x => Buffer.from(x)))), {status,headers: status===302?{location:'https://evil.invalid'}:{}});
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,fetchImpl});
await assert.rejects(client.download({payload},target), e => e instanceof UpdateError && e.message.includes(expected));
assert.deepEqual(await readdir(dir), []); await rm(dir,{recursive:true,force:true});
}
let persisted;
const state = {load:()=>persisted,saveAtomic:value=>{persisted=value;}};
const fetchImpl = async () => Response.json({data:signed});
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,state,fetchImpl,clock:()=>now});
persisted={scope:JSON.stringify(['i1','windows','x64','stable']),policy_revision:99};
assert.equal((await client.check('1.0.0','linux','x64','stable')).payload.policy_revision,3);
console.log('Node update SDK negative tests passed');

View File

@@ -0,0 +1,72 @@
import base64
import hashlib
import json
import tempfile
import unittest
from pathlib import Path
from datetime import datetime, timezone
import httpx
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from update_sdk import UpdateClient, UpdateError, verify_check
class MemoryState:
def __init__(self, value=None): self.value = value
def load(self): return self.value
def save_atomic(self, state): self.value = state
class SDKTests(unittest.TestCase):
def setUp(self):
self.private = ec.generate_private_key(ec.SECP256R1())
self.public = self.private.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()
self.now = __import__('time').time()
stamp = datetime.fromtimestamp(self.now, timezone.utc).isoformat().replace('+00:00', 'Z')
self.payload = {"version":"update-v1","instance_id":"i1","product_id":1,"customer_id":2,"current_version":"1.0.0","platform":"linux","arch":"x64","channel":"stable","server_time":stamp,"expires_at":datetime.fromtimestamp(self.now+600, timezone.utc).isoformat().replace('+00:00','Z'),"policy_revision":3,"policy_enabled":True,"recommended_version":"2.0.0","minimum_supported_version":"1.0.0","enforce_after":"","mandatory":False,"required_now":False,"update_available":True,"download_allowed":True,"release_id":7,"sha256":hashlib.sha256(b'good').hexdigest(),"size_bytes":4,"message":""}
self.envelope = self.sign(self.payload)
def sign(self, payload):
raw = json.dumps(payload, separators=(',', ':')).encode()
sig = self.private.sign(raw, ec.ECDSA(hashes.SHA256()))
return {"payload":base64.b64encode(raw).decode().rstrip('='),"signature":base64.b64encode(sig).decode().rstrip('='),"key_id":"k1"}
def test_signature_context_expiry_and_rollback(self):
verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_platform="linux", expected_arch="x64", expected_channel="stable", expected_current_version="1.0.0")
tampered = dict(self.envelope); tampered["payload"] = base64.b64encode(b'{"version":"update-v1"}').decode().rstrip('=')
with self.assertRaises(UpdateError): verify_check(tampered, {"k1":self.public}, "i1", now=self.now)
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "wrong", now=self.now)
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now+601)
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, previous={"policy_revision":4})
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_current_version="0.9")
def client(self, handler, state=None):
transport = httpx.MockTransport(handler)
client = httpx.Client(transport=transport, follow_redirects=False)
return UpdateClient('https://license.example', 'i1', 'secret', {"k1":self.public}, state=state, client=client)
def test_stream_download_bounds_redirect_and_cleanup(self):
cases = [
(lambda req: httpx.Response(200, content=b'good-extra'), 'package_too_large'),
(lambda req: httpx.Response(302, headers={"location":"https://evil.invalid"}), 'download_http_302'),
(lambda req: httpx.Response(200, content=b'evil'), 'package_integrity_failed'),
]
for handler, expected_error in cases:
with self.subTest(error=expected_error), tempfile.TemporaryDirectory() as directory:
target = Path(directory) / 'pkg.bin'
sdk = self.client(handler)
with self.assertRaises(UpdateError) as caught: sdk.download(type('R', (), {"payload":self.payload})(), target)
self.assertIn(expected_error, str(caught.exception))
self.assertFalse(target.exists())
self.assertEqual(list(Path(directory).iterdir()), [])
def test_scoped_revision_does_not_leak_between_platforms(self):
state = MemoryState({"scope": '["i1","windows","x64","stable"]', "policy_revision":99})
sdk = self.client(lambda req: httpx.Response(200, json={"data":self.envelope}), state)
result = sdk.check('1.0.0','linux','x64','stable')
self.assertEqual(result.payload['policy_revision'], 3)
if __name__ == '__main__': unittest.main()

View File

@@ -1,6 +1,6 @@
"""Reference client for the signed update-v1 contract.
Requires Python 3.11 and the ``cryptography`` package. No installer is executed
Requires Python 3.11+ and the ``cryptography`` and ``httpx`` packages. No installer is executed
by this module; callers inject an installer after verification.
"""
from __future__ import annotations

View File

@@ -66,7 +66,7 @@ canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校
## 时间与状态存储
参照 client/verify.mjs:now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。
客户端必须实现以下租约状态判断(升级 SDK 不实现 license-v2/lease-v2 授权):now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。
验签、范围检查后,先在受保护存储中原子保存实例 ID、租约、enabled、服务端与本地时间高水位,再启用业务。离线每次授权检查都应检查本地时间回拨,并持久化更新本地高水位。应用重新启动不得清除高水位绕过限制。
@@ -80,7 +80,7 @@ canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校
## 发布包下载
POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。支持 Range 续传,处理 200/206/416 和 Content-Range。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。
POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。服务端支持 Range 续传,调用方实现续传时须处理 200/206/416 和 Content-Range。随包 Python/Node 升级参考 SDK 仅完整下载并要求 HTTP 200,不实现续传。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。
## 模式约束

View File

@@ -10,13 +10,13 @@
`POST /api/v1/instances/{instance_id}/updates/check`
请求 JSON:`{"secret":"...","current_version":"1.2.3","platform":"windows","arch":"amd64","channel":"stable"}`。
请求 JSON:`{"secret":"...","current_version":"1.2.3","platform":"windows","arch":"x64","channel":"stable"}`。
响应 `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`。
客户端必须核对实例上下文、服务端时间与当前时间偏差不超过 5 分钟、`expires_at` 未过期且不超过 `server_time + 15min`,并持久化拒绝 `policy_revision` 回退。`required_now` 只在签名验证、策略有效且本地版本比较确认低于最低支持版本后生效;`mandatory` 不能绕过用户/维护窗口、下载或包校验。`enforce_after` 为空表示无截止时间。
无策略或策略关闭时,服务端返回 `policy_enabled=false` 且 release 元数据为空/不可下载。`canRun` 不得把升级检查通过、`download_allowed` 或 active entitlement 当成授权许可;业务运行仍由独立、已验证的 license-v2/lease-v2 状态决定。
无策略时,服务端返回 `policy_enabled=false`、空版本/摘要字符串和零 release ID/大小。策略关闭时可能保留 release 元数据,但 `download_allowed=false`、`update_available=false`,不得据此下载。`canRun` 不得把升级检查通过、`download_allowed` 或 active entitlement 当成授权许可;业务运行仍由独立、已验证的 license-v2/lease-v2 状态决定。
## 下载与安装边界
@@ -26,8 +26,16 @@ SDK 只提供 check、download、摘要校验和注入式 Installer。安装器
## 离线、错误与 rollout 限制
离线不能刷新检查结果或延长 15 分钟 envelope TTL;不能因检查失败伪造强制升级。有效 license lease 的离线运行按既有租约策略执行,过期或回拨必须 fail closed。网络错误、401/403、409、429 和 5xx 只允许有限重试,不把 HTTP 错误解释成策略。灰度由服务端策略决定,客户端不得自行伪造命中;当前协议不提供升级回报接口。策略 revision 是单调高水位,检测到回退立即拒绝。
离线不能刷新检查结果或延长 15 分钟 envelope TTL;不能因检查失败伪造强制升级。有效 license lease 的离线运行按既有租约策略执行,过期或回拨必须 fail closed。网络错误、401/403、409、429 和 5xx 只允许有限重试,不把 HTTP 错误解释成策略。当前仅按产品/平台/架构/渠道选择策略,不提供百分比灰度;当前协议不提供升级回报接口。策略 revision 是单调高水位,检测到回退立即拒绝。
## 参考实现
仓库提供 `client/update_sdk.py`(Python 3.11 + cryptography)和 `client/update-sdk.mjs`(Node.js 20+,内置 crypto/fetch),包含验签、上下文/TTL/回滚检查、禁止重定向的下载、长度与摘要校验及注入安装器。其它语言应按同一 raw payload、DER ECDSA、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。
仓库提供 `client/update_sdk.py`(Python 3.11+、cryptography 和 httpx)和 `client/update-sdk.mjs`(Node.js 20+,内置 crypto/fetch),包含验签、上下文/TTL/回滚检查、禁止重定向的下载、长度与摘要校验及注入安装器。其它语言应按同一 raw payload、DER ECDSA、时间和策略规则实现并覆盖篡改、上下文、过期、回拨、回退和哈希失败测试。没有独立包签名或安装器时只能检查/暂存,不得自动执行。
## 下载能力与验收运行
服务端支持 Range(200/206/416),随包参考 SDK 仅执行完整下载,要求 HTTP 200,拒绝 206,不提供断点续传。需要续传时由应用另外实现 Range/Content-Range 校验,最终仍须验证整个包的长度与 SHA-256。
解压 ZIP 后,在 client 目录运行 `python -m pip install -r requirements.txt`、`python -m unittest test_update_sdk -v`;Node.js 20+ 运行 `node test-update-sdk.mjs`,无需 npm 依赖。这些测试使用本地测试密钥和模拟网络,不验证生产下载或安装。
当前参考 SDK 没有完整 LicenseClient、canRun、本地强制升级评估、信任导入器或持久化存储实现。应用必须实现并注入持久化 StateStore,按实例/平台/架构/渠道保存 revision 高水位,并自行实现可信时间防回拨、本地 SemVer 比较和 deadline 判断。下载前及安装前重新检查策略,验证 TTL、授权和当前版本;安装器负责兼容性、跨进程锁、替换、重启、健康检查及回滚。