Files
hardlink/internal/paybridge/diagnostics_test.go
T

163 lines
6.9 KiB
Go

package paybridge
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
logtest "github.com/sirupsen/logrus/hooks/test"
)
func paybridgeDiagnosticLog(t *testing.T) *logtest.Hook {
t.Helper()
logger := log.StandardLogger()
oldOutput := logger.Out
oldHooks := logger.ReplaceHooks(make(log.LevelHooks))
hook := logtest.NewGlobal()
log.SetOutput(io.Discard)
t.Cleanup(func() { log.SetOutput(oldOutput); logger.ReplaceHooks(oldHooks) })
return hook
}
func TestPayBridgeFailureDiagnosticsKeepIdentityAndDoNotRetry(t *testing.T) {
for _, failure := range []string{"connect", "auth", "lost", "malformed", "uncertain", "provider_error", "payment_error", "cancelled"} {
t.Run(failure, func(t *testing.T) {
hook := paybridgeDiagnosticLog(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var financialPosts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("api_key") != "SYNTH-CREDENTIAL" {
t.Error("PayBridge connection omitted synthetic credential")
}
if failure == "connect" {
http.Error(w, "SYNTH-RAW-SECRET", 503)
return
}
connection, err := (&websocket.Upgrader{}).Upgrade(w, r, nil)
if err != nil {
t.Error(err)
return
}
defer connection.Close()
auth := `{"type":"auth_success","jwt":"SYNTH-JWT-PRIVATE"}`
if failure == "auth" {
auth = `{"type":"SYNTH-RAW-SECRET","jwt":"SYNTH-JWT-PRIVATE"}`
}
if err := connection.WriteMessage(websocket.TextMessage, []byte(auth)); err != nil {
t.Error(err)
return
}
if failure == "auth" {
return
}
var request struct {
Data PaymentRequest `json:"data"`
}
if err := connection.ReadJSON(&request); err != nil {
t.Error(err)
return
}
financialPosts.Add(1)
if request.Data.RequestID != "SYNTH-REQUEST" || request.Data.Amount != 2500 {
t.Errorf("PayBridge dispatched %+v, want original request identity/amount", request.Data)
}
body := ""
switch failure {
case "lost":
if err := connection.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "SYNTH-RAW-SECRET"), time.Now().Add(time.Second)); err != nil {
t.Error(err)
}
return
case "malformed":
body = `{"type":"payment_result","data":"SYNTH-RAW-SECRET"}`
case "uncertain":
body = `{"type":"payment_result","data":{"requestId":"SYNTH-REQUEST","transactionId":"SYNTH-PROVIDER-TXN","referenceNumber":"SYNTH-PROVIDER-REF","success":false,"status":"TIMEOUT","errorMessage":"SYNTH-RAW-SECRET card 4111111111111111","amount":2500}}`
case "provider_error":
body = `{"type":"error","error":{"code":"SYNTH-PRIVATE-CODE","message":"SYNTH-RAW-SECRET"}}`
case "payment_error":
body = `{"type":"payment_error","data":{"transactionId":"SYNTH-PROVIDER-TXN","status":"TIMEOUT","error":"SYNTH-RAW-SECRET"}}`
case "cancelled":
cancel()
return
}
if err := connection.WriteMessage(websocket.TextMessage, []byte(body)); err != nil {
t.Error(err)
}
}))
t.Cleanup(server.Close)
client := NewClient("ws"+strings.TrimPrefix(server.URL, "http"), "SYNTH-CREDENTIAL", 5)
result, err := client.Sale(ctx, paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Amount: 2500, Currency: "GBP"}, nil)
wantPosts := int32(1)
if failure == "connect" || failure == "auth" {
wantPosts = 0
}
if financialPosts.Load() != wantPosts {
t.Errorf("Sale(%s) dispatches=%d, want %d without retry", failure, financialPosts.Load(), wantPosts)
}
if failure == "uncertain" || failure == "payment_error" {
if err != nil || result == nil || result.Terminal.Outcome != "unknown" || result.Terminal.Retryable {
t.Fatalf("Sale(%s)=%+v/%v, want unchanged nonretryable unknown", failure, result, err)
}
if !strings.Contains(result.ErrorMessage, "SYNTH-RAW-SECRET") {
t.Error("diagnostic changes mutated the existing provider result")
}
} else if result != nil || err == nil {
t.Fatalf("Sale(%s)=%+v/%v, want original nil-result failure", failure, result, err)
}
if failure == "connect" && !errors.Is(err, ErrConnectionFailed) {
t.Errorf("Sale(connect) error=%v, want ErrConnectionFailed", err)
}
if failure == "cancelled" && !errors.Is(err, context.Canceled) {
t.Errorf("Sale(cancelled) error=%v, want context.Canceled", err)
}
var diagnostic *log.Entry
for _, entry := range hook.AllEntries() {
data, _ := json.Marshal(entry.Data)
for _, secret := range []string{"SYNTH-CREDENTIAL", "SYNTH-JWT-PRIVATE", "SYNTH-RAW-SECRET", "SYNTH-PRIVATE-CODE", "4111111111111111"} {
if strings.Contains(string(data)+entry.Message, secret) {
t.Errorf("Sale(%s) logged sensitive marker %q", failure, secret)
}
}
if entry.Message == "PayBridge payment requires reconciliation" {
diagnostic = entry
}
}
if diagnostic == nil {
t.Fatal("Sale failure emitted no reconciliation diagnostic")
}
for key, want := range map[string]string{"provider": "paybridge", "request_id": "SYNTH-REQUEST", "transaction_reference": "SYNTH-REQUEST"} {
if diagnostic.Data[key] != want {
t.Errorf("Sale(%s) diagnostic[%s]=%v, want %s", failure, key, diagnostic.Data[key], want)
}
}
stages := map[string]string{"connect": "connect", "auth": "authenticate", "lost": "read_result", "malformed": "decode_result", "uncertain": "decode_result", "provider_error": "provider_error", "payment_error": "decode_payment_error", "cancelled": "read_result"}
categories := map[string]string{"connect": "connection_failure", "auth": "authentication_failed", "lost": "response_lost", "malformed": "invalid_response", "uncertain": "unresolved_result", "provider_error": "invalid_response", "payment_error": "unresolved_result", "cancelled": "cancelled"}
if diagnostic.Data["stage"] != stages[failure] || diagnostic.Data["error_category"] != categories[failure] {
t.Errorf("Sale(%s) diagnostic=%v, want stage=%s category=%s", failure, diagnostic.Data, stages[failure], categories[failure])
}
if failure == "lost" && diagnostic.Data["websocket_close_code"] != websocket.ClosePolicyViolation {
t.Errorf("Sale(lost) close code=%v, want 1008", diagnostic.Data["websocket_close_code"])
}
if failure == "connect" && diagnostic.Data["http_status"] != 503 {
t.Errorf("Sale(connect) HTTP status=%v, want 503", diagnostic.Data["http_status"])
}
if failure == "uncertain" || failure == "payment_error" {
if diagnostic.Data["provider_transaction_id"] != "SYNTH-PROVIDER-TXN" {
t.Errorf("Sale(%s) provider transaction=%v, want retained identity", failure, diagnostic.Data["provider_transaction_id"])
}
}
})
}
}