From 9ba8053b5b384e477681e223d001135c8d5f22bf Mon Sep 17 00:00:00 2001 From: xiewenjun <88080888@163.com> Date: Mon, 12 Oct 2026 11:41:02 +0800 Subject: [PATCH] feat: retain encrypted instance credentials and reissue v2 certificates Co-Authored-By: Craft Agent --- .env.example | 3 + backend/cmd/server/main.go | 2 +- backend/internal/config/config.go | 27 ++-- backend/internal/config/config_test.go | 22 ++++ backend/internal/httpapi/activation.go | 56 ++++++++- .../httpapi/activation_integration_test.go | 93 ++++++++++++++ backend/internal/httpapi/business.go | 16 ++- .../internal/httpapi/instance_credentials.go | 82 ++++++++++++ .../httpapi/instance_credentials_test.go | 118 ++++++++++++++++++ .../httpapi/integration_assets/protocol.md | 4 +- backend/internal/httpapi/integration_kit.go | 2 +- backend/internal/httpapi/readiness.go | 2 +- .../000011_instance_credentials.down.sql | 1 + .../000011_instance_credentials.up.sql | 1 + backend/migrations/README.md | 2 + docs/admin-modules.md | 6 + docs/client-integration-center.md | 2 +- frontend/src/api.ts | 5 +- .../src/views/InstanceProvisionPanel.test.ts | 11 +- frontend/src/views/InstanceProvisionPanel.vue | 31 +++-- frontend/src/views/Overview.vue | 2 +- 21 files changed, 449 insertions(+), 39 deletions(-) create mode 100644 backend/internal/httpapi/instance_credentials.go create mode 100644 backend/internal/httpapi/instance_credentials_test.go create mode 100644 backend/migrations/000011_instance_credentials.down.sql create mode 100644 backend/migrations/000011_instance_credentials.up.sql diff --git a/.env.example b/.env.example index 8ecb8f2..73db50e 100644 --- a/.env.example +++ b/.env.example @@ -35,3 +35,6 @@ PACKAGE_STORAGE_ROOT= # Compose external path variables (not secret values): MYSQL_APP_SECRET_FILE, # MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST. # See docs/deployment-delivery.md for outstanding TLS/cookie/restore blockers. + +# Optional independent 32-byte raw AES-GCM key; absolute path, secure backup. +LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE= diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index a56f269..cb1e0d1 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -48,7 +48,7 @@ func run() error { if err != nil { return err } - httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring) + httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring, cfg.CredentialEncryptionKey) } // Readiness is registered only on the loopback operations listener. if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil { diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 52d3c4e..ba962af 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -11,14 +11,15 @@ import ( ) type Config struct { - HTTPAddr string - TrustedProxies []string - ReadHeaderTimeout time.Duration - ReadTimeout time.Duration - WriteTimeout time.Duration - IdleTimeout time.Duration - ShutdownTimeout time.Duration - SigningPrivateKeyPEM string + HTTPAddr string + TrustedProxies []string + ReadHeaderTimeout time.Duration + ReadTimeout time.Duration + WriteTimeout time.Duration + IdleTimeout time.Duration + ShutdownTimeout time.Duration + SigningPrivateKeyPEM string + CredentialEncryptionKey []byte } func Load(getenv func(string) string) (Config, error) { @@ -85,6 +86,16 @@ func Load(getenv func(string) string) (Config, error) { } c.SigningPrivateKeyPEM = string(data) } + if path := getenv("LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE"); path != "" { + if !filepath.IsAbs(path) { + return Config{}, fmt.Errorf("credential encryption key path must be absolute") + } + data, err := os.ReadFile(path) + if err != nil || len(data) != 32 { + return Config{}, fmt.Errorf("credential encryption key must be exactly 32 raw bytes") + } + c.CredentialEncryptionKey = data + } if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" { if !filepath.IsAbs(root) { return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute") diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index e62aab2..364d4e7 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -62,3 +62,25 @@ func TestLoadRejectsInvalid(t *testing.T) { }) } } + +func TestCredentialKeyFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "credentials.key") + for _, size := range []int{31, 32, 33} { + if err := os.WriteFile(path, make([]byte, size), 0600); err != nil { + t.Fatal(err) + } + c, err := Load(func(name string) string { + if name == "LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE" { + return path + } + return "" + }) + if size == 32 { + if err != nil || len(c.CredentialEncryptionKey) != 32 { + t.Fatal("valid key rejected") + } + } else if err == nil { + t.Fatal("invalid length accepted") + } + } +} diff --git a/backend/internal/httpapi/activation.go b/backend/internal/httpapi/activation.go index 5b9a911..56b0e38 100644 --- a/backend/internal/httpapi/activation.go +++ b/backend/internal/httpapi/activation.go @@ -20,7 +20,21 @@ import ( "github.com/gin-gonic/gin" ) +func instanceOnlineState(last *time.Time, now time.Time) string { + if last == nil { + return "never_seen" + } + if last.After(now) { + return "unknown" + } + if now.Sub(*last) <= 3*time.Minute { + return "online" + } + return "offline" +} + type instanceRecord struct { + OnlineState string `json:"online_state"` ID uint64 `json:"id"` InstanceID string `json:"instance_id"` LicenseID uint64 `json:"license_id"` @@ -98,6 +112,14 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) { } secret := base64.RawURLEncoding.EncodeToString(secretBytes) hash := sha256.Sum256(secretBytes) + var encrypted []byte + if len(a.credentialEncryptionKey) > 0 { + encrypted, err = sealInstanceSecret(a.credentialEncryptionKey, instanceID, secret) + if err != nil { + apiError(c, 503, "credentials_unavailable", "凭据加密不可用") + return + } + } tx, err := a.db.BeginTx(c, nil) if err != nil { apiError(c, 500, "internal_error", "服务暂时不可用") @@ -126,7 +148,7 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) { 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) + res, err := tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by,secret_encrypted) VALUES(?,?,?,?,?,?,?)", instanceID, licenseID, customerID, productID, hash[:], actor, encrypted) if err != nil { apiError(c, 409, "instance_conflict", "实例创建失败") return @@ -143,7 +165,7 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) { return } c.Header("Cache-Control", "no-store") - c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "secret_expires": "one-time"}) + c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "credentials_retained": len(encrypted) > 0}) } func (a *BusinessAPI) listInstances(c *gin.Context) { @@ -165,12 +187,14 @@ func (a *BusinessAPI) listInstances(c *gin.Context) { apiError(c, 500, "internal_error", "服务暂时不可用") return } + x.OnlineState = instanceOnlineState(x.LastSeenAt, time.Now().UTC()) out = append(out, x) } c.JSON(200, gin.H{"data": out}) } func (a *BusinessAPI) activateInstance(c *gin.Context) { + c.Header("Cache-Control", "no-store") if a.signingPrivateKeyPEM == "" { apiError(c, 503, "signing_unavailable", "签名密钥未配置") return @@ -254,10 +278,24 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) { apiError(c, 403, "forbidden", "实例secret无效") return } - if inst.Status == "activated" { + reissuing := inst.Status == "activated" && a.keyring != nil + if inst.Status == "activated" && !reissuing { apiError(c, 409, "invalid_state", "实例已经激活") return } + if inst.Status != "provisioned" && !reissuing { + apiError(c, 409, "invalid_state", "实例状态不允许签发") + return + } + var freeze string + if err = tx.QueryRowContext(c, "SELECT freeze_state FROM license_instances WHERE id=?", inst.ID).Scan(&freeze); err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if freeze != "none" { + apiError(c, 409, "invalid_state", "实例已冻结") + return + } var licenseStatus, customerStatus string var productActive bool var licenseCustomer, licenseProduct uint64 @@ -315,7 +353,7 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) { } 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 { + if _, err = tx.ExecContext(c, "UPDATE license_instances SET status='activated',activated_at=COALESCE(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 } @@ -326,7 +364,11 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) { 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 { + action := "instance.activated" + if reissuing { + action = "instance.certificate.reissued" + } + if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'license_instance',?,?)", actor, action, inst.ID, details); err != nil { apiError(c, 500, "internal_error", "服务暂时不可用") return } @@ -334,6 +376,10 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) { apiError(c, 500, "internal_error", "服务暂时不可用") return } + if reissuing { + c.JSON(200, response) + return + } c.JSON(201, response) } diff --git a/backend/internal/httpapi/activation_integration_test.go b/backend/internal/httpapi/activation_integration_test.go index a69cd5d..0ec26b6 100644 --- a/backend/internal/httpapi/activation_integration_test.go +++ b/backend/internal/httpapi/activation_integration_test.go @@ -4,8 +4,10 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "crypto/sha256" "crypto/x509" "database/sql" + "encoding/base64" "encoding/json" "encoding/pem" "fmt" @@ -15,6 +17,7 @@ import ( "strings" "sync" "testing" + "time" ) func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) { @@ -123,6 +126,96 @@ func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) { 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("v2-reissue", func(t *testing.T) { + publicDER, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) + ring := &Keyring{Current: "production-test", Keys: []VerificationKey{{KeyID: "production-test", PublicKeyPEM: string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER}))}}} + r2 := NewRouter() + RegisterBusinessWithKeyring(r2, db, string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})), ring) + req := func(b, idem string) *httptest.ResponseRecorder { + q := httptest.NewRequest("POST", path, strings.NewReader(b)) + q.Header.Set("Content-Type", "application/json") + q.Header.Set("Idempotency-Key", idem) + w := httptest.NewRecorder() + r2.ServeHTTP(w, q) + return w + } + var activated time.Time + db.QueryRow("SELECT activated_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&activated) + if w := req(string(badBytes), "v2-invalid"); w.Code != 403 { + t.Fatalf("bad credential=%d", w.Code) + } + db.Exec("UPDATE license_instances SET freeze_state='frozen' WHERE instance_id=?", instanceID) + if w := req(body, "v2-frozen"); w.Code != 409 { + t.Fatalf("frozen=%d", w.Code) + } + db.Exec("UPDATE license_instances SET freeze_state='none' WHERE instance_id=?", instanceID) + db.Exec("UPDATE licenses SET status='revoked' WHERE id=?", licenseID) + if w := req(body, "v2-revoked"); w.Code != 409 { + t.Fatalf("revoked=%d", w.Code) + } + db.Exec("UPDATE licenses SET status='active' WHERE id=?", licenseID) + 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 <- req(body, "v2-upgrade") }() + } + wg.Wait() + close(results) + var envelope []byte + for w := range results { + if w.Code != 200 { + t.Fatalf("reissue=%d %s", w.Code, w.Body.String()) + } + if envelope != nil && string(envelope) != w.Body.String() { + t.Fatal("idempotent responses differ") + } + envelope = w.Body.Bytes() + } + var response struct { + Data struct { + Certificate struct { + Payload struct { + Version string `json:"version"` + KeyID string `json:"key_id"` + Instance string `json:"instance_id"` + Starts time.Time `json:"starts_at"` + Expires time.Time `json:"expires_at"` + } + Signature string + } + } + } + if err := json.Unmarshal(envelope, &response); err != nil { + t.Fatal(err) + } + cert := response.Data.Certificate + if cert.Payload.Version != "license-v2" || cert.Payload.KeyID != ring.Current || cert.Payload.Instance != instanceID { + t.Fatal("v2 binding missing") + } + var customer, product uint64 + db.QueryRow("SELECT customer_id,product_id FROM licenses WHERE id=?", licenseID).Scan(&customer, &product) + canonical := canonicalCertificatePayload("license-v2", instanceID, licenseID, customer, product, cert.Payload.Starts, cert.Payload.Expires) + "\nkey_id=" + ring.Current + digest := sha256.Sum256([]byte(canonical)) + signature, _ := base64.RawStdEncoding.DecodeString(cert.Signature) + if !ecdsa.VerifyASN1(&key.PublicKey, digest[:], signature) { + t.Fatal("v2 signature invalid") + } + var after time.Time + db.QueryRow("SELECT activated_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&after) + if !activated.Equal(after) { + t.Fatal("activation timestamp changed") + } + var count int + db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.certificate.reissued'").Scan(&count) + if count != 1 { + t.Fatal("reissue audit not atomic") + } + if w := req(body, "activate"); w.Code != 200 || !strings.Contains(w.Body.String(), "license-v1") { + t.Fatal("legacy replay changed") + } + }) t.Run("heartbeat", func(t *testing.T) { testHeartbeatMySQL(t, db, r, cookie, instanceID, secret, licenseID, &key.PublicKey) }) diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go index 3c7eac4..5f8592a 100644 --- a/backend/internal/httpapi/business.go +++ b/backend/internal/httpapi/business.go @@ -16,9 +16,10 @@ import ( ) type BusinessAPI struct { - db *sql.DB - signingPrivateKeyPEM string - keyring *Keyring + db *sql.DB + signingPrivateKeyPEM string + keyring *Keyring + credentialEncryptionKey []byte } func secureSessionCookie(c *gin.Context) bool { @@ -35,11 +36,15 @@ func RegisterBusiness(r *gin.Engine, db *sql.DB, signingPrivateKeyPEM ...string) } registerBusinessRoutes(r, a) } -func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring) { +func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring, credentialKey ...[]byte) { if db == nil { return } - registerBusinessRoutes(r, &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring}) + a := &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring} + if len(credentialKey) > 0 { + a.credentialEncryptionKey = credentialKey[0] + } + registerBusinessRoutes(r, a) } func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { api := r.Group("/api/v1") @@ -87,6 +92,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { secured.GET("/licenses/:id", a.getLicense) secured.GET("/licenses/:id/instances", a.listInstances) secured.POST("/licenses/:id/instances", a.provisionInstance) + secured.GET("/licenses/:id/instance-credentials", a.instanceCredentials) secured.POST("/products/:id/releases", a.createRelease) secured.GET("/products/:id/releases", a.listReleases) api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease) diff --git a/backend/internal/httpapi/instance_credentials.go b/backend/internal/httpapi/instance_credentials.go new file mode 100644 index 0000000..efdf4ad --- /dev/null +++ b/backend/internal/httpapi/instance_credentials.go @@ -0,0 +1,82 @@ +package httpapi + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "database/sql" + "errors" + "strconv" + + "github.com/gin-gonic/gin" +) + +func sealInstanceSecret(key []byte, instanceID, secret string) ([]byte, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err = rand.Read(nonce); err != nil { + return nil, err + } + return gcm.Seal(nonce, nonce, []byte(secret), []byte("instance-secret-v1:"+instanceID)), nil +} +func openInstanceSecret(key []byte, instanceID string, data []byte) (string, error) { + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + if len(data) < gcm.NonceSize() { + return "", errors.New("invalid ciphertext") + } + plain, err := gcm.Open(nil, data[:gcm.NonceSize()], data[gcm.NonceSize():], []byte("instance-secret-v1:"+instanceID)) + return string(plain), err +} +func (a *BusinessAPI) instanceCredentials(c *gin.Context) { + c.Header("Cache-Control", "no-store") + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + apiError(c, 400, "invalid_request", "授权 ID 无效") + return + } + var instanceID, licenseKey string + var encrypted []byte + err = a.db.QueryRowContext(c, `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, id).Scan(&instanceID, &licenseKey, &encrypted) + if errors.Is(err, sql.ErrNoRows) { + apiError(c, 404, "not_found", "实例不存在") + return + } + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + if len(encrypted) == 0 { + apiError(c, 409, "credentials_not_retained", "旧实例仅保存密钥哈希,无法恢复激活凭据;请使用原始交付文件或重新签发授权") + return + } + if len(a.credentialEncryptionKey) == 0 { + apiError(c, 503, "credentials_unavailable", "未配置凭据加密密钥") + return + } + secret, err := openInstanceSecret(a.credentialEncryptionKey, instanceID, encrypted) + if err != nil { + apiError(c, 503, "credentials_unavailable", "凭据解密不可用,请检查加密密钥配置") + return + } + // No credential material in audit details. Do not disclose before audit succeeds. + _, err = a.db.ExecContext(c, `INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.credentials.viewed','license',?,?)`, c.MustGet("admin_id"), id, `{}`) + if err != nil { + apiError(c, 500, "internal_error", "服务暂时不可用") + return + } + c.JSON(200, gin.H{"data": gin.H{"instance_id": instanceID, "license_key": licenseKey, "secret": secret}}) +} diff --git a/backend/internal/httpapi/instance_credentials_test.go b/backend/internal/httpapi/instance_credentials_test.go new file mode 100644 index 0000000..4ab52f6 --- /dev/null +++ b/backend/internal/httpapi/instance_credentials_test.go @@ -0,0 +1,118 @@ +package httpapi + +import ( + "bytes" + "context" + "database/sql" + "database/sql/driver" + "errors" + "github.com/gin-gonic/gin" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestInstanceSecretEncryption(t *testing.T) { + key := bytes.Repeat([]byte{7}, 32) + data, err := sealInstanceSecret(key, "instance-a", "test-secret") + if err != nil || bytes.Contains(data, []byte("test-secret")) { + t.Fatal("encryption failed") + } + plain, err := openInstanceSecret(key, "instance-a", data) + if err != nil || plain != "test-secret" { + t.Fatal("roundtrip failed") + } + if _, err = openInstanceSecret(key, "instance-b", data); err == nil { + t.Fatal("cross-instance replay accepted") + } + if _, err = openInstanceSecret(bytes.Repeat([]byte{8}, 32), "instance-a", data); err == nil { + t.Fatal("wrong key accepted") + } + data[len(data)-1] ^= 1 + if _, err = openInstanceSecret(key, "instance-a", data); err == nil { + t.Fatal("tampering accepted") + } + if _, err = openInstanceSecret(key, "instance-a", nil); err == nil { + t.Fatal("empty accepted") + } +} +func TestInstanceCredentialsLegacy(t *testing.T) { + db, _ := newDashboardTestDB(t, []dashboardQuery{{sql: `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, args: []any{int64(2)}, rows: [][]driver.Value{{"instance-a", "test-license", nil}}}}) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/", nil) + c.Params = gin.Params{{Key: "id", Value: "2"}} + (&BusinessAPI{db: db}).instanceCredentials(c) + if w.Code != 409 || !strings.Contains(w.Body.String(), "credentials_not_retained") || w.Header().Get("Cache-Control") != "no-store" || strings.Contains(w.Body.String(), "test-license") { + t.Fatal("legacy credential disclosure") + } +} +func TestInstanceOnlineState(t *testing.T) { + now := time.Now().UTC() + for _, tc := range []struct { + age time.Duration + want string + }{{0, "online"}, {3 * time.Minute, "online"}, {3*time.Minute + time.Nanosecond, "offline"}, {-time.Second, "unknown"}} { + last := now.Add(-tc.age) + if instanceOnlineState(&last, now) != tc.want { + t.Fatal(tc.want) + } + } + if instanceOnlineState(nil, now) != "never_seen" { + t.Fatal("never seen") + } +} +func TestInstanceCredentialsRequiresSession(t *testing.T) { + db, _ := newDashboardTestDB(t, nil) + r := gin.New() + RegisterBusiness(r, db) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/licenses/2/instance-credentials", nil)) + if w.Code != 401 { + t.Fatal("unauthenticated access") + } +} + +type credentialsAuditDB struct { + *dashboardDB + fail bool + audited bool +} + +func (d *credentialsAuditDB) Connect(context.Context) (driver.Conn, error) { return d, nil } +func (d *credentialsAuditDB) ExecContext(_ context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + if !strings.Contains(query, "instance.credentials.viewed") || len(args) != 3 || args[2].Value != "{}" { + return nil, errors.New("unexpected audit") + } + d.audited = true + if d.fail { + return nil, errors.New("audit unavailable") + } + return driver.RowsAffected(1), nil +} +func TestInstanceCredentialsAuditBeforeDisclosure(t *testing.T) { + key := bytes.Repeat([]byte{1}, 32) + encrypted, _ := sealInstanceSecret(key, "instance-a", "test-secret") + for _, fail := range []bool{false, true} { + stub := &credentialsAuditDB{dashboardDB: &dashboardDB{t: t, queries: []dashboardQuery{{sql: `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, args: []any{int64(2)}, rows: [][]driver.Value{{"instance-a", "test-license", encrypted}}}}}, fail: fail} + db := sql.OpenDB(stub) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/", nil) + c.Params = gin.Params{{Key: "id", Value: "2"}} + c.Set("admin_id", uint64(1)) + (&BusinessAPI{db: db, credentialEncryptionKey: key}).instanceCredentials(c) + db.Close() + if !stub.audited { + t.Fatal("missing audit") + } + if fail { + if w.Code != 500 || strings.Contains(w.Body.String(), "test-secret") { + t.Fatal("disclosed before audit") + } + } else if w.Code != 200 || !strings.Contains(w.Body.String(), "test-secret") || w.Header().Get("Cache-Control") != "no-store" { + t.Fatal("read failed") + } + } +} diff --git a/backend/internal/httpapi/integration_assets/protocol.md b/backend/internal/httpapi/integration_assets/protocol.md index 0ce2ea7..2d329c2 100644 --- a/backend/internal/httpapi/integration_assets/protocol.md +++ b/backend/internal/httpapi/integration_assets/protocol.md @@ -4,7 +4,7 @@ ## 交付与激活 -管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和仅首次展示的 secret。secret 无法从后台恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。 +管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和secret。配置加密留存后管理员可重复查看并导出;旧实例仅存哈希时无法恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。 管理台操作:创建客户和产品 → 签发授权 → 在该授权行点击“实例” → “创建实例并获取激活凭据” → 安全保存并交付三个字段。当前每条授权只允许一个实例。 @@ -14,7 +14,7 @@ ### 授权文件导入(交付格式 v1) -创建实例成功后,管理员可在当前凭据窗口点击“导出授权文件”,下载 UTF-8 JSON(文件名 license-{instance_id}.license.json)。仅首次展示期间可导出;已有实例无法恢复 secret 或重新导出。文件包含明文实例凭据,须经安全渠道交付,导入后移入受保护存储并妥善处理原下载文件。 +创建实例成功后,管理员可在当前凭据窗口点击“导出授权文件”,下载 UTF-8 JSON(文件名 license-{instance_id}.license.json)。加密留存的实例可由管理员重复查看并导出;旧实例或未配置留存时仅首次返回。文件包含明文实例凭据,须经安全渠道交付,导入后移入受保护存储并妥善处理原下载文件。 ```json {"format":"yhy-license-activation","version":1,"api_base_url":"https://license.yihuiyong.cn","instance_id":"实例UUID","license_key":"授权密钥","secret":"实例激活密钥"} diff --git a/backend/internal/httpapi/integration_kit.go b/backend/internal/httpapi/integration_kit.go index 1a721d2..bfea926 100644 --- a/backend/internal/httpapi/integration_kit.go +++ b/backend/internal/httpapi/integration_kit.go @@ -118,7 +118,7 @@ func integrationPrompt(language, mode string) string { 默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。 -首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 仅首次展示但持续用于心跳和下载。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,丢失 secret 没有找回接口。 +首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 持续用于心跳和下载;配置加密留存后可重复查看,旧实例无法从哈希恢复。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,旧实例丢失 secret 无法恢复。 实现激活 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。 diff --git a/backend/internal/httpapi/readiness.go b/backend/internal/httpapi/readiness.go index 1701f59..bf7880c 100644 --- a/backend/internal/httpapi/readiness.go +++ b/backend/internal/httpapi/readiness.go @@ -9,7 +9,7 @@ import ( "github.com/gin-gonic/gin" ) -const RequiredSchemaVersion = 10 +const RequiredSchemaVersion = 11 func RegisterReadiness(r *gin.Engine, db *sql.DB) { r.GET("/api/v1/health/ready", func(c *gin.Context) { diff --git a/backend/migrations/000011_instance_credentials.down.sql b/backend/migrations/000011_instance_credentials.down.sql new file mode 100644 index 0000000..16cfb80 --- /dev/null +++ b/backend/migrations/000011_instance_credentials.down.sql @@ -0,0 +1 @@ +ALTER TABLE license_instances DROP COLUMN secret_encrypted; diff --git a/backend/migrations/000011_instance_credentials.up.sql b/backend/migrations/000011_instance_credentials.up.sql new file mode 100644 index 0000000..0cd3fc4 --- /dev/null +++ b/backend/migrations/000011_instance_credentials.up.sql @@ -0,0 +1 @@ +ALTER TABLE license_instances ADD COLUMN secret_encrypted VARBINARY(256) NULL; diff --git a/backend/migrations/README.md b/backend/migrations/README.md index f6dec3f..010bd3d 100644 --- a/backend/migrations/README.md +++ b/backend/migrations/README.md @@ -27,3 +27,5 @@ go run ./cmd/migrate -dsn "$MIGRATION_DSN" -version 12 force On 2026-09-30, a dedicated MySQL 8.0 container was used to verify an empty database up/down cycle and an intentionally invalid migration: failure left version 2 dirty, normal `up` was blocked, and explicit force to the last known-good version restored clean metadata. The probe migrations and container were removed after the test. Version 3 adds transactional license operation idempotency records for revoke/renew; it must be applied explicitly after version 2. No placeholder SQL is considered an executed business migration; formal entitlement schemas and CI database integration remain T04/T03 acceptance work. Schema 10 adds unique administrator usernames. Existing accounts become `admin-{id}` and retain their passwords; login requests must send `username` instead of `email`. Run migrations before starting the current server or `admin-init`. + +Schema 11 adds nullable `license_instances.secret_encrypted`. Apply before API startup. Configure `LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE` as an absolute path to an independent 32-byte raw random key. Mount read-only, back up securely with the database, and never commit it. Missing key preserves first-return-only creation. Existing hashes cannot recover secrets. Losing/changing the key makes ciphertext unreadable; rotation is not implemented. Down migration deletes retained ciphertext and requires backup and confirmation. diff --git a/docs/admin-modules.md b/docs/admin-modules.md index 7335b08..cbfb00b 100644 --- a/docs/admin-modules.md +++ b/docs/admin-modules.md @@ -54,3 +54,9 @@ go run ./cmd/admin-init -username admin -email admin@example.test -password 'YOU ``` 初始化命令按邮箱识别已有账户,用户名冲突将报错,不会重置另一个账户。重新初始化会撤销该账户的旧会话。已有部署只执行迁移即可,不需要重置密码。原始业务数据库没有在本次开发中迁移;本地隔离数据库的既有账号为 `admin-1`,密码保持 `123456`。 + +## 客户端凭据与在线状态 + +Schema 11 后,配置 LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE(独立 32 字节原始随机密钥,只读挂载、权限 0600)可加密保存新实例 secret。管理员可重复查看及导出 JSON,读取记录 instance.credentials.viewed 审计事件并返回 no-store;凭据只在当前视图,不写浏览器持久存储。旧实例无法恢复,未配置时仍仅首次返回。加密密钥须安全备份,不可随意替换,不提供自动轮换。 + +激活状态和连接状态分别展示;最近 3 分钟收到心跳为在线,超时为离线,无心跳为从未上报,未来时间为未知。点击刷新更新状态,离线不表示授权失效。 diff --git a/docs/client-integration-center.md b/docs/client-integration-center.md index bcb8eb9..8a74fd4 100644 --- a/docs/client-integration-center.md +++ b/docs/client-integration-center.md @@ -35,7 +35,7 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权 ## 首次激活交付与客户端字段 -管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。secret 只在创建响应及当前窗口展示,数据库保存哈希,关闭后无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。 +管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。配置凭据加密密钥后,新实例同时保存密文与验证哈希,管理员可重复查看和下载 JSON;旧实例或未配置时仅存哈希,无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。 ## 授权文件导出与导入 diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 0edd9dd..f5434e1 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -22,11 +22,12 @@ export async function deleteProduct(id:number) { return api.delete(`/products/${ export type License = { id:number; license_key:string; customer_id:number; customer_name:string; product_id:number; product_name:string; product_code:string; status:'active'|'scheduled'|'expired'|'revoked'|string; starts_at:string; expires_at:string; created_at:string } export async function listLicenses(params?:Record) { return api.get<{data:License[];meta:{page:number;page_size:number;total:number}}>('/licenses',{params}) } export async function issueLicense(value:{customer_id:number;product_id:number;starts_at:string;expires_at:string}, idempotencyKey:string) { return api.post('/licenses',value,{headers:{'Idempotency-Key':idempotencyKey}}) } -export type LicenseInstance = { id:number; instance_id:string; license_id:number; customer_id:number; product_id:number; status:string; activated_at?:string; certificate_version?:string; created_at:string; last_seen_at?:string; lease_expires_at?:string; freeze_state:string; observed_state:string; entitlement_state:string } +export type LicenseInstance = { online_state?:'online'|'offline'|'never_seen'|'unknown'; id:number; instance_id:string; license_id:number; customer_id:number; product_id:number; status:string; activated_at?:string; certificate_version?:string; created_at:string; last_seen_at?:string; lease_expires_at?:string; freeze_state:string; observed_state:string; entitlement_state:string } export async function setInstanceFrozen(instanceID:string,frozen:boolean,key:string) { return api.post(`/instances/${instanceID}/freeze`,{frozen},{headers:{'Idempotency-Key':key}}) } export async function listLicenseInstances(id:number) { return api.get<{data:LicenseInstance[]}>(`/licenses/${id}/instances`) } export async function getLicense(id:number) { return api.get<{data:License}>(`/licenses/${id}`) } export async function revokeLicense(id:number,idempotencyKey:string) { return api.post(`/licenses/${id}/revoke`,{}, {headers:{'Idempotency-Key':idempotencyKey}}) } export async function renewLicense(id:number,expires_at:string,idempotencyKey:string) { return api.post(`/licenses/${id}/renew`,{expires_at},{headers:{'Idempotency-Key':idempotencyKey}}) } -export async function provisionLicenseInstance(id:number) { return api.post<{data:{id:number;instance_id:string;license_id:number;status:string;secret:string}}>(`/licenses/${id}/instances`,{}) } +export async function getInstanceCredentials(id:number) { return api.get<{data:{instance_id:string;license_key:string;secret:string}}>(`/licenses/${id}/instance-credentials`) } +export async function provisionLicenseInstance(id:number) { return api.post<{data:{id:number;instance_id:string;license_id:number;status:string;secret:string};credentials_retained:boolean}>(`/licenses/${id}/instances`,{}) } diff --git a/frontend/src/views/InstanceProvisionPanel.test.ts b/frontend/src/views/InstanceProvisionPanel.test.ts index ffacc17..ae01e33 100644 --- a/frontend/src/views/InstanceProvisionPanel.test.ts +++ b/frontend/src/views/InstanceProvisionPanel.test.ts @@ -1,7 +1,7 @@ import { beforeEach, expect, it, vi } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' import ElementPlus, { ElMessageBox } from 'element-plus' -const api=vi.hoisted(()=>({getLicense:vi.fn(),provisionLicenseInstance:vi.fn()})) +const api=vi.hoisted(()=>({getLicense:vi.fn(),provisionLicenseInstance:vi.fn(),getInstanceCredentials:vi.fn()})) vi.mock('../api',()=>api) import Panel from './InstanceProvisionPanel.vue' beforeEach(()=>{vi.restoreAllMocks();vi.resetAllMocks();vi.spyOn(ElMessageBox,'confirm').mockResolvedValue('confirm' as Awaited>);api.getLicense.mockResolvedValue({data:{data:{license_key:'test-license'}}});api.provisionLicenseInstance.mockResolvedValue({data:{data:{instance_id:'test-instance',secret:'test-secret'}}})}) @@ -10,9 +10,14 @@ it('creates and displays first-return credentials, without another creation entr await w.get('button').trigger('click');await flushPromises() expect(api.provisionLicenseInstance).toHaveBeenCalledWith(7) expect(w.text()).toContain('test-license');expect(w.text()).toContain('test-instance');expect(w.text()).toContain('test-secret');expect(w.emitted('created')).toHaveLength(1) - expect(w.findAll('button').map(b=>b.text())).toEqual(['导出授权文件']);w.unmount() + expect(w.findAll('button').map(b=>b.text())).toEqual(['导出授权文件','隐藏凭据']);w.unmount() const reopened=mount(Panel,{props:{licenseId:7,hasInstance:true,ready:true},global:{plugins:[ElementPlus]}}) - expect(reopened.get('button').attributes('disabled')).toBeDefined();expect(reopened.text()).not.toContain('test-secret');reopened.unmount() + expect(reopened.get('button').attributes('disabled')).toBeUndefined();expect(reopened.text()).not.toContain('test-secret'); + api.getInstanceCredentials.mockResolvedValue({data:{data:{instance_id:'saved-instance',license_key:'saved-license',secret:'saved-secret'}}}) + await reopened.get('button').trigger('click');await flushPromises() + expect(api.getInstanceCredentials).toHaveBeenCalledWith(7);expect(reopened.text()).toContain('saved-secret') + await reopened.findAll('button').find(b=>b.text()==='隐藏凭据')!.trigger('click') + expect(reopened.text()).not.toContain('saved-secret');reopened.unmount() }) it('reports uncertain creation without automatically retrying',async()=>{ api.provisionLicenseInstance.mockRejectedValue(new Error('请求超时')) diff --git a/frontend/src/views/InstanceProvisionPanel.vue b/frontend/src/views/InstanceProvisionPanel.vue index 86acba4..9298f0c 100644 --- a/frontend/src/views/InstanceProvisionPanel.vue +++ b/frontend/src/views/InstanceProvisionPanel.vue @@ -1,7 +1,7 @@ @@ -31,18 +42,20 @@ async function create() {

客户端激活凭据

授权码就是授权密钥(license_key)。实例 ID 和激活密钥(secret)由平台创建实例时生成,每条授权仅绑定一个实例。

- 创建实例并获取激活凭据 -

已有实例的激活密钥无法再次查看。若未安全保存,请由管理员冻结旧实例、撤销旧授权,再签发新授权并交付新实例凭据;当前不支持密钥找回或轮换。

+ 创建实例并获取激活凭据 + 查看客户端激活凭据 +

已加密保留的凭据可重复查看及下载。旧实例仅存哈希,无法恢复;此类实例需使用原始交付文件,或冻结旧实例、撤销旧授权后重新签发。

diff --git a/frontend/src/views/Overview.vue b/frontend/src/views/Overview.vue index b1d3dfe..1cc2ff2 100644 --- a/frontend/src/views/Overview.vue +++ b/frontend/src/views/Overview.vue @@ -121,7 +121,7 @@ onMounted(() => { checkConnection(); checkSession() })

期限授权

共 {{ licenseTotal }} 条,签发后通过“实例”创建并交付客户端激活凭据

签发授权
-
License 密钥
{{detail.license_key}}
客户
{{detail.customer_name}}
产品
{{detail.product_name}}
类型
期限授权
开始时间
{{formatDateTime(detail.starts_at)}}
到期时间
{{formatDateTime(detail.expires_at)}}
状态
{{detail.status}}
查看实例 / 冻结管理
刷新状态

{{ instanceError }}

+
License 密钥
{{detail.license_key}}
客户
{{detail.customer_name}}
产品
{{detail.product_name}}
类型
期限授权
开始时间
{{formatDateTime(detail.starts_at)}}
到期时间
{{formatDateTime(detail.expires_at)}}
状态
{{detail.status}}
查看实例 / 冻结管理
刷新状态

在线表示服务端最近 3 分钟收到心跳;超时显示离线,从未心跳显示从未上报。离线不代表授权失效;状态在刷新时更新。

{{ instanceError }}