package httpapi import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "crypto/x509" "database/sql" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "github.com/gin-gonic/gin" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" ) 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("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) }) }