feat: retain encrypted instance credentials and reissue v2 certificates
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-12 11:41:02 +08:00
parent fad1fba710
commit 9ba8053b5b
21 changed files with 449 additions and 39 deletions

View File

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