342 lines
13 KiB
Go
342 lines
13 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto"
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"encoding/pem"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"sort"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"license-platform/backend/internal/payments"
|
|
)
|
|
|
|
func TestPaymentConfigEncryption(t *testing.T) {
|
|
key := bytes.Repeat([]byte{0x42}, 32)
|
|
config := payments.Config{"ALIPAY_PRIVATE_KEY": "private-value-that-must-stay-secret", "ALIPAY_APP_ID": "test-app"}
|
|
encrypted, err := encryptPaymentConfig(key, "alipay", 1, config)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if bytes.Contains(encrypted, []byte(config["ALIPAY_PRIVATE_KEY"])) || bytes.Contains(encrypted, []byte("ALIPAY_PRIVATE_KEY")) {
|
|
t.Fatal("plaintext stored")
|
|
}
|
|
repeated, err := encryptPaymentConfig(key, "alipay", 1, config)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if bytes.Equal(encrypted, repeated) {
|
|
t.Fatal("nonce reused")
|
|
}
|
|
restored, err := decryptPaymentConfig(key, "alipay", 1, encrypted)
|
|
if err != nil || restored["ALIPAY_PRIVATE_KEY"] != config["ALIPAY_PRIVATE_KEY"] {
|
|
t.Fatal("round trip failed")
|
|
}
|
|
for _, tc := range []struct {
|
|
name, channel string
|
|
version int64
|
|
key, data []byte
|
|
}{
|
|
{"wrong channel", "wechat", 1, key, encrypted}, {"wrong version", "alipay", 2, key, encrypted}, {"wrong key", "alipay", 1, bytes.Repeat([]byte{0x43}, 32), encrypted}, {"truncated", "alipay", 1, key, encrypted[:4]},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
if _, err := decryptPaymentConfig(tc.key, tc.channel, tc.version, tc.data); err == nil {
|
|
t.Fatal("invalid context accepted")
|
|
}
|
|
})
|
|
}
|
|
tampered := append([]byte(nil), encrypted...)
|
|
tampered[len(tampered)-1] ^= 1
|
|
if _, err = decryptPaymentConfig(key, "alipay", 1, tampered); err == nil {
|
|
t.Fatal("tampering accepted")
|
|
}
|
|
for _, length := range []int{0, 16, 31, 33} {
|
|
if _, err = encryptPaymentConfig(make([]byte, length), "alipay", 1, config); err == nil {
|
|
t.Fatalf("key length %d accepted", length)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPaymentConfigAccessGuards(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
t.Setenv("SESSION_COOKIE_SECURE", "false")
|
|
for _, tc := range []struct {
|
|
name, role, origin, site string
|
|
status int
|
|
}{
|
|
{"not admin", "viewer", "", "", 403}, {"foreign origin", "admin", "http://attacker.invalid", "", 403}, {"wrong scheme", "admin", "https://example.com", "", 403}, {"cross site", "admin", "", "cross-site", 403}, {"same site", "admin", "", "same-site", 403}, {"same origin missing key", "admin", "http://example.com", "same-origin", 409}, {"non browser missing key", "admin", "", "", 409},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
a := &BusinessAPI{}
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) { c.Set("admin_role", tc.role) })
|
|
r.PUT("/channels/:channel", a.updatePaymentChannel)
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodPut, "http://example.com/channels/alipay", strings.NewReader(`{"enabled":false}`))
|
|
req.Header.Set("Origin", tc.origin)
|
|
req.Header.Set("Sec-Fetch-Site", tc.site)
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != tc.status {
|
|
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
})
|
|
}
|
|
r := paymentTestEngine(nil, nil)
|
|
for _, method := range []string{http.MethodGet, http.MethodPut} {
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, httptest.NewRequest(method, "/api/v1/payment-channels/alipay", strings.NewReader(`{"enabled":false}`)))
|
|
if w.Code != 401 {
|
|
t.Fatalf("anonymous %s status=%d", method, w.Code)
|
|
}
|
|
}
|
|
a := &BusinessAPI{}
|
|
r = gin.New()
|
|
r.GET("/channels/:channel", a.getPaymentChannel)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/channels/alipay", nil))
|
|
if w.Code != 403 {
|
|
t.Fatalf("nonadmin GET=%d", w.Code)
|
|
}
|
|
view, err := a.paymentChannelView(context.Background(), "alipay")
|
|
if err != nil || view["configuration_source"] != "none" || view["can_save"] != false {
|
|
t.Fatalf("empty view=%v err=%v", view, err)
|
|
}
|
|
}
|
|
|
|
func paymentConfigTestValues(t *testing.T) (map[string]string, map[string]string) {
|
|
t.Helper()
|
|
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pk, err := x509.MarshalPKCS8PrivateKey(priv)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pub, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return map[string]string{"app_id": "config-test-app", "seller_id": "config-test-seller", "notify_url": "https://example.invalid/payment-notify"}, map[string]string{"private_key": string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk})), "public_key": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pub}))}
|
|
}
|
|
|
|
func TestPaymentConfigMySQL(t *testing.T) {
|
|
db, err := sql.Open("mysql", paymentIntegrationDSN(t))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
f := newPaymentFixture(t, db, "config")
|
|
defer func() { cleanPaymentFixture(t, db, f) }()
|
|
var prior sql.NullInt64
|
|
if err = db.QueryRow("SELECT active_version FROM payment_channel_configs WHERE channel='alipay'").Scan(&prior); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if prior.Valid {
|
|
t.Fatal("isolated fixture requires no existing alipay config")
|
|
}
|
|
defer func() {
|
|
for _, q := range []string{"UPDATE payment_orders SET provider_config_version=NULL WHERE order_id=?", "UPDATE payment_channel_configs SET active_version=NULL WHERE channel='alipay'", "DELETE FROM payment_channel_config_versions WHERE channel='alipay' AND created_by=?", "DELETE FROM audit_events WHERE actor_admin_id=? AND resource_type='payment_channel'", "DELETE FROM sessions WHERE admin_id=?"} {
|
|
var args []any
|
|
if strings.Contains(q, "order_id=?") {
|
|
args = []any{f.order}
|
|
} else if strings.Contains(q, "=?") {
|
|
args = []any{f.admin}
|
|
}
|
|
if _, e := db.Exec(q, args...); e != nil {
|
|
t.Error(e)
|
|
}
|
|
}
|
|
}()
|
|
key := bytes.Repeat([]byte{0x57}, 32)
|
|
r := gin.New()
|
|
a := RegisterBusinessWithPayments(r, db, "", nil, nil, map[string]payments.Provider{"alipay": paymentTestProvider{}}, key)
|
|
token, err := randomPaymentToken(32)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
decoded, err := hex.DecodeString(token)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
hash := sha256.Sum256(decoded)
|
|
if _, err = db.Exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", f.admin, hash[:], time.Now().Add(time.Hour)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fields, secrets := paymentConfigTestValues(t)
|
|
request := func(method string, body any, origin string, status int) map[string]any {
|
|
t.Helper()
|
|
raw, _ := json.Marshal(body)
|
|
req := httptest.NewRequest(method, "http://example.com/api/v1/payment-channels/alipay", bytes.NewReader(raw))
|
|
req.AddCookie(&http.Cookie{Name: "lp_session", Value: token})
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Origin", origin)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != status {
|
|
t.Fatalf("%s status=%d body=%s", method, w.Code, w.Body.String())
|
|
}
|
|
if status == http.StatusOK && w.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatal("missing no-store")
|
|
}
|
|
for _, secret := range secrets {
|
|
if strings.Contains(w.Body.String(), strings.TrimSpace(secret)) || strings.Contains(w.Body.String(), "BEGIN PRIVATE KEY") || strings.Contains(w.Body.String(), "BEGIN PUBLIC KEY") {
|
|
t.Fatal("secret exposed")
|
|
}
|
|
}
|
|
var out struct{ Data map[string]any }
|
|
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return out.Data
|
|
}
|
|
payload := func(enabled bool, s map[string]string) map[string]any {
|
|
return map[string]any{"enabled": enabled, "fields": fields, "secrets": s}
|
|
}
|
|
request(http.MethodPut, payload(true, secrets), "http://foreign.invalid", 403)
|
|
if _, err = db.Exec("UPDATE admins SET role='viewer' WHERE id=?", f.admin); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request(http.MethodPut, payload(true, secrets), "", 403)
|
|
if _, err = db.Exec("UPDATE admins SET role='admin' WHERE id=?", f.admin); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
view := request(http.MethodPut, payload(true, secrets), "http://example.com", 200)
|
|
if view["version"] != float64(1) || view["effective"] != true || view["configuration_source"] != "database" {
|
|
t.Fatalf("published view=%v", view)
|
|
}
|
|
var encrypted []byte
|
|
if err = db.QueryRow("SELECT config_encrypted FROM payment_channel_config_versions WHERE channel='alipay' AND version=1").Scan(&encrypted); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, secret := range secrets {
|
|
if bytes.Contains(encrypted, []byte(secret)) {
|
|
t.Fatal("plaintext secret in database")
|
|
}
|
|
}
|
|
if _, err = db.Exec("UPDATE payment_orders SET provider_config_version=1 WHERE id=?", f.payment); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
view = request(http.MethodPut, payload(false, map[string]string{"private_key": "", "public_key": ""}), "", 200)
|
|
if view["version"] != float64(2) || view["enabled"] != false || view["effective"] != false {
|
|
t.Fatalf("disabled view=%v", view)
|
|
}
|
|
one, _, err := a.paymentConfigVersion(context.Background(), "alipay", 1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
two, enabled, err := a.paymentConfigVersion(context.Background(), "alipay", 2)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if enabled || one["ALIPAY_PRIVATE_KEY"] != two["ALIPAY_PRIVATE_KEY"] || two["ALIPAY_PUBLIC_KEY"] != strings.TrimSpace(secrets["public_key"]) {
|
|
t.Fatal("blank secret did not preserve value")
|
|
}
|
|
view = request(http.MethodPut, payload(false, nil), "", 200)
|
|
if view["version"] != float64(3) {
|
|
t.Fatal("missing immutable new version")
|
|
}
|
|
three, _, err := a.paymentConfigVersion(context.Background(), "alipay", 3)
|
|
if err != nil || three["ALIPAY_PRIVATE_KEY"] != one["ALIPAY_PRIVATE_KEY"] {
|
|
t.Fatal("omitted secret not preserved")
|
|
}
|
|
request(http.MethodGet, nil, "", 200)
|
|
if _, _, err = a.currentPaymentProvider(context.Background(), "alipay"); err != errPaymentChannelDisabled {
|
|
t.Fatalf("disabled channel accepts new payments: %v", err)
|
|
}
|
|
if _, err = a.providerForPaymentVersion(context.Background(), "alipay", sql.NullInt64{Int64: 1, Valid: true}); err != nil {
|
|
t.Fatalf("historical provider unavailable: %v", err)
|
|
}
|
|
n := paymentNotification(f, "config-version-event", "config-version-trade", 12800)
|
|
for _, version := range []sql.NullInt64{{}, {Int64: 2, Valid: true}} {
|
|
if err = a.applyPayment(context.Background(), "alipay", n, version); err == nil {
|
|
t.Fatal("wrong config version accepted")
|
|
}
|
|
}
|
|
assertPaymentCounts(t, db, f, 0)
|
|
|
|
// A fresh order is rejected after disable; the previously bound order remains confirmable.
|
|
fresh := newPaymentFixture(t, db, "disabled")
|
|
defer func() { cleanPaymentFixture(t, db, fresh) }()
|
|
if _, err = db.Exec("DELETE FROM payment_orders WHERE order_id=?", fresh.order); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
newReq := httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://example.com/api/v1/orders/%d/payment", fresh.order), strings.NewReader(`{"channel":"alipay","license_days":30}`))
|
|
newReq.AddCookie(&http.Cookie{Name: "lp_session", Value: token})
|
|
newReq.Header.Set("Content-Type", "application/json")
|
|
newReq.Header.Set("Idempotency-Key", "config-disabled-new")
|
|
newResponse := httptest.NewRecorder()
|
|
r.ServeHTTP(newResponse, newReq)
|
|
if newResponse.Code != 503 {
|
|
t.Fatalf("disabled new payment status=%d body=%s", newResponse.Code, newResponse.Body.String())
|
|
}
|
|
var pending int
|
|
if err = db.QueryRow("SELECT COUNT(*) FROM payment_orders WHERE order_id=?", fresh.order).Scan(&pending); err != nil || pending != 0 {
|
|
t.Fatal("disabled channel created payment")
|
|
}
|
|
block, _ := pem.Decode([]byte(secrets["private_key"]))
|
|
rawKey, e := x509.ParsePKCS8PrivateKey(block.Bytes)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
form := url.Values{"app_id": {fields["app_id"]}, "seller_id": {fields["seller_id"]}, "notify_id": {n.EventID}, "out_trade_no": {n.MerchantOrderNo}, "trade_no": {n.TradeNo}, "trade_status": {"TRADE_SUCCESS"}, "total_amount": {"128.00"}}
|
|
keys := []string{}
|
|
for k := range form {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
parts := []string{}
|
|
for _, k := range keys {
|
|
parts = append(parts, k+"="+form.Get(k))
|
|
}
|
|
digest := sha256.Sum256([]byte(strings.Join(parts, "&")))
|
|
sig, e := rsa.SignPKCS1v15(rand.Reader, rawKey.(*rsa.PrivateKey), crypto.SHA256, digest[:])
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
form.Set("sign", base64.StdEncoding.EncodeToString(sig))
|
|
form.Set("sign_type", "RSA2")
|
|
callback := httptest.NewRequest(http.MethodPost, "/api/v1/payments/alipay/notify", strings.NewReader(form.Encode()))
|
|
callback.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
callbackResponse := httptest.NewRecorder()
|
|
r.ServeHTTP(callbackResponse, callback)
|
|
if callbackResponse.Code != 200 || callbackResponse.Body.String() != "success" {
|
|
t.Fatalf("historical callback status=%d body=%s", callbackResponse.Code, callbackResponse.Body.String())
|
|
}
|
|
if err = a.applyPayment(context.Background(), "alipay", n, sql.NullInt64{Int64: 1, Valid: true}); err != nil {
|
|
t.Fatalf("disabled historical payment failed: %v", err)
|
|
}
|
|
assertPaymentCounts(t, db, f, 1)
|
|
var stored []byte
|
|
if err = db.QueryRow("SELECT config_encrypted FROM payment_channel_config_versions WHERE channel='alipay' AND version=1").Scan(&stored); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !bytes.Equal(stored, encrypted) {
|
|
t.Fatal("old version changed")
|
|
}
|
|
var details string
|
|
if err = db.QueryRow("SELECT CAST(details AS CHAR) FROM audit_events WHERE actor_admin_id=? AND action='payment.channel_config_updated' ORDER BY id DESC LIMIT 1", f.admin).Scan(&details); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, secret := range secrets {
|
|
if strings.Contains(details, secret) {
|
|
t.Fatal("secret exposed in audit")
|
|
}
|
|
}
|
|
}
|