feat: retain encrypted instance credentials and reissue v2 certificates
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -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")
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
|
||||
82
backend/internal/httpapi/instance_credentials.go
Normal file
82
backend/internal/httpapi/instance_credentials.go
Normal file
@@ -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}})
|
||||
}
|
||||
118
backend/internal/httpapi/instance_credentials_test.go
Normal file
118
backend/internal/httpapi/instance_credentials_test.go
Normal file
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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":"实例激活密钥"}
|
||||
|
||||
@@ -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。
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user