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

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

View File

@@ -0,0 +1,314 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
)
// Stable SemVer only. Existing arbitrary release labels remain valid for manual downloads.
var stableVersion = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
func compareUpdateVersions(a, b string) (int, error) {
if len(a) > 64 || len(b) > 64 || !stableVersion.MatchString(a) || !stableVersion.MatchString(b) {
return 0, errors.New("version must be stable SemVer")
}
aa, bb := strings.Split(a, "."), strings.Split(b, ".")
for i := 0; i < 3; i++ {
if len(aa[i]) < len(bb[i]) {
return -1, nil
}
if len(aa[i]) > len(bb[i]) {
return 1, nil
}
if aa[i] < bb[i] {
return -1, nil
}
if aa[i] > bb[i] {
return 1, nil
}
}
return 0, nil
}
type UpdatePolicy struct {
ProductID uint64 `json:"product_id"`
Platform string `json:"platform"`
Arch string `json:"arch"`
Channel string `json:"channel"`
Enabled bool `json:"enabled"`
ReleaseID uint64 `json:"release_id"`
RecommendedVersion string `json:"recommended_version"`
MinimumSupportedVersion string `json:"minimum_supported_version"`
EnforceAfter string `json:"enforce_after"`
Message string `json:"message"`
Revision uint64 `json:"revision"`
}
func updateScopeValid(platform, arch, channel string) bool {
return (platform == "windows" || platform == "linux" || platform == "macos") && (arch == "x64" || arch == "arm64") && (channel == "stable" || channel == "beta")
}
const policySelect = `SELECT u.product_id,u.platform,u.arch,u.channel,u.enabled,u.release_id,r.version,u.minimum_supported_version,u.enforce_after,u.message,u.revision,r.sha256,r.size_bytes,r.published FROM product_update_policies u JOIN product_releases r ON r.id=u.release_id AND r.product_id=u.product_id`
func scanUpdatePolicy(row interface{ Scan(...any) error }) (UpdatePolicy, string, uint64, bool, error) {
var p UpdatePolicy
var deadline sql.NullTime
var digest string
var size uint64
var published bool
err := row.Scan(&p.ProductID, &p.Platform, &p.Arch, &p.Channel, &p.Enabled, &p.ReleaseID, &p.RecommendedVersion, &p.MinimumSupportedVersion, &deadline, &p.Message, &p.Revision, &digest, &size, &published)
if deadline.Valid {
p.EnforceAfter = deadline.Time.UTC().Format(time.RFC3339Nano)
}
return p, digest, size, published, err
}
func (a *BusinessAPI) listUpdatePolicies(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "产品无效")
return
}
rows, err := a.db.QueryContext(c, policySelect+" WHERE u.product_id=? ORDER BY u.platform,u.arch,u.channel", id)
if err != nil {
apiError(c, 503, "updates_unavailable", "升级策略不可用")
return
}
defer rows.Close()
out := []UpdatePolicy{}
for rows.Next() {
p, _, _, _, err := scanUpdatePolicy(rows)
if err != nil {
apiError(c, 503, "updates_unavailable", "升级策略不可用")
return
}
out = append(out, p)
}
if rows.Err() != nil {
apiError(c, 503, "updates_unavailable", "升级策略不可用")
return
}
c.JSON(200, gin.H{"data": out})
}
func (a *BusinessAPI) saveUpdatePolicy(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 8192)
var p UpdatePolicy
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 || c.ShouldBindJSON(&p) != nil || !updateScopeValid(p.Platform, p.Arch, p.Channel) || p.ReleaseID == 0 || utf8.RuneCountInString(p.Message) > 2000 {
apiError(c, 400, "invalid_request", "升级策略参数无效")
return
}
p.ProductID = id
var deadline any
if p.MinimumSupportedVersion != "" {
if _, err = compareUpdateVersions(p.MinimumSupportedVersion, p.MinimumSupportedVersion); err != nil {
apiError(c, 400, "invalid_version", "最低版本必须为 x.y.z")
return
}
t, e := time.Parse(time.RFC3339Nano, p.EnforceAfter)
if e != nil {
apiError(c, 400, "invalid_request", "强制升级必须设置生效时间")
return
}
deadline = t.UTC()
p.EnforceAfter = t.UTC().Format(time.RFC3339Nano)
} else if p.EnforceAfter != "" {
apiError(c, 400, "invalid_request", "没有最低版本时不能设置强制时间")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 503, "updates_unavailable", "保存失败")
return
}
defer tx.Rollback()
// Product lock serializes scope inserts and revision changes.
var locked uint64
if err = tx.QueryRowContext(c, "SELECT id FROM products WHERE id=? FOR UPDATE", id).Scan(&locked); err != nil {
apiError(c, 404, "not_found", "产品不存在")
return
}
var published bool
if err = tx.QueryRowContext(c, "SELECT version,published FROM product_releases WHERE id=? AND product_id=? FOR UPDATE", p.ReleaseID, id).Scan(&p.RecommendedVersion, &published); err != nil || !published {
apiError(c, 400, "invalid_release", "请选择该产品已发布版本")
return
}
if _, err = compareUpdateVersions(p.RecommendedVersion, p.RecommendedVersion); err != nil {
apiError(c, 400, "invalid_version", "目标版本必须为 x.y.z")
return
}
if p.MinimumSupportedVersion != "" {
cmp, _ := compareUpdateVersions(p.MinimumSupportedVersion, p.RecommendedVersion)
if cmp > 0 {
apiError(c, 400, "invalid_version", "最低支持版本不能高于目标版本")
return
}
}
_, err = tx.ExecContext(c, `INSERT INTO product_update_policies(product_id,platform,arch,channel,enabled,release_id,minimum_supported_version,enforce_after,message,updated_by) VALUES(?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE enabled=VALUES(enabled),release_id=VALUES(release_id),minimum_supported_version=VALUES(minimum_supported_version),enforce_after=VALUES(enforce_after),message=VALUES(message),updated_by=VALUES(updated_by),revision=revision+1`, id, p.Platform, p.Arch, p.Channel, p.Enabled, p.ReleaseID, p.MinimumSupportedVersion, deadline, p.Message, c.GetUint64("admin_id"))
if err != nil {
apiError(c, 503, "updates_unavailable", "保存失败")
return
}
if err = tx.QueryRowContext(c, "SELECT revision FROM product_update_policies WHERE product_id=? AND platform=? AND arch=? AND channel=?", id, p.Platform, p.Arch, p.Channel).Scan(&p.Revision); err != nil {
apiError(c, 503, "updates_unavailable", "保存失败")
return
}
details, _ := json.Marshal(p)
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'update_policy.saved','product',?,?)", c.GetUint64("admin_id"), id, details); err != nil {
apiError(c, 503, "audit_unavailable", "审计失败,策略未保存")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 503, "updates_unavailable", "保存失败")
return
}
c.JSON(200, gin.H{"data": p})
}
type UpdatePayload struct {
Version string `json:"version"`
InstanceID string `json:"instance_id"`
ProductID uint64 `json:"product_id"`
CustomerID uint64 `json:"customer_id"`
CurrentVersion string `json:"current_version"`
Platform string `json:"platform"`
Arch string `json:"arch"`
Channel string `json:"channel"`
ServerTime string `json:"server_time"`
ExpiresAt string `json:"expires_at"`
PolicyRevision uint64 `json:"policy_revision"`
PolicyEnabled bool `json:"policy_enabled"`
RecommendedVersion string `json:"recommended_version"`
MinimumSupportedVersion string `json:"minimum_supported_version"`
EnforceAfter string `json:"enforce_after"`
Mandatory bool `json:"mandatory"`
RequiredNow bool `json:"required_now"`
UpdateAvailable bool `json:"update_available"`
DownloadAllowed bool `json:"download_allowed"`
ReleaseID uint64 `json:"release_id"`
SHA256 string `json:"sha256"`
SizeBytes uint64 `json:"size_bytes"`
Message string `json:"message"`
}
func evaluateUpdate(p UpdatePolicy, current string, now time.Time) (available, mandatory, required bool) {
if !p.Enabled {
return
}
cmp, err := compareUpdateVersions(current, p.RecommendedVersion)
available = err == nil && cmp < 0
if p.MinimumSupportedVersion != "" {
cmp, err = compareUpdateVersions(current, p.MinimumSupportedVersion)
mandatory = err == nil && cmp < 0
t, e := time.Parse(time.RFC3339Nano, p.EnforceAfter)
required = mandatory && e == nil && !now.Before(t)
}
return
}
func (a *BusinessAPI) checkUpdate(c *gin.Context) {
c.Header("Cache-Control", "private, no-store")
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
var in struct {
Secret string `json:"secret"`
CurrentVersion string `json:"current_version"`
Platform string `json:"platform"`
Arch string `json:"arch"`
Channel string `json:"channel"`
}
instance := c.Param("instance_id")
if len(instance) != 36 || c.ShouldBindJSON(&in) != nil || len(in.Secret) > 128 || !updateScopeValid(in.Platform, in.Arch, in.Channel) {
apiError(c, 400, "invalid_request", "升级检查参数无效")
return
}
if _, err := compareUpdateVersions(in.CurrentVersion, in.CurrentVersion); err != nil {
apiError(c, 400, "invalid_version", "当前版本必须为 x.y.z")
return
}
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
if err != nil || len(raw) != 32 {
apiError(c, 403, "forbidden", "实例凭据无效")
return
}
sum := sha256.Sum256(raw)
if a.keyring == nil {
apiError(c, 503, "keyring_unavailable", "升级签名不可用")
return
}
key, err := readSigningKey(a.signingPrivateKeyPEM)
if err != nil || a.keyring.Current == "" {
apiError(c, 503, "keyring_unavailable", "升级签名不可用")
return
}
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
if err != nil {
apiError(c, 503, "updates_unavailable", "升级检查不可用")
return
}
defer tx.Rollback()
var rowID, actor, owner, product uint64
var stored []byte
var istate, freeze, lstate, cstate string
var active bool
var starts, ends, now time.Time
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.secret_hash,i.status,i.freeze_state,l.status,c.status,p.active,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id AND l.customer_id=i.customer_id AND l.product_id=i.product_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=?`, instance).Scan(&rowID, &actor, &owner, &product, &stored, &istate, &freeze, &lstate, &cstate, &active, &starts, &ends)
if err == sql.ErrNoRows || (err == nil && !bytesEqual(stored, sum[:])) {
apiError(c, 403, "forbidden", "实例凭据无效")
return
}
if err != nil {
apiError(c, 503, "updates_unavailable", "升级检查不可用")
return
}
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
apiError(c, 503, "updates_unavailable", "升级检查不可用")
return
}
p, digest, size, published, err := scanUpdatePolicy(tx.QueryRowContext(c, policySelect+" WHERE u.product_id=? AND u.platform=? AND u.arch=? AND u.channel=?", product, in.Platform, in.Arch, in.Channel))
if err != nil && err != sql.ErrNoRows {
apiError(c, 503, "updates_unavailable", "升级检查不可用")
return
}
if err == sql.ErrNoRows {
p = UpdatePolicy{}
}
// Never disable an enabled mandatory policy silently when its target is unavailable.
if p.Enabled && !published {
apiError(c, 503, "update_target_unavailable", "升级目标不可用,请联系管理员")
return
}
available, mandatory, required := evaluateUpdate(p, in.CurrentVersion, now)
payload := UpdatePayload{Version: "update-v1", InstanceID: instance, ProductID: product, CustomerID: owner, CurrentVersion: in.CurrentVersion, Platform: in.Platform, Arch: in.Arch, Channel: in.Channel, ServerTime: now.UTC().Format(time.RFC3339Nano), ExpiresAt: now.Add(15 * time.Minute).UTC().Format(time.RFC3339Nano), PolicyRevision: p.Revision, PolicyEnabled: p.Enabled, RecommendedVersion: p.RecommendedVersion, MinimumSupportedVersion: p.MinimumSupportedVersion, EnforceAfter: p.EnforceAfter, Mandatory: mandatory, RequiredNow: required, UpdateAvailable: available, DownloadAllowed: leaseState(istate, freeze, lstate, cstate, active, starts, ends, now) == "active" && p.Enabled, ReleaseID: p.ReleaseID, SHA256: digest, SizeBytes: size, Message: p.Message}
bytes, err := json.Marshal(payload)
if err != nil {
apiError(c, 503, "updates_unavailable", "升级检查不可用")
return
}
hash := sha256.Sum256(bytes)
signature, err := ecdsa.SignASN1(rand.Reader, key, hash[:])
if err != nil {
apiError(c, 503, "updates_unavailable", "升级签名不可用")
return
}
details, _ := json.Marshal(gin.H{"client_actor": "instance", "current_version": in.CurrentVersion, "policy_revision": p.Revision, "required_now": required, "platform": in.Platform, "arch": in.Arch, "channel": in.Channel})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'update.checked','license_instance',?,?)", actor, rowID, details); err != nil {
apiError(c, 503, "audit_unavailable", "审计失败")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 503, "updates_unavailable", "升级检查不可用")
return
}
c.JSON(200, gin.H{"data": gin.H{"payload": base64.RawStdEncoding.EncodeToString(bytes), "signature": base64.RawStdEncoding.EncodeToString(signature), "key_id": a.keyring.Current}})
}