package httpapi import ( "context" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "errors" "fmt" "github.com/gin-gonic/gin" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/go-sql-driver/mysql" migrate "github.com/golang-migrate/migrate/v4" _ "github.com/golang-migrate/migrate/v4/database/mysql" _ "github.com/golang-migrate/migrate/v4/source/file" "license-platform/backend/internal/payments" ) func paymentIntegrationDSN(t *testing.T) string { t.Helper() if dsn := os.Getenv("TEST_MYSQL_DSN"); dsn != "" { return dsn } if dsn := os.Getenv("MYSQL_TEST_DSN"); dsn != "" { return dsn } t.Skip("TEST_MYSQL_DSN or MYSQL_TEST_DSN is not set; payment MySQL integration skipped") return "" } func TestPaymentsMySQLMigration13RoundTrip(t *testing.T) { if os.Getenv("PAYMENT_MIGRATION_ROUNDTRIP") != "1" { t.Skip("set PAYMENT_MIGRATION_ROUNDTRIP=1 for an explicitly isolated migration database") } dsn := paymentIntegrationDSN(t) cfg, err := mysql.ParseDSN(dsn) if err != nil { t.Fatal(err) } cfg.MultiStatements = true migrationDSN := cfg.FormatDSN() dir, err := filepath.Abs("../../migrations") if err != nil { t.Fatal(err) } m, err := migrate.New((&url.URL{Scheme: "file", Path: filepath.ToSlash(dir)}).String(), "mysql://"+migrationDSN) if err != nil { t.Fatal(err) } defer m.Close() v, _, err := m.Version() if err != nil { t.Fatal(err) } if v != 13 && v != 14 { t.Fatalf("expected version 13 or 14, got %d", v) } original := v if v == 14 { if err = m.Steps(-1); err != nil { t.Fatal(err) } } if err = m.Steps(-1); err != nil { t.Fatal(err) } if err = m.Steps(1); err != nil { t.Fatal(err) } if original == 14 { if err = m.Steps(1); err != nil { t.Fatal(err) } } v, dirty, err := m.Version() if err != nil || dirty || v != original { t.Fatalf("version=%d dirty=%v err=%v", v, dirty, err) } } type paymentFixture struct { db *sql.DB admin, customer, product, order, payment uint64 merchant string } func newPaymentFixture(t *testing.T, db *sql.DB, suffix string) paymentFixture { t.Helper() var f paymentFixture unique, err := randomPaymentToken(6) if err != nil { t.Fatal(err) } suffix += "-" + unique mustExec := func(q string, args ...any) { if _, err := db.Exec(q, args...); err != nil { t.Fatal(err) } } email := "payment-" + suffix + "@example.invalid" username := "pay" + suffix mustExec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", username, email, "test") if err := db.QueryRow("SELECT id FROM admins WHERE username=?", username).Scan(&f.admin); err != nil { t.Fatal(err) } mustExec("INSERT INTO customers(name,contact_email) VALUES(?,?)", "Payment "+suffix, email) if err := db.QueryRow("SELECT id FROM customers WHERE contact_email=?", email).Scan(&f.customer); err != nil { t.Fatal(err) } mustExec("INSERT INTO products(code,name,description) VALUES(?,?,?)", "payment-"+suffix, "Payment Product", "test") if err := db.QueryRow("SELECT id FROM products WHERE code=?", "payment-"+suffix).Scan(&f.product); err != nil { t.Fatal(err) } orderNo := "pay-order-" + unique mustExec("INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,status,created_by) VALUES(?,?,?,?,?,?,?)", orderNo, f.customer, f.product, 12800, "CNY", "pending_payment", f.admin) if err := db.QueryRow("SELECT id FROM offline_orders WHERE order_no=?", orderNo).Scan(&f.order); err != nil { t.Fatal(err) } f.merchant = "pay-merchant-" + unique token, err := randomPaymentToken(32) if err != nil { t.Fatal(err) } mustExec("INSERT INTO payment_orders(order_id,merchant_order_no,channel,amount_cents,currency,license_days,checkout_token,expires_at) VALUES(?,?,?,?,?,?,?,?)", f.order, f.merchant, "alipay", 12800, "CNY", 30, token, time.Now().Add(time.Hour)) if err := db.QueryRow("SELECT id FROM payment_orders WHERE merchant_order_no=?", f.merchant).Scan(&f.payment); err != nil { t.Fatal(err) } return f } func cleanPaymentFixture(t *testing.T, db *sql.DB, f paymentFixture) { t.Helper() for _, q := range []string{ "DELETE FROM payment_notifications WHERE merchant_order_no=?", "DELETE FROM authorization_grant_logs WHERE order_id=?", "DELETE FROM payment_orders WHERE order_id=?", "UPDATE offline_orders SET issued_license_id=NULL WHERE id=?", "DELETE FROM audit_events WHERE resource_id=? AND resource_type='order'", "DELETE FROM licenses WHERE idempotency_key=?", "DELETE FROM offline_orders WHERE id=?", "DELETE FROM products WHERE id=?", "DELETE FROM customers WHERE id=?", "DELETE FROM admins WHERE id=?", } { var arg any = f.order if strings.Contains(q, "merchant_order_no") { arg = f.merchant } if strings.Contains(q, "products") { arg = f.product } if strings.Contains(q, "customers") { arg = f.customer } if strings.Contains(q, "admins") { arg = f.admin } if strings.Contains(q, "licenses") { arg = fmt.Sprintf("online-order-%d", f.order) } if _, err := db.Exec(q, arg); err != nil { t.Errorf("cleanup %s: %v", q, err) } } } func paymentNotification(f paymentFixture, event, trade string, amount int64) payments.Notification { return payments.Notification{Paid: true, EventID: event, MerchantOrderNo: f.merchant, TradeNo: trade, Currency: "CNY", AmountCents: amount} } func TestApplyPaymentMySQLTransactions(t *testing.T) { dsn := paymentIntegrationDSN(t) db, err := sql.Open("mysql", dsn) if err != nil { t.Fatal(err) } defer db.Close() if err = db.Ping(); err != nil { t.Fatal(err) } for _, suffix := range []string{"amt", "dup", "conc", "audit", "offline", "event"} { t.Run(suffix, func(t *testing.T) { f := newPaymentFixture(t, db, suffix) defer func() { cleanPaymentFixture(t, db, f) }() a := &BusinessAPI{db: db} switch suffix { case "amt": if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-amt", "trade-amt", 12799)); err == nil { t.Fatal("amount mismatch was accepted") } var n int db.QueryRow("SELECT COUNT(*) FROM licenses WHERE idempotency_key=?", fmt.Sprintf("online-order-%d", f.order)).Scan(&n) if n != 0 { t.Fatalf("licenses=%d", n) } case "dup": n := paymentNotification(f, "evt-dup-1", "trade-dup", 12800) if err := a.applyPayment(context.Background(), "alipay", n); err != nil { t.Fatal(err) } if err := a.applyPayment(context.Background(), "alipay", n); err != nil { t.Fatal(err) } if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-dup-2", "trade-dup", 12800)); err != nil { t.Fatal(err) } assertPaymentCounts(t, db, f, 1) case "conc": n := paymentNotification(f, "evt-concurrent", "trade-concurrent", 12800) errs := make(chan error, 2) var wg sync.WaitGroup wg.Add(2) for i := 0; i < 2; i++ { go func() { defer wg.Done(); errs <- a.applyPayment(context.Background(), "alipay", n) }() } wg.Wait() close(errs) successes := 0 for e := range errs { if e == nil { successes++ } } if successes != 2 { t.Fatalf("successful concurrent applies=%d", successes) } assertPaymentCounts(t, db, f, 1) case "audit": trigger := "payment_audit_fail_" + suffix if _, err := db.Exec("CREATE TRIGGER `" + trigger + "` BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='payment audit failure'"); err != nil { t.Fatal(err) } err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-audit", "trade-audit", 12800)) _, dropErr := db.Exec("DROP TRIGGER `" + trigger + "`") if dropErr != nil { t.Fatal(dropErr) } if err == nil { t.Fatal("audit failure was accepted") } assertPaymentCounts(t, db, f, 0) if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-audit", "trade-audit", 12800)); err != nil { t.Fatal(err) } assertPaymentCounts(t, db, f, 1) case "offline": if _, err := db.Exec("UPDATE offline_orders SET status='paid',payment_status='paid' WHERE id=?", f.order); err != nil { t.Fatal(err) } if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-offline", "trade-offline", 12800)); err == nil { t.Fatal("offline-paid order was accepted") } assertPaymentCounts(t, db, f, 0) case "event": if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-conflict", "trade-one", 12800)); err != nil { t.Fatal(err) } if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-conflict", "trade-two", 12800)); err == nil { t.Fatal("notification event conflict was accepted") } assertPaymentCounts(t, db, f, 1) } }) } } func assertPaymentCounts(t *testing.T, db *sql.DB, f paymentFixture, licenses int) { t.Helper() var n int if err := db.QueryRow("SELECT COUNT(*) FROM licenses WHERE idempotency_key=?", fmt.Sprintf("online-order-%d", f.order)).Scan(&n); err != nil { t.Fatal(err) } if n != licenses { t.Fatalf("licenses=%d want=%d", n, licenses) } if err := db.QueryRow("SELECT COUNT(*) FROM authorization_grant_logs WHERE order_id=?", f.order).Scan(&n); err != nil { t.Fatal(err) } if n != licenses { t.Fatalf("grant logs=%d want=%d", n, licenses) } var status string if err := db.QueryRow("SELECT status FROM payment_orders WHERE order_id=?", f.order).Scan(&status); err != nil { t.Fatal(err) } want := "created" if licenses == 1 { want = "paid" } if status != want { t.Fatalf("payment state=%s want=%s", status, want) } if err := db.QueryRow("SELECT COUNT(*) FROM payment_notifications WHERE merchant_order_no=?", f.merchant).Scan(&n); err != nil { t.Fatal(err) } if licenses == 0 && n != 0 { t.Fatalf("rolled back notifications=%d", n) } if licenses == 1 { var issuer uint64 if err := db.QueryRow("SELECT issued_by FROM licenses WHERE idempotency_key=?", fmt.Sprintf("online-order-%d", f.order)).Scan(&issuer); err != nil { t.Fatal(err) } if issuer != f.admin { t.Fatalf("issuer=%d want=%d", issuer, f.admin) } var actorType string if err := db.QueryRow("SELECT JSON_UNQUOTE(JSON_EXTRACT(details,'$.actor_type')) FROM audit_events WHERE resource_id=? AND action='payment.auto_issued'", f.order).Scan(&actorType); err != nil { t.Fatal(err) } if actorType != "payment_channel" { t.Fatalf("actor_type=%s", actorType) } } } func TestPaymentNotifyVerificationFailureWithMySQL(t *testing.T) { dsn := paymentIntegrationDSN(t) db, err := sql.Open("mysql", dsn) if err != nil { t.Fatal(err) } defer db.Close() if err = db.Ping(); err != nil { t.Fatal(err) } before := 0 if err = db.QueryRow("SELECT COUNT(*) FROM payment_notifications").Scan(&before); err != nil { t.Fatal(err) } provider := paymentTestProvider{verifyErr: errors.New("invalid signature")} r := paymentTestEngine(db, map[string]payments.Provider{"alipay": provider}) req := httptest.NewRequest(http.MethodPost, "/api/v1/payments/alipay/notify", strings.NewReader("bad")) w := httptest.NewRecorder() r.ServeHTTP(w, req) if w.Code != http.StatusBadRequest { t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) } var after int if err = db.QueryRow("SELECT COUNT(*) FROM payment_notifications").Scan(&after); err != nil { t.Fatal(err) } if before != after { t.Fatalf("notifications changed %d -> %d", before, after) } } func TestPaymentOnlineCheckoutMySQL(t *testing.T) { db, err := sql.Open("mysql", paymentIntegrationDSN(t)) if err != nil { t.Fatal(err) } defer db.Close() f := newPaymentFixture(t, db, "http") defer func() { cleanPaymentFixture(t, db, f) }() // This fixture is a legacy NULL-version payment; new payments require a real encrypted provider snapshot. if _, err = db.Exec("UPDATE offline_orders SET payment_channel='alipay',payment_expires_at=(SELECT expires_at FROM payment_orders WHERE order_id=?) WHERE id=?", f.order, f.order); err != nil { t.Fatal(err) } defer func() { if _, e := db.Exec("DELETE FROM order_operations WHERE order_id=?", f.order); e != nil { t.Error(e) } }() provider := &paymentTestProvider{} a := &BusinessAPI{db: db, paymentProviders: map[string]payments.Provider{"alipay": provider}} gin.SetMode(gin.TestMode) r := gin.New() r.Use(func(c *gin.Context) { c.Set("admin_id", f.admin); c.Next() }) r.POST("/orders/:id/payment", a.createOnlinePayment) r.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") }) r.POST("/checkout", a.paymentCheckout) request := func(path, body, key string) *httptest.ResponseRecorder { t.Helper() w := httptest.NewRecorder() req := httptest.NewRequest("POST", path, strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Idempotency-Key", key) r.ServeHTTP(w, req) return w } path := fmt.Sprintf("/orders/%d/payment", f.order) w := request(path, `{"channel":"alipay","license_days":30}`, "online-http") if w.Code != 200 { t.Fatalf("create=%d %s", w.Code, w.Body.String()) } var response struct { Data struct { Merchant string `json:"merchant_order_no"` Token string `json:"checkout_token"` } } if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil { t.Fatal(err) } f.merchant = response.Data.Merchant repeat := request(path, `{"channel":"alipay","license_days":30}`, "online-http") if repeat.Code != 200 || repeat.Body.String() != w.Body.String() { t.Fatalf("idempotent response %d %s", repeat.Code, repeat.Body.String()) } conflict := request(path, `{"channel":"alipay","license_days":31}`, "online-http") if conflict.Code != 409 { t.Fatalf("idempotency conflict=%d", conflict.Code) } conflict = request(path, `{"channel":"alipay","license_days":31}`, "other-key") if conflict.Code != 409 { t.Fatalf("duration conflict=%d", conflict.Code) } var amount int64 var days int var expires time.Time if err = db.QueryRow("SELECT amount_cents,license_days,expires_at FROM payment_orders WHERE order_id=?", f.order).Scan(&amount, &days, &expires); err != nil { t.Fatal(err) } if amount != 12800 || days != 30 || time.Until(expires) < 59*time.Minute || time.Until(expires) > 61*time.Minute { t.Fatalf("frozen amount=%d days=%d", amount, days) } manual := request(fmt.Sprintf("/orders/%d/confirm-payment", f.order), `{"payment_reference":"manual","amount_cents":12800}`, "manual-http") if manual.Code != 409 { t.Fatalf("manual confirm=%d %s", manual.Code, manual.Body.String()) } provider.notification = paymentNotification(f, "http-event", "http-trade", 12800) checkout := request("/checkout", fmt.Sprintf(`{"token":%q}`, response.Data.Token), "") if checkout.Code != 200 { t.Fatalf("checkout=%d %s", checkout.Code, checkout.Body.String()) } var result struct { Data struct { Key string `json:"license_key"` } } if err = json.Unmarshal(checkout.Body.Bytes(), &result); err != nil { t.Fatal(err) } if len(result.Data.Key) != 32 { t.Fatalf("missing license key: %s", checkout.Body.String()) } assertPaymentCounts(t, db, f, 1) } func TestPaymentManagementMySQL(t *testing.T) { db, err := sql.Open("mysql", paymentIntegrationDSN(t)) if err != nil { t.Fatal(err) } defer db.Close() f := newPaymentFixture(t, db, "management") defer func() { cleanPaymentFixture(t, db, f) }() token, err := randomPaymentToken(32) if err != nil { t.Fatal(err) } decoded, err := hex.DecodeString(token) if err != nil { t.Fatal(err) } sum := sha256.Sum256(decoded) if _, err = db.Exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", f.admin, sum[:], time.Now().Add(time.Hour)); err != nil { t.Fatal(err) } defer func() { if _, e := db.Exec("DELETE FROM sessions WHERE admin_id=?", f.admin); e != nil { t.Error(e) } }() r := paymentTestEngine(db, map[string]payments.Provider{"alipay": paymentTestProvider{}}) request := func(method, path string) *httptest.ResponseRecorder { t.Helper() w := httptest.NewRecorder() req := httptest.NewRequest(method, path, nil) req.AddCookie(&http.Cookie{Name: "lp_session", Value: token}) r.ServeHTTP(w, req) if w.Code != 200 && !(method == http.MethodDelete && w.Code == http.StatusNoContent) { t.Fatalf("%s %s status=%d body=%s", method, path, w.Code, w.Body.String()) } return w } channels := request(http.MethodGet, "/api/v1/payment-channels") if !strings.Contains(channels.Body.String(), `"enabled":true`) || !strings.Contains(channels.Body.String(), `"enabled":false`) { t.Fatal("missing enabled/disabled channel") } a := &BusinessAPI{db: db} if err = a.applyPayment(context.Background(), "alipay", paymentNotification(f, "management-event", "management-trade", 12800)); err != nil { t.Fatal(err) } var licenseID uint64 var licenseKey, checkoutToken string if err = db.QueryRow("SELECT l.id,l.license_key,p.checkout_token FROM licenses l JOIN offline_orders o ON o.issued_license_id=l.id JOIN payment_orders p ON p.order_id=o.id WHERE o.id=?", f.order).Scan(&licenseID, &licenseKey, &checkoutToken); err != nil { t.Fatal(err) } getOrder := func() map[string]any { t.Helper() w := request(http.MethodGet, "/api/v1/payment-orders") if w.Header().Get("Cache-Control") != "no-store" { t.Fatal("missing no-store") } body := w.Body.String() for _, secret := range []string{token, licenseKey, checkoutToken, `"checkout_token"`, `"license_key"`, "sensitive provider failure test-value"} { if strings.Contains(body, secret) { t.Fatal("management response exposes secret") } } var response struct{ Data []map[string]any } if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { t.Fatal(err) } for _, row := range response.Data { if row["merchant_order_no"] == f.merchant { return row } } t.Fatal("payment order missing") return nil } row := getOrder() if row["amount_cents"] != float64(12800) || row["channel_trade_no"] != "management-trade" || row["status"] != "paid" || row["order_status"] != "issued" || row["license_id"] != float64(licenseID) || row["paid_at"] == nil || row["expires_at"] == nil || row["last_error"] != nil { t.Fatalf("unexpected paid order: %v", row) } const rawError = "sensitive provider failure test-value" if _, err = db.Exec("UPDATE payment_orders SET last_error=? WHERE id=?", rawError, f.payment); err != nil { t.Fatal(err) } row = getOrder() if row["last_error"] != "authorization_transaction_failed" { t.Fatalf("error not sanitized: %v", row["last_error"]) } defer func() { if _, e := db.Exec("DELETE FROM audit_events WHERE action='license.deleted' AND resource_type='license' AND resource_id=? AND actor_admin_id=?", licenseID, f.admin); e != nil { t.Error(e) } }() request(http.MethodDelete, fmt.Sprintf("/api/v1/licenses/%d", licenseID)) row = getOrder() if row["order_status"] != "authorization_removed" || row["license_id"] != nil || row["channel_trade_no"] != "management-trade" || row["status"] != "paid" { t.Fatalf("unexpected removed authorization: %v", row) } var retained int if err = db.QueryRow("SELECT COUNT(*) FROM authorization_grant_logs WHERE order_id=? AND license_id IS NULL", f.order).Scan(&retained); err != nil { t.Fatal(err) } if retained != 1 { t.Fatalf("grant audit retention=%d", retained) } }