feat: implement license platform business flows and delivery tooling
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

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:
2026-10-09 15:33:22 +08:00
parent 3ab651d3a8
commit 54c318c615
142 changed files with 11105 additions and 178 deletions

View File

@@ -0,0 +1,348 @@
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
}

View File

@@ -0,0 +1,129 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"database/sql"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
der, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatal(err)
}
r := NewRouter()
RegisterBusiness(r, db, string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})))
var licenseID uint64
var licenseKey string
if err = db.QueryRow("SELECT l.id,l.license_key FROM licenses l JOIN offline_orders o ON o.issued_license_id=l.id WHERE o.status='issued' LIMIT 1").Scan(&licenseID, &licenseKey); err != nil {
t.Fatal(err)
}
request := func(method, path, body, idem string, auth bool) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", idem)
if auth {
req.AddCookie(cookie)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
provisionPath := fmt.Sprintf("/api/v1/licenses/%d/instances", licenseID)
if w := request("POST", provisionPath, "{}", "", false); w.Code != 401 {
t.Fatalf("unauthorized status=%d", w.Code)
}
w := request("POST", provisionPath, "{}", "", true)
if w.Code != 201 {
t.Fatalf("provision status=%d", w.Code)
}
var response struct {
Data struct {
InstanceID string `json:"instance_id"`
Secret string `json:"secret"`
}
}
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
instanceID, secret := response.Data.InstanceID, response.Data.Secret
if instanceID == "" || secret == "" {
t.Fatal("provision fields missing")
}
if w = request("POST", provisionPath, "{}", "", true); w.Code != 409 || strings.Contains(w.Body.String(), secret) {
t.Fatal("duplicate provision result invalid")
}
w = request("GET", provisionPath, "", "", true)
if w.Code != 200 || strings.Contains(w.Body.String(), secret) || strings.Contains(w.Body.String(), "secret_hash") {
t.Fatal("instance list leaked secret")
}
path := "/api/v1/activation/instances/" + instanceID
bodyBytes, _ := json.Marshal(gin.H{"license_key": licenseKey, "secret": secret})
body := string(bodyBytes)
badBytes, _ := json.Marshal(gin.H{"license_key": "wrong", "secret": secret})
if w = request("POST", path, string(badBytes), "activate", false); w.Code != 403 {
t.Fatalf("wrong credential=%d", w.Code)
}
if _, err = db.Exec("CREATE TRIGGER activation_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'"); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS activation_audit_failure") })
if w = request("POST", path, body, "activate", false); w.Code != 500 {
t.Fatalf("rollback status=%d", w.Code)
}
var status string
db.QueryRow("SELECT status FROM license_instances WHERE instance_id=?", instanceID).Scan(&status)
if status != "provisioned" {
t.Fatal("audit failure committed activation")
}
db.Exec("DROP TRIGGER activation_audit_failure")
var wg sync.WaitGroup
codes := make(chan int, 2)
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); codes <- request("POST", path, body, "activate", false).Code }()
}
wg.Wait()
close(codes)
successes, replays := 0, 0
for code := range codes {
if code == 201 {
successes++
} else if code == 200 {
replays++
} else {
t.Fatalf("concurrent activation=%d", code)
}
}
if successes != 1 || replays != 1 {
t.Fatal("activation did not serialize")
}
if w = request("POST", path, body, "different", false); w.Code != 409 {
t.Fatalf("repeat activation=%d", w.Code)
}
var count int
if err = db.QueryRow("SELECT COUNT(*) FROM activation_operations").Scan(&count); err != nil || count != 1 {
t.Fatal("operation count mismatch")
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.activated'").Scan(&count); err != nil || count != 1 {
t.Fatal("activation audit count mismatch")
}
t.Run("heartbeat", func(t *testing.T) {
testHeartbeatMySQL(t, db, r, cookie, instanceID, secret, licenseID, &key.PublicKey)
})
}

View File

@@ -0,0 +1,28 @@
package httpapi
import (
"crypto/x509"
"encoding/pem"
"github.com/gin-gonic/gin"
)
func (a *BusinessAPI) activationPublicKey(c *gin.Context) {
key, err := readSigningKey(a.signingPrivateKeyPEM)
if err != nil {
apiError(c, 503, "signing_unavailable", "签名密钥未配置或无效")
return
}
der, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
version := "license-v1"
data := gin.H{"algorithm": "ECDSA-P256-SHA256", "signature_encoding": "ASN.1-DER/base64-no-padding", "public_key_pem": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))}
if a.keyring != nil {
version = "license-v2"
data["key_id"] = a.keyring.Current
}
data["certificate_version"] = version
c.JSON(200, gin.H{"data": data})
}

View File

@@ -0,0 +1,49 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"testing"
"time"
)
func TestActivationCanonicalSignature(t *testing.T) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
der, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatal(err)
}
loaded, err := readSigningKey(string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})))
if err != nil {
t.Fatal(err)
}
start := time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)
end := start.AddDate(1, 0, 0)
canonical := canonicalCertificatePayload("license-v1", "00000000-0000-4000-8000-000000000001", 1, 2, 3, start, end)
expected := "version=license-v1\ninstance_id=00000000-0000-4000-8000-000000000001\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-09-30T00:00:00Z\nexpires_at=2027-09-30T00:00:00Z"
if canonical != expected {
t.Fatal("canonical payload mismatch")
}
sum := sha256.Sum256([]byte(canonical))
sig, err := ecdsa.SignASN1(rand.Reader, loaded, sum[:])
if err != nil {
t.Fatal(err)
}
if !ecdsa.VerifyASN1(&loaded.PublicKey, sum[:], sig) {
t.Fatal("signature not valid")
}
modified := sha256.Sum256([]byte(canonical + "x"))
if ecdsa.VerifyASN1(&loaded.PublicKey, modified[:], sig) {
t.Fatal("modified payload accepted")
}
if _, err = readSigningKey(""); err == nil {
t.Fatal("missing key accepted")
}
}

View File

@@ -0,0 +1,246 @@
package httpapi
import (
"errors"
"net/http"
"net/mail"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
type adminAccount struct {
ID uint64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
}
func normalizeAdminUsername(value string) string { return strings.ToLower(strings.TrimSpace(value)) }
func validAdminUsername(value string) bool {
if len(value) < 3 || len(value) > 32 {
return false
}
for _, r := range value {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
return false
}
}
return true
}
func validAdminPassword(value string) bool { return value != "" && len(value) <= 72 }
func (a *BusinessAPI) listAdmins(c *gin.Context) {
rows, err := a.db.QueryContext(c, "SELECT id,username,email,active,created_at FROM admins ORDER BY id")
if err != nil {
apiError(c, 500, "internal_error", "管理员列表加载失败")
return
}
defer rows.Close()
items := []adminAccount{}
for rows.Next() {
var item adminAccount
if err = rows.Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil {
apiError(c, 500, "internal_error", "管理员列表加载失败")
return
}
items = append(items, item)
}
if rows.Err() != nil {
apiError(c, 500, "internal_error", "管理员列表加载失败")
return
}
c.JSON(200, gin.H{"data": items})
}
func (a *BusinessAPI) createAdmin(c *gin.Context) {
var in struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
if c.ShouldBindJSON(&in) != nil {
apiError(c, 400, "invalid_request", "用户名、邮箱和密码不能为空")
return
}
in.Username = normalizeAdminUsername(in.Username)
in.Email = strings.ToLower(strings.TrimSpace(in.Email))
address, emailErr := mail.ParseAddress(in.Email)
if !validAdminUsername(in.Username) || emailErr != nil || address.Address != in.Email || len(in.Email) > 190 || !validAdminPassword(in.Password) {
apiError(c, 400, "invalid_request", "用户名须为 3–32 位小写字母、数字、下划线或短横线;邮箱和密码必须有效")
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
if err != nil {
apiError(c, 500, "internal_error", "管理员创建失败")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "管理员创建失败")
return
}
defer tx.Rollback()
result, err := tx.ExecContext(c, "INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", in.Username, in.Email, string(hash))
if err != nil {
var duplicate *mysql.MySQLError
if errors.As(err, &duplicate) && duplicate.Number == 1062 {
apiError(c, 409, "conflict", "用户名或邮箱已存在")
} else {
apiError(c, 500, "internal_error", "管理员创建失败")
}
return
}
id, _ := result.LastInsertId()
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.created','admin',?,?)", c.GetUint64("admin_id"), id, `{"fields":["username","email"]}`); err != nil {
apiError(c, 500, "internal_error", "管理员创建失败")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "管理员创建结果未确认,请刷新检查")
return
}
var item adminAccount
if err = a.db.QueryRowContext(c, "SELECT id,username,email,active,created_at FROM admins WHERE id=?", id).Scan(&item.ID, &item.Username, &item.Email, &item.Active, &item.CreatedAt); err != nil {
apiError(c, 500, "internal_error", "管理员已创建,请刷新检查")
return
}
c.JSON(http.StatusCreated, gin.H{"data": item})
}
func (a *BusinessAPI) setAdminActive(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 in struct {
Active *bool `json:"active"`
}
if c.ShouldBindJSON(&in) != nil || in.Active == nil {
apiError(c, 400, "invalid_request", "必须指定 active")
return
}
if id == c.GetUint64("admin_id") && !*in.Active {
apiError(c, 400, "invalid_request", "不能停用当前登录的管理员")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "管理员状态更新失败")
return
}
defer tx.Rollback()
// Lock accounts in a stable order to serialize simultaneous disable operations.
rows, err := tx.QueryContext(c, "SELECT id,active FROM admins ORDER BY id FOR UPDATE")
if err != nil {
apiError(c, 500, "internal_error", "管理员状态更新失败")
return
}
found, current, actorActive := false, false, false
for rows.Next() {
var accountID uint64
var active bool
if err = rows.Scan(&accountID, &active); err != nil {
break
}
if accountID == id {
found, current = true, active
}
if accountID == c.GetUint64("admin_id") {
actorActive = active
}
}
if err == nil {
err = rows.Err()
}
rows.Close()
if err != nil {
apiError(c, 500, "internal_error", "管理员状态更新失败")
return
}
if !actorActive {
apiError(c, 401, "unauthorized", "当前管理员已停用")
return
}
if !found {
apiError(c, 404, "not_found", "管理员不存在")
return
}
if current == *in.Active {
c.Status(http.StatusNoContent)
return
}
if _, err = tx.ExecContext(c, "UPDATE admins SET active=? WHERE id=?", *in.Active, id); err != nil {
apiError(c, 500, "internal_error", "管理员状态更新失败")
return
}
if !*in.Active {
_, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id)
}
if err == nil {
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.active_changed','admin',?,?)", c.GetUint64("admin_id"), id, `{"active":`+map[bool]string{true: "true", false: "false"}[*in.Active]+`}`)
}
if err != nil {
apiError(c, 500, "internal_error", "管理员状态更新失败")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "管理员状态更新结果未确认,请刷新检查")
return
}
c.Status(http.StatusNoContent)
}
func (a *BusinessAPI) resetAdminPassword(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 in struct {
Password string `json:"password"`
}
if c.ShouldBindJSON(&in) != nil || !validAdminPassword(in.Password) {
apiError(c, 400, "invalid_request", "新密码不能为空,且最多 72 字节")
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
if err != nil {
apiError(c, 500, "internal_error", "密码重置失败")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "密码重置失败")
return
}
defer tx.Rollback()
result, err := tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id)
if err != nil {
apiError(c, 500, "internal_error", "密码重置失败")
return
}
affected, _ := result.RowsAffected()
if affected == 0 {
apiError(c, 404, "not_found", "管理员不存在")
return
}
if _, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND revoked_at IS NULL", time.Now().UTC(), id); err == nil {
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_reset','admin',?,?)", c.GetUint64("admin_id"), id, `{"sessions_revoked":true}`)
}
if err != nil {
apiError(c, 500, "internal_error", "密码重置失败")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "密码重置结果未确认,请刷新检查")
return
}
c.Status(http.StatusNoContent)
}

View File

@@ -0,0 +1,47 @@
package httpapi
import (
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestAdminCredentialValidation(t *testing.T) {
for _, name := range []string{"admin", "admin-1", "ops_team", strings.Repeat("a", 32)} {
if !validAdminUsername(name) {
t.Fatalf("valid username rejected: %s", name)
}
}
for _, name := range []string{"", "ab", "name with space", "root@example.test", "管理员", "ADMIN", strings.Repeat("a", 33)} {
if validAdminUsername(name) {
t.Fatalf("invalid username accepted: %s", name)
}
}
if normalizeAdminUsername(" TEAM_1 ") != "team_1" {
t.Fatal("normalization")
}
for _, password := range []string{"x", strings.Repeat("a", 72), strings.Repeat("中", 24)} {
if !validAdminPassword(password) {
t.Fatal("valid password rejected")
}
}
for _, password := range []string{"", strings.Repeat("a", 73), strings.Repeat("中", 25)} {
if validAdminPassword(password) {
t.Fatal("invalid password accepted")
}
}
}
func TestAdminCannotDisableSelf(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/admins/1/active", strings.NewReader(`{"active":false}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Params = gin.Params{{Key: "id", Value: "1"}}
c.Set("admin_id", uint64(1))
(&BusinessAPI{}).setAdminActive(c)
if w.Code != 400 || !strings.Contains(w.Body.String(), "不能停用当前登录的管理员") {
t.Fatalf("%d %s", w.Code, w.Body)
}
}

View File

@@ -0,0 +1,255 @@
package httpapi
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"net/mail"
"strings"
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
type platformSettings struct {
SiteName string `json:"site_name"`
SupportEmail string `json:"support_email"`
Announcement string `json:"announcement"`
UpdatedAt *time.Time `json:"updated_at"`
}
func validateSettings(s *platformSettings) bool {
s.SiteName = strings.TrimSpace(s.SiteName)
s.SupportEmail = strings.TrimSpace(s.SupportEmail)
if s.SiteName == "" || utf8.RuneCountInString(s.SiteName) > 100 || len(s.SupportEmail) > 254 || utf8.RuneCountInString(s.Announcement) > 2000 {
return false
}
if s.SupportEmail != "" {
a, err := mail.ParseAddress(s.SupportEmail)
if err != nil || a.Address != s.SupportEmail {
return false
}
}
return true
}
func (a *BusinessAPI) getSettings(c *gin.Context) {
var s platformSettings
if err := a.db.QueryRowContext(c, "SELECT site_name,support_email,announcement,updated_at FROM system_settings WHERE id=1").Scan(&s.SiteName, &s.SupportEmail, &s.Announcement, &s.UpdatedAt); err != nil {
apiError(c, 500, "internal_error", "设置加载失败")
return
}
c.JSON(200, gin.H{"data": s})
}
func (a *BusinessAPI) updateSettings(c *gin.Context) {
var s platformSettings
if c.ShouldBindJSON(&s) != nil || !validateSettings(&s) {
apiError(c, 400, "invalid_request", "平台名称为1至100字,联系邮箱必须有效,公告最多2000字")
return
}
now := time.Now().UTC()
s.UpdatedAt = &now
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "设置保存失败")
return
}
defer tx.Rollback()
// Lock the singleton so concurrent saves are serialized with their audit record.
var id int
if err = tx.QueryRowContext(c, "SELECT id FROM system_settings WHERE id=1 FOR UPDATE").Scan(&id); err == nil {
_, err = tx.ExecContext(c, "UPDATE system_settings SET site_name=?,support_email=?,announcement=?,updated_at=? WHERE id=1", s.SiteName, s.SupportEmail, s.Announcement, now)
}
if err == nil {
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'settings.updated','system_settings',1,?)", c.GetUint64("admin_id"), `{"fields":["site_name","support_email","announcement"]}`)
}
if err != nil {
apiError(c, 500, "internal_error", "设置保存失败")
return
}
if tx.Commit() != nil {
apiError(c, 500, "internal_error", "设置保存结果未确认,请刷新检查")
return
}
c.JSON(200, gin.H{"data": s})
}
func (a *BusinessAPI) changePassword(c *gin.Context) {
var in struct {
Current string `json:"current_password"`
New string `json:"new_password"`
}
if c.ShouldBindJSON(&in) != nil || in.Current == "" || in.New == "" || len(in.New) > 72 {
apiError(c, 400, "invalid_request", "当前密码和新密码不能为空,新密码最多72字节")
return
}
// Hash before acquiring the row lock to keep the write transaction short.
hash, err := bcrypt.GenerateFromPassword([]byte(in.New), bcrypt.DefaultCost)
if err != nil {
apiError(c, 500, "internal_error", "密码修改失败")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "密码修改失败")
return
}
defer tx.Rollback()
var old string
id := c.GetUint64("admin_id")
err = tx.QueryRowContext(c, "SELECT password_hash FROM admins WHERE id=? AND active=1 FOR UPDATE", id).Scan(&old)
if err == sql.ErrNoRows {
apiError(c, 401, "unauthorized", "账号已失效")
return
}
if err != nil {
apiError(c, 500, "internal_error", "密码修改失败")
return
}
if bcrypt.CompareHashAndPassword([]byte(old), []byte(in.Current)) != nil {
apiError(c, 400, "invalid_credentials", "当前密码错误")
return
}
raw, _ := c.Cookie("lp_session")
decoded, _ := hex.DecodeString(raw)
sum := sha256.Sum256(decoded)
if _, err = tx.ExecContext(c, "UPDATE admins SET password_hash=? WHERE id=?", string(hash), id); err == nil {
_, err = tx.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE admin_id=? AND token_hash<>? AND revoked_at IS NULL", time.Now().UTC(), id, sum[:])
}
if err == nil {
_, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'admin.password_changed','admin',?,?)", id, id, `{"other_sessions_revoked":true}`)
}
if err != nil {
apiError(c, 500, "internal_error", "密码修改失败")
return
}
if tx.Commit() != nil {
apiError(c, 500, "internal_error", "密码修改结果未确认,请重新登录检查")
return
}
c.Status(204)
}
type auditRecord struct {
ID uint64 `json:"id"`
ActorID uint64 `json:"actor_admin_id"`
ActorEmail string `json:"actor_email"`
Action string `json:"action"`
ResourceType string `json:"resource_type"`
ResourceID uint64 `json:"resource_id"`
Details map[string]any `json:"details"`
CreatedAt time.Time `json:"created_at"`
}
// Expose known business fields only. Future events cannot accidentally expose credentials.
func publicAuditDetails(raw []byte) map[string]any {
var input map[string]any
_ = json.Unmarshal(raw, &input)
out := map[string]any{}
for _, key := range []string{"client_actor", "customer_id", "product_id", "license_id", "order_id", "instance_id", "release_id", "starts_at", "expires_at", "operation", "amount_cents", "currency", "certificate_version", "state", "previous_state", "freeze_state", "lease_expires_at", "version", "sha256", "size_bytes", "fields", "other_sessions_revoked"} {
if v, ok := input[key]; ok {
switch v.(type) {
case string, float64, bool, nil:
out[key] = v
case []any:
if key == "fields" {
out[key] = []string{"site_name", "support_email", "announcement"}
}
}
}
}
return out
}
func auditFilter(c *gin.Context) (string, []any, bool) {
clauses := []string{"1=1"}
args := []any{}
for _, item := range []struct{ key, column string }{{"action", "e.action"}, {"resource_type", "e.resource_type"}} {
if v := strings.TrimSpace(c.Query(item.key)); v != "" {
if len(v) > 64 {
return "", nil, false
}
clauses = append(clauses, item.column+"=?")
args = append(args, v)
}
}
if q := strings.TrimSpace(c.Query("q")); q != "" {
if utf8.RuneCountInString(q) > 200 {
return "", nil, false
}
clauses = append(clauses, "(a.email LIKE ? OR e.action LIKE ? OR e.resource_type LIKE ?)")
for i := 0; i < 3; i++ {
args = append(args, "%"+q+"%")
}
}
var from, to time.Time
for _, key := range []string{"from", "to"} {
if v := c.Query(key); v != "" {
t, err := time.Parse(time.RFC3339, v)
if err != nil {
return "", nil, false
}
op := ">="
if key == "to" {
op = "<="
to = t
} else {
from = t
}
clauses = append(clauses, "e.created_at"+op+"?")
args = append(args, t.UTC())
}
}
if !from.IsZero() && !to.IsZero() && from.After(to) {
return "", nil, false
}
return strings.Join(clauses, " AND "), args, true
}
func (a *BusinessAPI) listAuditEvents(c *gin.Context) {
where, args, ok := auditFilter(c)
if !ok {
apiError(c, 400, "invalid_request", "审计筛选参数无效,时间请使用ISO格式")
return
}
p, size := page(c)
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
if err != nil {
apiError(c, 500, "internal_error", "日志加载失败")
return
}
defer tx.Rollback()
base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE " + where
var total int64
if err = tx.QueryRowContext(c, "SELECT COUNT(*)"+base, args...).Scan(&total); err != nil {
apiError(c, 500, "internal_error", "日志加载失败")
return
}
pageArgs := append(append([]any{}, args...), size, (p-1)*size)
rows, err := tx.QueryContext(c, "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at"+base+" ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", pageArgs...)
if err != nil {
apiError(c, 500, "internal_error", "日志加载失败")
return
}
defer rows.Close()
out := []auditRecord{}
for rows.Next() {
var v auditRecord
var raw []byte
if err = rows.Scan(&v.ID, &v.ActorID, &v.ActorEmail, &v.Action, &v.ResourceType, &v.ResourceID, &raw, &v.CreatedAt); err != nil {
apiError(c, 500, "internal_error", "日志加载失败")
return
}
v.Details = publicAuditDetails(raw)
out = append(out, v)
}
if rows.Err() != nil {
apiError(c, 500, "internal_error", "日志加载失败")
return
}
rows.Close()
if tx.Commit() != nil {
apiError(c, 500, "internal_error", "日志加载失败")
return
}
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
}

View File

@@ -0,0 +1,99 @@
package httpapi
import (
"database/sql/driver"
"encoding/json"
"github.com/gin-gonic/gin"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestAuditListSnapshot(t *testing.T) {
now := time.Date(2026, 10, 9, 2, 0, 0, 0, time.UTC)
base := " FROM audit_events e JOIN admins a ON a.id=e.actor_admin_id WHERE 1=1 AND e.action=?"
db, stub := newDashboardTestDB(t, []dashboardQuery{
{sql: "SELECT COUNT(*)" + base, args: []any{"license.issued"}, rows: [][]driver.Value{{int64(21)}}},
{sql: "SELECT e.id,e.actor_admin_id,a.email,e.action,e.resource_type,e.resource_id,e.details,e.created_at" + base + " ORDER BY e.created_at DESC,e.id DESC LIMIT ? OFFSET ?", args: []any{"license.issued", 20, 20}, rows: [][]driver.Value{{int64(1), int64(2), "admin@example.test", "license.issued", "license", int64(3), []byte(`{"license_id":3,"password":"hidden"}`), now}}},
})
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/?action=license.issued&page=2", nil)
(&BusinessAPI{db: db}).listAuditEvents(c)
if w.Code != 200 || strings.Contains(w.Body.String(), "hidden") {
t.Fatalf("%d %s", w.Code, w.Body.String())
}
var result struct {
Data []auditRecord `json:"data"`
Meta struct {
Total int `json:"total"`
Page int `json:"page"`
} `json:"meta"`
}
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.Meta.Total != 21 || result.Meta.Page != 2 || len(result.Data) != 1 || !stub.committed || !stub.txOptions.ReadOnly {
t.Fatalf("unexpected snapshot: %s", w.Body.String())
}
}
func TestPlatformSettingsValidation(t *testing.T) {
for _, tc := range []struct {
s platformSettings
ok bool
}{
{platformSettings{SiteName: " 管理台 "}, true},
{platformSettings{SiteName: ""}, false},
{platformSettings{SiteName: strings.Repeat("中", 101)}, false},
{platformSettings{SiteName: "平台", SupportEmail: "admin@example.test"}, true},
{platformSettings{SiteName: "平台", SupportEmail: "Name <admin@example.test>"}, false},
{platformSettings{SiteName: "平台", Announcement: strings.Repeat("中", 2001)}, false},
} {
if got := validateSettings(&tc.s); got != tc.ok {
t.Fatalf("validation=%v want %v", got, tc.ok)
}
}
}
func TestAuditDetailsAllowlist(t *testing.T) {
out := publicAuditDetails([]byte(`{"license_id":3,"password":"private","token":"private","instance_secret":"private","state":{"password":"private"},"fields":["private"]}`))
if len(out) != 2 || out["license_id"] != float64(3) {
t.Fatalf("unsafe details: %#v", out)
}
if len(publicAuditDetails([]byte(`invalid`))) != 0 {
t.Fatal("invalid JSON exposed")
}
}
func TestAuditFilterValidation(t *testing.T) {
for _, tc := range []struct {
query string
ok bool
}{
{"?action=license.issued&resource_type=license&q=admin", true},
{"?from=2026-10-09T00:00:00Z&to=2026-10-10T00:00:00Z", true},
{"?from=not-a-date", false},
{"?from=2026-10-10T00:00:00Z&to=2026-10-09T00:00:00Z", false},
{"?action=" + strings.Repeat("x", 65), false},
} {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("GET", "/"+tc.query, nil)
where, _, ok := auditFilter(c)
if ok != tc.ok {
t.Fatalf("%s got %v", tc.query, ok)
}
if ok && where == "" {
t.Fatal("missing predicate")
}
}
}
func TestAdminModuleAuthentication(t *testing.T) {
r := gin.New()
registerBusinessRoutes(r, &BusinessAPI{})
for _, tc := range []struct{ method, path string }{{"GET", "/api/v1/audit-events"}, {"GET", "/api/v1/settings"}, {"PUT", "/api/v1/settings"}, {"POST", "/api/v1/settings/password"}} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
if w.Code != 401 {
t.Fatalf("%s %s: %d", tc.method, tc.path, w.Code)
}
}
}

View File

@@ -0,0 +1,372 @@
package httpapi
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
type BusinessAPI struct {
db *sql.DB
signingPrivateKeyPEM string
keyring *Keyring
}
func secureSessionCookie(c *gin.Context) bool {
return c.Request.TLS != nil || os.Getenv("SESSION_COOKIE_SECURE") == "true"
}
func RegisterBusiness(r *gin.Engine, db *sql.DB, signingPrivateKeyPEM ...string) {
if db == nil {
return
}
a := &BusinessAPI{db: db}
if len(signingPrivateKeyPEM) > 0 {
a.signingPrivateKeyPEM = signingPrivateKeyPEM[0]
}
registerBusinessRoutes(r, a)
}
func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring) {
if db == nil {
return
}
registerBusinessRoutes(r, &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring})
}
func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
api := r.Group("/api/v1")
api.POST("/auth/login", a.login)
api.POST("/portal/snapshot", a.portalSnapshot)
api.POST("/activation/instances/:instance_id", a.activateInstance)
api.GET("/activation/public-key", a.activationPublicKey)
api.GET("/activation/keyring", func(c *gin.Context) {
if a.keyring == nil {
apiError(c, 404, "not_found", "Keyring unavailable")
return
}
c.JSON(200, gin.H{"data": a.keyring})
})
api.POST("/instances/:instance_id/heartbeat", a.heartbeat)
api.POST("/auth/logout", a.authenticated, a.logout)
secured := api.Group("", a.authenticated)
secured.GET("/me", a.me)
secured.GET("/admins", a.listAdmins)
secured.POST("/admins", a.createAdmin)
secured.POST("/admins/:id/active", a.setAdminActive)
secured.POST("/admins/:id/reset-password", a.resetAdminPassword)
secured.GET("/dashboard/summary", a.dashboardSummary)
secured.GET("/audit-events", a.listAuditEvents)
secured.GET("/settings", a.getSettings)
secured.PUT("/settings", a.updateSettings)
secured.POST("/settings/password", a.changePassword)
secured.GET("/integration-kit", a.integrationKit)
secured.GET("/integration-kit/download", a.downloadIntegrationKit)
secured.GET("/integration-kit/archive", a.downloadIntegrationArchive)
secured.GET("/customers", a.listCustomers)
secured.POST("/customers", a.createCustomer)
secured.PUT("/customers/:id", a.updateCustomer)
secured.DELETE("/customers/:id", a.deleteCustomer)
secured.GET("/products", a.listProducts)
secured.POST("/products", a.createProduct)
secured.PUT("/products/:id", a.updateProduct)
secured.DELETE("/products/:id", a.deleteProduct)
secured.GET("/orders", a.listOrders)
secured.GET("/orders/:id", a.getOrder)
secured.POST("/orders", func(c *gin.Context) { a.writeOrder(c, "create") })
secured.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") })
secured.POST("/orders/:id/issue", func(c *gin.Context) { a.writeOrder(c, "issue") })
secured.GET("/licenses", a.listLicenses)
secured.GET("/licenses/:id", a.getLicense)
secured.GET("/licenses/:id/instances", a.listInstances)
secured.POST("/licenses/:id/instances", a.provisionInstance)
secured.POST("/products/:id/releases", a.createRelease)
secured.GET("/products/:id/releases", a.listReleases)
api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease)
secured.POST("/instances/:instance_id/freeze", a.freezeInstance)
secured.POST("/licenses", a.issueLicense)
secured.POST("/licenses/:id/revoke", func(c *gin.Context) { a.operateLicense(c, "revoke") })
secured.POST("/licenses/:id/renew", func(c *gin.Context) { a.operateLicense(c, "renew") })
}
func (a *BusinessAPI) login(c *gin.Context) {
var in struct {
Username string `json:"username"`
Password string `json:"password"`
}
if c.ShouldBindJSON(&in) != nil {
apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空")
return
}
username := strings.ToLower(strings.TrimSpace(in.Username))
if username == "" || in.Password == "" {
apiError(c, http.StatusBadRequest, "invalid_credentials", "用户名和密码不能为空")
return
}
var id uint64
var hash string
var role string
var email string
err := a.db.QueryRowContext(c, "SELECT id,email,password_hash,role FROM admins WHERE username=? AND active=1", username).Scan(&id, &email, &hash, &role)
if err != nil || bcrypt.CompareHashAndPassword([]byte(hash), []byte(in.Password)) != nil {
apiError(c, http.StatusUnauthorized, "invalid_credentials", "用户名或密码错误")
return
}
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
expires := time.Now().UTC().Add(8 * time.Hour)
sum := sha256.Sum256(raw)
if _, err = a.db.ExecContext(c, "INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", id, sum[:], expires); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.SetSameSite(http.SameSiteStrictMode)
secure := secureSessionCookie(c)
c.SetCookie("lp_session", hex.EncodeToString(raw), 8*3600, "/", "", secure, true)
c.JSON(http.StatusOK, gin.H{"data": gin.H{"username": username, "email": email, "role": role, "expires_at": expires}})
}
func (a *BusinessAPI) authenticated(c *gin.Context) {
raw, err := c.Cookie("lp_session")
if err != nil || len(raw) != 64 {
apiError(c, 401, "unauthorized", "请先登录")
c.Abort()
return
}
decoded, err := hex.DecodeString(raw)
if err != nil {
apiError(c, 401, "unauthorized", "请先登录")
c.Abort()
return
}
sum := sha256.Sum256(decoded)
var id uint64
var username, email, role string
err = a.db.QueryRowContext(c, "SELECT a.id,a.username,a.email,a.role FROM sessions s JOIN admins a ON a.id=s.admin_id WHERE s.token_hash=? AND s.revoked_at IS NULL AND s.expires_at>? AND a.active=1", sum[:], time.Now().UTC()).Scan(&id, &username, &email, &role)
if err != nil {
apiError(c, 401, "unauthorized", "会话已失效")
c.Abort()
return
}
if role != "admin" {
apiError(c, http.StatusForbidden, "forbidden", "无权访问管理接口")
c.Abort()
return
}
c.Set("admin_id", id)
c.Set("admin_username", username)
c.Set("admin_email", email)
c.Set("admin_role", role)
c.Next()
}
func (a *BusinessAPI) logout(c *gin.Context) {
if raw, err := c.Cookie("lp_session"); err == nil {
if b, e := hex.DecodeString(raw); e == nil {
sum := sha256.Sum256(b)
_, _ = a.db.ExecContext(c, "UPDATE sessions SET revoked_at=? WHERE token_hash=?", time.Now().UTC(), sum[:])
}
}
c.SetSameSite(http.SameSiteStrictMode)
c.SetCookie("lp_session", "", -1, "/", "", secureSessionCookie(c), true)
c.Status(http.StatusNoContent)
}
func (a *BusinessAPI) me(c *gin.Context) {
c.JSON(200, gin.H{"data": gin.H{"username": c.GetString("admin_username"), "email": c.GetString("admin_email"), "role": c.GetString("admin_role")}})
}
type customer struct {
ID uint64 `json:"id"`
Name string `json:"name"`
ContactEmail string `json:"contact_email"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type product struct {
ID uint64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func page(c *gin.Context) (int, int) {
p, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if p < 1 {
p = 1
}
if size < 1 || size > 100 {
size = 20
}
return p, size
}
func (a *BusinessAPI) listCustomers(c *gin.Context) {
p, size := page(c)
q := strings.TrimSpace(c.Query("q"))
like := "%" + q + "%"
var total int
if err := a.db.QueryRowContext(c, "SELECT COUNT(*) FROM customers WHERE name LIKE ? OR contact_email LIKE ?", like, like).Scan(&total); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
rows, err := a.db.QueryContext(c, "SELECT id,name,contact_email,status,created_at,updated_at FROM customers WHERE name LIKE ? OR contact_email LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?", like, like, size, (p-1)*size)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer rows.Close()
out := []customer{}
for rows.Next() {
var x customer
if err := rows.Scan(&x.ID, &x.Name, &x.ContactEmail, &x.Status, &x.CreatedAt, &x.UpdatedAt); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
out = append(out, x)
}
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
}
func (a *BusinessAPI) createCustomer(c *gin.Context) {
var in struct {
Name string `json:"name"`
ContactEmail string `json:"contact_email"`
}
if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") {
apiError(c, 400, "invalid_request", "客户名称和邮箱格式不正确")
return
}
res, err := a.db.ExecContext(c, "INSERT INTO customers(name,contact_email) VALUES(?,?)", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)))
if err != nil {
apiError(c, 409, "customer_conflict", "客户创建失败")
return
}
id, _ := res.LastInsertId()
c.JSON(201, gin.H{"data": gin.H{"id": id}})
}
func (a *BusinessAPI) updateCustomer(c *gin.Context) {
id := c.Param("id")
var in struct {
Name string `json:"name"`
ContactEmail string `json:"contact_email"`
Status string `json:"status"`
}
if c.ShouldBindJSON(&in) != nil || len(strings.TrimSpace(in.Name)) < 2 || !strings.Contains(in.ContactEmail, "@") {
apiError(c, 400, "invalid_request", "客户字段不正确")
return
}
res, err := a.db.ExecContext(c, "UPDATE customers SET name=?,contact_email=?,status=? WHERE id=?", strings.TrimSpace(in.Name), strings.TrimSpace(strings.ToLower(in.ContactEmail)), in.Status, id)
if err != nil || func() bool { n, _ := res.RowsAffected(); return n == 0 }() {
apiError(c, 404, "not_found", "客户不存在")
return
}
c.Status(204)
}
func (a *BusinessAPI) deleteCustomer(c *gin.Context) {
res, err := a.db.ExecContext(c, "DELETE FROM customers WHERE id=?", c.Param("id"))
if err != nil {
apiError(c, 500, "internal_error", "删除失败")
return
}
n, _ := res.RowsAffected()
if n == 0 {
apiError(c, 404, "not_found", "客户不存在")
return
}
c.Status(204)
}
func (a *BusinessAPI) listProducts(c *gin.Context) {
rows, err := a.db.QueryContext(c, "SELECT id,code,name,description,active,created_at,updated_at FROM products ORDER BY id DESC")
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer rows.Close()
out := []product{}
for rows.Next() {
var x product
if rows.Scan(&x.ID, &x.Code, &x.Name, &x.Description, &x.Active, &x.CreatedAt, &x.UpdatedAt) != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
out = append(out, x)
}
c.JSON(200, gin.H{"data": out})
}
func (a *BusinessAPI) createProduct(c *gin.Context) {
var in struct {
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
}
if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 {
apiError(c, 400, "invalid_request", "产品编码和名称不能为空")
return
}
res, err := a.db.ExecContext(c, "INSERT INTO products(code,name,description) VALUES(?,?,?)", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description)
if err != nil {
apiError(c, 409, "product_conflict", "产品编码已存在")
return
}
id, _ := res.LastInsertId()
c.JSON(201, gin.H{"data": gin.H{"id": id}})
}
func (a *BusinessAPI) updateProduct(c *gin.Context) {
var in struct {
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
Active *bool `json:"active"`
}
if c.ShouldBindJSON(&in) != nil || len(in.Code) < 2 || len(in.Name) < 2 {
apiError(c, 400, "invalid_request", "产品字段不正确")
return
}
active := true
if in.Active != nil {
active = *in.Active
}
res, err := a.db.ExecContext(c, "UPDATE products SET code=?,name=?,description=?,active=? WHERE id=?", strings.TrimSpace(in.Code), strings.TrimSpace(in.Name), in.Description, active, c.Param("id"))
if err != nil {
apiError(c, 409, "product_conflict", "产品更新失败")
return
}
n, _ := res.RowsAffected()
if n == 0 {
apiError(c, 404, "not_found", "产品不存在")
return
}
c.Status(204)
}
func (a *BusinessAPI) deleteProduct(c *gin.Context) {
res, err := a.db.ExecContext(c, "DELETE FROM products WHERE id=?", c.Param("id"))
if err != nil {
apiError(c, 500, "internal_error", "删除失败")
return
}
n, _ := res.RowsAffected()
if n == 0 {
apiError(c, 404, "not_found", "产品不存在")
return
}
c.Status(204)
}
func apiError(c *gin.Context, status int, code, message string) {
if status >= 500 {
message = "Service unavailable"
}
c.Set("error_code", code)
c.JSON(status, gin.H{"error": gin.H{"code": code, "message": message, "request_id": c.GetString("request_id")}})
}

View File

@@ -0,0 +1,293 @@
package httpapi
import (
"crypto/tls"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
func TestBusinessMySQLIntegration(t *testing.T) {
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN is not set")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = db.Ping(); err != nil {
t.Fatal(err)
}
for _, table := range []string{"instance_state_operations", "heartbeat_operations", "activation_operations", "license_instances", "order_operations", "offline_orders"} {
if _, err = db.Exec("DELETE FROM " + table); err != nil {
t.Fatal(err)
}
}
if _, err = db.Exec("DELETE FROM audit_events"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM license_operations"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM licenses"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM sessions"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM products"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM customers"); err != nil {
t.Fatal(err)
}
if _, err = db.Exec("DELETE FROM admins"); err != nil {
t.Fatal(err)
}
hash, err := bcrypt.GenerateFromPassword([]byte("Integration-Test-Password-2026!"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", "integration", "integration@example.test", string(hash)); err != nil {
t.Fatal(err)
}
r := NewRouter()
RegisterBusiness(r, db)
request := func(method, path, body, cookie string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if strings.HasPrefix(path, "/api/v1/auth/login") {
req.TLS = &tls.ConnectionState{}
}
if cookie != "" {
req.Header.Set("Cookie", cookie)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
if w := request("GET", "/api/v1/customers", "", ""); w.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated code=%d body=%s", w.Code, w.Body)
}
w := request("POST", "/api/v1/auth/login", `{"username":"integration","password":"Integration-Test-Password-2026!"}`, "")
if w.Code != 200 {
t.Fatalf("login code=%d body=%s", w.Code, w.Body)
}
cookie := w.Result().Cookies()[0]
if cookie.Name != "lp_session" || !cookie.HttpOnly || !cookie.Secure {
t.Fatalf("insecure session cookie: %+v", cookie)
}
w = request("POST", "/api/v1/customers", `{"name":"Integration customer","contact_email":"customer@example.test"}`, cookie.Name+"="+cookie.Value)
if w.Code != 201 {
t.Fatalf("create customer code=%d body=%s", w.Code, w.Body)
}
var customerID, productID uint64
if err = db.QueryRow("SELECT id FROM customers ORDER BY id DESC LIMIT 1").Scan(&customerID); err != nil {
t.Fatal(err)
}
w = request("GET", "/api/v1/customers?page=1&page_size=20", "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Integration customer") {
t.Fatalf("list customers code=%d body=%s", w.Code, w.Body)
}
w = request("POST", "/api/v1/products", `{"code":"integration-product","name":"Integration Product","description":"probe"}`, cookie.Name+"="+cookie.Value)
if w.Code != 201 {
t.Fatalf("create product code=%d body=%s", w.Code, w.Body)
}
if err = db.QueryRow("SELECT id FROM products ORDER BY id DESC LIMIT 1").Scan(&productID); err != nil {
t.Fatal(err)
}
w = request("GET", "/api/v1/products", "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), "integration-product") {
t.Fatalf("list products code=%d body=%s", w.Code, w.Body)
}
issueBody := fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"starts_at":"2026-09-30T00:00:00Z","expires_at":"2027-09-30T00:00:00Z"}`, customerID, productID)
w = request("POST", "/api/v1/licenses", issueBody, "")
if w.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated issue code=%d", w.Code)
}
requestWithKey := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/v1/licenses", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "integration-issue-1")
req.AddCookie(cookie)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
w = requestWithKey(issueBody)
if w.Code != http.StatusCreated {
t.Fatalf("issue code=%d body=%s", w.Code, w.Body)
}
var first struct {
Data licenseRecord `json:"data"`
}
if err = json.Unmarshal(w.Body.Bytes(), &first); err != nil {
t.Fatal(err)
}
w = requestWithKey(issueBody)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) || !strings.Contains(w.Body.String(), first.Data.LicenseKey) {
t.Fatalf("idempotent replay code=%d body=%s", w.Code, w.Body)
}
var licenseCount, auditCount int
if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil {
t.Fatal(err)
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='license.issued'").Scan(&auditCount); err != nil {
t.Fatal(err)
}
if licenseCount != 1 || auditCount != 1 {
t.Fatalf("expected single license/audit; got %d/%d", licenseCount, auditCount)
}
w = request("GET", "/api/v1/licenses?page=1&page_size=20", "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"active"`) {
t.Fatalf("list licenses code=%d body=%s", w.Code, w.Body)
}
w = request("GET", fmt.Sprintf("/api/v1/licenses/%d", first.Data.ID), "", cookie.Name+"="+cookie.Value)
if w.Code != 200 || !strings.Contains(w.Body.String(), first.Data.LicenseKey) {
t.Fatalf("license detail code=%d body=%s", w.Code, w.Body)
}
operation := func(method, path, body, key string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
req.AddCookie(cookie)
out := httptest.NewRecorder()
r.ServeHTTP(out, req)
return out
}
licensePath := func(suffix string) string { return fmt.Sprintf("/api/v1/licenses/%d/%s", first.Data.ID, suffix) }
w = operation("POST", licensePath("renew"), `{"expires_at":"2028-01-01T00:00:00Z"}`, "renew-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"expires_at":"2028-01-01T00:00:00Z"`) {
t.Fatalf("renew code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("renew"), `{"expires_at":"2028-01-01T00:00:00Z"}`, "renew-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) {
t.Fatalf("renew replay code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("renew"), `{"expires_at":"2029-01-01T00:00:00Z"}`, "renew-1")
if w.Code != 409 {
t.Fatalf("renew conflict code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("revoke"), "{}", "revoke-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"revoked"`) {
t.Fatalf("revoke code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("revoke"), "{}", "revoke-1")
if w.Code != 200 || !strings.Contains(w.Body.String(), `"idempotent_replay":true`) {
t.Fatalf("revoke replay code=%d body=%s", w.Code, w.Body)
}
w = operation("POST", licensePath("renew"), `{"expires_at":"2029-01-01T00:00:00Z"}`, "renew-after-revoke")
if w.Code != 400 {
t.Fatalf("renew revoked code=%d body=%s", w.Code, w.Body)
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events").Scan(&auditCount); err != nil {
t.Fatal(err)
}
if auditCount != 3 {
t.Fatalf("audit count after operations=%d", auditCount)
}
w = requestWithKey(fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"starts_at":"bad","expires_at":"2027-01-01T00:00:00Z"}`, customerID, productID))
if w.Code != 400 {
t.Fatalf("invalid dates code=%d body=%s", w.Code, w.Body)
}
w = requestWithKey(strings.Replace(issueBody, "2027-09-30", "2027-10-30", 1))
if w.Code != 409 {
t.Fatalf("changed payload code=%d body=%s", w.Code, w.Body)
}
if _, err = db.Exec("UPDATE admins SET role='viewer' WHERE email='integration@example.test'"); err != nil {
t.Fatal(err)
}
w = requestWithKey(issueBody)
if w.Code != 403 {
t.Fatalf("viewer issue code=%d body=%s", w.Code, w.Body)
}
if _, err = db.Exec("UPDATE admins SET role='admin' WHERE email='integration@example.test'"); err != nil {
t.Fatal(err)
}
// A new key must still validate current master-data state.
if _, err = db.Exec("UPDATE products SET active=0 WHERE id=?", productID); err != nil {
t.Fatal(err)
}
newKeyRequest := func(key string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/v1/licenses", strings.NewReader(issueBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
req.AddCookie(cookie)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
w = newKeyRequest("inactive-product")
if w.Code != 400 {
t.Fatalf("inactive product code=%d body=%s", w.Code, w.Body)
}
if _, err = db.Exec("UPDATE products SET active=1 WHERE id=?", productID); err != nil {
t.Fatal(err)
}
// Inject a test-only audit failure to prove issuance rolls back atomically.
if _, err = db.Exec("CREATE TRIGGER integration_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='integration audit failure'"); err != nil {
t.Fatal(err)
}
w = newKeyRequest("audit-failure")
_, dropErr := db.Exec("DROP TRIGGER integration_audit_failure")
if dropErr != nil {
t.Fatal(dropErr)
}
if w.Code != 500 {
t.Fatalf("audit failure code=%d body=%s", w.Code, w.Body)
}
if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil {
t.Fatal(err)
}
if licenseCount != 1 {
t.Fatalf("audit failure left %d licenses", licenseCount)
}
results := make(chan *httptest.ResponseRecorder, 2)
for i := 0; i < 2; i++ {
go func() { results <- newKeyRequest("concurrent-issue") }()
}
created, replayed := 0, 0
for i := 0; i < 2; i++ {
response := <-results
switch response.Code {
case 201:
created++
case 200:
replayed++
default:
t.Fatalf("concurrent issue code=%d body=%s", response.Code, response.Body)
}
}
if created != 1 || replayed != 1 {
t.Fatalf("concurrent created/replayed=%d/%d", created, replayed)
}
if err = db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&licenseCount); err != nil {
t.Fatal(err)
}
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events").Scan(&auditCount); err != nil {
t.Fatal(err)
}
if licenseCount != 2 || auditCount != 4 {
t.Fatalf("concurrent license/audit=%d/%d", licenseCount, auditCount)
}
t.Run("orders", func(t *testing.T) { testOrdersMySQL(t, db, r, cookie, customerID, productID) })
t.Run("activation", func(t *testing.T) { testActivationMySQL(t, db, cookie) })
w = request("POST", "/api/v1/auth/logout", "", cookie.Name+"="+cookie.Value)
if w.Code != http.StatusNoContent {
t.Fatalf("logout code=%d", w.Code)
}
w = request("GET", "/api/v1/me", "", cookie.Name+"="+cookie.Value)
if w.Code != http.StatusUnauthorized {
t.Fatalf("revoked session code=%d", w.Code)
}
}

View File

@@ -0,0 +1,111 @@
package httpapi
import (
"database/sql"
"time"
"github.com/gin-gonic/gin"
)
type licenseTrendPoint struct {
Month string `json:"month"`
Issued int64 `json:"issued"`
Expired int64 `json:"expired"`
}
type dashboardSummaryRecord struct {
ActiveLicenses int64 `json:"active_licenses"`
NewCustomers int64 `json:"new_customers"`
PaidRevenueCents int64 `json:"paid_revenue_cents"`
Currency string `json:"currency"`
ExpiringLicenses int64 `json:"expiring_licenses"`
LicenseTrend []licenseTrendPoint `json:"license_trend"`
UpcomingExpirations []licenseRecord `json:"upcoming_expirations"`
RecentLicenses []licenseRecord `json:"recent_licenses"`
GeneratedAt time.Time `json:"generated_at"`
}
func dashboardMonths(c *gin.Context) (int, bool) {
switch c.DefaultQuery("months", "6") {
case "6":
return 6, true
case "12":
return 12, true
default:
apiError(c, 400, "invalid_request", "months 必须为 6 或 12")
return 0, false
}
}
func (a *BusinessAPI) dashboardSummary(c *gin.Context) {
months, ok := dashboardMonths(c)
if !ok {
return
}
now := time.Now().UTC()
out, err := a.loadDashboardSummary(c, now, months)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.JSON(200, gin.H{"data": out})
}
// A read-only consistent snapshot prevents concurrent issuance/payment from making
// the summary counts and its lists disagree. No application rows are changed.
func (a *BusinessAPI) loadDashboardSummary(c *gin.Context, now time.Time, months int) (dashboardSummaryRecord, error) {
now = now.UTC()
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
nextMonth := monthStart.AddDate(0, 1, 0)
out := dashboardSummaryRecord{Currency: "CNY", GeneratedAt: now,
LicenseTrend: make([]licenseTrendPoint, months),
UpcomingExpirations: []licenseRecord{}, RecentLicenses: []licenseRecord{}}
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
if err != nil {
return out, err
}
defer tx.Rollback()
err = tx.QueryRowContext(c, `SELECT
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?),
(SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at<?),
(SELECT COALESCE(SUM(amount_cents),0) FROM offline_orders WHERE status IN ('paid','issued') AND currency='CNY' AND paid_at>=? AND paid_at<?),
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)`,
now, now, monthStart, nextMonth, monthStart, nextMonth, now, now, now.Add(30*24*time.Hour)).Scan(
&out.ActiveLicenses, &out.NewCustomers, &out.PaidRevenueCents, &out.ExpiringLicenses)
if err != nil {
return out, err
}
// Range aggregates use UTC boundaries rather than the database session's date
// formatting/timezone. Each bucket includes its start and excludes its end.
for i := range out.LicenseTrend {
start := monthStart.AddDate(0, i-months+1, 0)
end := start.AddDate(0, 1, 0)
point := &out.LicenseTrend[i]
point.Month = start.Format("2006-01")
err = tx.QueryRowContext(c, `SELECT
(SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at<?),
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND expires_at>=? AND expires_at<? AND expires_at<=?)`,
start, end, start, end, now).Scan(&point.Issued, &point.Expired)
if err != nil {
return out, err
}
}
where, args, _ := licenseFilter("expiring", "", now)
rows, err := tx.QueryContext(c, licenseSelect+where+" ORDER BY l.expires_at ASC,l.id ASC LIMIT 10", args...)
if err != nil {
return out, err
}
out.UpcomingExpirations, err = readLicenseRecords(rows, now)
if err != nil {
return out, err
}
rows, err = tx.QueryContext(c, licenseSelect+" ORDER BY l.created_at DESC,l.id DESC LIMIT 10")
if err != nil {
return out, err
}
out.RecentLicenses, err = readLicenseRecords(rows, now)
if err != nil {
return out, err
}
return out, tx.Commit()
}

View File

@@ -0,0 +1,355 @@
package httpapi
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
)
// This driver has no network or filesystem access. Every query must consume an
// explicit expectation, so an accidental write or unfiltered query fails.
type dashboardQuery struct {
sql string
args []any
rows [][]driver.Value
err error
rowErr error
}
type dashboardDB struct {
t *testing.T
queries []dashboardQuery
txOptions driver.TxOptions
began, committed, rolledBack bool
}
func (d *dashboardDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
func (d *dashboardDB) Driver() driver.Driver { return dashboardDriver{d} }
type dashboardDriver struct{ db *dashboardDB }
func (d dashboardDriver) Open(string) (driver.Conn, error) { return d.db, nil }
func (*dashboardDB) Prepare(string) (driver.Stmt, error) {
return nil, errors.New("unexpected prepare")
}
func (*dashboardDB) Close() error { return nil }
func (*dashboardDB) Begin() (driver.Tx, error) { return nil, errors.New("use BeginTx") }
func (d *dashboardDB) BeginTx(_ context.Context, options driver.TxOptions) (driver.Tx, error) {
d.began = true
d.txOptions = options
return d, nil
}
func (d *dashboardDB) Commit() error { d.committed = true; return nil }
func (d *dashboardDB) Rollback() error { d.rolledBack = true; return nil }
func (d *dashboardDB) QueryContext(_ context.Context, query string, values []driver.NamedValue) (driver.Rows, error) {
if len(d.queries) == 0 {
d.t.Errorf("unexpected SQL: %s", query)
return nil, errors.New("unexpected SQL")
}
q := d.queries[0]
d.queries = d.queries[1:]
if strings.Join(strings.Fields(query), " ") != strings.Join(strings.Fields(q.sql), " ") {
d.t.Errorf("SQL mismatch\ngot: %s\nwant: %s", query, q.sql)
}
got := make([]any, len(values))
for i, v := range values {
got[i] = v.Value
}
// database/sql converts integer bind arguments to int64.
want := make([]any, len(q.args))
for i, v := range q.args {
if n, ok := v.(int); ok {
want[i] = int64(n)
} else {
want[i] = v
}
}
if !reflect.DeepEqual(got, want) {
d.t.Errorf("arguments got %#v want %#v", got, want)
}
if q.err != nil {
return nil, q.err
}
width := 1
if len(q.rows) > 0 {
width = len(q.rows[0])
} else if strings.HasPrefix(query, "SELECT l.id") {
width = 11
}
return &dashboardRows{rows: q.rows, width: width, err: q.rowErr}, nil
}
type dashboardRows struct {
rows [][]driver.Value
width int
err error
}
func (r *dashboardRows) Columns() []string {
out := make([]string, r.width)
for i := range out {
out[i] = fmt.Sprint(i)
}
return out
}
func (*dashboardRows) Close() error { return nil }
func (r *dashboardRows) Next(dst []driver.Value) error {
if len(r.rows) == 0 {
if r.err != nil {
return r.err
}
return io.EOF
}
copy(dst, r.rows[0])
r.rows = r.rows[1:]
return nil
}
func newDashboardTestDB(t *testing.T, queries []dashboardQuery) (*sql.DB, *dashboardDB) {
t.Helper()
stub := &dashboardDB{t: t, queries: queries}
db := sql.OpenDB(stub)
t.Cleanup(func() {
db.Close()
if len(stub.queries) > 0 {
t.Errorf("%d unconsumed SQL expectations", len(stub.queries))
}
})
return db, stub
}
const dashboardTotalsSQL = `SELECT
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?),
(SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at<?),
(SELECT COALESCE(SUM(amount_cents),0) FROM offline_orders WHERE status IN ('paid','issued') AND currency='CNY' AND paid_at>=? AND paid_at<?),
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)`
const dashboardTrendSQL = `SELECT
(SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at<?),
(SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND expires_at>=? AND expires_at<? AND expires_at<=?)`
func dashboardExpectations(now time.Time, months int) []dashboardQuery {
start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
end := start.AddDate(0, 1, 0)
queries := []dashboardQuery{{sql: dashboardTotalsSQL, args: []any{now, now, start, end, start, end, now, now, now.Add(30 * 24 * time.Hour)}, rows: [][]driver.Value{{int64(123), int64(45), int64(987654321), int64(27)}}}}
for i := 0; i < months; i++ {
from := start.AddDate(0, i-months+1, 0)
to := from.AddDate(0, 1, 0)
queries = append(queries, dashboardQuery{sql: dashboardTrendSQL, args: []any{from, to, from, to, now}, rows: [][]driver.Value{{int64(i), int64(i % 2)}}})
}
queries = append(queries,
dashboardQuery{sql: licenseSelect + " WHERE 1=1 AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>? AND l.expires_at<=? ORDER BY l.expires_at ASC,l.id ASC LIMIT 10", args: []any{now, now, now.Add(30 * 24 * time.Hour)}, rows: [][]driver.Value{testLicenseRow(1, "active", now.Add(-time.Hour), now.Add(time.Hour), now)}},
dashboardQuery{sql: licenseSelect + " ORDER BY l.created_at DESC,l.id DESC LIMIT 10", rows: [][]driver.Value{testLicenseRow(2, "active", now.Add(time.Hour), now.Add(2*time.Hour), now)}})
return queries
}
func testLicenseRow(id int64, status string, start, end, created time.Time) []driver.Value {
return []driver.Value{id, "key", int64(7), "Customer", int64(8), "Product", "code", status, start, end, created}
}
func TestDashboardSummarySnapshot(t *testing.T) {
for _, months := range []int{6, 12} {
t.Run(fmt.Sprint(months), func(t *testing.T) {
// January in UTC+8 is still December in UTC; also tests crossing a year.
now := time.Date(2027, 1, 1, 1, 0, 0, 0, time.FixedZone("UTC+8", 8*3600)).UTC()
db, stub := newDashboardTestDB(t, dashboardExpectations(now, months))
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("GET", "/", nil)
out, err := (&BusinessAPI{db: db}).loadDashboardSummary(c, now, months)
if err != nil {
t.Fatal(err)
}
if out.ActiveLicenses != 123 || out.NewCustomers != 45 || out.PaidRevenueCents != 987654321 || out.ExpiringLicenses != 27 || out.Currency != "CNY" {
t.Fatalf("wrong totals: %+v", out)
}
if !stub.began || !stub.committed || stub.rolledBack || !stub.txOptions.ReadOnly || stub.txOptions.Isolation != driver.IsolationLevel(sql.LevelRepeatableRead) {
t.Fatalf("snapshot transaction: %+v", stub)
}
if len(out.LicenseTrend) != months || out.LicenseTrend[months-1].Month != "2026-12" || out.LicenseTrend[0].Issued != 0 {
t.Fatalf("trend: %+v", out.LicenseTrend)
}
if len(out.UpcomingExpirations) != 1 || len(out.RecentLicenses) != 1 || out.RecentLicenses[0].Status != "scheduled" || out.UpcomingExpirations[0].CustomerName != "Customer" {
t.Fatalf("records: %+v", out)
}
data, err := json.Marshal(out)
if err != nil {
t.Fatal(err)
}
var fields map[string]json.RawMessage
json.Unmarshal(data, &fields)
for _, field := range []string{"active_licenses", "new_customers", "paid_revenue_cents", "currency", "expiring_licenses", "license_trend", "upcoming_expirations", "recent_licenses", "generated_at"} {
if _, ok := fields[field]; !ok {
t.Errorf("missing %s", field)
}
}
var generated string
json.Unmarshal(fields["generated_at"], &generated)
parsed, err := time.Parse(time.RFC3339, generated)
if err != nil || !parsed.Equal(now) {
t.Fatalf("generated_at %s", generated)
}
})
}
}
func TestDashboardEmptyAndFailure(t *testing.T) {
now := time.Date(2026, 10, 8, 10, 0, 0, 0, time.UTC)
for _, mode := range []string{"empty", "aggregate error", "trend error", "list error", "row error", "scan error"} {
t.Run(mode, func(t *testing.T) {
qs := dashboardExpectations(now, 6)
switch mode {
case "empty":
for i := 0; i < 7; i++ {
for j := range qs[i].rows[0] {
qs[i].rows[0][j] = int64(0)
}
}
qs[7].rows = nil
qs[8].rows = nil
case "aggregate error":
qs = qs[:1]
qs[0].err = errors.New("private database detail")
case "trend error":
qs = qs[:2]
qs[1].err = errors.New("failure")
case "list error":
qs = qs[:8]
qs[7].err = errors.New("failure")
case "row error":
qs = qs[:8]
qs[7].rowErr = errors.New("failure")
case "scan error":
qs = qs[:8]
qs[7].rows[0][0] = "invalid id"
}
db, stub := newDashboardTestDB(t, qs)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("GET", "/", nil)
out, err := (&BusinessAPI{db: db}).loadDashboardSummary(c, now, 6)
if mode == "empty" {
if err != nil || out.PaidRevenueCents != 0 || out.UpcomingExpirations == nil || out.RecentLicenses == nil || len(out.LicenseTrend) != 6 {
t.Fatalf("empty summary %+v %v", out, err)
}
} else if err == nil || !stub.rolledBack || stub.committed {
t.Fatalf("failure err=%v rollback=%v commit=%v", err, stub.rolledBack, stub.committed)
}
})
}
}
func TestDashboardMonthsValidation(t *testing.T) {
for _, tc := range []struct {
query string
want int
ok bool
}{{"", 6, true}, {"?months=6", 6, true}, {"?months=12", 12, true}, {"?months=", 0, false}, {"?months=3", 0, false}, {"?months=abc", 0, false}, {"?months=06", 0, false}} {
t.Run(tc.query, func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/"+tc.query, nil)
got, ok := dashboardMonths(c)
if got != tc.want || ok != tc.ok {
t.Fatalf("got %d/%v", got, ok)
}
if !ok && (w.Code != 400 || !strings.Contains(w.Body.String(), "invalid_request")) {
t.Fatal(w.Body.String())
}
})
}
}
func TestDashboardAndLicenseAdminRoutes(t *testing.T) {
// Authentication is exercised through real route registration. An unauthorized
// request must never reach summary/list SQL, even with invalid query parameters.
for _, path := range []string{"/api/v1/dashboard/summary?months=invalid", "/api/v1/licenses?status=invalid"} {
for _, mode := range []string{"missing", "malformed", "viewer", "expired", "admin"} {
t.Run(path+mode, func(t *testing.T) {
db, stub := newDashboardTestDB(t, nil)
r := gin.New()
RegisterBusiness(r, db)
req := httptest.NewRequest("GET", path, nil)
if mode == "malformed" {
req.AddCookie(&http.Cookie{Name: "lp_session", Value: strings.Repeat("z", 64)})
}
if mode == "viewer" || mode == "expired" || mode == "admin" {
req.AddCookie(&http.Cookie{Name: "lp_session", Value: strings.Repeat("0", 64)})
// The expiry cutoff is generated by authentication; capture and check it in
// a dedicated connector rather than relying on a wall-clock exact match.
db.Close()
auth := &dashboardAuthDB{t: t, mode: mode}
db = sql.OpenDB(auth)
defer db.Close()
r = gin.New()
RegisterBusiness(r, db)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
want := 401
if mode == "viewer" {
want = 403
}
if mode == "admin" {
want = 400 // Valid administrator reaches the handler's validation.
}
if w.Code != want {
t.Fatalf("got %d %s", w.Code, w.Body)
}
if stub.began {
t.Fatal("unauthorized aggregate")
}
})
}
}
}
// Authentication queries contain a live expiry cutoff, checked independently.
type dashboardAuthDB struct {
t *testing.T
mode string
}
func (d *dashboardAuthDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
func (d *dashboardAuthDB) Driver() driver.Driver { return dashboardAuthDriver{d} }
type dashboardAuthDriver struct{ db *dashboardAuthDB }
func (d dashboardAuthDriver) Open(string) (driver.Conn, error) { return d.db, nil }
func (*dashboardAuthDB) Close() error { return nil }
func (*dashboardAuthDB) Prepare(string) (driver.Stmt, error) {
return nil, errors.New("unexpected prepare")
}
func (*dashboardAuthDB) Begin() (driver.Tx, error) { return nil, errors.New("unexpected transaction") }
func (d *dashboardAuthDB) QueryContext(_ context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {
if !strings.Contains(q, "s.expires_at>?") || !strings.Contains(q, "a.active=1") || len(args) != 2 {
d.t.Errorf("unexpected auth SQL %s", q)
return nil, errors.New("unexpected auth SQL")
}
if cutoff, ok := args[1].Value.(time.Time); !ok || time.Since(cutoff) > time.Second {
d.t.Error("invalid session expiry cutoff")
}
if d.mode == "expired" {
return &dashboardRows{width: 4}, nil
}
role := "viewer"
if d.mode == "admin" {
role = "admin"
}
return &dashboardRows{width: 4, rows: [][]driver.Value{{int64(1), "admin-1", "admin@example.test", role}}}, nil
}
func TestDashboardSummaryHTTPFailure(t *testing.T) {
db, _ := newDashboardTestDB(t, nil)
// A closed, network-free database exercises the handler's failure response.
db.Close()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/api/v1/dashboard/summary", nil)
(&BusinessAPI{db: db}).dashboardSummary(c)
if w.Code != 500 || !strings.Contains(w.Body.String(), `"code":"internal_error"`) || !strings.Contains(w.Body.String(), `"message":"Service unavailable"`) || strings.Contains(w.Body.String(), "database is closed") {
t.Fatalf("%d %s", w.Code, w.Body)
}
}

View File

@@ -0,0 +1,253 @@
package httpapi
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
var packageKeyPattern = regexp.MustCompile(`^[0-9a-f]{64}\.bin$`)
var releaseVersionPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
// Each package must be a regular file directly below a trusted, non-public root.
func localPackage(root, key string) (string, error) {
if root == "" || !filepath.IsAbs(root) || !packageKeyPattern.MatchString(key) {
return "", errors.New("invalid storage configuration")
}
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return "", err
}
path := filepath.Join(realRoot, key)
info, err := os.Lstat(path)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() {
return "", errors.New("not a regular package")
}
return path, nil
}
func (a *BusinessAPI) createRelease(c *gin.Context) {
productID, err := strconv.ParseUint(c.Param("id"), 10, 64)
version := c.Query("version")
root := os.Getenv("PACKAGE_STORAGE_ROOT")
if err != nil || productID == 0 || !releaseVersionPattern.MatchString(version) {
apiError(c, 400, "invalid_request", "产品或版本无效")
return
}
if root == "" || !filepath.IsAbs(root) {
apiError(c, 503, "storage_unavailable", "文件存储未配置")
return
}
root, err = filepath.EvalSymlinks(root)
if err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var active bool
if err = tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", productID).Scan(&active); err != nil || !active {
apiError(c, 409, "invalid_state", "产品不可发布")
return
}
file, err := os.CreateTemp(root, ".upload-")
if err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
defer os.Remove(file.Name())
defer file.Close()
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<20)
hash := sha256.New()
n, err := io.Copy(io.MultiWriter(file, hash), c.Request.Body)
if err != nil || n == 0 {
apiError(c, 400, "invalid_package", "包为空或超过DEV 64MiB限制")
return
}
digest := hex.EncodeToString(hash.Sum(nil))
key := digest + ".bin"
if _, err = tx.ExecContext(c, "INSERT INTO package_objects(sha256,size_bytes) VALUES(?,?) ON DUPLICATE KEY UPDATE sha256=sha256", digest, n); err != nil {
apiError(c, 500, "internal_error", "发布失败")
return
}
var storedSize int64
if err = tx.QueryRowContext(c, "SELECT size_bytes FROM package_objects WHERE sha256=? FOR UPDATE", digest).Scan(&storedSize); err != nil || storedSize != n {
apiError(c, 409, "package_integrity", "包元数据不匹配")
return
}
if err = file.Sync(); err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
file.Close()
// Hard link publishes immutable bytes without overwriting an existing digest.
publishedPath := filepath.Join(root, key)
linked := false
if err = os.Link(file.Name(), publishedPath); err != nil && !os.IsExist(err) {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
if err == nil {
linked = true
}
cleanupPublished := func() {
if linked {
_ = os.Remove(publishedPath)
}
}
path, err := localPackage(root, key)
if err != nil {
cleanupPublished()
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
existing, err := os.Open(path)
if err != nil {
cleanupPublished()
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
verify := sha256.New()
size, err := io.Copy(verify, existing)
existing.Close()
if err != nil || size != n || hex.EncodeToString(verify.Sum(nil)) != digest {
cleanupPublished()
apiError(c, 409, "package_integrity", "已存文件不匹配")
return
}
result, err := tx.ExecContext(c, "INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,?,?,?,?,?)", productID, version, key, digest, n, c.GetUint64("admin_id"))
if err != nil {
cleanupPublished()
apiError(c, 409, "release_conflict", "版本已存在或不可发布")
return
}
id, err := result.LastInsertId()
if err != nil {
cleanupPublished()
apiError(c, 500, "internal_error", "发布失败")
return
}
details, _ := json.Marshal(gin.H{"product_id": productID, "version": version, "sha256": digest, "size_bytes": n})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'release.published','product_release',?,?)", c.GetUint64("admin_id"), id, details); err != nil {
cleanupPublished()
apiError(c, 500, "internal_error", "发布失败")
return
}
if err = tx.Commit(); err != nil {
// Commit can succeed remotely even when its acknowledgement is lost.
// Keep the private content object for reconciliation, never delete here.
apiError(c, 500, "internal_error", "发布失败")
return
}
c.JSON(201, gin.H{"data": gin.H{"id": id, "product_id": productID, "version": version, "sha256": digest, "size_bytes": n}})
}
func (a *BusinessAPI) downloadRelease(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
var in struct {
InstanceID string `json:"instance_id"`
Secret string `json:"secret"`
}
if c.ShouldBindJSON(&in) != nil || len(in.InstanceID) != 36 || 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
}
customerID, err := strconv.ParseUint(c.Param("customer_id"), 10, 64)
if err != nil || customerID == 0 {
apiError(c, 400, "invalid_request", "客户无效")
return
}
releaseID, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || releaseID == 0 {
apiError(c, 400, "invalid_request", "版本无效")
return
}
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var id, actor, owner, productID uint64
var stored []byte
var status, freeze, licenseStatus, customerStatus string
var active bool
var starts, expires, 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=? FOR UPDATE`, in.InstanceID).Scan(&id, &actor, &owner, &productID, &stored, &status, &freeze, &licenseStatus, &customerStatus, &active, &starts, &expires)
sum := sha256.Sum256(raw)
if err != nil || !bytesEqual(stored, sum[:]) {
apiError(c, 403, "forbidden", "下载凭据无效")
return
}
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
allowed := owner == customerID && leaseState(status, freeze, licenseStatus, customerStatus, active, starts, expires, now) == "active"
var key, digest string
var n uint64
if allowed {
err = tx.QueryRowContext(c, "SELECT storage_key,sha256,size_bytes FROM product_releases WHERE id=? AND product_id=? AND published=1 FOR UPDATE", releaseID, productID).Scan(&key, &digest, &n)
allowed = err == nil
}
action := "release.download_denied"
if allowed {
action = "release.download_authorized"
}
details, _ := json.Marshal(gin.H{"instance_id": in.InstanceID, "customer_id": customerID, "release_id": releaseID, "client_actor": "instance"})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'license_instance',?,?)", actor, action, id, details); err != nil {
apiError(c, 500, "internal_error", "下载审计失败")
return
}
if !allowed {
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "下载审计失败")
return
}
apiError(c, 403, "forbidden", "无下载权限")
return
}
path, err := localPackage(os.Getenv("PACKAGE_STORAGE_ROOT"), key)
if err != nil {
apiError(c, 503, "storage_unavailable", "文件存储不可用")
return
}
info, err := os.Stat(path)
if err != nil || uint64(info.Size()) != n {
apiError(c, 503, "storage_unavailable", "文件存储不匹配")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "下载审计失败")
return
}
c.Header("X-Accel-Redirect", "/_packages/"+key)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", `attachment; filename="`+key+`"`)
c.Header("X-Package-SHA256", digest)
c.Header("Cache-Control", "private, no-store")
c.Status(200)
}

View File

@@ -0,0 +1,270 @@
package httpapi
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
osexec "os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
func TestDownloadsMySQLIntegration(t *testing.T) {
dsn := os.Getenv("DOWNLOAD_TEST_DSN")
if dsn == "" {
t.Skip("DOWNLOAD_TEST_DSN must name an isolated migrated database")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
root := t.TempDir()
t.Setenv("PACKAGE_STORAGE_ROOT", root)
exec := func(q string, args ...any) int64 {
t.Helper()
r, e := db.Exec(q, args...)
if e != nil {
t.Fatal(e)
}
id, _ := r.LastInsertId()
return id
}
suffix := fmt.Sprint(time.Now().UnixNano())
admin := exec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@download.test", "unused")
raw := make([]byte, 32)
rand.Read(raw)
sessionHash := sha256.Sum256(raw)
exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", admin, sessionHash[:], time.Now().Add(time.Hour))
cookie := &http.Cookie{Name: "lp_session", Value: hex.EncodeToString(raw)}
customer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'download@example.test')", suffix)
otherCustomer := exec("INSERT INTO customers(name,contact_email) VALUES(?,'other@example.test')", suffix+"other")
product := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, suffix)
otherProduct := exec("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", suffix)
license := exec("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", hex.EncodeToString(raw[:16]), customer, product, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix, admin)
secret := make([]byte, 32)
rand.Read(secret)
secretHash := sha256.Sum256(secret)
instanceID, _ := newInstanceID()
instanceRow := exec("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,status,created_by) VALUES(?,?,?,?,?,'activated',?)", instanceID, license, customer, product, secretHash[:], admin)
r := NewRouter()
RegisterBusiness(r, db)
req := func(path string, body io.Reader, auth bool) *httptest.ResponseRecorder {
q := httptest.NewRequest("POST", path, body)
if auth {
q.AddCookie(cookie)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
return w
}
publish := func(p int64, v, body string, auth bool) *httptest.ResponseRecorder {
return req(fmt.Sprintf("/api/v1/products/%d/releases?version=%s", p, v), strings.NewReader(body), auth)
}
releaseID := func(w *httptest.ResponseRecorder) int64 {
t.Helper()
if w.Code != 201 {
t.Fatalf("publish %d %s", w.Code, w.Body)
}
var out struct{ Data struct{ ID int64 } }
if e := json.Unmarshal(w.Body.Bytes(), &out); e != nil {
t.Fatal(e)
}
return out.Data.ID
}
if w := publish(product, "unauth", "body", false); w.Code != 401 {
t.Fatal(w.Code)
}
id := releaseID(publish(product, "v1", "package bytes", true))
otherID := releaseID(publish(otherProduct, "v1", "other bytes", true))
download := func(cust, id int64, sec string) *httptest.ResponseRecorder {
body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": sec})
return req(fmt.Sprintf("/api/v1/customers/%d/releases/%d/download", cust, id), strings.NewReader(string(body)), false)
}
encoded := base64.RawURLEncoding.EncodeToString(secret)
auditCount := func(action string) int {
t.Helper()
var n int
if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action=? AND resource_type='license_instance' AND resource_id=?", action, instanceRow).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
check := func(cust, id int64, sec string, code int) {
t.Helper()
w := download(cust, id, sec)
if w.Code != code {
t.Fatalf("download %d want %d: %s", w.Code, code, w.Body)
}
if code != 200 && w.Header().Get("X-Accel-Redirect") != "" {
t.Fatal("denied request exposes file redirect")
}
}
check(customer, id, encoded, 200)
deniedBefore := auditCount("release.download_denied")
exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(-time.Minute), license)
check(customer, id, encoded, 403)
if auditCount("release.download_denied") != deniedBefore+1 {
t.Fatal("expired download was not audited")
}
exec("UPDATE licenses SET expires_at=? WHERE id=?", time.Now().Add(time.Hour), license)
unpublished := exec("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,published,created_by) VALUES(?,?,?,?,?,0,?)", product, "unpublished", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin", strings.Repeat("a", 64), 1, admin)
deniedBefore = auditCount("release.download_denied")
check(customer, unpublished, encoded, 403)
if auditCount("release.download_denied") != deniedBefore+1 {
t.Fatal("unpublished download was not audited")
}
deniedBefore = auditCount("release.download_denied")
check(customer, id+999999, encoded, 403)
if auditCount("release.download_denied") != deniedBefore+1 {
t.Fatal("missing release was not audited")
}
check(otherCustomer, id, encoded, 403)
check(customer, otherID, encoded, 403)
check(customer, id, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), 403)
for _, state := range []struct{ deny, restore string }{
{"UPDATE license_instances SET freeze_state='frozen' WHERE license_id=?", "UPDATE license_instances SET freeze_state='none' WHERE license_id=?"},
{"UPDATE licenses SET status='revoked' WHERE id=?", "UPDATE licenses SET status='active' WHERE id=?"},
} {
exec(state.deny, license)
check(customer, id, encoded, 403)
exec(state.restore, license)
}
exec("UPDATE customers SET status='inactive' WHERE id=?", customer)
check(customer, id, encoded, 403)
exec("UPDATE customers SET status='active' WHERE id=?", customer)
exec("UPDATE products SET active=0 WHERE id=?", product)
check(customer, id, encoded, 403)
exec("UPDATE products SET active=1 WHERE id=?", product)
exec("CREATE TRIGGER download_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'")
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS download_audit_failure") })
check(customer, id, encoded, 500)
failedBody := "audit fails unique body"
digest := sha256.Sum256([]byte(failedBody))
if w := publish(product, "audit-fails", failedBody, true); w.Code != 500 {
t.Fatalf("audit upload %d", w.Code)
}
var count int
db.QueryRow("SELECT COUNT(*) FROM product_releases WHERE version='audit-fails'").Scan(&count)
if count != 0 {
t.Fatal("failed release committed")
}
if _, e := os.Stat(filepath.Join(root, hex.EncodeToString(digest[:])+".bin")); !os.IsNotExist(e) {
t.Fatal("failed upload left new file")
}
exec("DROP TRIGGER download_audit_failure")
var wg sync.WaitGroup
codes := make(chan int, 2)
for i, p := range []int64{product, otherProduct} {
wg.Add(1)
go func(i int, p int64) {
defer wg.Done()
codes <- publish(p, fmt.Sprintf("concurrent-%d", i), "same digest bytes", true).Code
}(i, p)
}
wg.Wait()
close(codes)
for code := range codes {
if code != 201 {
t.Fatalf("concurrent digest %d", code)
}
}
digest = sha256.Sum256([]byte("same digest bytes"))
data, e := os.ReadFile(filepath.Join(root, hex.EncodeToString(digest[:])+".bin"))
if e != nil || string(data) != "same digest bytes" {
t.Fatal("shared digest damaged")
}
if w := publish(product, "v1", "conflicting version bytes", true); w.Code != 409 {
t.Fatal(w.Code)
}
if w := publish(product, "empty", "", true); w.Code != 400 {
t.Fatal(w.Code)
}
for _, n := range []int64{64 << 20, (64 << 20) + 1} {
w := req(fmt.Sprintf("/api/v1/products/%d/releases?version=limit-%d", product, n), io.LimitReader(zeroReader{}, n), true)
want := 201
if n > 64<<20 {
want = 400
}
if w.Code != want {
t.Fatalf("size %d code=%d want=%d %s", n, w.Code, want, w.Body)
}
}
files, _ := filepath.Glob(filepath.Join(root, ".upload-*"))
if len(files) != 0 {
t.Fatal("temporary uploads leaked")
}
if os.Getenv("DOWNLOAD_NGINX_E2E") == "1" {
server := &http.Server{Addr: "0.0.0.0:18082", Handler: r}
go server.ListenAndServe()
defer server.Close()
conf, _ := filepath.Abs("../../../deploy/nginx/download-local.conf")
cmd := osexec.Command("docker", "run", "-d", "--name", "license-download-e2e", "-p", "127.0.0.1:18181:18181", "--mount", "type=bind,source="+root+",target=/srv/license-packages,readonly", "--mount", "type=bind,source="+conf+",target=/etc/nginx/conf.d/default.conf,readonly", "nginx:stable-alpine")
if out, e := cmd.CombinedOutput(); e != nil {
t.Fatalf("nginx start: %v %s", e, out)
}
defer osexec.Command("docker", "stop", "license-download-e2e").Run()
defer osexec.Command("docker", "rm", "-f", "license-download-e2e").Run()
time.Sleep(2 * time.Second)
client := &http.Client{Timeout: 10 * time.Second}
body, _ := json.Marshal(map[string]string{"instance_id": instanceID, "secret": encoded})
url := fmt.Sprintf("http://127.0.0.1:18181/api/v1/customers/%d/releases/%d/download", customer, id)
for _, partial := range []bool{false, true} {
q, _ := http.NewRequest("POST", url, strings.NewReader(string(body)))
q.Header.Set("Content-Type", "application/json")
if partial {
q.Header.Set("Range", "bytes=0-6")
}
resp, e := client.Do(q)
if e != nil {
t.Fatal(e)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if partial {
if resp.StatusCode != 206 || string(b) != "package" {
t.Fatalf("range %d %q", resp.StatusCode, b)
}
} else {
sum := sha256.Sum256(b)
if resp.StatusCode != 200 || string(b) != "package bytes" || hex.EncodeToString(sum[:]) != resp.Header.Get("X-Package-SHA256") {
t.Fatalf("bytes/hash %d %q", resp.StatusCode, b)
}
}
}
direct := download(customer, id, encoded).Header().Get("X-Accel-Redirect")
resp, e := client.Get("http://127.0.0.1:18181" + direct)
if e != nil {
t.Fatal(e)
}
resp.Body.Close()
if resp.StatusCode != 404 && resp.StatusCode != 403 {
t.Fatalf("public internal path %d", resp.StatusCode)
}
resp, e = client.Post(url, "application/json", strings.NewReader("{}"))
if e != nil {
t.Fatal(e)
}
resp.Body.Close()
if resp.StatusCode < 400 {
t.Fatal("unauthenticated download succeeded")
}
t.Log("Nginx 18181: actual bytes/SHA256, Range 206, external internal-path denial and unauthenticated denial verified; temporary E2E service stopped")
}
t.Log("customer/product/state isolation, wrong secret, audit rollback, file cleanup, duplicate digest concurrency and exact 64MiB boundary verified")
}
type zeroReader struct{}
func (zeroReader) Read(p []byte) (int, error) { clear(p); return len(p), nil }

View File

@@ -0,0 +1,34 @@
package httpapi
import (
"os"
"path/filepath"
"testing"
)
func TestLocalPackageRejectsTraversalAndSymlink(t *testing.T) {
root := t.TempDir()
good := filepath.Join(root, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin")
if err := os.WriteFile(good, []byte("ok"), 0600); err != nil {
t.Fatal(err)
}
if _, err := localPackage(root, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bin"); err != nil {
t.Fatal(err)
}
for _, key := range []string{"../secret.bin", "short.bin", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.bin"} {
if _, err := localPackage(root, key); err == nil {
t.Fatalf("accepted unsafe key %q", key)
}
}
outside := filepath.Join(t.TempDir(), "outside.bin")
if err := os.WriteFile(outside, []byte("secret"), 0600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.bin")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if _, err := localPackage(root, filepath.Base(link)); err == nil {
t.Fatal("accepted symlink package")
}
}

View 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)
}

View File

@@ -0,0 +1,140 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
)
func testHeartbeatMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Cookie, instanceID, secret string, licenseID uint64, publicKey *ecdsa.PublicKey) {
request := func(path, body, key string, auth bool) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
if auth {
req.AddCookie(cookie)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
path := "/api/v1/instances/" + instanceID + "/heartbeat"
bodyFor := func(secret string, at time.Time) string {
b, _ := json.Marshal(gin.H{"secret": secret, "client_time": at.UTC().Format(time.RFC3339Nano)})
return string(b)
}
now := time.Now().UTC()
body := bodyFor(secret, now)
if w := request(path, bodyFor(base64.RawURLEncoding.EncodeToString(make([]byte, 32)), now), "wrong", false); w.Code != 403 {
t.Fatalf("wrong secret status=%d", w.Code)
}
if _, err := db.Exec("CREATE TRIGGER heartbeat_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'"); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS heartbeat_audit_failure") })
if w := request(path, body, "first", false); w.Code != 500 {
t.Fatalf("rollback status=%d", w.Code)
}
var last sql.NullTime
db.QueryRow("SELECT last_seen_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&last)
if last.Valid {
t.Fatal("audit failure committed last_seen")
}
db.Exec("DROP TRIGGER heartbeat_audit_failure")
var wg sync.WaitGroup
results := make(chan *httptest.ResponseRecorder, 2)
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); results <- request(path, body, "first", false) }()
}
wg.Wait()
close(results)
var response struct {
Data struct {
Payload leasePayload `json:"payload"`
Signature string `json:"signature"`
}
}
for w := range results {
if w.Code != 200 {
t.Fatalf("concurrent status=%d", w.Code)
}
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
}
digest := sha256.Sum256([]byte(canonicalLease(response.Data.Payload)))
sig, err := base64.RawStdEncoding.DecodeString(response.Data.Signature)
if err != nil || !ecdsa.VerifyASN1(publicKey, digest[:], sig) {
t.Fatal("lease signature invalid")
}
p := response.Data.Payload
server, _ := time.Parse(time.RFC3339Nano, p.ServerTime)
end, _ := time.Parse(time.RFC3339Nano, p.LeaseExpiresAt)
entitlement, _ := time.Parse(time.RFC3339Nano, p.EntitlementExpiresAt)
if p.State != "active" || end.After(server.Add(maxOfflineLease)) || end.After(entitlement) {
t.Fatal("lease bound invalid")
}
var count int
db.QueryRow("SELECT COUNT(*) FROM heartbeat_operations").Scan(&count)
if count != 1 {
t.Fatal("duplicate heartbeat operation")
}
if w := request(path, body, "new", false); w.Code != 429 {
t.Fatalf("limit status=%d", w.Code)
}
if w := request(path, bodyFor(secret, now.Add(time.Second)), "first", false); w.Code != 409 {
t.Fatalf("conflict=%d", w.Code)
}
if w := request(path, bodyFor(secret, now.Add(-time.Hour)), "clock", false); w.Code != 409 {
t.Fatalf("clock skew=%d", w.Code)
}
freezePath := "/api/v1/instances/" + instanceID + "/freeze"
if w := request(freezePath, `{"frozen":true}`, "freeze", false); w.Code != 401 {
t.Fatal("freeze unauthorized")
}
if w := request(freezePath, `{"frozen":true}`, "freeze", true); w.Code != 200 {
t.Fatalf("freeze=%d", w.Code)
}
if w := request(path, body, "first", false); w.Code != 409 {
t.Fatal("old allow replay masked freeze")
}
w := request(path, body, "frozen", false)
if w.Code != 200 {
t.Fatalf("frozen heartbeat=%d", w.Code)
}
json.Unmarshal(w.Body.Bytes(), &response)
if response.Data.Payload.State != "frozen" || response.Data.Payload.LeaseExpiresAt != response.Data.Payload.ServerTime {
t.Fatal("frozen lease allowed use")
}
if w = request(freezePath, `{"frozen":false}`, "unfreeze", true); w.Code != 200 {
t.Fatal("unfreeze failed")
}
w = request(path, body, "resume", false)
if w.Code != 200 {
t.Fatal("resume heartbeat failed")
}
revokePath := "/api/v1/licenses/" + strconv.FormatUint(licenseID, 10) + "/revoke"
if w = request(revokePath, `{}`, "heartbeat-revoke", true); w.Code != 200 {
t.Fatalf("revoke=%d", w.Code)
}
w = request(path, body, "revoked", false)
if w.Code != 200 {
t.Fatalf("revoked heartbeat=%d", w.Code)
}
json.Unmarshal(w.Body.Bytes(), &response)
if response.Data.Payload.State != "revoked" {
t.Fatal("revocation not propagated")
}
}

View File

@@ -0,0 +1,67 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"testing"
"time"
)
func TestLeaseBoundsAndCanonical(t *testing.T) {
now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
far := now.AddDate(10, 0, 0)
if got := boundedLease(now, far); !got.Equal(now.Add(14 * 24 * time.Hour)) {
t.Fatal("far-future entitlement gave permanent offline lease")
}
short := now.Add(time.Hour)
if !boundedLease(now, short).Equal(short) {
t.Fatal("lease exceeded entitlement")
}
p := leasePayload{"lease-v1", "00000000-0000-4000-8000-000000000001", "active", "2026-09-30T12:00:00Z", "2036-09-30T12:00:00Z", "2026-10-14T12:00:00Z"}
expected := "version=lease-v1\ninstance_id=00000000-0000-4000-8000-000000000001\nstate=active\nserver_time=2026-09-30T12:00:00Z\nentitlement_expires_at=2036-09-30T12:00:00Z\nlease_expires_at=2026-10-14T12:00:00Z"
if canonicalLease(p) != expected {
t.Fatal("canonical lease changed")
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
digest := sha256.Sum256([]byte(expected))
signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
if err != nil {
t.Fatal(err)
}
der, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatal(err)
}
if !ecdsa.VerifyASN1(&key.PublicKey, digest[:], signature) {
t.Fatal("signature failed")
}
_ = der
block, _ := pem.Decode([]byte("-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz39VZCPp0fPgbDhKOM0jUHqzJAe3\n7GSZpcSe1TO9UGqv8BO3PBI8Th3Z9Fy5EdPaVggh8V/pjW/dcsUg9QbzWA==\n-----END PUBLIC KEY-----"))
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
t.Fatal(err)
}
fixedSig, err := base64.RawStdEncoding.DecodeString("MEQCIFHuseC8F3iv6Jz9W3yywkacJ5qBOcDRJSNFLdFWS2w9AiBRZEmPGOzti3IJ0VOPccUOmmtVfWs6ZxtjcSDKJLH8BQ")
if err != nil {
t.Fatal(err)
}
if hex.EncodeToString(digest[:]) != "777150ed1107b51f17dd1ffaefac303310a32ec415e3d83a4b16cb05b9aac379" || !ecdsa.VerifyASN1(pub.(*ecdsa.PublicKey), digest[:], fixedSig) {
t.Fatal("published vector invalid")
}
changed := sha256.Sum256([]byte(expected + "\n"))
if ecdsa.VerifyASN1(pub.(*ecdsa.PublicKey), changed[:], fixedSig) {
t.Fatal("tampered vector accepted")
}
if leaseState("activated", "frozen", "revoked", "active", true, now.Add(-time.Hour), far, now) != "revoked" {
t.Fatal("revocation must dominate freeze")
}
}

View File

@@ -0,0 +1,92 @@
package httpapi
import (
"crypto/sha256"
"database/sql"
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
)
func (a *BusinessAPI) freezeInstance(c *gin.Context) {
key, ok := parseOperationKey(c)
if !ok {
return
}
var in struct {
Frozen *bool `json:"frozen"`
}
if c.ShouldBindJSON(&in) != nil || in.Frozen == nil {
apiError(c, 400, "invalid_request", "必须指定 frozen")
return
}
state := "none"
if *in.Frozen {
state = "frozen"
}
fingerprint := sha256.Sum256([]byte(c.Param("instance_id") + "\x00" + state))
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", "冻结操作失败,请使用相同幂等键重试") }
actor := c.MustGet("admin_id")
var adminID uint64
if err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? FOR UPDATE", actor).Scan(&adminID); err != nil {
fail()
return
}
var id uint64
var previous string
err = tx.QueryRowContext(c, "SELECT id,freeze_state FROM license_instances WHERE instance_id=? FOR UPDATE", c.Param("instance_id")).Scan(&id, &previous)
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "实例不存在")
return
}
if err != nil {
fail()
return
}
var oldFingerprint, oldResponse []byte
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM instance_state_operations WHERE actor_admin_id=? AND idempotency_key=?", actor, key).Scan(&oldFingerprint, &oldResponse)
if err == nil {
if !bytesEqual(oldFingerprint, fingerprint[:]) {
apiError(c, 409, "idempotency_conflict", "幂等键请求不同")
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 _, err = tx.ExecContext(c, "UPDATE license_instances SET freeze_state=? WHERE id=?", state, id); err != nil {
fail()
return
}
response := gin.H{"data": gin.H{"instance_id": c.Param("instance_id"), "freeze_state": state}}
encoded, _ := json.Marshal(response)
if _, err = tx.ExecContext(c, "INSERT INTO instance_state_operations(instance_id,actor_admin_id,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?)", id, actor, key, fingerprint[:], encoded); err != nil {
fail()
return
}
details, _ := json.Marshal(gin.H{"previous_state": previous, "freeze_state": state})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.freeze_changed','license_instance',?,?)", actor, id, details); err != nil {
fail()
return
}
if err = tx.Commit(); err != nil {
fail()
return
}
c.JSON(200, response)
}

View File

@@ -0,0 +1,106 @@
package httpapi
import (
"archive/zip"
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/gin-gonic/gin"
)
func languageRequirements(language string) string {
return map[string]string{
"python": "Python:使用 cryptography 的 ECDSA(SHA256) 和 httpx;base64 补齐填充后解码 DER;pytest 覆盖验签与状态机。密钥库通过可注入接口实现,禁止以硬编码加密密钥充当保护。",
"go": "Go:使用 crypto/ecdsa.VerifyASN1、crypto/x509、sha256 和 base64.RawStdEncoding;所有网络调用支持 context、超时及取消;sync.Mutex 与跨进程文件锁保护状态;go test 覆盖行为。",
"java": "Java:使用 JCA SHA256withECDSA、KeyFactory EC、X509EncodedKeySpec 与 HttpClient;Base64 解码 DER;受控调度器与原子文件替换;JUnit 覆盖行为。",
"dotnet": ".NET:使用 ECDsa.VerifyData 并显式选择 DSASignatureFormat.Rfc3279DerSequence,不使用默认 P1363;HttpClient、CancellationToken、受控 IHostedService 与可注入受保护存储;xUnit 覆盖行为。",
"nodejs": "Node.js:使用 node:crypto 的 verify('sha256', canonicalBytes, publicKey, DER),参照 client/verify.mjs;使用安全整数解析 ID;node:test 覆盖行为;不得将服务端 SDK 打包进浏览器。",
}[language]
}
func signedKitVectors() ([]byte, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
publicDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return nil, err
}
sign := func(payload map[string]any, canonical string) (map[string]any, error) {
digest := sha256.Sum256([]byte(canonical))
signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
if err != nil {
return nil, err
}
return map[string]any{"payload": payload, "signature": base64.RawStdEncoding.EncodeToString(signature), "canonical_sha256": hex.EncodeToString(digest[:]), "canonical": canonical}, nil
}
instance := "11111111-2222-3333-4444-555555555555"
licensePayload := map[string]any{"version": "license-v2", "instance_id": instance, "license_id": 1, "customer_id": 2, "product_id": 3, "starts_at": "2026-10-09T03:00:00Z", "expires_at": "2027-10-09T03:00:00Z", "key_id": "integration-test-only"}
licenseCanonical := "version=license-v2\ninstance_id=" + instance + "\nlicense_id=1\ncustomer_id=2\nproduct_id=3\nstarts_at=2026-10-09T03:00:00Z\nexpires_at=2027-10-09T03:00:00Z\nkey_id=integration-test-only"
leasePayload := map[string]any{"version": "lease-v2", "instance_id": instance, "state": "active", "server_time": "2026-10-09T03:00:00Z", "entitlement_expires_at": "2027-10-09T03:00:00Z", "lease_expires_at": "2026-10-23T03:00:00Z", "key_id": "integration-test-only"}
leaseCanonical := "version=lease-v2\ninstance_id=" + instance + "\nstate=active\nserver_time=2026-10-09T03:00:00Z\nentitlement_expires_at=2027-10-09T03:00:00Z\nlease_expires_at=2026-10-23T03:00:00Z\nkey_id=integration-test-only"
license, err := sign(licensePayload, licenseCanonical)
if err != nil {
return nil, err
}
lease, err := sign(leasePayload, leaseCanonical)
if err != nil {
return nil, err
}
return json.MarshalIndent(map[string]any{"warning": "TEST ONLY: never trust this key in production; use frozen now=2026-10-09T03:00:00Z for state tests", "pinned_keys": []map[string]any{{"key_id": "integration-test-only", "public_key_pem": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER})), "revoked": false}}, "license": license, "lease": lease}, "", " ")
}
func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
language, mode, ok := integrationKitInput(c)
if !ok {
return
}
vectors, err := signedKitVectors()
if err != nil {
apiError(c, 500, "internal_error", "测试资料生成失败")
return
}
kit := buildIntegrationKit(language, mode)
files := map[string][]byte{
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md 与 openapi.json,将 prompt.md 提供给实现工程师。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"),
"prompt.md": []byte(kit.Prompt),
"test-vectors.json": vectors,
}
for _, name := range []string{"protocol.md", "openapi.json"} {
content, err := integrationAsset(name)
if err != nil {
apiError(c, 500, "internal_error", "接入资料不可用")
return
}
files[name] = content
}
var buffer bytes.Buffer
archive := zip.NewWriter(&buffer)
for _, name := range []string{"README.md", "protocol.md", "openapi.json", "prompt.md", "test-vectors.json"} {
file, err := archive.Create(name)
if err == nil {
_, err = file.Write(files[name])
}
if err != nil {
apiError(c, 500, "internal_error", "接入包生成失败")
return
}
}
if err := archive.Close(); err != nil {
apiError(c, 500, "internal_error", "接入包生成失败")
return
}
c.Header("Cache-Control", "no-store")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s.zip", language, mode))
c.Data(200, "application/zip", buffer.Bytes())
}

View File

@@ -0,0 +1,43 @@
{
"openapi": "3.0.3",
"info": {"title": "License Platform Client API", "version": "1.0.0", "description": "Client-facing endpoints. Admin session is not a client credential. See protocol.md for canonical signature and trust-root rules."},
"servers": [{"url": "https://license.example.com", "description": "Replace with deployed HTTPS origin"}],
"paths": {
"/api/v1/activation/instances/{instance_id}": {"post": {
"operationId": "activateInstance", "summary": "Activate pre-provisioned instance",
"parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}],
"requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["license_key", "secret"], "properties": {"license_key": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}},
"responses": {"200": {"description": "Activation certificate; verify data.certificate before accepting", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"instance_id": {"type": "string"}, "status": {"type": "string", "enum": ["activated"]}, "certificate": {"$ref": "#/components/schemas/Certificate"}}}, "idempotent_replay": {"type": "boolean"}}}}}}, "default": {"$ref": "#/components/responses/Error"}}
}},
"/api/v1/instances/{instance_id}/heartbeat": {"post": {
"operationId": "heartbeat", "summary": "Refresh signed runtime lease",
"parameters": [{"$ref": "#/components/parameters/InstanceID"}, {"$ref": "#/components/parameters/IdempotencyKey"}],
"requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["secret", "client_time"], "properties": {"secret": {"type": "string", "format": "password"}, "client_time": {"type": "string", "format": "date-time"}}}}}},
"responses": {"200": {"description": "Signed lease; HTTP 200 does not imply active state", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Lease"}}}}}}, "429": {"description": "Rate limited; respect Retry-After", "headers": {"Retry-After": {"schema": {"type": "string"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "default": {"$ref": "#/components/responses/Error"}}
}},
"/api/v1/customers/{customer_id}/releases/{id}/download": {"post": {
"operationId": "downloadRelease", "summary": "Download entitled release; repeat credentials for Range retries",
"parameters": [{"name": "customer_id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "id", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}, {"name": "Range", "in": "header", "schema": {"type": "string"}}],
"requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["instance_id", "secret"], "properties": {"instance_id": {"type": "string"}, "secret": {"type": "string", "format": "password"}}}}}},
"responses": {"200": {"description": "Full file (through configured download gateway)", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "206": {"description": "Partial file", "headers": {"Content-Range": {"schema": {"type": "string"}}}, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "416": {"description": "Unsatisfiable Range"}, "default": {"$ref": "#/components/responses/Error"}}
}},
"/api/v1/activation/keyring": {"get": {
"operationId": "discoverKeyring", "summary": "Discovery only, NOT a trust-root bootstrap",
"responses": {"200": {"description": "Configured verification keys", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"current_key_id": {"type": "string"}, "keys": {"type": "array", "items": {"type": "object", "properties": {"key_id": {"type": "string"}, "public_key_pem": {"type": "string"}, "revoked": {"type": "boolean"}}}}}}}}}}}, "default": {"$ref": "#/components/responses/Error"}}
}}
},
"components": {
"parameters": {
"InstanceID": {"name": "instance_id", "in": "path", "required": true, "schema": {"type": "string"}},
"IdempotencyKey": {"name": "Idempotency-Key", "in": "header", "required": true, "schema": {"type": "string"}, "description": "Same key and unchanged body for retries of one operation; new key for a new operation"}
},
"responses": {"Error": {"description": "See error.code and HTTP status; never blindly retry conflicts", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}},
"schemas": {
"Error": {"type": "object", "properties": {"error": {"type": "object", "properties": {"code": {"type": "string"}, "message": {"type": "string"}}}}},
"Certificate": {"type": "object", "required": ["version", "payload", "signature", "canonical_sha256"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "payload": {"$ref": "#/components/schemas/CertificatePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}}},
"CertificatePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "license_id", "customer_id", "product_id", "starts_at", "expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["license-v2"]}, "instance_id": {"type": "string"}, "license_id": {"type": "integer", "minimum": 1}, "customer_id": {"type": "integer", "minimum": 1}, "product_id": {"type": "integer", "minimum": 1}, "starts_at": {"type": "string", "format": "date-time"}, "expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}},
"Lease": {"type": "object", "required": ["payload", "signature", "canonical_sha256", "algorithm", "next_heartbeat_seconds"], "properties": {"payload": {"$ref": "#/components/schemas/LeasePayload"}, "signature": {"type": "string", "description": "ASN.1 DER ECDSA, unpadded standard Base64"}, "canonical_sha256": {"type": "string"}, "algorithm": {"type": "string", "enum": ["ECDSA-P256-SHA256"]}, "next_heartbeat_seconds": {"type": "integer", "minimum": 60}}},
"LeasePayload": {"type": "object", "additionalProperties": false, "required": ["version", "instance_id", "state", "server_time", "entitlement_expires_at", "lease_expires_at", "key_id"], "properties": {"version": {"type": "string", "enum": ["lease-v2"]}, "instance_id": {"type": "string"}, "state": {"type": "string", "enum": ["active", "frozen", "revoked", "expired", "not_started", "not_activated"]}, "server_time": {"type": "string", "format": "date-time"}, "entitlement_expires_at": {"type": "string", "format": "date-time"}, "lease_expires_at": {"type": "string", "format": "date-time"}, "key_id": {"type": "string"}}}
}
}
}

View File

@@ -0,0 +1,75 @@
# 客户端接入协议 1.0
本资料对应当前平台实现,不是独立完成生产验收的 SDK。运行 API 基地址由部署方提供,例如 https://license.example.com。必须使用 HTTPS,并验证服务端证书。管理员接口仅用于交付实例凭据,不应封装到客户端中。
## 交付与激活
管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和一次性 secret。secret 无法从后台恢复;不得跨安装复制共享凭据。
POST /api/v1/activation/instances/{instance_id}
头部:Content-Type: application/json,Idempotency-Key: 唯一业务操作标识。
请求:{"license_key":"部署方交付值","secret":"部署方交付值"}
成功 200:{"data":{"instance_id":"...","status":"activated","certificate":{"version":"license-v2","payload":{},"signature":"...","canonical_sha256":"..."}},"idempotent_replay":false}
同一次激活的网络重试复用请求内容和 Idempotency-Key。只持久化验签且绑定预期实例、产品、客户及有效期的证书。激活证书不等于运行租约,激活后仍需心跳。
## 心跳与运行租约
POST /api/v1/instances/{instance_id}/heartbeat
请求:{"secret":"部署方交付值","client_time":"2026-10-09T03:00:00Z"},要求 Idempotency-Key。
成功 200:{"data":{"payload":{"version":"lease-v2","instance_id":"...","state":"active","server_time":"...","entitlement_expires_at":"...","lease_expires_at":"...","key_id":"..."},"signature":"...","canonical_sha256":"...","algorithm":"ECDSA-P256-SHA256","next_heartbeat_seconds":60}}
服务端允许的租约状态:active、frozen、revoked、expired、not_started、not_activated。非 active 的已签名租约必须关闭业务运行;HTTP 200 本身不代表授权有效。
新心跳操作生成新键。网络重试复用原键及原 client_time,不得修改请求时间后继续使用原键。成功 active 心跳最短间隔 60 秒;根据 next_heartbeat_seconds 调度并加少量正向抖动。
## 验签规范
算法 ECDSA P-256 + SHA-256。公钥为 PEM SubjectPublicKeyInfo。signature 是 ASN.1 DER 的 ECDSA 签名,再进行标准 Base64 编码,不带 = 填充,不是 Base64URL,也不是固定 64 字节 r||s。
拒绝未知版本、缺少或额外字段、非法类型、包含 CR/LF/NUL 的字段、未知或撤销的 key_id、公钥不是 P-256,以及绑定到其他实例的信封。
按以下固定顺序输出 key=value,用单个 LF 连接,无末尾 LF,以 UTF-8 编码。时间使用收到的原始签名字符串,不能在验签前格式化或重新序列化。
license-v2:version、instance_id、license_id、customer_id、product_id、starts_at、expires_at、key_id。
lease-v2:version、instance_id、state、server_time、entitlement_expires_at、lease_expires_at、key_id。
ID 使用正十进制整数。Node.js 实现限制为安全整数。若部署数据超出安全整数范围,必须先约定解析方案。
canonical_sha256 是规范化字节的 SHA-256 十六进制;它仅是辅助校验,不能代替公钥验签。激活应验证 data.certificate,心跳应验证 data。
服务端未配置 keyring 时会生成 legacy v1;本接入方案拒绝 v1。部署前由运维确认 keyring 已配置并交付可信公钥与 key_id。GET /api/v1/activation/keyring、/activation/public-key 只是发现接口,不能自建信任根。
## 时间与状态存储
参照 client/verify.mjs:now 不得低于上次 local_high_water,server_time 不得低于 server_high_water;当前本地时间与服务端时间差不得超过 5 分钟。租约结束必须不晚于授权结束,且不超过服务端签发时间 + 14 天。两个到期时间都必须严格晚于 now 才能运行。
验签、范围检查后,先在受保护存储中原子保存实例 ID、租约、enabled、服务端与本地时间高水位,再启用业务。离线每次授权检查都应检查本地时间回拨,并持久化更新本地高水位。应用重新启动不得清除高水位绕过限制。
离线冻结和撤销不能立即让旧租约失效,最长残留授权可达 14 天。网络失败不得延长已接受的租约;有有效租约可在策略允许范围内继续,无有效租约必须 fail closed。一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,不能宣称硬件绑定或防克隆。
## 重试与错误
错误结构为 {"error":{"code":"...","message":"..."}}。根据状态、code 和操作区分错误,不记录 secret 或原始请求正文。
400 修复参数;401/403 需要重新交付凭据或人工检查,不做无限重试;409 是冲突,需要检查 code 和实例状态,不自动重激活。429 在至少等待 Retry-After 后有界重试;无该头时指数退避。超时、连接错误和 5xx 有界退避,同一操作维持相同请求与键。心跳拒绝不能替代已签名撤销事件;在未收到可验证的非 active 租约时,已有租约的处理由离线策略决定,不得延长。
## 发布包下载
POST /api/v1/customers/{customer_id}/releases/{id}/download,正文 {"instance_id":"...","secret":"..."}。每个请求都提交凭据。支持 Range 续传,处理 200/206/416 和 Content-Range。使用受控的发布元数据校验完整包 size_bytes 和 SHA-256 后才安装。未经校验的部分文件不得覆盖运行版本。Nginx 内部文件路径不可作为客户端公共下载 URL。
## 模式约束
桌面:系统密钥库与单实例状态锁。服务:受限服务账户、超时、取消和受控后台任务。容器:稳定持久卷及 Secret 注入;重建不能生成新身份,多个副本不得共享同一实例凭据冒充独立席位。Kubernetes 集群授权需要额外的 License Agent 和席位策略,不在当前 SDK 范围内。
SPA 应通过同源 BFF 调用,不得在浏览器长期保存实例 secret。移动端、CI 短命实例和完全离线设备需要专门身份与交付策略,不能直接承诺当前协议覆盖。
## 交付验收
覆盖正常验签、篡改字段/签名、未知/撤销密钥、v1/额外字段、实例不匹配、过期和超过 14 天、时钟回拨、非 active、幂等重试、429、掉线与原子存储失败。测试向量只使用随机测试密钥,绝不能导入生产信任配置。

View File

@@ -0,0 +1,154 @@
package httpapi
import (
"embed"
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
//go:embed integration_assets/*
var integrationAssets embed.FS
const defaultIntegrationBaseURL = "https://license.yihuiyong.cn"
var integrationLanguages = map[string]string{
"python": "Python 3.11+",
"go": "Go 1.22+",
"java": "Java 17+",
"dotnet": ".NET 8+",
"nodejs": "Node.js 20+",
}
var integrationModes = map[string]string{
"desktop": "桌面客户端",
"service": "常驻服务",
"container": "容器部署",
}
type integrationKitResponse struct {
ProtocolVersion string `json:"protocol_version"`
PlatformBaseURL string `json:"platform_base_url"`
Language string `json:"language"`
LanguageLabel string `json:"language_label"`
Mode string `json:"mode"`
ModeLabel string `json:"mode_label"`
Endpoints []kitAPI `json:"endpoints"`
SecurityRules []string `json:"security_rules"`
Prompt string `json:"prompt"`
TestVector kitVector `json:"payload_example"`
Protocol string `json:"protocol"`
}
type kitAPI struct {
Method string `json:"method"`
Path string `json:"path"`
Purpose string `json:"purpose"`
}
type kitVector 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 integrationKitInput(c *gin.Context) (string, string, bool) {
language, mode := c.DefaultQuery("language", "python"), c.DefaultQuery("mode", "service")
if _, ok := integrationLanguages[language]; !ok {
apiError(c, http.StatusBadRequest, "invalid_request", "不支持的客户端语言")
return "", "", false
}
if _, ok := integrationModes[mode]; !ok {
apiError(c, http.StatusBadRequest, "invalid_request", "不支持的接入模式")
return "", "", false
}
return language, mode, true
}
func buildIntegrationKit(language, mode string) integrationKitResponse {
label, modeLabel := integrationLanguages[language], integrationModes[mode]
protocol, _ := integrationAsset("protocol.md")
return integrationKitResponse{
ProtocolVersion: "license-v2 / lease-v2",
PlatformBaseURL: defaultIntegrationBaseURL,
Language: language,
LanguageLabel: label,
Mode: mode,
ModeLabel: modeLabel,
Endpoints: []kitAPI{
{Method: "POST", Path: "/api/v1/activation/instances/{instance_id}", Purpose: "首次激活,提交 license_key、secret 和 Idempotency-Key"},
{Method: "POST", Path: "/api/v1/instances/{instance_id}/heartbeat", Purpose: "刷新已签名运行租约,提交 secret、client_time 和 Idempotency-Key"},
{Method: "POST", Path: "/api/v1/customers/{customer_id}/releases/{release_id}/download", Purpose: "以实例凭据下载当前有权访问的发布包"},
},
SecurityRules: []string{
"仅信任随软件或受控部署渠道固定分发的 P-256 公钥;不得将 keyring 发现接口作为信任根。",
"secret 只可放在系统密钥库、Vault、Docker/Kubernetes Secret 或受限加密文件中;不得进入 URL、日志、镜像、源码或浏览器 LocalStorage。",
"每次网络重试复用同一 Idempotency-Key;新的业务操作必须生成新的键。",
"验签后核对 version、key_id、instance_id、state、授权到期和租约到期;仅 active 且未到期时可执行业务。",
"保存服务端时间与本地时间高水位,拒绝显著回拨;正常心跳最短 60 秒,租约最长 14 天。",
"403/409 进入不可用或人工处理状态;429 遵循 Retry-After;不得无限自动重试。",
},
Protocol: string(protocol),
Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md 与 openapi.json。签名规范化不是 JSON:固定顺序 key=value、LF 连接、UTF-8、无末尾换行;签名是 DER ECDSA 的无填充标准 Base64。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。",
TestVector: kitVector{
Version: "lease-v2", InstanceID: "11111111-2222-3333-4444-555555555555", State: "active",
ServerTime: "2026-10-09T03:00:00Z", EntitlementExpiresAt: "2027-10-09T03:00:00Z", LeaseExpiresAt: "2026-10-23T03:00:00Z",
},
}
}
func integrationAsset(name string) ([]byte, error) {
content, err := integrationAssets.ReadFile("integration_assets/" + name)
if err != nil {
return nil, err
}
return []byte(strings.ReplaceAll(string(content), "https://license.example.com", defaultIntegrationBaseURL)), nil
}
func integrationPrompt(language, mode string) string {
return fmt.Sprintf(`你正在为 %s %s 接入授权平台。实现可复用的 LicenseClient,不要调用管理员接口,也不要把实例 secret 暴露给浏览器。
默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。
实现激活 POST /api/v1/activation/instances/{instance_id},提交 license_key、secret 和 Idempotency-Key;实现心跳 POST /api/v1/instances/{instance_id}/heartbeat,提交 secret、RFC3339 UTC client_time 和 Idempotency-Key。
必须使用受控渠道预置的 ECDSA P-256 公钥验证 license-v2 / lease-v2 信封,验证 key_id、version、instance_id、state、entitlement_expires_at、lease_expires_at。仅 active 且授权/租约均未过期时允许业务运行。持久化并原子更新已接受租约及本地、服务端时间高水位。secret 不得写入 URL、日志、异常、镜像或源码;403/409 停止自动重试,429 遵循 Retry-After。
请交付:LicenseClient、受保护状态存储接口、激活与刷新租约实现、验签单元测试、网络/时钟回拨/过期租约负向测试,以及业务侧 canRun 调用示例。`, language, mode, defaultIntegrationBaseURL)
}
func (a *BusinessAPI) integrationKit(c *gin.Context) {
language, mode, ok := integrationKitInput(c)
if !ok {
return
}
c.JSON(http.StatusOK, gin.H{"data": buildIntegrationKit(language, mode)})
}
func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) {
language, mode, ok := integrationKitInput(c)
if !ok {
return
}
kit := buildIntegrationKit(language, mode)
var b strings.Builder
fmt.Fprintf(&b, "# 授权平台客户端接入包\n\n协议版本:%s\n\n默认授权平台根地址:%s\n\n", kit.ProtocolVersion, kit.PlatformBaseURL)
fmt.Fprintf(&b, "目标:%s,%s\n\n## 工程提示词\n\n%s\n\n## 接口\n\n", kit.LanguageLabel, kit.ModeLabel, kit.Prompt)
for _, endpoint := range kit.Endpoints {
fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose)
}
b.WriteString("\n## 安全检查\n\n")
for _, rule := range kit.SecurityRules {
fmt.Fprintf(&b, "- %s\n", rule)
}
fmt.Fprintf(&b, "\n## 租约字段示例(不是签名测试向量)\n\n```json\n{\n \"version\": \"%s\",\n \"instance_id\": \"%s\",\n \"state\": \"%s\",\n \"server_time\": \"%s\",\n \"entitlement_expires_at\": \"%s\",\n \"lease_expires_at\": \"%s\"\n}\n```\n", kit.TestVector.Version, kit.TestVector.InstanceID, kit.TestVector.State, kit.TestVector.ServerTime, kit.TestVector.EntitlementExpiresAt, kit.TestVector.LeaseExpiresAt)
fmt.Fprintf(&b, "\n\n%s\n", kit.Protocol)
c.Header("Cache-Control", "no-store")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s-integration.md", language, mode))
c.Data(http.StatusOK, "text/markdown; charset=utf-8", []byte(b.String()))
}

View File

@@ -0,0 +1,119 @@
package httpapi
import (
"archive/zip"
"bytes"
"crypto/ecdsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"io"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestIntegrationAuthentication(t *testing.T) {
r := gin.New()
registerBusinessRoutes(r, &BusinessAPI{})
for _, path := range []string{"/api/v1/integration-kit", "/api/v1/integration-kit/download", "/api/v1/integration-kit/archive"} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code != 401 {
t.Fatalf("%s: %d", path, w.Code)
}
}
}
func TestIntegrationInputs(t *testing.T) {
for _, query := range []string{"?language=rust", "?mode=browser", "?language=../../secret"} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/"+query, nil)
(&BusinessAPI{}).integrationKit(c)
if w.Code != 400 {
t.Fatalf("%s: %d", query, w.Code)
}
}
for language := range integrationLanguages {
kit := buildIntegrationKit(language, "service")
if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") {
t.Fatal("incomplete kit")
}
}
content, err := integrationAssets.ReadFile("integration_assets/openapi.json")
if err != nil {
t.Fatal(err)
}
var spec map[string]any
if err = json.Unmarshal(content, &spec); err != nil {
t.Fatal(err)
}
if spec["openapi"] != "3.0.3" {
t.Fatal("invalid OpenAPI")
}
}
func TestIntegrationArchiveAndSignatures(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil)
(&BusinessAPI{}).downloadIntegrationArchive(c)
if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" {
t.Fatalf("%d %s", w.Code, w.Body)
}
archive, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
if err != nil {
t.Fatal(err)
}
if len(archive.File) != 5 {
t.Fatal("missing files")
}
for _, file := range archive.File {
reader, err := file.Open()
if err != nil {
t.Fatal(err)
}
content, err := io.ReadAll(reader)
reader.Close()
if err != nil {
t.Fatal(err)
}
if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) {
t.Fatal("OpenAPI does not use the default platform address")
}
if file.Name != "test-vectors.json" {
continue
}
var vectors struct {
PinnedKeys []struct {
PublicKey string `json:"public_key_pem"`
} `json:"pinned_keys"`
License, Lease struct{ Signature, Canonical string }
}
if err := json.Unmarshal(content, &vectors); err != nil {
t.Fatal(err)
}
block, _ := pem.Decode([]byte(vectors.PinnedKeys[0].PublicKey))
key, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
t.Fatal(err)
}
for _, vector := range []struct{ Signature, Canonical string }{vectors.License, vectors.Lease} {
sig, err := base64.RawStdEncoding.DecodeString(vector.Signature)
if err != nil {
t.Fatal(err)
}
digest := sha256.Sum256([]byte(vector.Canonical))
if !ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), digest[:], sig) {
t.Fatal("bad signature")
}
digest = sha256.Sum256([]byte(vector.Canonical + "tampered"))
if ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), digest[:], sig) {
t.Fatal("accepted tampering")
}
}
}
}

View File

@@ -0,0 +1,91 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"os"
"path/filepath"
"regexp"
"sort"
)
type VerificationKey struct {
KeyID string `json:"key_id"`
PublicKeyPEM string `json:"public_key_pem"`
Revoked bool `json:"revoked"`
}
type Keyring struct {
Current string `json:"current_key_id"`
Keys []VerificationKey `json:"keys"`
}
var keyIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
func LoadKeyring(path, privatePEM string) (*Keyring, error) {
if path == "" {
return nil, nil
}
if !filepath.IsAbs(path) {
return nil, errors.New("keyring file must be absolute")
}
info, err := os.Stat(path)
if err != nil || !info.Mode().IsRegular() || info.Size() > 65536 {
return nil, errors.New("invalid keyring file")
}
data, err := os.ReadFile(path)
if err != nil {
return nil, errors.New("keyring unavailable")
}
var ring Keyring
if json.Unmarshal(data, &ring) != nil {
return nil, errors.New("invalid keyring JSON")
}
if err := ring.Validate(privatePEM); err != nil {
return nil, err
}
return &ring, nil
}
func (r *Keyring) Validate(privatePEM string) error {
if !keyIDPattern.MatchString(r.Current) || len(r.Keys) == 0 || len(r.Keys) > 32 {
return errors.New("invalid keyring")
}
private, err := readSigningKey(privatePEM)
if err != nil {
return errors.New("invalid current private key")
}
seen := map[string]bool{}
current := false
for _, k := range r.Keys {
if !keyIDPattern.MatchString(k.KeyID) || seen[k.KeyID] {
return errors.New("duplicate or invalid key ID")
}
seen[k.KeyID] = true
block, rest := pem.Decode([]byte(k.PublicKeyPEM))
if block == nil || len(rest) != 0 {
return errors.New("invalid public key")
}
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return errors.New("invalid public key")
}
pub, ok := parsed.(*ecdsa.PublicKey)
if !ok || pub.Curve != elliptic.P256() {
return errors.New("public key must be P256")
}
if k.KeyID == r.Current {
if k.Revoked || !pub.Equal(&private.PublicKey) {
return errors.New("current key revoked or mismatched")
}
current = true
}
}
if !current {
return errors.New("current key missing")
}
sort.Slice(r.Keys, func(i, j int) bool { return r.Keys[i].KeyID < r.Keys[j].KeyID })
return nil
}

View File

@@ -0,0 +1,36 @@
package httpapi
import (
"database/sql"
"io"
"log/slog"
"net/http/httptest"
"strings"
"testing"
)
func TestKeyringHTTPAndFileBoundary(t *testing.T) {
if _, err := LoadKeyring("relative.json", ""); err == nil {
t.Fatal("relative ring accepted")
}
for _, enabled := range []bool{false, true} {
router := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil))))
var ring *Keyring
if enabled {
ring = &Keyring{Current: "test", Keys: []VerificationKey{{KeyID: "test", PublicKeyPEM: "public-only", Revoked: false}}}
}
RegisterBusinessWithKeyring(router, &sql.DB{}, "", ring)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest("GET", "/api/v1/activation/keyring", nil))
expected := 404
if enabled {
expected = 200
}
if response.Code != expected {
t.Fatal(response.Code)
}
if strings.Contains(response.Body.String(), "PRIVATE KEY") {
t.Fatal("private key disclosure")
}
}
}

View File

@@ -0,0 +1,87 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
func TestKeyringCrossLanguageRotation(t *testing.T) {
old, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
current, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
public := func(k *ecdsa.PrivateKey) string {
der, _ := x509.MarshalPKIXPublicKey(&k.PublicKey)
return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))
}
der, _ := x509.MarshalECPrivateKey(current)
private := string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}))
ring := Keyring{Current: "new", Keys: []VerificationKey{{KeyID: "old", PublicKeyPEM: public(old)}, {KeyID: "new", PublicKeyPEM: public(current)}}}
if err := ring.Validate(private); err != nil {
t.Fatal(err)
}
bad := ring
bad.Keys = append([]VerificationKey(nil), ring.Keys...)
for i := range bad.Keys {
if bad.Keys[i].KeyID == "new" {
bad.Keys[i].Revoked = true
}
}
if bad.Validate(private) == nil {
t.Fatal("revoked current accepted")
}
if ring.Validate(string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: func() []byte { d, _ := x509.MarshalECPrivateKey(old); return d }()}))) == nil {
t.Fatal("mismatch accepted")
}
now := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
id := "00000000-0000-4000-8000-000000000001"
sign := func(k *ecdsa.PrivateKey, keyID, kind string) map[string]any {
var p map[string]any
var text string
if kind == "license" {
p = map[string]any{"version": "license-v2", "instance_id": id, "license_id": 1, "customer_id": 2, "product_id": 3, "starts_at": now.Format(time.RFC3339), "expires_at": now.Add(time.Hour).Format(time.RFC3339), "key_id": keyID}
text = canonicalCertificatePayload("license-v2", id, 1, 2, 3, now, now.Add(time.Hour)) + "\nkey_id=" + keyID
} else {
lease := leasePayload{"lease-v2", id, "active", now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)}
p = map[string]any{"version": lease.Version, "instance_id": lease.InstanceID, "state": lease.State, "server_time": lease.ServerTime, "entitlement_expires_at": lease.EntitlementExpiresAt, "lease_expires_at": lease.LeaseExpiresAt, "key_id": keyID}
text = canonicalLease(lease) + "\nkey_id=" + keyID
}
hash := sha256.Sum256([]byte(text))
sig, _ := ecdsa.SignASN1(rand.Reader, k, hash[:])
return map[string]any{"payload": p, "signature": base64.RawStdEncoding.EncodeToString(sig)}
}
vectors := map[string]any{"keys": ring.Keys, "old": sign(old, "old", "license"), "current": sign(current, "new", "license"), "lease": sign(current, "new", "lease"), "now": now.UnixMilli(), "instance": id}
data, _ := json.Marshal(vectors)
path := filepath.Join(t.TempDir(), "vectors.json")
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
// Only public keys/signatures leave Go; private keys stay in test process memory.
script := `import fs from 'node:fs'; import assert from 'node:assert/strict'; import {verifyEnvelope,acceptLease,canRunOffline} from '../../../client/verify.mjs';
const v=JSON.parse(fs.readFileSync(process.argv[1]));
assert.equal(verifyEnvelope(v.old,v.keys).key_id,'old');assert.equal(verifyEnvelope(v.current,v.keys).key_id,'new');
assert.throws(()=>verifyEnvelope(v.old,v.keys.map(k=>({...k,revoked:k.key_id==='old'}))),/revoked/);
assert.throws(()=>verifyEnvelope(v.current,[]),/unknown/);
assert.throws(()=>verifyEnvelope({...v.current,payload:{...v.current.payload,key_id:'old'}},v.keys),/signature/);
assert.throws(()=>verifyEnvelope({...v.current,payload:{...v.current.payload,product_id:99}},v.keys),/signature/);
const state=acceptLease(v.lease,v.keys,v.instance,null,v.now);assert.ok(state.enabled);assert.ok(canRunOffline(state,v.instance,v.now+1));assert.ok(!canRunOffline(state,v.instance,v.now-1));assert.ok(!canRunOffline(state,v.instance,state.lease_expires));
assert.throws(()=>acceptLease(v.lease,v.keys,'other',null,v.now),/instance/);
assert.throws(()=>acceptLease(v.lease,v.keys,v.instance,{...state,server_high_water:v.now+1},v.now),/rollback/);
assert.throws(()=>acceptLease(v.lease,v.keys,v.instance,state,v.now-1),/rollback/);
console.log('Go -> Node: old/current signatures, revoked/unknown/tampered rejection, lease high-water passed');`
cmd := exec.Command("node", "--input-type=module", "-e", script, path)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Node vectors failed: %s", out)
}
t.Log(string(out))
}

View File

@@ -0,0 +1,384 @@
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}})
}

View File

@@ -0,0 +1,102 @@
package httpapi
import (
"database/sql/driver"
"encoding/json"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
)
func TestCurrentLicenseStatus(t *testing.T) {
now := time.Date(2026, 9, 30, 8, 0, 0, 0, time.UTC)
for _, tc := range []struct {
name, status string
starts, expires time.Time
want string
}{
{"scheduled", "active", now.Add(time.Hour), now.Add(2 * time.Hour), "scheduled"},
{"start boundary", "active", now, now.Add(time.Hour), "active"},
{"expiry boundary", "active", now.Add(-time.Hour), now, "expired"},
{"revoked", "revoked", now.Add(time.Hour), now.Add(2 * time.Hour), "revoked"},
} {
t.Run(tc.name, func(t *testing.T) {
if got := currentLicenseStatus(tc.status, tc.starts, tc.expires, now); got != tc.want {
t.Fatalf("got %s want %s", got, tc.want)
}
})
}
}
func TestLicenseFilterPredicates(t *testing.T) {
now := time.Date(2026, 10, 8, 10, 0, 0, 0, time.UTC)
for _, tc := range []struct {
status, predicate string
times []any
}{
{"", "", nil},
{"active", " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>?", []any{now, now}},
{"pending", " AND l.status<>'revoked' AND l.starts_at>? AND l.expires_at>?", []any{now, now}},
{"expired", " AND l.status<>'revoked' AND l.expires_at<=?", []any{now}},
{"revoked", " AND l.status='revoked'", nil},
{"expiring", " AND l.status<>'revoked' AND l.starts_at<=? AND l.expires_at>? AND l.expires_at<=?", []any{now, now, now.Add(30 * 24 * time.Hour)}},
} {
t.Run(tc.status, func(t *testing.T) {
where, args, ok := licenseFilter(tc.status, "customer' OR 1=1", now)
want := " WHERE 1=1 AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?)" + tc.predicate
if !ok || where != want {
t.Fatalf("predicate %s", where)
}
expected := []any{"%customer' OR 1=1%", "%customer' OR 1=1%", "%customer' OR 1=1%", "%customer' OR 1=1%"}
expected = append(expected, tc.times...)
if !reflect.DeepEqual(args, expected) {
t.Fatalf("args %#v", args)
}
})
}
for _, status := range []string{"scheduled", "unknown", "ACTIVE"} {
if _, _, ok := licenseFilter(status, "", now); ok {
t.Errorf("accepted %s", status)
}
}
}
func TestListLicensesFilteredPage(t *testing.T) {
// No time-dependent predicate is needed here; each status predicate is checked
// above with exact boundaries. Count and page must both join all search fields.
where := " WHERE 1=1 AND (l.license_key LIKE ? OR c.name LIKE ? OR p.name LIKE ? OR p.code LIKE ?) AND l.status='revoked'"
args := []any{"%Acme%", "%Acme%", "%Acme%", "%Acme%"}
now := time.Now().UTC()
db, _ := newDashboardTestDB(t, []dashboardQuery{
{sql: "SELECT COUNT(*)" + licenseFrom + where, args: args, rows: [][]driver.Value{{int64(31)}}},
{sql: licenseSelect + where + " ORDER BY l.id DESC LIMIT ? OFFSET ?", args: append(append([]any{}, args...), 10, 10), rows: [][]driver.Value{testLicenseRow(25, "revoked", now.Add(-time.Hour), now.Add(time.Hour), now)}},
})
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/api/v1/licenses?q=%20Acme%20&status=%20revoked%20&page=2&page_size=10", nil)
(&BusinessAPI{db: db}).listLicenses(c)
var out struct {
Data []licenseRecord `json:"data"`
Meta struct {
Total, Page int
PageSize int `json:"page_size"`
} `json:"meta"`
}
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || out.Meta.Total != 31 || out.Meta.Page != 2 || out.Meta.PageSize != 10 || len(out.Data) != 1 || out.Data[0].Status != "revoked" {
t.Fatalf("%d %s", w.Code, w.Body)
}
}
func TestListLicensesInvalidStatus(t *testing.T) {
db, _ := newDashboardTestDB(t, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/api/v1/licenses?status=invalid", nil)
(&BusinessAPI{db: db}).listLicenses(c)
if w.Code != 400 || !strings.Contains(w.Body.String(), "invalid_request") {
t.Fatalf("%d %s", w.Code, w.Body)
}
}

View File

@@ -0,0 +1,189 @@
package httpapi
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type operationSample struct {
Count uint64
Seconds float64
}
type Operations struct {
mu sync.Mutex
samples map[string]operationSample
buckets map[string]rateBucket
now func() time.Time
logger *slog.Logger
nextSweep time.Time
limiter EntryLimiter
}
type rateBucket struct {
start time.Time
count int
}
func NewOperations(logger *slog.Logger) *Operations {
return &Operations{samples: make(map[string]operationSample), buckets: make(map[string]rateBucket), now: time.Now, logger: logger}
}
func operation(path string) string {
switch path {
case "/api/v1/portal/snapshot":
return "login"
case "/api/v1/auth/login":
return "login"
case "/api/v1/activation/instances/:instance_id":
return "activation"
case "/api/v1/instances/:instance_id/heartbeat":
return "heartbeat"
case "/api/v1/customers/:customer_id/releases/:id/download":
return "download"
}
if strings.HasPrefix(path, "/api/v1/licenses") {
return "authorization"
}
return "other"
}
// Local fixed-window limits are deliberately per process, never a distributed guarantee.
func (o *Operations) allow(key string, limit int) bool {
o.mu.Lock()
defer o.mu.Unlock()
now := o.now()
if !now.Before(o.nextSweep) {
for k, b := range o.buckets {
if now.Sub(b.start) >= time.Minute {
delete(o.buckets, k)
}
}
o.nextSweep = now.Add(time.Minute)
}
b, exists := o.buckets[key]
if !exists && len(o.buckets) >= 10000 {
return false
}
if !exists || now.Sub(b.start) >= time.Minute {
b = rateBucket{start: now}
}
if b.count >= limit {
return false
}
b.count++
o.buckets[key] = b
return true
}
func (o *Operations) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
raw := make([]byte, 16)
if _, err := rand.Read(raw); err != nil {
c.AbortWithStatus(http.StatusServiceUnavailable)
return
}
id := hex.EncodeToString(raw)
c.Set("request_id", id)
c.Header("X-Request-ID", id)
started := time.Now()
path := c.FullPath()
op := operation(path)
defer func() {
elapsed := time.Since(started).Seconds()
outcome := "success"
if c.Writer.Status() >= 400 {
outcome = "failure"
}
key := op + "/" + outcome
o.mu.Lock()
sample := o.samples[key]
sample.Count++
sample.Seconds += elapsed
o.samples[key] = sample
o.mu.Unlock()
// No bodies, query strings, raw paths, IPs, cookies, headers, SQL errors or panic values.
o.logger.Info("http_request", "request_id", id, "trace_id", id, "route", path, "operation", op, "status", c.Writer.Status(), "error_code", c.GetString("error_code"), "duration_seconds", elapsed)
}()
defer func() {
if recover() != nil {
apiError(c, 500, "internal_error", "Service unavailable")
c.Abort()
}
}()
if op == "login" || op == "activation" || op == "heartbeat" || op == "download" {
limit := 60
if op == "login" {
limit = 10
}
sum := sha256.Sum256([]byte(c.ClientIP()))
key := op + hex.EncodeToString(sum[:])
allowed := false
if o.limiter != nil {
var err error
allowed, err = o.limiter.Allow(c.Request.Context(), key, limit)
if err != nil {
apiError(c, 503, "rate_limit_unavailable", "Service unavailable")
c.Abort()
return
}
} else {
allowed = o.allow(key, limit)
}
if !allowed {
c.Header("Retry-After", "60")
apiError(c, 429, "rate_limited", "Too many requests")
c.Abort()
return
}
}
if c.Request.Method != "GET" && c.Request.Method != "HEAD" && c.Request.Method != "OPTIONS" {
origin := c.GetHeader("Origin")
if origin != "" {
u, err := url.Parse(origin)
scheme := "http"
if secureSessionCookie(c) {
scheme = "https"
}
if err != nil || u.Host != c.Request.Host || u.Scheme != scheme || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
apiError(c, 403, "origin_forbidden", "Cross-origin request denied")
c.Abort()
return
}
}
if c.GetHeader("Sec-Fetch-Site") == "cross-site" {
apiError(c, 403, "origin_forbidden", "Cross-site request denied")
c.Abort()
return
}
}
// Uploads have their own 64 MiB streaming bound; other JSON routes get a 64 KiB ceiling.
if !(path == "/api/v1/products/:id/releases" && c.Request.Method == "POST") {
if c.Request.ContentLength > 64<<10 {
apiError(c, 413, "body_too_large", "Request body too large")
c.Abort()
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<10)
}
c.Next()
}
}
// Expose only on a separate loopback/private monitoring listener, never the public router.
func (o *Operations) Metrics(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
o.mu.Lock()
defer o.mu.Unlock()
fmt.Fprintln(w, "# TYPE license_requests_total counter\n# TYPE license_request_duration_seconds_sum counter")
for key, s := range o.samples {
parts := strings.Split(key, "/")
fmt.Fprintf(w, "license_requests_total{operation=%q,outcome=%q} %d\nlicense_request_duration_seconds_sum{operation=%q,outcome=%q} %g\n", parts[0], parts[1], s.Count, parts[0], parts[1], s.Seconds)
}
}

View File

@@ -0,0 +1,74 @@
package httpapi
import (
"github.com/gin-gonic/gin"
"io"
"log/slog"
"net/http/httptest"
"strings"
"testing"
)
func TestPublicEntryLimitsBeforeHandlers(t *testing.T) {
for _, path := range []string{"/api/v1/auth/login", "/api/v1/activation/instances/:instance_id", "/api/v1/instances/:instance_id/heartbeat", "/api/v1/customers/:customer_id/releases/:id/download"} {
t.Run(path, func(t *testing.T) {
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
calls := 0
r.POST(path, func(c *gin.Context) { calls++; c.Status(401) })
n := 60
if strings.Contains(path, "login") {
n = 10
}
for i := 0; i <= n; i++ {
q := httptest.NewRequest("POST", strings.ReplaceAll(strings.ReplaceAll(path, ":instance_id", "x"), ":customer_id", "1"), nil)
q.URL.Path = strings.ReplaceAll(q.URL.Path, ":id", "1")
q.RemoteAddr = "127.0.0.1:1234"
q.Header.Set("X-Forwarded-For", strings.Repeat("1", i)+".2.3.4")
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
if i == n && w.Code != 429 {
t.Fatal(w.Code)
}
}
if calls != n {
t.Fatal(calls)
}
})
}
}
func TestChunkedBodyCORSAndMalformedSession(t *testing.T) {
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
r.POST("/json", func(c *gin.Context) {
var data map[string]any
if c.ShouldBindJSON(&data) != nil {
apiError(c, 400, "invalid_request", "Invalid JSON")
return
}
c.Status(204)
})
q := httptest.NewRequest("POST", "/json", strings.NewReader(`{"secret":"`+strings.Repeat("x", 65537)+`"}`))
q.ContentLength = -1
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
if w.Code != 400 {
t.Fatal(w.Code)
}
q = httptest.NewRequest("OPTIONS", "/json", nil)
q.Header.Set("Origin", "https://evil.example")
w = httptest.NewRecorder()
r.ServeHTTP(w, q)
if w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Fatal("CORS must not allow external origin")
}
a := &BusinessAPI{}
r.GET("/session", a.authenticated, func(c *gin.Context) { t.Fatal("malformed session authenticated") })
for _, cookie := range []string{"", "lp_session=bad", "lp_session=" + strings.Repeat("z", 64)} {
q = httptest.NewRequest("GET", "/session", nil)
q.Header.Set("Cookie", cookie)
w = httptest.NewRecorder()
r.ServeHTTP(w, q)
if w.Code != 401 {
t.Fatal(w.Code)
}
}
}

View File

@@ -0,0 +1,127 @@
package httpapi
import (
"bytes"
"encoding/json"
"github.com/gin-gonic/gin"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestOperationsSecurity(t *testing.T) {
var logs bytes.Buffer
ops := NewOperations(slog.New(slog.NewJSONHandler(&logs, nil)))
r := NewOperationalRouter(ops)
r.POST("/api/v1/auth/login", func(c *gin.Context) { apiError(c, 401, "invalid_credentials", "Denied") })
r.GET("/panic/:secret", func(c *gin.Context) { panic("PRIVATE_PEM_password") })
request := func(method, path, body, origin string) *httptest.ResponseRecorder {
q := httptest.NewRequest(method, path, strings.NewReader(body))
q.RemoteAddr = "127.0.0.1:1234"
q.Header.Set("Origin", origin)
q.Header.Set("Cookie", "lp_session=PRIVATE_COOKIE")
q.Header.Set("X-Request-ID", "FORGED_ID")
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
return w
}
for i := 0; i < 10; i++ {
if w := request("POST", "/api/v1/auth/login?password=PRIVATE_QUERY", "PRIVATE_PASSWORD", ""); w.Code != 401 {
t.Fatal(w.Code)
}
}
w := request("POST", "/api/v1/auth/login", "", "")
if w.Code != 429 || w.Header().Get("Retry-After") == "" {
t.Fatal(w.Code)
}
w = request("GET", "/panic/PRIVATE_PATH", "", "")
if w.Code != 500 || strings.Contains(w.Body.String(), "PRIVATE") {
t.Fatal(w.Body.String())
}
if strings.Contains(logs.String(), "PRIVATE") || strings.Contains(logs.String(), "FORGED_ID") {
t.Fatal("secret or forged ID in logs")
}
dec := json.NewDecoder(&logs)
n := 0
for {
var row map[string]any
err := dec.Decode(&row)
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
if row["request_id"] == "" || row["trace_id"] != row["request_id"] {
t.Fatal(row)
}
n++
}
if n != 12 {
t.Fatal(n)
}
mw := httptest.NewRecorder()
ops.Metrics(mw, httptest.NewRequest("GET", "/metrics", nil))
if !strings.Contains(mw.Body.String(), "license_requests_total{operation=\"login\",outcome=\"failure\"} 11") {
t.Fatal(mw.Body.String())
}
if request("GET", "/metrics", "", "").Code != 404 {
t.Fatal("public metrics exposed")
}
}
func TestOriginAndBodyGuards(t *testing.T) {
r := NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil))))
r.POST("/write", func(c *gin.Context) { c.Status(204) })
for _, tc := range []struct {
origin, body string
status int
}{{"https://evil.example", "", 403}, {"http://example.com", "", 204}, {"", "", 204}, {"", strings.Repeat("x", 65537), 413}} {
q := httptest.NewRequest("POST", "http://example.com/write", strings.NewReader(tc.body))
q.Header.Set("Origin", tc.origin)
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
if w.Code != tc.status {
t.Fatalf("origin=%s status=%d", tc.origin, w.Code)
}
}
}
func TestLocalLimiterBoundaryAndScope(t *testing.T) {
now := time.Now()
a := NewOperations(slog.Default())
a.now = func() time.Time { return now }
if !a.allow("test", 1) || a.allow("test", 1) {
t.Fatal("limit not enforced")
}
b := NewOperations(slog.Default())
if !b.allow("test", 1) {
t.Fatal("independent process scope")
}
now = now.Add(time.Minute)
if !a.allow("test", 1) {
t.Fatal("window not reset")
}
for i := 0; i < 10000; i++ {
a.buckets[string(rune(i))] = rateBucket{start: now}
}
if a.allow("new_key", 1) {
t.Fatal("capacity must fail closed")
}
}
func TestSessionCookieAttributes(t *testing.T) {
t.Setenv("SESSION_COOKIE_SECURE", "true")
r := gin.New()
r.GET("/cookie", func(c *gin.Context) {
c.SetSameSite(http.SameSiteStrictMode)
c.SetCookie("lp_session", "test", 60, "/", "", secureSessionCookie(c), true)
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/cookie", nil))
cookies := w.Result().Cookies()
if len(cookies) != 1 || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode {
t.Fatal(cookies)
}
}

View File

@@ -0,0 +1,346 @@
package httpapi
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type orderRecord struct {
ID uint64 `json:"id"`
OrderNo string `json:"order_no"`
CustomerID uint64 `json:"customer_id"`
CustomerName string `json:"customer_name"`
ProductID uint64 `json:"product_id"`
ProductName string `json:"product_name"`
AmountCents uint64 `json:"amount_cents"`
Currency string `json:"currency"`
Status string `json:"status"`
PaymentReference *string `json:"payment_reference"`
PaidAt *time.Time `json:"paid_at"`
LicenseID *uint64 `json:"license_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
const orderSelect = `SELECT o.id,o.order_no,o.customer_id,c.name,o.product_id,p.name,o.amount_cents,o.currency,o.status,o.payment_reference,o.paid_at,o.issued_license_id,o.created_at,o.updated_at FROM offline_orders o JOIN customers c ON c.id=o.customer_id JOIN products p ON p.id=o.product_id`
type orderScanner interface{ Scan(...any) error }
func scanOrder(s orderScanner) (o orderRecord, err error) {
err = s.Scan(&o.ID, &o.OrderNo, &o.CustomerID, &o.CustomerName, &o.ProductID, &o.ProductName, &o.AmountCents, &o.Currency, &o.Status, &o.PaymentReference, &o.PaidAt, &o.LicenseID, &o.CreatedAt, &o.UpdatedAt)
return
}
func (a *BusinessAPI) listOrders(c *gin.Context) {
p, size := page(c)
var total int
if a.db.QueryRowContext(c, "SELECT COUNT(*) FROM offline_orders").Scan(&total) != nil {
apiError(c, 500, "internal_error", "订单加载失败")
return
}
rows, err := a.db.QueryContext(c, orderSelect+" ORDER BY o.id DESC LIMIT ? OFFSET ?", size, (p-1)*size)
if err != nil {
apiError(c, 500, "internal_error", "订单加载失败")
return
}
defer rows.Close()
out := []orderRecord{}
for rows.Next() {
o, e := scanOrder(rows)
if e != nil {
apiError(c, 500, "internal_error", "订单加载失败")
return
}
out = append(out, o)
}
if rows.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}})
}
func (a *BusinessAPI) getOrder(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "订单 ID 无效")
return
}
o, err := scanOrder(a.db.QueryRowContext(c, orderSelect+" WHERE o.id=?", id))
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "订单不存在")
return
}
if err != nil {
apiError(c, 500, "internal_error", "订单加载失败")
return
}
c.JSON(200, gin.H{"data": o})
}
type orderInput struct {
CustomerID uint64 `json:"customer_id"`
ProductID uint64 `json:"product_id"`
AmountCents uint64 `json:"amount_cents"`
Currency string `json:"currency"`
PaymentReference string `json:"payment_reference"`
StartsAt string `json:"starts_at"`
ExpiresAt string `json:"expires_at"`
}
func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
key, ok := parseOperationKey(c)
if !ok {
return
}
for _, r := range key {
if r < 33 || r > 126 {
apiError(c, 400, "invalid_idempotency_key", "幂等键仅允许可见 ASCII 字符")
return
}
}
var in orderInput
if c.ShouldBindJSON(&in) != nil {
apiError(c, 400, "invalid_request", "订单参数无效")
return
}
var id uint64
var err error
if operation != "create" {
id, err = strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "订单 ID 无效")
return
}
}
var starts, expires time.Time
switch operation {
case "create":
if in.CustomerID == 0 || in.ProductID == 0 || in.AmountCents == 0 || in.AmountCents > 100000000000 || in.Currency != "CNY" {
apiError(c, 400, "invalid_request", "客户产品必填,金额须为1至100000000000分,币种为CNY")
return
}
in = orderInput{CustomerID: in.CustomerID, ProductID: in.ProductID, AmountCents: in.AmountCents, Currency: in.Currency}
case "confirm-payment":
in.PaymentReference = strings.TrimSpace(in.PaymentReference)
if in.AmountCents == 0 || len(in.PaymentReference) == 0 || len(in.PaymentReference) > 190 {
apiError(c, 400, "invalid_request", "实际收款金额和收款凭据编号必填(编号最多190字节)")
return
}
in = orderInput{AmountCents: in.AmountCents, PaymentReference: in.PaymentReference}
case "issue":
starts, err = time.Parse(time.RFC3339, in.StartsAt)
if err != nil {
apiError(c, 400, "invalid_request", "开始时间必须为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", "授权期限无效或超出TIMESTAMP范围")
return
}
in = orderInput{StartsAt: starts.Format(time.RFC3339Nano), ExpiresAt: expires.Format(time.RFC3339Nano)}
default:
apiError(c, 400, "invalid_request", "未知订单操作")
return
}
payload, _ := json.Marshal(struct {
ID uint64
Input orderInput
}{id, in})
fingerprint := sha256.Sum256(payload)
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", "订单操作失败,请保留相同幂等键重试") }
actor := c.MustGet("admin_id")
// Consistent administrator-first lock order serializes same-actor retry keys across orders.
var locked uint64
err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", actor).Scan(&locked)
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 403, "forbidden", "无权操作订单")
return
}
if err != nil {
fail()
return
}
var storedFingerprint, storedResponse []byte
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM order_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", actor, operation, key).Scan(&storedFingerprint, &storedResponse)
if err == nil {
if !bytes.Equal(storedFingerprint, fingerprint[:]) {
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同订单请求")
return
}
var result gin.H
if json.Unmarshal(storedResponse, &result) != nil {
fail()
return
}
result["idempotent_replay"] = true
c.JSON(200, result)
return
}
if !errors.Is(err, sql.ErrNoRows) {
fail()
return
}
var o orderRecord
if operation != "create" {
o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=? FOR UPDATE", id))
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "订单不存在")
return
}
if err != nil {
fail()
return
}
}
var license *licenseRecord
if operation == "create" || operation == "issue" {
customerID, productID := o.CustomerID, o.ProductID
if operation == "create" {
customerID, productID = in.CustomerID, in.ProductID
}
var customerStatus string
var active bool
err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", customerID).Scan(&o.CustomerName, &customerStatus)
if errors.Is(err, sql.ErrNoRows) || err == nil && customerStatus != "active" {
apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用")
return
}
if err != nil {
fail()
return
}
err = tx.QueryRowContext(c, "SELECT name,active FROM products WHERE id=? FOR UPDATE", productID).Scan(&o.ProductName, &active)
if errors.Is(err, sql.ErrNoRows) || err == nil && !active {
apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用")
return
}
if err != nil {
fail()
return
}
}
switch operation {
case "create":
raw := make([]byte, 16)
if _, err = rand.Read(raw); err != nil {
fail()
return
}
res, e := tx.ExecContext(c, "INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,created_by) VALUES(?,?,?,?,?,?)", hex.EncodeToString(raw), in.CustomerID, in.ProductID, in.AmountCents, in.Currency, actor)
if e != nil {
fail()
return
}
n, e := res.LastInsertId()
if e != nil {
fail()
return
}
id = uint64(n)
case "confirm-payment":
if o.Status != "pending_payment" {
apiError(c, 409, "invalid_state", "只有待收款订单可确认收款")
return
}
if o.AmountCents != in.AmountCents {
apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额")
return
}
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='paid',payment_reference=?,paid_at=?,paid_by=? WHERE id=?", in.PaymentReference, time.Now().UTC(), actor, id)
if err != nil {
fail()
return
}
case "issue":
if o.Status != "paid" || o.LicenseID != nil {
apiError(c, 409, "invalid_state", "只有已收款且未发放的订单可发放授权")
return
}
raw := make([]byte, 16)
if _, err = rand.Read(raw); err != nil {
fail()
return
}
// Random internal key avoids collisions with administrator-supplied direct-issuance keys.
internalKey := "order-" + strconv.FormatUint(id, 10) + "-" + hex.EncodeToString(raw)
res, e := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", hex.EncodeToString(raw), o.CustomerID, o.ProductID, starts, expires, internalKey, actor)
if e != nil {
fail()
return
}
n, e := res.LastInsertId()
if e != nil {
fail()
return
}
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='issued',issued_license_id=? WHERE id=?", n, id)
if err != nil {
fail()
return
}
l := 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=?`, n).Scan(&l.ID, &l.LicenseKey, &l.CustomerID, &l.CustomerName, &l.ProductID, &l.ProductName, &l.ProductCode, &l.Status, &l.StartsAt, &l.ExpiresAt, &l.CreatedAt)
if err != nil {
fail()
return
}
l.Status = currentLicenseStatus(l.Status, l.StartsAt, l.ExpiresAt, time.Now().UTC())
license = &l
details, _ := json.Marshal(gin.H{"order_id": id, "customer_id": o.CustomerID, "product_id": o.ProductID, "starts_at": starts, "expires_at": expires})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", actor, n, details); err != nil {
fail()
return
}
}
o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=?", id))
if err != nil {
fail()
return
}
result := gin.H{"data": o, "idempotent_replay": false}
if license != nil {
result["license"] = license
}
response, err := json.Marshal(result)
if err != nil {
fail()
return
}
if _, err = tx.ExecContext(c, "INSERT INTO order_operations(order_id,actor_admin_id,operation,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?,?)", id, actor, operation, key, fingerprint[:], response); err != nil {
fail()
return
}
details, _ := json.Marshal(gin.H{"customer_id": o.CustomerID, "product_id": o.ProductID, "amount_cents": o.AmountCents, "currency": o.Currency, "license_id": o.LicenseID})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'order',?,?)", actor, "order."+operation, id, details); err != nil {
fail()
return
}
if tx.Commit() != nil {
fail()
return
}
if operation == "create" {
c.Header("Location", "/api/v1/orders/"+strconv.FormatUint(id, 10))
c.JSON(201, result)
} else {
c.JSON(200, result)
}
}

View File

@@ -0,0 +1,150 @@
package httpapi
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func testOrdersMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Cookie, customerID, productID uint64) {
request := func(method, path, body, key string, authenticated bool) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
if authenticated {
req.AddCookie(cookie)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
check := func(w *httptest.ResponseRecorder, code int) {
t.Helper()
if w.Code != code {
t.Fatalf("code=%d want=%d body=%s", w.Code, code, w.Body)
}
}
exec := func(query string, args ...any) {
t.Helper()
if _, err := db.Exec(query, args...); err != nil {
t.Fatal(err)
}
}
body := fmt.Sprintf(`{"customer_id":%d,"product_id":%d,"amount_cents":12800,"currency":"CNY"}`, customerID, productID)
check(request("POST", "/api/v1/orders", body, "create", false), 401)
exec("UPDATE admins SET role='viewer' WHERE email='integration@example.test'")
check(request("POST", "/api/v1/orders", body, "create", true), 403)
exec("UPDATE admins SET role='admin' WHERE email='integration@example.test'")
check(request("POST", "/api/v1/orders", body, "", true), 400)
check(request("POST", "/api/v1/orders", strings.Replace(body, "12800", "0", 1), "invalid", true), 400)
exec("UPDATE customers SET status='inactive' WHERE id=?", customerID)
check(request("POST", "/api/v1/orders", body, "inactive-customer", true), 400)
exec("UPDATE customers SET status='active' WHERE id=?", customerID)
w := request("POST", "/api/v1/orders", body, "create", true)
check(w, 201)
var result struct {
Data orderRecord `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
id := result.Data.ID
path := fmt.Sprintf("/api/v1/orders/%d", id)
check(request("POST", "/api/v1/orders", body, "create", true), 200)
check(request("POST", "/api/v1/orders", strings.Replace(body, "12800", "12900", 1), "create", true), 409)
check(request("GET", path, "", "", true), 200)
check(request("GET", "/api/v1/orders?page=1&page_size=20", "", "", true), 200)
dates := `{"starts_at":"2026-09-30T00:00:00Z","expires_at":"2027-09-30T00:00:00Z"}`
check(request("POST", path+"/issue", dates, "issue", true), 409)
payment := `{"amount_cents":12800,"payment_reference":"BANK-TEST-001"}`
check(request("POST", path+"/confirm-payment", strings.Replace(payment, "12800", "12799", 1), "payment", true), 400)
exec("CREATE TRIGGER order_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'")
t.Cleanup(func() { db.Exec("DROP TRIGGER IF EXISTS order_audit_failure") })
check(request("POST", path+"/confirm-payment", payment, "payment", true), 500)
exec("DROP TRIGGER order_audit_failure")
var status string
if err := db.QueryRow("SELECT status FROM offline_orders WHERE id=?", id).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "pending_payment" {
t.Fatal("failed payment changed order")
}
check(request("POST", path+"/confirm-payment", payment, "payment", true), 200)
check(request("POST", path+"/confirm-payment", payment, "payment", true), 200)
check(request("POST", path+"/confirm-payment", payment, "different-payment", true), 409)
check(request("POST", path+"/confirm-payment", strings.Replace(payment, "001", "002", 1), "payment", true), 409)
exec("UPDATE products SET active=0 WHERE id=?", productID)
check(request("POST", path+"/issue", dates, "issue", true), 400)
exec("UPDATE products SET active=1 WHERE id=?", productID)
var before int
if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&before); err != nil {
t.Fatal(err)
}
exec("CREATE TRIGGER order_audit_failure BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='test failure'")
check(request("POST", path+"/issue", dates, "issue", true), 500)
exec("DROP TRIGGER order_audit_failure")
var after int
if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&after); err != nil {
t.Fatal(err)
}
if before != after {
t.Fatal("failed audit leaked license")
}
if err := db.QueryRow("SELECT status FROM offline_orders WHERE id=?", id).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "paid" {
t.Fatal("failed issuance changed order")
}
results := make(chan *httptest.ResponseRecorder, 2)
for i := 0; i < 2; i++ {
go func() { results <- request("POST", path+"/issue", dates, "issue", true) }()
}
replay := 0
for i := 0; i < 2; i++ {
w := <-results
check(w, 200)
if strings.Contains(w.Body.String(), `"idempotent_replay":true`) {
replay++
}
}
if replay != 1 {
t.Fatalf("replays=%d", replay)
}
check(request("POST", path+"/issue", dates, "different-issue", true), 409)
check(request("POST", path+"/issue", strings.Replace(dates, "2027", "2028", 1), "issue", true), 409)
if err := db.QueryRow("SELECT COUNT(*) FROM licenses").Scan(&after); err != nil {
t.Fatal(err)
}
if after != before+1 {
t.Fatal("duplicate issuance")
}
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE resource_type='order' AND resource_id=?", id).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 3 {
t.Fatalf("order audits=%d", count)
}
if err := db.QueryRow("SELECT COUNT(*) FROM order_operations WHERE order_id=?", id).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 3 {
t.Fatalf("operations=%d", count)
}
var licenseID uint64
if err := db.QueryRow("SELECT issued_license_id FROM offline_orders WHERE id=? AND status='issued'", id).Scan(&licenseID); err != nil {
t.Fatal(err)
}
if err := db.QueryRow("SELECT COUNT(*) FROM licenses WHERE id=? AND customer_id=? AND product_id=?", licenseID, customerID, productID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatal("license scope mismatch")
}
}

View File

@@ -0,0 +1,104 @@
package httpapi
import (
"crypto/sha256"
"database/sql"
"encoding/base64"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// Instance credentials authorize only this instance, never an entire customer account.
func (a *BusinessAPI) portalSnapshot(c *gin.Context) {
c.Header("Cache-Control", "private, no-store")
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
var in struct {
InstanceID string `json:"instance_id"`
Secret string `json:"secret"`
}
if c.Query("customer_id") != "" || c.ShouldBindJSON(&in) != nil || len(in.InstanceID) != 36 || len(in.Secret) > 128 {
apiError(c, 400, "invalid_request", "Invalid portal request")
return
}
raw, err := base64.RawURLEncoding.DecodeString(in.Secret)
if err != nil || len(raw) != 32 {
apiError(c, 403, "forbidden", "Invalid credentials")
return
}
sum := sha256.Sum256(raw)
tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
if err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
defer tx.Rollback()
var rowID, actor, owner, productID, licenseID uint64
var stored []byte
var customerName, customerState, productName, productCode, instanceState, freeze, licenseState, observed string
var active bool
var starts, expires, now time.Time
var seen, lease sql.NullTime
err = tx.QueryRowContext(c, `SELECT i.id,i.created_by,i.customer_id,i.product_id,i.license_id,i.secret_hash,c.name,c.status,p.name,p.code,p.active,i.status,i.freeze_state,l.status,l.starts_at,l.expires_at,i.observed_state,i.last_seen_at,i.lease_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=?`, in.InstanceID).Scan(&rowID, &actor, &owner, &productID, &licenseID, &stored, &customerName, &customerState, &productName, &productCode, &active, &instanceState, &freeze, &licenseState, &starts, &expires, &observed, &seen, &lease)
if err == sql.ErrNoRows || (err == nil && !bytesEqual(stored, sum[:])) {
apiError(c, 403, "forbidden", "Invalid credentials")
return
}
if err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
if err = tx.QueryRowContext(c, "SELECT UTC_TIMESTAMP(6)").Scan(&now); err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
state := leaseState(instanceState, freeze, licenseState, customerState, active, starts, expires, now)
p, size := page(c)
// Bound offset independently of integer overflow and expensive arbitrary scans.
if p > 10000 {
apiError(c, 400, "invalid_page", "Page out of range")
return
}
var total int
if err = tx.QueryRowContext(c, "SELECT COUNT(*) FROM product_releases WHERE product_id=? AND published=1", productID).Scan(&total); err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
rows, err := tx.QueryContext(c, "SELECT id,version,sha256,size_bytes FROM product_releases WHERE product_id=? AND published=1 ORDER BY id DESC LIMIT ? OFFSET ?", productID, size, (p-1)*size)
if err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
releases := []gin.H{}
for rows.Next() {
var id, sizeBytes uint64
var version, digest string
if err = rows.Scan(&id, &version, &digest, &sizeBytes); err != nil {
break
}
releases = append(releases, gin.H{"id": id, "version": version, "sha256": digest, "size_bytes": sizeBytes, "download_allowed": state == "active"})
}
scanErr := rows.Err()
rows.Close()
if err != nil || scanErr != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
// Audit attributes the client to an instance, not to the provisioning administrator.
if _, err = tx.ExecContext(c, `INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'portal.viewed','license_instance',?,JSON_OBJECT('client_actor','instance','customer_id',?))`, actor, rowID, owner); err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
if err = tx.Commit(); err != nil {
apiError(c, 503, "portal_unavailable", "Portal unavailable")
return
}
nullable := func(v sql.NullTime) any {
if v.Valid {
return v.Time
}
return nil
}
c.JSON(200, gin.H{"data": gin.H{"scope": "instance", "customer": gin.H{"id": owner, "name": customerName}, "product": gin.H{"id": productID, "code": productCode, "name": productName}, "license": gin.H{"id": licenseID, "status": licenseState, "starts_at": starts, "expires_at": expires}, "instance": gin.H{"instance_id": in.InstanceID, "status": instanceState, "freeze_state": freeze}, "lease": gin.H{"observed_state": observed, "last_seen_at": nullable(seen), "expires_at": nullable(lease), "current_state": state}, "releases": releases}, "meta": gin.H{"page": p, "page_size": size, "total": total}})
}

View File

@@ -0,0 +1,193 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
)
func TestPortalKeyringMySQL(t *testing.T) {
dsn := os.Getenv("PORTAL_TEST_DSN")
if dsn == "" {
t.Skip("PORTAL_TEST_DSN isolated schema008 required")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal("database configuration invalid")
}
defer db.Close()
// Never run the fixture against a named business database.
var database string
if err = db.QueryRow("SELECT DATABASE()").Scan(&database); err != nil || !strings.HasPrefix(database, "license_portal_test_") {
t.Fatal("dedicated portal test database required")
}
insert := func(q string, args ...any) int64 {
t.Helper()
r, e := db.Exec(q, args...)
if e != nil {
t.Fatal("fixture SQL failed")
}
id, _ := r.LastInsertId()
return id
}
suffix := fmt.Sprint(time.Now().UnixNano())
admin := insert("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", suffix, suffix+"@portal.test", "unused")
owner := insert("INSERT INTO customers(name,contact_email) VALUES(?,'portal@test.invalid')", suffix)
other := insert("INSERT INTO customers(name,contact_email) VALUES(?,'other@test.invalid')", suffix+"other")
product := insert("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix, "PortalProduct")
otherProduct := insert("INSERT INTO products(code,name,description) VALUES(?,?,'')", suffix+"other", "HiddenProduct")
old, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
next, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
pub := func(k *ecdsa.PrivateKey) string {
d, _ := x509.MarshalPKIXPublicKey(&k.PublicKey)
return string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: d}))
}
router := func(k *ecdsa.PrivateKey, id string) *gin.Engine {
d, _ := x509.MarshalECPrivateKey(k)
private := string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: d}))
ring := &Keyring{Current: id, Keys: []VerificationKey{{KeyID: "old", PublicKeyPEM: pub(old)}, {KeyID: "new", PublicKeyPEM: pub(next)}}}
if e := ring.Validate(private); e != nil {
t.Fatal(e)
}
r := NewRouter()
RegisterBusinessWithKeyring(r, db, private, ring)
return r
}
r := router(old, "old")
request := func(path string, body any, idem string) *httptest.ResponseRecorder {
b, _ := json.Marshal(body)
q := httptest.NewRequest("POST", path, strings.NewReader(string(b)))
q.Header.Set("Content-Type", "application/json")
q.Header.Set("Idempotency-Key", idem)
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
return w
}
type fixture struct {
instance, secret, key string
license int64
}
create := func(customer, prod int64, label string) fixture {
raw := make([]byte, 32)
rand.Read(raw)
key := hex.EncodeToString(raw[:16])
license := insert("INSERT INTO licenses(license_key,customer_id,product_id,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,?,?,?,?)", key, customer, prod, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), suffix+label, admin)
secret := make([]byte, 32)
rand.Read(secret)
sum := sha256.Sum256(secret)
id, _ := newInstanceID()
insert("INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", id, license, customer, prod, sum[:], admin)
return fixture{id, base64.RawURLEncoding.EncodeToString(secret), key, license}
}
first := create(owner, product, "first")
hidden := create(other, otherProduct, "hidden")
activate := func(f fixture) *httptest.ResponseRecorder {
return request("/api/v1/activation/instances/"+f.instance, map[string]string{"secret": f.secret, "license_key": f.key}, "activate")
}
envelopes := []json.RawMessage{}
collect := func(w *httptest.ResponseRecorder, key string) {
t.Helper()
if w.Code != 200 && w.Code != 201 {
t.Fatalf("issuance status %d", w.Code)
}
var out struct {
Data struct {
Certificate json.RawMessage `json:"certificate"`
Payload json.RawMessage `json:"payload"`
Signature string `json:"signature"`
} `json:"data"`
}
if json.Unmarshal(w.Body.Bytes(), &out) != nil {
t.Fatal("invalid response")
}
envelope := out.Data.Certificate
if len(envelope) == 0 {
var err error
envelope, err = json.Marshal(map[string]any{"payload": json.RawMessage(out.Data.Payload), "signature": out.Data.Signature})
if err != nil {
t.Fatal("invalid heartbeat envelope")
}
}
if !strings.Contains(string(envelope), `"key_id":"`+key+`"`) {
t.Fatal("wrong signing key")
}
envelopes = append(envelopes, envelope)
}
initial := activate(first)
collect(initial, "old")
beat := func(f fixture, idem string) *httptest.ResponseRecorder {
return request("/api/v1/instances/"+f.instance+"/heartbeat", map[string]string{"secret": f.secret, "client_time": time.Now().UTC().Format(time.RFC3339Nano)}, idem)
}
collect(beat(first, "old-beat"), "old")
r = router(next, "new")
replay := activate(first)
collect(replay, "old")
var a, b any
json.Unmarshal(initial.Body.Bytes(), &a)
json.Unmarshal(replay.Body.Bytes(), &b)
aa, _ := json.Marshal(a)
bb, _ := json.Marshal(b)
if string(aa) != string(bb) {
t.Fatal("rotation changed historical replay")
}
second := create(owner, product, "second")
collect(activate(second), "new")
collect(beat(second, "new-beat"), "new")
// Recreate router after rotation with same private material: application re-registration, not OS process restart.
r = router(next, "new")
collect(activate(second), "new")
insert("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,'v1',?,?,1,?)", product, strings.Repeat("a", 64)+".bin", strings.Repeat("a", 64), admin)
insert("INSERT INTO product_releases(product_id,version,storage_key,sha256,size_bytes,created_by) VALUES(?,'hidden-version',?,?,1,?)", otherProduct, strings.Repeat("b", 64)+".bin", strings.Repeat("b", 64), admin)
snapshot := func(f fixture, path string) *httptest.ResponseRecorder {
return request(path, map[string]string{"instance_id": f.instance, "secret": f.secret}, "")
}
w := snapshot(first, "/api/v1/portal/snapshot?page_size=1")
if w.Code != 200 || strings.Contains(w.Body.String(), "HiddenProduct") || strings.Contains(w.Body.String(), "hidden-version") || strings.Contains(w.Body.String(), first.secret) || strings.Contains(w.Body.String(), "secret_hash") {
t.Fatal("portal isolation failed")
}
if len(w.Result().Cookies()) != 0 || w.Header().Get("Cache-Control") != "private, no-store" {
t.Fatal("portal cookie/cache boundary")
}
if w = snapshot(first, "/api/v1/portal/snapshot?customer_id="+fmt.Sprint(other)); w.Code != 400 {
t.Fatal("customer override accepted")
}
bad := first
bad.instance = hidden.instance
if w = snapshot(bad, "/api/v1/portal/snapshot"); w.Code != 403 {
t.Fatal("cross-instance credentials accepted")
}
if w = snapshot(first, "/api/v1/portal/snapshot?page=10001"); w.Code != 400 {
t.Fatal("unbounded pagination")
}
var n int
if db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='portal.viewed'").Scan(&n) != nil || n < 1 {
t.Fatal("portal audit missing")
}
path := filepath.Join(t.TempDir(), "public-vectors.json")
vectors, _ := json.Marshal(map[string]any{"keys": []VerificationKey{{KeyID: "old", PublicKeyPEM: pub(old)}, {KeyID: "new", PublicKeyPEM: pub(next)}}, "envelopes": envelopes})
if os.WriteFile(path, vectors, 0600) != nil {
t.Fatal("vectors unavailable")
}
output, e := exec.Command("node", "--input-type=module", "-e", `import fs from 'node:fs';import {verifyEnvelope} from '../../../client/verify.mjs';const v=JSON.parse(fs.readFileSync(process.argv[1]));for(const e of v.envelopes)verifyEnvelope(e,v.keys);console.log('MySQL-issued v2 old/new/replay envelopes verified');`, path).CombinedOutput()
if e != nil {
t.Fatalf("Node validation failed: %s", output)
}
t.Log(string(output))
}

View File

@@ -0,0 +1,37 @@
package httpapi
import (
"io"
"log/slog"
"net/http/httptest"
"strings"
"testing"
)
func TestPortalCredentialCookieBoundary(t *testing.T) {
r := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil))))
a := &BusinessAPI{}
r.POST("/api/v1/portal/snapshot", a.portalSnapshot)
for _, tc := range []struct {
body, path, origin string
want int
}{
{"{}", "/api/v1/portal/snapshot", "", 400},
{`{"instance_id":"00000000-0000-4000-8000-000000000001","secret":"wrong"}`, "/api/v1/portal/snapshot", "", 403},
{"{}", "/api/v1/portal/snapshot?customer_id=2", "", 400},
{"{}", "/api/v1/portal/snapshot", "https://evil.test", 403},
} {
q := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))
q.Header.Set("Cookie", "lp_session=administrator-cookie")
q.Header.Set("Content-Type", "application/json")
q.Header.Set("Origin", tc.origin)
w := httptest.NewRecorder()
r.ServeHTTP(w, q)
if w.Code != tc.want {
t.Fatalf("status %d want %d", w.Code, tc.want)
}
if len(w.Result().Cookies()) != 0 {
t.Fatal("portal issued cookie")
}
}
}

View File

@@ -0,0 +1,47 @@
package httpapi
import (
"context"
"database/sql"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const RequiredSchemaVersion = 10
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
r.GET("/api/v1/health/ready", func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
defer cancel()
if err := CheckSchema(ctx, db); err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "not_ready"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ready"})
})
}
func CheckSchema(ctx context.Context, db *sql.DB) error {
if db == nil {
return sql.ErrConnDone
}
var version uint64
var dirty bool
rows, err := db.QueryContext(ctx, "SELECT version, dirty FROM schema_migrations")
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return sql.ErrNoRows
}
if err := rows.Scan(&version, &dirty); err != nil {
return err
}
if rows.Next() || rows.Err() != nil || version != RequiredSchemaVersion || dirty {
return sql.ErrNoRows
}
return nil
}

View File

@@ -0,0 +1,95 @@
package httpapi
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
type readinessDriver struct{}
type readinessConn struct{ mode string }
type readinessRows struct {
mode string
read bool
}
func (readinessDriver) Open(mode string) (driver.Conn, error) { return readinessConn{mode}, nil }
func (readinessConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("not supported") }
func (readinessConn) Close() error { return nil }
func (readinessConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") }
func (c readinessConn) QueryContext(context.Context, string, []driver.NamedValue) (driver.Rows, error) {
if c.mode == "unavailable" {
return nil, errors.New("private connection detail")
}
return &readinessRows{mode: c.mode}, nil
}
func (*readinessRows) Columns() []string { return []string{"version", "dirty"} }
func (*readinessRows) Close() error { return nil }
func (r *readinessRows) Next(values []driver.Value) error {
if r.read || r.mode == "empty" {
return io.EOF
}
r.read = true
version := int64(RequiredSchemaVersion)
if r.mode == "old" {
version--
}
if r.mode == "future" {
version++
}
values[0] = version
values[1] = r.mode == "dirty"
return nil
}
func init() { sql.Register("readiness-test", readinessDriver{}) }
func TestReadinessSchemaGate(t *testing.T) {
for _, mode := range []string{"ready", "old", "future", "dirty", "empty", "unavailable", "nil"} {
t.Run(mode, func(t *testing.T) {
var db *sql.DB
if mode != "nil" {
var err error
db, err = sql.Open("readiness-test", mode)
if err != nil {
t.Fatal(err)
}
defer db.Close()
}
r := gin.New()
RegisterReadiness(r, db)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/health/ready", nil))
want := 503
body := `{"status":"not_ready"}`
if mode == "ready" {
want = 200
body = `{"status":"ready"}`
}
if w.Code != want || w.Body.String() != body {
t.Fatalf("%d %s", w.Code, w.Body.String())
}
})
}
}
func TestSecureSessionCookie(t *testing.T) {
t.Setenv("SESSION_COOKIE_SECURE", "true")
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("GET", "http://localhost/", nil)
if !secureSessionCookie(c) {
t.Fatal("forced secure lost")
}
t.Setenv("SESSION_COOKIE_SECURE", "false")
c.Request.Header.Set("X-Forwarded-Proto", "https")
if secureSessionCookie(c) {
t.Fatal("untrusted header enabled cookie security")
}
c.Request = httptest.NewRequest("GET", "https://localhost/", nil)
if !secureSessionCookie(c) {
t.Fatal("direct TLS must be secure")
}
}

View File

@@ -0,0 +1,84 @@
package httpapi
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
type EntryLimiter interface {
Allow(context.Context, string, int) (bool, error)
}
type RedisLimiter struct {
client *redis.Client
prefix string
}
var entryLimitScript = redis.NewScript(`
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('PEXPIRE', KEYS[1], 60000) end
if n > tonumber(ARGV[1]) then return 0 end
return 1
`)
func NewRedisLimiter(client *redis.Client, prefix string) *RedisLimiter {
return &RedisLimiter{client: client, prefix: prefix}
}
func (l *RedisLimiter) Allow(ctx context.Context, key string, limit int) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
result, err := entryLimitScript.Run(ctx, l.client, []string{l.prefix + key}, limit).Int()
return result == 1, err
}
// Redis errors never fall back to per-process counters.
func ConfigureEntryLimiter(ops *Operations, getenv func(string) string) (func(), error) {
mode := getenv("ENTRY_LIMIT_MODE")
if mode == "local-dev" {
return func() {}, nil
}
if mode != "" && mode != "redis" {
return nil, fmt.Errorf("invalid entry limit mode")
}
addr := getenv("ENTRY_REDIS_ADDR")
if addr == "" {
return nil, fmt.Errorf("Redis entry limiting required; local-dev must be explicitly opted into")
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("invalid Redis address")
}
opts := &redis.Options{Addr: addr, Username: getenv("ENTRY_REDIS_USERNAME"), DialTimeout: 500 * time.Millisecond, ReadTimeout: 500 * time.Millisecond, WriteTimeout: 500 * time.Millisecond, MaxRetries: -1, ContextTimeoutEnabled: true}
if path := getenv("ENTRY_REDIS_PASSWORD_FILE"); path != "" {
if !filepath.IsAbs(path) {
return nil, fmt.Errorf("Redis password file must be absolute")
}
bytes, err := os.ReadFile(path)
if err != nil || len(bytes) == 0 || len(bytes) > 4096 {
return nil, fmt.Errorf("invalid Redis password file")
}
opts.Password = strings.TrimSpace(string(bytes))
}
// Current profile permits only numeric loopback/private IP transport. Remote TLS remains a release gate.
ip := net.ParseIP(host)
if ip == nil || (!ip.IsLoopback() && !ip.IsPrivate()) {
return nil, fmt.Errorf("Redis must use a numeric private or loopback IP")
}
client := redis.NewClient(opts)
prefix := getenv("ENTRY_REDIS_NAMESPACE")
if prefix == "" {
prefix = "license-platform:entry:"
}
if len(prefix) > 100 {
client.Close()
return nil, fmt.Errorf("invalid Redis namespace")
}
ops.limiter = NewRedisLimiter(client, prefix)
return func() { client.Close() }, nil
}

View File

@@ -0,0 +1,83 @@
package httpapi
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
)
func TestRedisEntryIntegration(t *testing.T) {
addr := os.Getenv("ENTRY_REDIS_TEST_ADDR")
if addr == "" {
t.Skip("isolated Redis required")
}
prefix := fmt.Sprintf("test:entry:%d:", time.Now().UnixNano())
clients := []*redis.Client{redis.NewClient(&redis.Options{Addr: addr}), redis.NewClient(&redis.Options{Addr: addr})}
for _, c := range clients {
defer c.Close()
if err := c.Ping(context.Background()).Err(); err != nil {
t.Fatal("isolated Redis unavailable")
}
}
servers := make([]*httptest.Server, 2)
calls := 0
for i := range servers {
ops := NewOperations(slog.New(slog.NewJSONHandler(io.Discard, nil)))
ops.limiter = NewRedisLimiter(clients[i], prefix)
r := NewOperationalRouter(ops)
r.POST("/api/v1/auth/login", func(c *gin.Context) { calls++; c.Status(401) })
servers[i] = httptest.NewServer(r)
defer servers[i].Close()
}
for i := 0; i < 11; i++ {
req, _ := http.NewRequest("POST", servers[i%2].URL+"/api/v1/auth/login", nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
want := 401
if i == 10 {
want = 429
}
if res.StatusCode != want {
t.Fatal(i, res.StatusCode)
}
}
if calls != 10 {
t.Fatal(calls)
}
clients[0].Close()
res, err := http.Post(servers[0].URL+"/api/v1/auth/login", "application/json", nil)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 503 || calls != 10 {
t.Fatal("Redis failure must block handler", res.StatusCode, calls)
}
}
func TestEntryModeRequiresExplicitDevelopment(t *testing.T) {
ops := NewOperations(slog.Default())
if _, err := ConfigureEntryLimiter(ops, func(string) string { return "" }); err == nil {
t.Fatal("implicit fallback")
}
close, err := ConfigureEntryLimiter(ops, func(k string) string {
if k == "ENTRY_LIMIT_MODE" {
return "local-dev"
}
return ""
})
if err != nil {
t.Fatal(err)
}
close()
}

View File

@@ -0,0 +1,42 @@
package httpapi
import (
"github.com/gin-gonic/gin"
"strconv"
)
func (a *BusinessAPI) listReleases(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "产品无效")
return
}
p, size := page(c)
var total int
if err = a.db.QueryRowContext(c, "SELECT COUNT(*) FROM product_releases WHERE product_id=?", id).Scan(&total); err != nil {
apiError(c, 500, "internal_error", "加载失败")
return
}
rows, err := a.db.QueryContext(c, "SELECT id,version,sha256,size_bytes,published FROM product_releases WHERE product_id=? ORDER BY id DESC LIMIT ? OFFSET ?", id, size, (p-1)*size)
if err != nil {
apiError(c, 500, "internal_error", "加载失败")
return
}
defer rows.Close()
data := []gin.H{}
for rows.Next() {
var rid, n uint64
var version, digest string
var published bool
if err = rows.Scan(&rid, &version, &digest, &n, &published); err != nil {
apiError(c, 500, "internal_error", "加载失败")
return
}
data = append(data, gin.H{"id": rid, "version": version, "sha256": digest, "size_bytes": n, "published": published})
}
if rows.Err() != nil {
apiError(c, 500, "internal_error", "加载失败")
return
}
c.JSON(200, gin.H{"data": data, "meta": gin.H{"total": total, "page": p, "page_size": size}})
}

View File

@@ -1,14 +1,22 @@
package httpapi
import (
"log/slog"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func NewRouter() *gin.Engine {
return NewOperationalRouter(NewOperations(slog.New(slog.NewJSONHandler(os.Stdout, nil))))
}
func NewOperationalRouter(ops *Operations) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Logger(), gin.Recovery())
_ = r.SetTrustedProxies(nil)
r.Use(ops.Middleware())
r.NoRoute(func(c *gin.Context) { apiError(c, 404, "not_found", "Not found") })
r.GET("/api/v1/health/live", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})

View File

@@ -13,7 +13,9 @@ func TestLiveness(t *testing.T) {
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var body struct{ Status string `json:"status"` }
var body struct {
Status string `json:"status"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Status != "ok" {
t.Fatalf("body = %q, err = %v", w.Body.String(), err)
}

View File

@@ -0,0 +1,42 @@
package httpapi
import (
"context"
"errors"
"net"
"net/http"
"time"
)
func Serve(ctx context.Context, server *http.Server, shutdownTimeout time.Duration) error {
listener, err := net.Listen("tcp", server.Addr)
if err != nil {
return err
}
return serveListener(ctx, server, listener, shutdownTimeout)
}
func serveListener(ctx context.Context, server *http.Server, listener net.Listener, timeout time.Duration) error {
result := make(chan error, 1)
go func() { result <- server.Serve(listener) }()
select {
case err := <-result:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
_ = server.Close()
<-result
return err
}
err := <-result
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
}

View File

@@ -0,0 +1,105 @@
package httpapi
import (
"context"
"errors"
"net"
"net/http"
"testing"
"time"
)
func TestShutdown(t *testing.T) {
for _, graceful := range []bool{true, false} {
name := "timeout"
if graceful {
name = "drain"
}
t.Run(name, func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
started, release := make(chan struct{}), make(chan struct{})
defer close(release)
handlerDone := make(chan struct{})
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(started)
defer close(handlerDone)
select {
case <-release:
case <-r.Context().Done():
}
w.WriteHeader(http.StatusNoContent)
})}
defer server.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
finished := make(chan error, 1)
go func() { finished <- serveListener(ctx, server, listener, 150*time.Millisecond) }()
requested := make(chan error, 1)
go func() {
client := &http.Client{Timeout: 3 * time.Second}
response, err := client.Get("http://" + listener.Addr().String())
if err == nil {
response.Body.Close()
if response.StatusCode != http.StatusNoContent {
err = errors.New("unexpected status")
}
}
requested <- err
}()
select {
case <-started:
case <-time.After(3 * time.Second):
t.Fatal("request did not start")
}
cancel()
if graceful {
select {
case err := <-finished:
t.Fatalf("exited with active request: %v", err)
case <-time.After(20 * time.Millisecond):
}
release <- struct{}{}
}
select {
case err := <-finished:
if graceful && err != nil {
t.Fatal(err)
}
if !graceful && !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("expected deadline: %v", err)
}
case <-time.After(3 * time.Second):
t.Fatal("shutdown did not finish")
}
select {
case err := <-requested:
if graceful && err != nil {
t.Fatal(err)
}
case <-time.After(3 * time.Second):
t.Fatal("request did not finish")
}
select {
case <-handlerDone:
case <-time.After(3 * time.Second):
t.Fatal("handler did not exit")
}
})
}
}
func TestServeListenFailure(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
err = Serve(context.Background(), &http.Server{Addr: listener.Addr().String()}, time.Second)
if err == nil {
t.Fatal("expected address in use error")
}
}

View File

@@ -0,0 +1,178 @@
package httpapi
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/json"
"encoding/pem"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func TestSigningFileAPIRestart(t *testing.T) {
dsn := os.Getenv("SIGNING_RESTART_TEST_DSN")
if dsn == "" {
t.Skip("isolated clean008 MySQL required")
}
// os.MkdirTemp default is outside the repository; never persist test private material in session data.
dir, err := os.MkdirTemp("", "license-protected-restart-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
if runtime.GOOS == "windows" {
user := os.Getenv("USERNAME")
if user == "" {
t.Fatal("user ACL required")
}
if err := exec.Command("icacls", dir, "/inheritance:r", "/grant:r", user+":(OI)(CI)F").Run(); err != nil {
t.Fatal("cannot protect key directory")
}
} else {
if err := os.Chmod(dir, 0700); err != nil {
t.Fatal(err)
}
}
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
der, _ := x509.MarshalECPrivateKey(key)
keyPath := filepath.Join(dir, "signing.pem")
if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}), 0600); err != nil {
t.Fatal(err)
}
bin := filepath.Join(dir, "api")
if runtime.GOOS == "windows" {
bin += ".exe"
}
build := exec.Command("go", "build", "-o", bin, "../../cmd/server")
if err := build.Run(); err != nil {
t.Fatal("server build failed")
}
now := time.Now().UTC().Truncate(time.Second)
payloads := []string{canonicalCertificatePayload("license-v1", "00000000-0000-4000-8000-000000000001", 1, 2, 3, now, now.Add(time.Hour)), canonicalLease(leasePayload{Version: "lease-v1", InstanceID: "00000000-0000-4000-8000-000000000001", State: "active", ServerTime: now.Format(time.RFC3339), EntitlementExpiresAt: now.Add(time.Hour).Format(time.RFC3339), LeaseExpiresAt: now.Add(time.Hour).Format(time.RFC3339)})}
signatures := make([][]byte, 2)
for i, p := range payloads {
sum := sha256.Sum256([]byte(p))
signatures[i], err = ecdsa.SignASN1(rand.Reader, key, sum[:])
if err != nil {
t.Fatal(err)
}
}
var prior string
for iteration := 0; iteration < 2; iteration++ {
listener, _ := net.Listen("tcp", "127.0.0.1:0")
addr := listener.Addr().String()
listener.Close()
monitor, _ := net.Listen("tcp", "127.0.0.1:0")
monitorAddr := monitor.Addr().String()
monitor.Close()
cmd := exec.Command(bin)
cmd.Env = append(os.Environ(), "HTTP_ADDR="+addr, "MYSQL_DSN="+dsn, "LICENSE_SIGNING_PRIVATE_KEY_PEM=", "LICENSE_SIGNING_PRIVATE_KEY_FILE="+keyPath, "METRICS_ADDR="+monitorAddr, "ENTRY_LIMIT_MODE=redis", "ENTRY_REDIS_ADDR="+os.Getenv("ENTRY_REDIS_TEST_ADDR"))
// Discard child output: neither private material nor connection errors become artifacts.
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
func() {
defer func() { cmd.Process.Kill(); cmd.Wait() }()
client := &http.Client{Timeout: time.Second}
var res *http.Response
for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); {
res, err = client.Get("http://" + addr + "/api/v1/activation/public-key")
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
t.Fatal("isolated API unavailable")
}
defer res.Body.Close()
var out struct {
Data struct {
PublicKey string `json:"public_key_pem"`
}
}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
t.Fatal(err)
}
if iteration > 0 && out.Data.PublicKey != prior {
t.Fatal("public key changed across restart")
}
prior = out.Data.PublicKey
block, _ := pem.Decode([]byte(prior))
if block == nil {
t.Fatal("no public key")
}
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
t.Fatal(err)
}
pub := parsed.(*ecdsa.PublicKey)
for i, p := range payloads {
sum := sha256.Sum256([]byte(p))
if !ecdsa.VerifyASN1(pub, sum[:], signatures[i]) {
t.Fatal("old certificate/lease signature invalid after restart")
}
}
for _, p := range []string{"/api/v1/health/ready", "/metrics"} {
r, e := client.Get("http://" + addr + p)
if e != nil {
t.Fatal(e)
}
r.Body.Close()
if r.StatusCode != 404 {
t.Fatal("internal route publicly exposed")
}
}
r, e := client.Get("http://" + monitorAddr + "/api/v1/health/ready")
if e != nil {
t.Fatal(e)
}
r.Body.Close()
if r.StatusCode != 200 {
t.Fatal("internal readiness", r.StatusCode)
}
r, e = client.Get("http://" + monitorAddr + "/metrics")
if e != nil {
t.Fatal(e)
}
r.Body.Close()
if r.StatusCode != 200 {
t.Fatal("internal metrics", r.StatusCode)
}
for _, tc := range []struct {
path, body, origin string
status int
}{
{"/api/v1/products", "", "", 401},
{"/api/v1/auth/login", "{}", "https://evil.example", 403},
{"/api/v1/auth/login", strings.Repeat("x", 65537), "", 413},
} {
q, _ := http.NewRequest("POST", "http://"+addr+tc.path, strings.NewReader(tc.body))
q.Header.Set("Origin", tc.origin)
q.Header.Set("Content-Type", "application/json")
response, e := client.Do(q)
if e != nil {
t.Fatal(e)
}
response.Body.Close()
if response.StatusCode != tc.status || response.Header.Get("X-Request-ID") == "" {
t.Fatal("new API security smoke", response.StatusCode)
}
}
t.Logf("isolated API start %d: public key stable, old canonical signatures valid, ready/metrics internal only", iteration+1)
}()
}
}

View File

@@ -0,0 +1,50 @@
package httpapi
import (
"github.com/gin-gonic/gin"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestTLSOriginCookieBoundary(t *testing.T) {
r := NewOperationalRouter(NewOperations(slog.New(slog.NewTextHandler(io.Discard, nil))))
r.POST("/write", func(c *gin.Context) {
c.SetSameSite(http.SameSiteStrictMode)
c.SetCookie("test_session", "not-a-real-session", 10, "/", "", secureSessionCookie(c), true)
c.JSON(200, gin.H{"ip": c.ClientIP()})
})
s := httptest.NewTLSServer(r)
defer s.Close()
client := s.Client()
for _, tc := range []struct {
origin string
status int
}{{s.URL, 200}, {"https://foreign.invalid", 403}, {strings.Replace(s.URL, "https:", "http:", 1), 403}} {
q, _ := http.NewRequest("POST", s.URL+"/write", strings.NewReader("{}"))
q.Header.Set("Origin", tc.origin)
q.Header.Set("X-Forwarded-For", "198.51.100.1")
q.Header.Set("X-Forwarded-Proto", "https")
resp, err := client.Do(q)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != tc.status {
t.Fatal(resp.StatusCode)
}
if tc.status == 200 {
cookies := resp.Cookies()
if len(cookies) != 1 || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode {
t.Fatal("unsafe cookie")
}
if strings.Contains(string(body), "198.51.100.1") {
t.Fatal("untrusted forwarded IP accepted")
}
}
}
}