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)
|
||||
Reference in New Issue
Block a user