feat: delete never-activated licenses and bundle deployment verification keys
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -94,6 +94,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
secured.GET("/licenses/:id/instances", a.listInstances)
|
||||
secured.POST("/licenses/:id/instances", a.provisionInstance)
|
||||
secured.GET("/licenses/:id/instance-credentials", a.instanceCredentials)
|
||||
secured.DELETE("/licenses/:id", a.deleteLicense)
|
||||
secured.POST("/products/:id/releases", a.createRelease)
|
||||
secured.GET("/products/:id/releases", a.listReleases)
|
||||
api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease)
|
||||
|
||||
@@ -71,10 +71,16 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
kit := buildIntegrationKit(language, mode)
|
||||
keys, err := a.deploymentVerificationKeys()
|
||||
if err != nil {
|
||||
apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥")
|
||||
return
|
||||
}
|
||||
files := map[string][]byte{
|
||||
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json,将 prompt.md 提供给实现工程师。upgrade.md 说明当前可用下载能力和自动升级待建设的契约;当前没有客户端版本检查或签名升级清单。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"),
|
||||
"prompt.md": []byte(kit.Prompt),
|
||||
"test-vectors.json": vectors,
|
||||
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json,将 prompt.md 提供给实现工程师。verification-keys.md 包含当前部署验签公钥,经可信渠道核对指纹后预置;test-vectors.json 使用随机测试密钥,绝不能导入生产。upgrade.md 说明当前可用下载能力和自动升级待建设的契约;当前没有客户端版本检查或签名升级清单。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"),
|
||||
"verification-keys.md": []byte(keys),
|
||||
"prompt.md": []byte(kit.Prompt),
|
||||
"test-vectors.json": vectors,
|
||||
}
|
||||
for _, name := range []string{"protocol.md", "upgrade.md", "openapi.json"} {
|
||||
content, err := integrationAsset(name)
|
||||
@@ -86,7 +92,7 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
archive := zip.NewWriter(&buffer)
|
||||
for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "test-vectors.json"} {
|
||||
for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "verification-keys.md", "test-vectors.json"} {
|
||||
file, err := archive.Create(name)
|
||||
if err == nil {
|
||||
_, err = file.Write(files[name])
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -135,15 +138,41 @@ func (a *BusinessAPI) integrationKit(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"data": buildIntegrationKit(language, mode)})
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) deploymentVerificationKeys() (string, error) {
|
||||
if a.keyring == nil {
|
||||
return "", fmt.Errorf("keyring unavailable")
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("## 当前部署验签公钥\n\n以下公钥来自当前服务端已配置的 keyring,不是 test-vectors.json 中的随机测试密钥。请经可信的管理员交付渠道核对公钥指纹后固定到客户端;不得直接信任网络下载或发现接口取得的密钥。轮换时按受控流程更新信任配置。私钥绝不能交付给客户端。\n\n")
|
||||
fmt.Fprintf(&b, "当前签名 key_id:`%s`。所有非撤销密钥均可用于验证有效期内已签发的证书和租约。\n\n", a.keyring.Current)
|
||||
for _, key := range a.keyring.Keys {
|
||||
if key.Revoked {
|
||||
continue
|
||||
}
|
||||
block, _ := pem.Decode([]byte(key.PublicKeyPEM))
|
||||
if block == nil {
|
||||
return "", fmt.Errorf("invalid public key")
|
||||
}
|
||||
digest := sha256.Sum256(block.Bytes)
|
||||
fmt.Fprintf(&b, "### key_id: %s\n\nSPKI SHA-256:`%s`\n\n```pem\n%s\n```\n\n", key.KeyID, hex.EncodeToString(digest[:]), strings.TrimSpace(key.PublicKeyPEM))
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) {
|
||||
language, mode, ok := integrationKitInput(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
kit := buildIntegrationKit(language, mode)
|
||||
keys, err := a.deploymentVerificationKeys()
|
||||
if err != nil {
|
||||
apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥")
|
||||
return
|
||||
}
|
||||
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)
|
||||
fmt.Fprintf(&b, "目标:%s,%s\n\n%s## 工程提示词\n\n%s\n\n## 接口\n\n", kit.LanguageLabel, kit.ModeLabel, keys, kit.Prompt)
|
||||
for _, endpoint := range kit.Endpoints {
|
||||
fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose)
|
||||
}
|
||||
|
||||
@@ -57,10 +57,19 @@ func TestIntegrationInputs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
const public = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----\n"
|
||||
a := &BusinessAPI{keyring: &Keyring{Current: "prod-test", Keys: []VerificationKey{{KeyID: "prod-test", PublicKeyPEM: public}, {KeyID: "retired", PublicKeyPEM: public, Revoked: true}}}}
|
||||
md := httptest.NewRecorder()
|
||||
mc, _ := gin.CreateTestContext(md)
|
||||
mc.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil)
|
||||
a.downloadIntegrationKit(mc)
|
||||
if md.Code != 200 || !strings.Contains(md.Body.String(), public) || !strings.Contains(md.Body.String(), "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562") || strings.Contains(md.Body.String(), "retired") || md.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("markdown lacks trusted deployment key")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil)
|
||||
(&BusinessAPI{}).downloadIntegrationArchive(c)
|
||||
a.downloadIntegrationArchive(c)
|
||||
if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
@@ -68,7 +77,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(archive.File) != 6 {
|
||||
if len(archive.File) != 7 {
|
||||
t.Fatal("missing files")
|
||||
}
|
||||
for _, file := range archive.File {
|
||||
@@ -84,6 +93,9 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
|
||||
if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) {
|
||||
t.Fatal("OpenAPI does not use the default platform address")
|
||||
}
|
||||
if file.Name == "verification-keys.md" && (!strings.Contains(string(content), public) || strings.Contains(string(content), "retired")) {
|
||||
t.Fatal("incorrect deployment key in archive")
|
||||
}
|
||||
if file.Name == "upgrade.md" && !strings.Contains(string(content), "自动升级所需服务端契约") {
|
||||
t.Fatal("missing upgrade plan")
|
||||
}
|
||||
|
||||
86
backend/internal/httpapi/license_delete_test.go
Normal file
86
backend/internal/httpapi/license_delete_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type deleteDB struct {
|
||||
*dashboardDB
|
||||
commands []string
|
||||
failAudit bool
|
||||
}
|
||||
|
||||
func (d *deleteDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
|
||||
func (d *deleteDB) ExecContext(_ context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
|
||||
d.commands = append(d.commands, query)
|
||||
if strings.Contains(query, "INSERT INTO audit_events") {
|
||||
if len(args) != 3 {
|
||||
d.t.Fatal("audit arguments missing")
|
||||
}
|
||||
var details map[string]any
|
||||
if err := json.Unmarshal(args[2].Value.([]byte), &details); err != nil || details["removed_instances"] != float64(1) || details["detached_orders"] != float64(1) {
|
||||
d.t.Fatal("missing deletion audit context", err, details)
|
||||
}
|
||||
if d.failAudit {
|
||||
return nil, errors.New("audit unavailable")
|
||||
}
|
||||
}
|
||||
return driver.RowsAffected(1), nil
|
||||
}
|
||||
|
||||
func TestDeleteLicense(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
activated int64
|
||||
failAudit bool
|
||||
want int
|
||||
}{
|
||||
{"provisioned with order and operations", 0, false, 204},
|
||||
{"activated", 1, false, 409},
|
||||
{"audit failure", 0, true, 500},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
const activationQuery = `SELECT COUNT(*) FROM license_instances i WHERE i.license_id=? AND (i.status='activated' OR i.activated_at IS NOT NULL OR i.certificate_payload IS NOT NULL OR i.certificate_signature IS NOT NULL OR EXISTS (SELECT 1 FROM activation_operations o WHERE o.instance_id=i.id))`
|
||||
queries := []dashboardQuery{
|
||||
{sql: "SELECT status,license_key FROM licenses WHERE id=? FOR UPDATE", args: []any{int64(2)}, rows: [][]driver.Value{{"revoked", "test-key"}}},
|
||||
{sql: activationQuery, args: []any{int64(2)}, rows: [][]driver.Value{{tc.activated}}},
|
||||
}
|
||||
if tc.activated == 0 {
|
||||
queries = append(queries,
|
||||
dashboardQuery{sql: "SELECT COUNT(*) FROM license_instances WHERE license_id=?", args: []any{int64(2)}, rows: [][]driver.Value{{int64(1)}}},
|
||||
dashboardQuery{sql: "SELECT COUNT(*) FROM offline_orders WHERE issued_license_id=?", args: []any{int64(2)}, rows: [][]driver.Value{{int64(1)}}},
|
||||
dashboardQuery{sql: "SELECT COUNT(*) FROM license_operations WHERE license_id=?", args: []any{int64(2)}, rows: [][]driver.Value{{int64(2)}}},
|
||||
)
|
||||
}
|
||||
stub := &deleteDB{dashboardDB: &dashboardDB{t: t, queries: queries}, failAudit: tc.failAudit}
|
||||
db := sql.OpenDB(stub)
|
||||
defer db.Close()
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("DELETE", "/licenses/2", nil)
|
||||
c.Params = gin.Params{{Key: "id", Value: "2"}}
|
||||
c.Set("admin_id", uint64(1))
|
||||
(&BusinessAPI{db: db}).deleteLicense(c)
|
||||
c.Writer.WriteHeaderNow()
|
||||
if w.Code != tc.want || len(stub.queries) != 0 || stub.committed != (tc.want == 204) {
|
||||
t.Fatalf("response=%d body=%s remaining=%d committed=%v", w.Code, w.Body.String(), len(stub.queries), stub.committed)
|
||||
}
|
||||
if tc.want == 204 {
|
||||
if len(stub.commands) != 8 || !strings.Contains(stub.commands[0], "audit_events") || !strings.Contains(stub.commands[1], "UPDATE offline_orders") || !strings.Contains(stub.commands[7], "DELETE FROM licenses") {
|
||||
t.Fatalf("unexpected deletion order: %v", stub.commands)
|
||||
}
|
||||
} else if len(stub.commands) > 1 {
|
||||
t.Fatalf("unexpected cleanup on failure: %v", stub.commands)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,76 @@ func (a *BusinessAPI) issueLicense(c *gin.Context) {
|
||||
c.JSON(201, gin.H{"data": rec, "idempotent_replay": false})
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) deleteLicense(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
apiError(c, 400, "invalid_request", "授权 ID 无效")
|
||||
return
|
||||
}
|
||||
adminID := c.MustGet("admin_id")
|
||||
tx, err := a.db.BeginTx(c, nil)
|
||||
if err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var status, licenseKey string
|
||||
if err = tx.QueryRowContext(c, "SELECT status,license_key FROM licenses WHERE id=? FOR UPDATE", id).Scan(&status, &licenseKey); errors.Is(err, sql.ErrNoRows) {
|
||||
apiError(c, 404, "not_found", "授权不存在")
|
||||
return
|
||||
} else if err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
var activated int
|
||||
if err = tx.QueryRowContext(c, `SELECT COUNT(*) FROM license_instances i WHERE i.license_id=? AND (i.status='activated' OR i.activated_at IS NOT NULL OR i.certificate_payload IS NOT NULL OR i.certificate_signature IS NOT NULL OR EXISTS (SELECT 1 FROM activation_operations o WHERE o.instance_id=i.id))`, id).Scan(&activated); err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
if activated > 0 {
|
||||
apiError(c, 409, "license_activated", "该授权已激活,不能删除,请使用撤销")
|
||||
return
|
||||
}
|
||||
var instances, orders, operations int
|
||||
for _, check := range []struct {
|
||||
query string
|
||||
count *int
|
||||
}{
|
||||
{"SELECT COUNT(*) FROM license_instances WHERE license_id=?", &instances},
|
||||
{"SELECT COUNT(*) FROM offline_orders WHERE issued_license_id=?", &orders},
|
||||
{"SELECT COUNT(*) FROM license_operations WHERE license_id=?", &operations},
|
||||
} {
|
||||
if err = tx.QueryRowContext(c, check.query, id).Scan(check.count); err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
}
|
||||
details, _ := json.Marshal(map[string]any{"license_id": id, "license_key": licenseKey, "status": status, "removed_instances": instances, "detached_orders": orders, "removed_operations": operations})
|
||||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.deleted','license',?,?)", adminID, id, details); err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
for _, query := range []string{
|
||||
"UPDATE offline_orders SET issued_license_id=NULL WHERE issued_license_id=?",
|
||||
"DELETE FROM activation_operations WHERE instance_id IN (SELECT id FROM license_instances WHERE license_id=?)",
|
||||
"DELETE FROM heartbeat_operations WHERE instance_id IN (SELECT id FROM license_instances WHERE license_id=?)",
|
||||
"DELETE FROM instance_state_operations WHERE instance_id IN (SELECT id FROM license_instances WHERE license_id=?)",
|
||||
"DELETE FROM license_instances WHERE license_id=?",
|
||||
"DELETE FROM license_operations WHERE license_id=?",
|
||||
"DELETE FROM licenses WHERE id=?",
|
||||
} {
|
||||
if _, err = tx.ExecContext(c, query, id); err != nil {
|
||||
apiError(c, 500, "internal_error", "删除授权失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||||
return
|
||||
}
|
||||
c.Status(204)
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) getLicense(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
|
||||
Reference in New Issue
Block a user