feat: implement license platform business flows and delivery tooling
Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation. Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
213
backend/internal/httpapi/heartbeat.go
Normal file
213
backend/internal/httpapi/heartbeat.go
Normal file
@@ -0,0 +1,213 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const maxOfflineLease = 14 * 24 * time.Hour
|
||||
const heartbeatInterval = time.Minute
|
||||
const clockTolerance = 5 * time.Minute
|
||||
|
||||
type leasePayload struct {
|
||||
Version string `json:"version"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
State string `json:"state"`
|
||||
ServerTime string `json:"server_time"`
|
||||
EntitlementExpiresAt string `json:"entitlement_expires_at"`
|
||||
LeaseExpiresAt string `json:"lease_expires_at"`
|
||||
}
|
||||
|
||||
func canonicalLease(p leasePayload) string {
|
||||
return strings.Join([]string{"version=" + p.Version, "instance_id=" + p.InstanceID, "state=" + p.State, "server_time=" + p.ServerTime, "entitlement_expires_at=" + p.EntitlementExpiresAt, "lease_expires_at=" + p.LeaseExpiresAt}, "\n")
|
||||
}
|
||||
|
||||
func leaseState(instanceStatus, freeze, licenseStatus, customerStatus string, productActive bool, starts, expires, now time.Time) string {
|
||||
if licenseStatus == "revoked" {
|
||||
return "revoked"
|
||||
}
|
||||
if freeze == "frozen" || customerStatus != "active" || !productActive {
|
||||
return "frozen"
|
||||
}
|
||||
if instanceStatus != "activated" {
|
||||
return "not_activated"
|
||||
}
|
||||
return currentLicenseStatus(licenseStatus, starts, expires, now)
|
||||
}
|
||||
|
||||
func boundedLease(now, entitlement time.Time) time.Time {
|
||||
end := now.Add(maxOfflineLease)
|
||||
if entitlement.Before(end) {
|
||||
end = entitlement
|
||||
}
|
||||
return end
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) heartbeat(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
|
||||
key, ok := parseOperationKey(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Secret string `json:"secret"`
|
||||
ClientTime string `json:"client_time"`
|
||||
}
|
||||
if c.ShouldBindJSON(&in) != nil || len(in.Secret) > 128 {
|
||||
apiError(c, 400, "invalid_request", "心跳请求无效")
|
||||
return
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
|
||||
if err != nil || len(raw) != 32 {
|
||||
apiError(c, 403, "forbidden", "实例凭据无效")
|
||||
return
|
||||
}
|
||||
clientTime, err := time.Parse(time.RFC3339Nano, in.ClientTime)
|
||||
if err != nil {
|
||||
apiError(c, 400, "invalid_request", "client_time 必须为 RFC3339")
|
||||
return
|
||||
}
|
||||
clientTime = clientTime.UTC().Truncate(time.Microsecond)
|
||||
hash := sha256.Sum256(raw)
|
||||
fingerprint := sha256.Sum256([]byte(clientTime.Format(time.RFC3339Nano)))
|
||||
tx, err := a.db.BeginTx(c, nil)
|
||||
if err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
fail := func() { apiError(c, 500, "internal_error", "心跳失败,请使用相同幂等键重试") }
|
||||
var id, actor uint64
|
||||
var stored []byte
|
||||
var instanceStatus, freeze, licenseStatus, customerStatus string
|
||||
var productActive bool
|
||||
var starts, expires time.Time
|
||||
var last, previousClient sql.NullTime
|
||||
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.secret_hash,i.status,i.freeze_state,i.last_seen_at,i.client_seen_at,l.status,l.starts_at,l.expires_at,c.status,p.active FROM license_instances i JOIN licenses l ON l.id=i.license_id JOIN customers c ON c.id=i.customer_id JOIN products p ON p.id=i.product_id WHERE i.instance_id=? FOR UPDATE`, c.Param("instance_id")).Scan(&id, &actor, &stored, &instanceStatus, &freeze, &last, &previousClient, &licenseStatus, &starts, &expires, &customerStatus, &productActive)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
apiError(c, 403, "forbidden", "实例凭据无效")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if !bytesEqual(stored, hash[:]) {
|
||||
apiError(c, 403, "forbidden", "实例凭据无效")
|
||||
return
|
||||
}
|
||||
var now time.Time
|
||||
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
now = now.UTC()
|
||||
if last.Valid && now.Before(last.Time.Add(-clockTolerance)) {
|
||||
apiError(c, 409, "server_clock_rollback", "服务时钟回拨,暂停签发租约")
|
||||
return
|
||||
}
|
||||
if last.Valid && now.Before(last.Time) {
|
||||
now = last.Time.UTC()
|
||||
}
|
||||
state := leaseState(instanceStatus, freeze, licenseStatus, customerStatus, productActive, starts, expires, now)
|
||||
var oldFingerprint, oldResponse []byte
|
||||
var oldState string
|
||||
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response,state FROM heartbeat_operations WHERE instance_id=? AND idempotency_key=?", id, key).Scan(&oldFingerprint, &oldResponse, &oldState)
|
||||
if err == nil {
|
||||
if !bytesEqual(oldFingerprint, fingerprint[:]) {
|
||||
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同心跳")
|
||||
return
|
||||
}
|
||||
if oldState != state {
|
||||
apiError(c, 409, "state_changed", "实例状态已变化,请使用新幂等键心跳")
|
||||
return
|
||||
}
|
||||
var replay any
|
||||
if json.Unmarshal(oldResponse, &replay) != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
c.JSON(200, replay)
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if clientTime.Before(now.Add(-clockTolerance)) || clientTime.After(now.Add(clockTolerance)) || (previousClient.Valid && clientTime.Before(previousClient.Time.Add(-clockTolerance))) {
|
||||
apiError(c, 409, "clock_skew", "客户端时钟偏差或回拨超过五分钟")
|
||||
return
|
||||
}
|
||||
// State changes bypass the normal interval so revocation/freeze can propagate promptly.
|
||||
var observed string
|
||||
if err = tx.QueryRowContext(c, "SELECT observed_state FROM license_instances WHERE id=?", id).Scan(&observed); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if last.Valid && now.Sub(last.Time) < heartbeatInterval && state == observed {
|
||||
c.Header("Retry-After", "60")
|
||||
apiError(c, 429, "rate_limited", "心跳间隔至少一分钟")
|
||||
return
|
||||
}
|
||||
privateKey, err := readSigningKey(a.signingPrivateKeyPEM)
|
||||
if err != nil {
|
||||
apiError(c, 503, "signing_unavailable", "签名服务不可用")
|
||||
return
|
||||
}
|
||||
leaseEnd := now
|
||||
if state == "active" {
|
||||
leaseEnd = boundedLease(now, expires)
|
||||
}
|
||||
payload := leasePayload{"lease-v1", c.Param("instance_id"), state, now.Format(time.RFC3339Nano), expires.UTC().Format(time.RFC3339Nano), leaseEnd.Format(time.RFC3339Nano)}
|
||||
canonical := canonicalLease(payload)
|
||||
var responsePayload any = payload
|
||||
if a.keyring != nil {
|
||||
payload.Version = "lease-v2"
|
||||
canonical = canonicalLease(payload) + "\nkey_id=" + a.keyring.Current
|
||||
responsePayload = gin.H{"version": payload.Version, "instance_id": payload.InstanceID, "state": payload.State, "server_time": payload.ServerTime, "entitlement_expires_at": payload.EntitlementExpiresAt, "lease_expires_at": payload.LeaseExpiresAt, "key_id": a.keyring.Current}
|
||||
}
|
||||
digest := sha256.Sum256([]byte(canonical))
|
||||
sig, err := ecdsa.SignASN1(rand.Reader, privateKey, digest[:])
|
||||
if err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
response := gin.H{"data": gin.H{"payload": responsePayload, "signature": base64.RawStdEncoding.EncodeToString(sig), "canonical_sha256": hex.EncodeToString(digest[:]), "algorithm": "ECDSA-P256-SHA256", "next_heartbeat_seconds": 60}}
|
||||
responseJSON, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if previousClient.Valid && clientTime.Before(previousClient.Time) {
|
||||
clientTime = previousClient.Time.UTC()
|
||||
}
|
||||
if _, err = tx.ExecContext(c, "UPDATE license_instances SET last_seen_at=?,client_seen_at=?,lease_expires_at=?,observed_state=? WHERE id=?", now, clientTime, leaseEnd, state, id); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if _, err = tx.ExecContext(c, "INSERT INTO heartbeat_operations(instance_id,idempotency_key,request_fingerprint,response,state) VALUES(?,?,?,?,?)", id, key, fingerprint[:], responseJSON, state); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
details, _ := json.Marshal(gin.H{"state": state, "previous_state": observed, "lease_expires_at": leaseEnd, "client_actor": "instance"})
|
||||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.heartbeat','license_instance',?,?)", actor, id, details); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
c.JSON(200, response)
|
||||
}
|
||||
Reference in New Issue
Block a user