package dojo import ( "context" "encoding/json" "errors" "io" "net/http" "strings" "testing" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc" log "github.com/sirupsen/logrus" logtest "github.com/sirupsen/logrus/hooks/test" ) type diagnosticTransport func(*http.Request) (*http.Response, error) func (f diagnosticTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func dojoDiagnosticLog(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 TestDojoFailureDiagnosticsKeepIdentityWithoutRawErrors(t *testing.T) { for _, failure := range []string{"transport", "lost", "malformed", "http", "expired"} { t.Run(failure, func(t *testing.T) { hook := dojoDiagnosticLog(t) financialPosts := 0 client, err := NewClient(Config{BaseURL: "https://synthetic.invalid", APIKey: "SYNTH-CREDENTIAL", SoftwareHouseID: "SYNTH-HOUSE", TerminalID: "SYNTH-PED"}) if err != nil { t.Fatal(err) } client.httpClient = &http.Client{Transport: diagnosticTransport(func(r *http.Request) (*http.Response, error) { body := "" switch { case r.Method == http.MethodPost && r.URL.Path == "/payment-intents": financialPosts++ if failure == "transport" { return nil, errors.New("SYNTH-RAW-SECRET https://user:password@private.invalid") } body = `{"id":"SYNTH-INTENT"}` case r.Method == http.MethodPost && r.URL.Path == "/terminal-sessions": body = `{"id":"SYNTH-SESSION","paymentDetails":{"transactionId":"SYNTH-PROVIDER-TXN"}}` case r.Method == http.MethodGet && r.URL.Path == "/terminal-sessions/SYNTH-SESSION": switch failure { case "lost": return nil, io.ErrUnexpectedEOF case "malformed": body = `{"SYNTH-RAW-SECRET":nope}` case "http": return &http.Response{StatusCode: 502, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("SYNTH-RAW-SECRET card 4111111111111111"))}, nil case "expired": body = `{"id":"SYNTH-SESSION","status":"Expired","paymentDetails":{"transactionId":"SYNTH-PROVIDER-TXN"}}` default: t.Errorf("unexpected poll for %s", failure) } default: t.Errorf("Dojo Sale requested unexpected %s %s", r.Method, r.URL.Path) } return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil })} request := paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Reference: "SYNTH-BOOK", Amount: 2500, Currency: "GBP"} result, err := client.Sale(context.Background(), request, nil) if failure == "expired" { if err != nil || result == nil || result.Terminal.Outcome != "unknown" || result.Terminal.Retryable { t.Fatalf("Sale(expired)=%+v/%v, want unchanged nonretryable unknown", result, err) } } else if err == nil || result != nil { t.Fatalf("Sale(%s)=%+v/%v, want original nil-result error", failure, result, err) } if failure == "http" && !strings.Contains(err.Error(), "SYNTH-RAW-SECRET") { t.Error("Sale(http) changed the existing returned error") } if financialPosts != 1 { t.Errorf("Sale(%s) financial posts=%d, want one", failure, financialPosts) } var diagnostic *log.Entry for _, entry := range hook.AllEntries() { data, _ := json.Marshal(entry.Data) for _, secret := range []string{"SYNTH-CREDENTIAL", "SYNTH-RAW-SECRET", "4111111111111111", "user:password"} { if strings.Contains(string(data)+entry.Message, secret) { t.Errorf("Sale(%s) logged sensitive marker %q", failure, secret) } } if entry.Message == "Dojo payment requires reconciliation" { diagnostic = entry } } if diagnostic == nil { t.Fatal("Sale failure emitted no reconciliation diagnostic") } for key, want := range map[string]any{"provider": "dojo", "request_id": "SYNTH-REQUEST", "transaction_reference": "SYNTH-REQUEST"} { if diagnostic.Data[key] != want { t.Errorf("Sale(%s) diagnostic[%s]=%v, want %v", failure, key, diagnostic.Data[key], want) } } wantStage, wantCategory := "read_terminal_session", "unresolved_result" switch failure { case "transport": wantStage, wantCategory = "create_payment_intent", "connection_failure" case "lost": wantCategory = "response_lost" case "malformed": wantCategory = "invalid_response" case "http": wantCategory = "http_error" } if diagnostic.Data["stage"] != wantStage || diagnostic.Data["error_category"] != wantCategory { t.Errorf("Sale(%s) diagnostic=%v, want stage=%s category=%s", failure, diagnostic.Data, wantStage, wantCategory) } if failure != "transport" { for key, want := range map[string]string{"payment_intent_id": "SYNTH-INTENT", "terminal_session_id": "SYNTH-SESSION", "provider_transaction_id": "SYNTH-PROVIDER-TXN"} { if diagnostic.Data[key] != want { t.Errorf("Sale(%s) diagnostic[%s]=%v, want %s", failure, key, diagnostic.Data[key], want) } } } if failure == "http" && diagnostic.Data["http_status"] != 502 { t.Errorf("Sale(http) status=%v, want 502", diagnostic.Data["http_status"]) } }) } } func TestDojoPollFailureRetainsLastObservedTransactionIdentity(t *testing.T) { hook := dojoDiagnosticLog(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() client, err := NewClient(Config{BaseURL: "https://synthetic.invalid", APIKey: "SYNTH", SoftwareHouseID: "SYNTH", TerminalID: "SYNTH"}) if err != nil { t.Fatal(err) } client.httpClient = &http.Client{Transport: diagnosticTransport(func(r *http.Request) (*http.Response, error) { body := `{"id":"SYNTH-INTENT"}` if strings.HasPrefix(r.URL.Path, "/terminal-sessions") { body = `{"id":"SYNTH-SESSION"}` } if r.Method == "GET" { body = `{"id":"SYNTH-SESSION","status":"Initiated","paymentDetails":{"transactionId":"SYNTH-POLL-TXN"}}` cancel() } return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil })} result, err := client.Sale(ctx, paymentsvc.SaleRequest{RequestID: "SYNTH-REQUEST", Amount: 2500}, nil) if result != nil || !errors.Is(err, context.Canceled) { t.Fatalf("Sale(cancel after poll)=%+v/%v, want unchanged cancellation", result, err) } for _, entry := range hook.AllEntries() { if entry.Message == "Dojo payment requires reconciliation" { if entry.Data["provider_transaction_id"] != "SYNTH-POLL-TXN" || entry.Data["error_category"] != "cancelled" { t.Errorf("Sale(cancel after poll) diagnostic=%v, want last observed transaction and cancellation", entry.Data) } return } } t.Fatalf("Sale(cancel after poll) emitted no diagnostic; entries=%d", len(hook.AllEntries())) }