feat: add signed client upgrade policies
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
37
client/test-update-sdk.mjs
Normal file
37
client/test-update-sdk.mjs
Normal 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',platform:'linux',arch:'x64',channel:'stable',server_time:new Date(now).toISOString().replace('.000Z','Z'),expires_at:new Date(now+600000).toISOString().replace('.000Z','Z'),policy_revision:3,policy_enabled:true,recommended_version:'2.0',minimum_supported_version:'1.0',enforce_after:null,mandatory:false,required_now:false,update_available:true,download_allowed:true,release_id:7,sha256:createHash('sha256').update('good').digest('hex'),size_bytes:4,message:''};
|
||||
function envelope(p = payload) { const raw = Buffer.from(JSON.stringify(p)); return {payload:raw.toString('base64').replace(/=+$/,''),signature:sign('sha256',raw,privateKey).toString('base64').replace(/=+$/,''),key_id:'k1'}; }
|
||||
const keys = {k1:publicKey.export({type:'spki',format:'pem'})};
|
||||
const signed = envelope();
|
||||
verifyCheck(signed, keys, 'i1', {now,expectedPlatform:'linux',expectedArch:'x64',expectedChannel:'stable',expectedCurrentVersion:'1.0'});
|
||||
const tampered = {...signed, payload:Buffer.from('{"version":"update-v1"}').toString('base64').replace(/=+$/,'')};
|
||||
assert.throws(() => verifyCheck(tampered, keys, 'i1', {now}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'wrong', {now}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'i1', {now:now+600001}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'i1', {now,previous:{policy_revision:4}}), UpdateError);
|
||||
assert.throws(() => verifyCheck(signed, keys, 'i1', {now,expectedCurrentVersion:'0.9'}), UpdateError);
|
||||
|
||||
for (const [status, chunks, expected] of [[200,['good-extra'],'package_too_large'],[206,['good'],'download_http_206'],[302,[],'download_http_302'],[500,[],'download_http_500'],[200,['evil'],'package_integrity_failed']]) {
|
||||
const dir = await mkdtemp(join(tmpdir(),'update-sdk-')); const target = join(dir,'pkg.bin');
|
||||
const fetchImpl = async () => new Response(Readable.toWeb(Readable.from(chunks.map(x => Buffer.from(x)))), {status,headers: status===302?{location:'https://evil.invalid'}:{}});
|
||||
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,fetchImpl});
|
||||
await assert.rejects(client.download({payload},target), e => e instanceof UpdateError && e.message.includes(expected));
|
||||
assert.deepEqual(await readdir(dir), []); await rm(dir,{recursive:true,force:true});
|
||||
}
|
||||
|
||||
let persisted;
|
||||
const state = {load:()=>persisted,saveAtomic:value=>{persisted=value;}};
|
||||
const fetchImpl = async () => Response.json({data:signed});
|
||||
const client = new UpdateClient({baseUrl:'https://license.example',instanceId:'i1',secret:'secret',publicKeys:keys,state,fetchImpl,clock:()=>now});
|
||||
persisted={scope:JSON.stringify(['i1','windows','x64','stable']),policy_revision:99};
|
||||
assert.equal((await client.check('1.0','linux','x64','stable')).payload.policy_revision,3);
|
||||
console.log('Node update SDK negative tests passed');
|
||||
72
client/test_update_sdk.py
Normal file
72
client/test_update_sdk.py
Normal 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","platform":"linux","arch":"x64","channel":"stable","server_time":stamp,"expires_at":datetime.fromtimestamp(self.now+600, timezone.utc).isoformat().replace('+00:00','Z'),"policy_revision":3,"policy_enabled":True,"recommended_version":"2.0","minimum_supported_version":"1.0","enforce_after":None,"mandatory":False,"required_now":False,"update_available":True,"download_allowed":True,"release_id":7,"sha256":hashlib.sha256(b'good').hexdigest(),"size_bytes":4,"message":""}
|
||||
self.envelope = self.sign(self.payload)
|
||||
|
||||
def sign(self, payload):
|
||||
raw = json.dumps(payload, separators=(',', ':')).encode()
|
||||
sig = self.private.sign(raw, ec.ECDSA(hashes.SHA256()))
|
||||
return {"payload":base64.b64encode(raw).decode().rstrip('='),"signature":base64.b64encode(sig).decode().rstrip('='),"key_id":"k1"}
|
||||
|
||||
def test_signature_context_expiry_and_rollback(self):
|
||||
verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_platform="linux", expected_arch="x64", expected_channel="stable", expected_current_version="1.0")
|
||||
tampered = dict(self.envelope); tampered["payload"] = base64.b64encode(b'{"version":"update-v1"}').decode().rstrip('=')
|
||||
with self.assertRaises(UpdateError): verify_check(tampered, {"k1":self.public}, "i1", now=self.now)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "wrong", now=self.now)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now+601)
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, previous={"policy_revision":4})
|
||||
with self.assertRaises(UpdateError): verify_check(self.envelope, {"k1":self.public}, "i1", now=self.now, expected_current_version="0.9")
|
||||
|
||||
def client(self, handler, state=None):
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = httpx.Client(transport=transport, follow_redirects=False)
|
||||
return UpdateClient('https://license.example', 'i1', 'secret', {"k1":self.public}, state=state, client=client)
|
||||
|
||||
def test_stream_download_bounds_redirect_and_cleanup(self):
|
||||
cases = [
|
||||
(lambda req: httpx.Response(200, content=b'good-extra'), 'package_too_large'),
|
||||
(lambda req: httpx.Response(302, headers={"location":"https://evil.invalid"}), 'download_http_302'),
|
||||
(lambda req: httpx.Response(200, content=b'evil'), 'package_integrity_failed'),
|
||||
]
|
||||
for handler, expected_error in cases:
|
||||
with self.subTest(error=expected_error), tempfile.TemporaryDirectory() as directory:
|
||||
target = Path(directory) / 'pkg.bin'
|
||||
sdk = self.client(handler)
|
||||
with self.assertRaises(UpdateError) as caught: sdk.download(type('R', (), {"payload":self.payload})(), target)
|
||||
self.assertIn(expected_error, str(caught.exception))
|
||||
self.assertFalse(target.exists())
|
||||
self.assertEqual(list(Path(directory).iterdir()), [])
|
||||
|
||||
def test_scoped_revision_does_not_leak_between_platforms(self):
|
||||
state = MemoryState({"scope": '["i1","windows","x64","stable"]', "policy_revision":99})
|
||||
sdk = self.client(lambda req: httpx.Response(200, json={"data":self.envelope}), state)
|
||||
result = sdk.check('1.0','linux','x64','stable')
|
||||
self.assertEqual(result.payload['policy_revision'], 3)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
73
client/update-sdk.mjs
Normal file
73
client/update-sdk.mjs
Normal 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); }
|
||||
}
|
||||
182
client/update_sdk.py
Normal file
182
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)
|
||||
14
client/upgrade-sdk-testing.md
Normal file
14
client/upgrade-sdk-testing.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Upgrade SDK tests
|
||||
|
||||
Run the Python test from the client directory so the module import resolves:
|
||||
|
||||
```sh
|
||||
cd client
|
||||
python -m unittest test_update_sdk -v
|
||||
```
|
||||
|
||||
Run the Node.js negative tests from the repository root:
|
||||
|
||||
```sh
|
||||
node client/test-update-sdk.mjs
|
||||
```
|
||||
Reference in New Issue
Block a user