Files
yhy-mager/backend/internal/httpapi/activation.go
xiewenjun 54c318c615
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
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>
2026-10-09 15:33:22 +08:00

349 lines
14 KiB
Go

package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type instanceRecord struct {
ID uint64 `json:"id"`
InstanceID string `json:"instance_id"`
LicenseID uint64 `json:"license_id"`
CustomerID uint64 `json:"customer_id"`
ProductID uint64 `json:"product_id"`
Status string `json:"status"`
ActivatedAt *time.Time `json:"activated_at,omitempty"`
CertificateVersion string `json:"certificate_version,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastSeenAt *time.Time `json:"last_seen_at,omitempty"`
LeaseExpiresAt *time.Time `json:"lease_expires_at,omitempty"`
FreezeState string `json:"freeze_state"`
ObservedState string `json:"observed_state"`
EntitlementState string `json:"entitlement_state"`
}
func newInstanceID() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%s-%s-%s-%s-%s", hex.EncodeToString(b[:4]), hex.EncodeToString(b[4:6]), hex.EncodeToString(b[6:8]), hex.EncodeToString(b[8:10]), hex.EncodeToString(b[10:])), nil
}
func readSigningKey(pemText string) (*ecdsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemText))
if block == nil {
return nil, errors.New("missing PEM")
}
if key, err := x509.ParseECPrivateKey(block.Bytes); err == nil && key.Curve == elliptic.P256() {
return key, nil
}
keyAny, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
key, ok := keyAny.(*ecdsa.PrivateKey)
if !ok || key.Curve != elliptic.P256() {
return nil, errors.New("signing key must be P-256 ECDSA")
}
return key, nil
}
// canonicalCertificatePayload is newline-delimited key=value with fixed order and no whitespace.
func canonicalCertificatePayload(version, instanceID string, licenseID, customerID, productID uint64, startsAt, expiresAt time.Time) string {
return strings.Join([]string{
"version=" + version,
"instance_id=" + instanceID,
"license_id=" + strconv.FormatUint(licenseID, 10),
"customer_id=" + strconv.FormatUint(customerID, 10),
"product_id=" + strconv.FormatUint(productID, 10),
"starts_at=" + startsAt.UTC().Format(time.RFC3339Nano),
"expires_at=" + expiresAt.UTC().Format(time.RFC3339Nano),
}, "\n")
}
func (a *BusinessAPI) provisionInstance(c *gin.Context) {
licenseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || licenseID == 0 {
apiError(c, 400, "invalid_request", "授权 ID 无效")
return
}
actor := c.MustGet("admin_id")
instanceID, err := newInstanceID()
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
secretBytes := make([]byte, 32)
if _, err = rand.Read(secretBytes); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
secret := base64.RawURLEncoding.EncodeToString(secretBytes)
hash := sha256.Sum256(secretBytes)
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var customerID, productID uint64
var status string
if err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM licenses WHERE id=? FOR UPDATE", licenseID).Scan(&customerID, &productID, &status); errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "授权不存在")
return
} else if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if status == "revoked" {
apiError(c, 409, "invalid_state", "已撤销授权不能创建实例")
return
}
var existing string
if err = tx.QueryRowContext(c, "SELECT instance_id FROM license_instances WHERE license_id=?", licenseID).Scan(&existing); err == nil {
apiError(c, 409, "instance_conflict", "授权已绑定实例")
return
} else if !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
var id uint64
res, err := tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", instanceID, licenseID, customerID, productID, hash[:], actor)
if err != nil {
apiError(c, 409, "instance_conflict", "实例创建失败")
return
}
id64, _ := res.LastInsertId()
id = uint64(id64)
details, _ := json.Marshal(gin.H{"license_id": licenseID, "instance_id": instanceID})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.provisioned','license_instance',?,?)", actor, id, details); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "secret_expires": "one-time"})
}
func (a *BusinessAPI) listInstances(c *gin.Context) {
licenseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || licenseID == 0 {
apiError(c, 400, "invalid_request", "授权 ID 无效")
return
}
rows, err := a.db.QueryContext(c, "SELECT id,instance_id,license_id,customer_id,product_id,status,activated_at,COALESCE(certificate_version,''),created_at,last_seen_at,lease_expires_at,freeze_state,observed_state,(SELECT status FROM licenses WHERE id=license_id) FROM license_instances WHERE license_id=? ORDER BY id", licenseID)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer rows.Close()
out := []instanceRecord{}
for rows.Next() {
var x instanceRecord
if err = rows.Scan(&x.ID, &x.InstanceID, &x.LicenseID, &x.CustomerID, &x.ProductID, &x.Status, &x.ActivatedAt, &x.CertificateVersion, &x.CreatedAt, &x.LastSeenAt, &x.LeaseExpiresAt, &x.FreezeState, &x.ObservedState, &x.EntitlementState); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
out = append(out, x)
}
c.JSON(200, gin.H{"data": out})
}
func (a *BusinessAPI) activateInstance(c *gin.Context) {
if a.signingPrivateKeyPEM == "" {
apiError(c, 503, "signing_unavailable", "签名密钥未配置")
return
}
instanceID := strings.TrimSpace(c.Param("instance_id"))
if len(instanceID) != 36 {
apiError(c, 400, "invalid_request", "instance_id 无效")
return
}
key, ok := parseOperationKey(c)
if !ok {
return
}
var in struct {
Secret string `json:"secret"`
LicenseKey string `json:"license_key"`
}
if c.ShouldBindJSON(&in) != nil || len(in.Secret) < 20 || len(in.Secret) > 128 {
apiError(c, 400, "invalid_request", "secret 无效")
return
}
secretBytes, err := base64.RawURLEncoding.DecodeString(in.Secret)
if err != nil {
apiError(c, 400, "invalid_request", "secret 无效")
return
}
secretHash := sha256.Sum256(secretBytes)
fingerprint := sha256.Sum256([]byte(instanceID + "\x00" + hex.EncodeToString(secretHash[:])))
var actor uint64
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var inst instanceRecord
var storedHash []byte
var startsAt, expiresAt time.Time
err = tx.QueryRowContext(c, `SELECT i.id,i.instance_id,i.license_id,i.customer_id,i.product_id,i.status,i.activated_at,COALESCE(i.certificate_version,''),i.created_at,i.secret_hash,l.starts_at,l.expires_at FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.instance_id=? FOR UPDATE`, instanceID).Scan(&inst.ID, &inst.InstanceID, &inst.LicenseID, &inst.CustomerID, &inst.ProductID, &inst.Status, &inst.ActivatedAt, &inst.CertificateVersion, &inst.CreatedAt, &storedHash, &startsAt, &expiresAt)
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "实例不存在")
return
}
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if err = tx.QueryRowContext(c, "SELECT created_by FROM license_instances WHERE id=?", inst.ID).Scan(&actor); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
var licenseKey string
if err = tx.QueryRowContext(c, "SELECT license_key FROM licenses WHERE id=?", inst.LicenseID).Scan(&licenseKey); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if !bytesEqual([]byte(in.LicenseKey), []byte(licenseKey)) || !bytesEqual(storedHash, secretHash[:]) {
apiError(c, 403, "forbidden", "激活凭据无效")
return
}
var opID uint64
var oldInstance uint64
var oldFingerprint []byte
var oldResponse []byte
err = tx.QueryRowContext(c, "SELECT id,instance_id,request_fingerprint,response FROM activation_operations WHERE instance_id=? AND idempotency_key=?", inst.ID, key).Scan(&opID, &oldInstance, &oldFingerprint, &oldResponse)
if err == nil {
if oldInstance != inst.ID || !bytesEqual(oldFingerprint, fingerprint[:]) {
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同激活请求")
return
}
var replay any
_ = json.Unmarshal(oldResponse, &replay)
c.JSON(200, replay)
return
}
if !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if !bytesEqual(storedHash, secretHash[:]) {
apiError(c, 403, "forbidden", "实例secret无效")
return
}
if inst.Status == "activated" {
apiError(c, 409, "invalid_state", "实例已经激活")
return
}
var licenseStatus, customerStatus string
var productActive bool
var licenseCustomer, licenseProduct uint64
if err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM licenses WHERE id=? FOR UPDATE", inst.LicenseID).Scan(&licenseCustomer, &licenseProduct, &licenseStatus); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if licenseCustomer != inst.CustomerID || licenseProduct != inst.ProductID || currentLicenseStatus(licenseStatus, startsAt, expiresAt, time.Now().UTC()) != "active" {
apiError(c, 409, "invalid_state", "授权归属或有效期无效")
return
}
if err = tx.QueryRowContext(c, "SELECT status FROM customers WHERE id=? FOR UPDATE", inst.CustomerID).Scan(&customerStatus); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if err = tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", inst.ProductID).Scan(&productActive); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if customerStatus != "active" || !productActive {
apiError(c, 409, "invalid_state", "客户或产品未启用")
return
}
var orderCustomer, orderProduct uint64
var orderStatus string
err = tx.QueryRowContext(c, "SELECT customer_id,product_id,status FROM offline_orders WHERE issued_license_id=? FOR UPDATE", inst.LicenseID).Scan(&orderCustomer, &orderProduct, &orderStatus)
if err == nil && (orderCustomer != inst.CustomerID || orderProduct != inst.ProductID || orderStatus != "issued") {
apiError(c, 409, "invalid_state", "订单归属无效")
return
}
if err != nil && !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
privateKey, err := readSigningKey(a.signingPrivateKeyPEM)
if err != nil {
apiError(c, 503, "signing_unavailable", "签名密钥无效")
return
}
version := "license-v1"
canonical := canonicalCertificatePayload(version, instanceID, inst.LicenseID, inst.CustomerID, inst.ProductID, startsAt, expiresAt)
if a.keyring != nil {
version = "license-v2"
canonical = canonicalCertificatePayload(version, instanceID, inst.LicenseID, inst.CustomerID, inst.ProductID, startsAt, expiresAt) + "\nkey_id=" + a.keyring.Current
}
digest := sha256.Sum256([]byte(canonical))
signature, err := ecdsa.SignASN1(rand.Reader, privateKey, digest[:])
if err != nil {
apiError(c, 500, "internal_error", "签发失败")
return
}
payload := gin.H{"version": version, "instance_id": instanceID, "license_id": inst.LicenseID, "customer_id": inst.CustomerID, "product_id": inst.ProductID, "starts_at": startsAt.UTC().Format(time.RFC3339Nano), "expires_at": expiresAt.UTC().Format(time.RFC3339Nano)}
if a.keyring != nil {
payload["key_id"] = a.keyring.Current
}
payloadJSON, _ := json.Marshal(payload)
now := time.Now().UTC().Truncate(time.Microsecond)
if _, err = tx.ExecContext(c, "UPDATE license_instances SET status='activated',activated_at=?,certificate_version=?,certificate_payload=?,certificate_signature=? WHERE id=?", now, version, payloadJSON, base64.RawStdEncoding.EncodeToString(signature), inst.ID); err != nil {
apiError(c, 500, "internal_error", "激活失败")
return
}
response := gin.H{"data": gin.H{"instance_id": instanceID, "status": "activated", "certificate": gin.H{"version": version, "payload": payload, "signature": base64.RawStdEncoding.EncodeToString(signature), "canonical_sha256": hex.EncodeToString(digest[:])}}, "idempotent_replay": false}
responseJSON, _ := json.Marshal(response)
if _, err = tx.ExecContext(c, "INSERT INTO activation_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?)", inst.ID, actor, key, fingerprint[:], responseJSON); err != nil {
apiError(c, 500, "internal_error", "激活失败,请使用相同幂等键重试")
return
}
details, _ := json.Marshal(gin.H{"instance_id": instanceID, "license_id": inst.LicenseID, "certificate_version": version})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.activated','license_instance',?,?)", actor, inst.ID, details); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.JSON(201, response)
}
func bytesEqual(a, b []byte) bool {
if len(a) != len(b) {
return false
}
var x byte
for i := range a {
x |= a[i] ^ b[i]
}
return x == 0
}