Files
yhy-mager/backend/internal/httpapi/licenses.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

385 lines
15 KiB
Go

package httpapi
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type licenseOperation struct {
ID uint64 `json:"id"`
LicenseID uint64 `json:"license_id"`
Operation string `json:"operation"`
IdempotencyKey string `json:"-"`
RequestFingerprint []byte `json:"-"`
}
type licenseRecord struct {
ID uint64 `json:"id"`
LicenseKey string `json:"license_key"`
CustomerID uint64 `json:"customer_id"`
CustomerName string `json:"customer_name"`
ProductID uint64 `json:"product_id"`
ProductName string `json:"product_name"`
ProductCode string `json:"product_code"`
Status string `json:"status"`
StartsAt time.Time `json:"starts_at"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
func currentLicenseStatus(status string, starts, expires time.Time, now time.Time) string {
if status == "revoked" {
return status
}
if !now.Before(expires) {
return "expired"
}
if now.Before(starts) {
return "scheduled"
}
return "active"
}
func (a *BusinessAPI) issueLicense(c *gin.Context) {
key := strings.TrimSpace(c.GetHeader("Idempotency-Key"))
if len(key) == 0 || len(key) > 128 {
apiError(c, 400, "invalid_idempotency_key", "Idempotency-Key 必须为 1 至 128 个字符")
return
}
var in struct {
CustomerID uint64 `json:"customer_id"`
ProductID uint64 `json:"product_id"`
StartsAt string `json:"starts_at"`
ExpiresAt string `json:"expires_at"`
}
if c.ShouldBindJSON(&in) != nil || in.CustomerID == 0 || in.ProductID == 0 {
apiError(c, 400, "invalid_request", "客户、产品和期限必填")
return
}
starts, err := time.Parse(time.RFC3339, in.StartsAt)
if err != nil {
apiError(c, 400, "invalid_request", "starts_at 必须为 RFC3339 时间")
return
}
expires, err := time.Parse(time.RFC3339, in.ExpiresAt)
starts = starts.UTC().Truncate(time.Microsecond)
expires = expires.UTC().Truncate(time.Microsecond)
if err != nil || !expires.After(starts) || starts.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
apiError(c, 400, "invalid_request", "expires_at 必须为晚于开始时间的 RFC3339 时间")
return
}
adminID, ok := c.Get("admin_id")
if !ok {
apiError(c, 401, "unauthorized", "请先登录")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
// Serialize issuance per administrator so concurrent retries see the committed record.
var lockedAdmin uint64
if err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", adminID).Scan(&lockedAdmin); err != nil {
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 403, "forbidden", "无权签发授权")
} else {
apiError(c, 500, "internal_error", "服务暂时不可用")
}
return
}
var rec licenseRecord
err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.issued_by=? AND l.idempotency_key=?`, adminID, key).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt)
if err == nil {
if rec.CustomerID != in.CustomerID || rec.ProductID != in.ProductID || !rec.StartsAt.Equal(starts) || !rec.ExpiresAt.Equal(expires) {
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同授权请求")
return
}
rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
c.JSON(200, gin.H{"data": rec, "idempotent_replay": true})
return
}
if !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
var customerStatus string
var productActive bool
err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", in.CustomerID).Scan(&rec.CustomerName, &customerStatus)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if errors.Is(err, sql.ErrNoRows) || customerStatus != "active" {
apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用")
return
}
err = tx.QueryRowContext(c, "SELECT name,code,active FROM products WHERE id=? FOR UPDATE", in.ProductID).Scan(&rec.ProductName, &rec.ProductCode, &productActive)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if errors.Is(err, sql.ErrNoRows) || !productActive {
apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用")
return
}
raw := make([]byte, 16)
if _, err = rand.Read(raw); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
rec.LicenseKey = hex.EncodeToString(raw)
rec.CustomerID = in.CustomerID
rec.ProductID = in.ProductID
rec.StartsAt = starts.UTC()
rec.ExpiresAt = expires.UTC()
rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
res, err := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", rec.LicenseKey, in.CustomerID, in.ProductID, rec.StartsAt, rec.ExpiresAt, key, adminID)
if err != nil {
apiError(c, 500, "internal_error", "签发失败,请使用相同幂等键重试")
return
}
id, err := res.LastInsertId()
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
rec.ID = uint64(id)
if err = tx.QueryRowContext(c, "SELECT created_at FROM licenses WHERE id=?", rec.ID).Scan(&rec.CreatedAt); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
details, _ := json.Marshal(map[string]any{"customer_id": in.CustomerID, "product_id": in.ProductID, "starts_at": rec.StartsAt, "expires_at": rec.ExpiresAt})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", adminID, rec.ID, details); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.Header("Location", "/api/v1/licenses/"+strconv.FormatUint(rec.ID, 10))
c.JSON(201, gin.H{"data": rec, "idempotent_replay": false})
}
func (a *BusinessAPI) getLicense(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "授权 ID 无效")
return
}
var rec licenseRecord
err = a.db.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=?`, id).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt)
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "授权不存在")
return
}
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
c.JSON(200, gin.H{"data": rec})
}
func parseOperationKey(c *gin.Context) (string, bool) {
key := strings.TrimSpace(c.GetHeader("Idempotency-Key"))
if len(key) < 1 || len(key) > 128 {
apiError(c, 400, "invalid_idempotency_key", "Idempotency-Key 必须为 1 至 128 个字符")
return "", false
}
return key, true
}
func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "授权 ID 无效")
return
}
key, ok := parseOperationKey(c)
if !ok {
return
}
var in struct {
ExpiresAt string `json:"expires_at"`
}
if operation == "renew" && c.ShouldBindJSON(&in) != nil {
apiError(c, 400, "invalid_request", "expires_at 必填")
return
}
var expires time.Time
if operation == "renew" {
expires, err = time.Parse(time.RFC3339, in.ExpiresAt)
if err != nil {
apiError(c, 400, "invalid_request", "expires_at 必须为 RFC3339 时间")
return
}
expires = expires.UTC().Truncate(time.Microsecond)
if expires.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
apiError(c, 400, "invalid_request", "expires_at 超出允许范围")
return
}
}
adminID := c.MustGet("admin_id")
fingerprintInput := operation + "\x00" + strconv.FormatUint(id, 10) + "\x00" + expires.Format(time.RFC3339Nano)
fingerprint := sha256.Sum256([]byte(fingerprintInput))
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var rec licenseRecord
err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=? FOR UPDATE`, id).Scan(&rec.ID, &rec.LicenseKey, &rec.CustomerID, &rec.CustomerName, &rec.ProductID, &rec.ProductName, &rec.ProductCode, &rec.Status, &rec.StartsAt, &rec.ExpiresAt, &rec.CreatedAt)
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "授权不存在")
return
}
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
var op licenseOperation
err = tx.QueryRowContext(c, "SELECT id,license_id,operation,idempotency_key,request_fingerprint FROM license_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", adminID, operation, key).Scan(&op.ID, &op.LicenseID, &op.Operation, &op.IdempotencyKey, &op.RequestFingerprint)
if err == nil {
if op.LicenseID != id || !bytes.Equal(op.RequestFingerprint, fingerprint[:]) {
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同授权操作")
return
}
rec.Status = currentLicenseStatus(rec.Status, rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
c.JSON(200, gin.H{"data": rec, "idempotent_replay": true})
return
}
if !errors.Is(err, sql.ErrNoRows) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if operation == "revoke" {
if rec.Status == "revoked" {
apiError(c, 409, "invalid_state", "授权已经撤销")
return
}
if _, err = tx.ExecContext(c, "UPDATE licenses SET status='revoked',revoked_at=? WHERE id=?", time.Now().UTC(), id); err != nil {
apiError(c, 500, "internal_error", "撤销失败")
return
}
} else {
if rec.Status == "revoked" || !expires.After(rec.ExpiresAt) {
apiError(c, 400, "invalid_request", "续期时间必须晚于当前结束时间且授权未撤销")
return
}
if _, err = tx.ExecContext(c, "UPDATE licenses SET expires_at=?,status='active' WHERE id=?", expires, id); err != nil {
apiError(c, 500, "internal_error", "续期失败")
return
}
}
if _, err = tx.ExecContext(c, "INSERT INTO license_operations(license_id,actor_admin_id,operation,idempotency_key,request_fingerprint) VALUES(?,?,?,?,?)", id, adminID, operation, key, fingerprint[:]); err != nil {
apiError(c, 500, "internal_error", "操作失败,请使用相同幂等键重试")
return
}
details, _ := json.Marshal(map[string]any{"operation": operation, "expires_at": expires, "license_id": id})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?, 'license',?,?)", adminID, "license."+operation, id, details); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if operation == "revoke" {
rec.Status = "revoked"
} else {
rec.ExpiresAt = expires
rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC())
}
c.JSON(200, gin.H{"data": rec, "idempotent_replay": false})
}
const licenseFrom = ` FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id`
const licenseSelect = `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at` + licenseFrom
// Use the same instant and predicate for the count and page, including expiry boundaries.
func licenseFilter(status, q string, now time.Time) (string, []any, bool) {
where := " WHERE 1=1"
args := []any{}
if q != "" {
where += " AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?)"
like := "%" + q + "%"
args = append(args, like, like, like, like)
}
switch status {
case "":
case "revoked":
where += " AND l.status='revoked'"
case "active", "expiring":
where += " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>?"
args = append(args, now, now)
if status == "expiring" {
where += " AND l.expires_at<=?"
args = append(args, now.Add(30*24*time.Hour))
}
case "pending":
where += " AND l.status<>'revoked' AND l.starts_at>? AND l.expires_at>?"
args = append(args, now, now)
case "expired":
where += " AND l.status<>'revoked' AND l.expires_at<=?"
args = append(args, now)
default:
return "", nil, false
}
return where, args, true
}
func readLicenseRecords(rows *sql.Rows, now time.Time) ([]licenseRecord, error) {
defer rows.Close()
out := []licenseRecord{}
for rows.Next() {
var x licenseRecord
if err := rows.Scan(&x.ID, &x.LicenseKey, &x.CustomerID, &x.CustomerName, &x.ProductID, &x.ProductName, &x.ProductCode, &x.Status, &x.StartsAt, &x.ExpiresAt, &x.CreatedAt); err != nil {
return nil, err
}
x.Status = currentLicenseStatus(x.Status, x.StartsAt, x.ExpiresAt, now)
out = append(out, x)
}
return out, rows.Err()
}
func (a *BusinessAPI) listLicenses(c *gin.Context) {
p, size := page(c)
now := time.Now().UTC()
where, args, ok := licenseFilter(strings.TrimSpace(c.Query("status")), strings.TrimSpace(c.Query("q")), now)
if !ok {
apiError(c, 400, "invalid_request", "授权状态无效")
return
}
var total int
if err := a.db.QueryRowContext(c, "SELECT COUNT(*)"+licenseFrom+where, args...).Scan(&total); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
pageArgs := append(append([]any{}, args...), size, (p-1)*size)
rows, err := a.db.QueryContext(c, licenseSelect+where+" ORDER BY l.id DESC LIMIT ? OFFSET ?", pageArgs...)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
out, err := readLicenseRecords(rows, now)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
}