package handlers import ( "bytes" "context" "encoding/json" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "sync/atomic" "testing" "time" "gitea.futuresens.co.uk/futuresens/hardlink/v2/config" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/paymentsvc" "gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/trustpayments" ) type trustFixtureTransport func(*http.Request) (*http.Response, error) func (f trustFixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func fixtureTrustApp(t *testing.T, dir string) *trustFixtureApp { t.Helper() client, err := trustpayments.New(trustpayments.Config{BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "fixture-site", Password: "synthetic", Terminal: "fixture-ped", Currency: "GBP", Timezone: "Europe/London", Transport: trustFixtureTransport(func(r *http.Request) (*http.Response, error) { var input map[string]string if err := json.NewDecoder(r.Body).Decode(&input); err != nil { return nil, err } if strings.HasSuffix(r.URL.Path, "/status") { return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"errorcode":2003}`))}, nil } f, err := os.OpenFile(filepath.Join(dir, "starts"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { return nil, err } _, err = f.WriteString(input["refid"] + "\n") closeErr := f.Close() if err != nil { return nil, err } if closeErr != nil { return nil, closeErr } outcome, auth := "Approved", "123456" if _, err := os.Stat(filepath.Join(dir, "decline-preauth")); err == nil && input["type"] == "preauth" { outcome, auth = "Declined", "" } if _, err := os.Stat(filepath.Join(dir, "uncertain")); err == nil { outcome, auth = "Pending", "" } body, _ := json.Marshal(map[string]string{"refid": input["refid"], "siteid": "fixture-site", "terminalserialnumber": "fixture-ped", "type": input["type"], "amount": input["amount"], "finalamount": input["amount"], "resultcode": outcome, "authcode": auth, "cardtype": "Visa", "last4": "1133", "receipt": "Receipt: 31\nSequence number: 42\nPAN: 4111111111111111"}) return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(body))}, nil })}) if err != nil { t.Fatal(err) } app := &trustFixtureApp{App: &App{isPayment: true, cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}}, trustReceipt: func(string) {}} app.SetTrustPayments(client) app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(s string) { app.trustReceipt(s) }})) return app } // This opt-in subprocess only uses an in-memory gateway and synthetic receipts. func TestTrustFixtureProcess(t *testing.T) { dir := os.Getenv("TRUST_FIXTURE_DIR") if dir == "" { t.Skip("offline subprocess helper") } app := fixtureTrustApp(t, dir) mux := http.NewServeMux() app.RegisterRoutes(mux) server := httptest.NewServer(mux) defer server.Close() b, _ := json.Marshal(map[string]string{"url": server.URL}) if err := os.WriteFile(filepath.Join(dir, "ready.json"), b, 0600); err != nil { t.Fatal(err) } for { if _, err := os.Stat(filepath.Join(dir, "stop")); err == nil { return } time.Sleep(10 * time.Millisecond) } } func trustStreamRequest(preauth bool) *http.Request { path, body := "/api/payment/sale", `{"reference":"SYNTH-BOOK","amount":2500,"currency":"GBP"}` if preauth { path, body = "/api/payment/preauth", `{"amount":2500,"currency":"GBP","transactionType":"Sale","checkoutDate":"synthetic"}` } r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) r.Header.Set("Content-Type", "application/json") return r } func TestTrustExistingEndpointsAndSafeFrames(t *testing.T) { for _, preauth := range []bool{false, true} { t.Run(map[bool]string{false: "sale", true: "preauth"}[preauth], func(t *testing.T) { dir := t.TempDir() app := fixtureTrustApp(t, dir) prints := 0 app.trustReceipt = func(s string) { prints++ if strings.Contains(s, "4111111111111111") || !strings.Contains(s, "************1133") { t.Error("unsafe or missing masked receipt") } } mux := http.NewServeMux() app.RegisterRoutes(mux) w := httptest.NewRecorder() mux.ServeHTTP(w, trustStreamRequest(preauth)) decoder := json.NewDecoder(w.Body) statuses, results := 0, 0 for { var frame paymentStreamMessage if err := decoder.Decode(&frame); err == io.EOF { break } else if err != nil { t.Fatal(err) } if frame.Type == "status" { statuses++ if strings.Contains(frame.Code, "PIN") || strings.Contains(frame.Code, "INSERT") { t.Error("invented terminal prompt") } } if frame.Result != nil { results++ if frame.Result.Outcome != "approved" || frame.Result.AmountMinor != 2500 || frame.Result.CurrencyCode != "GBP" || frame.Result.ReceiptNumber != "31" || frame.Result.SequenceNumber != "42" { t.Errorf("approved result=%+v", frame.Result) } } } if w.Code != 200 || statuses != 3 || results != 1 || prints != 1 { t.Errorf("HTTP/statuses/results/prints=%d/%d/%d/%d", w.Code, statuses, results, prints) } starts, _ := os.ReadFile(filepath.Join(dir, "starts")) if strings.Count(string(starts), "\n") != 1 { t.Errorf("financial starts=%q", starts) } if strings.Contains(w.Body.String(), "4111111111111111") || strings.Contains(w.Body.String(), "synthetic") { t.Error("private provider data escaped") } }) } } func TestTrustUnknownNeverDeclinesOrReposts(t *testing.T) { dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "uncertain"), nil, 0600); err != nil { t.Fatal(err) } app := fixtureTrustApp(t, dir) app.trustReceipt = func(string) { t.Error("uncertain payment printed approval") } w := httptest.NewRecorder() app.streamTrustPayment(w, trustStreamRequest(false), false) if !strings.Contains(w.Body.String(), `"outcome":"unknown"`) || strings.Contains(w.Body.String(), `"outcome":"declined"`) { t.Errorf("uncertain stream=%s", w.Body.String()) } starts, _ := os.ReadFile(filepath.Join(dir, "starts")) if strings.Count(string(starts), "\n") != 1 { t.Errorf("financial starts=%q", starts) } } func TestTrustInvalidRequestsAndNoOperationAPI(t *testing.T) { app := fixtureTrustApp(t, t.TempDir()) mux := http.NewServeMux() app.RegisterRoutes(mux) for _, body := range []string{`{"amount":0,"currency":"GBP"}`, `{`} { w := httptest.NewRecorder() r := httptest.NewRequest("POST", "/api/payment/sale", strings.NewReader(body)) mux.ServeHTTP(w, r) if w.Code != 400 { t.Errorf("invalid input=%q status=%d", body, w.Code) } } w := httptest.NewRecorder() mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/payment/trust/v1/capabilities", nil)) if w.Code != 404 { t.Errorf("removed operation API=%d", w.Code) } r := trustStreamRequest(false) ctx, cancel := context.WithCancel(r.Context()) cancel() w = httptest.NewRecorder() mux.ServeHTTP(w, r.WithContext(ctx)) if w.Body.Len() != 0 { t.Error("cancelled-before-dispatch request produced result") } } type trustBlockingWriter struct { entered chan struct{} release chan struct{} once sync.Once } func (w *trustBlockingWriter) Header() http.Header { return make(http.Header) } func (w *trustBlockingWriter) WriteHeader(int) {} func (w *trustBlockingWriter) Flush() {} func (w *trustBlockingWriter) Write(p []byte) (int, error) { w.once.Do(func() { close(w.entered) }) <-w.release return len(p), nil } func TestTrustBackpressureAndDisconnectDoNotCancelFinancialWorker(t *testing.T) { for _, disconnect := range []bool{false, true} { t.Run(map[bool]string{false: "backpressure", true: "disconnect"}[disconnect], func(t *testing.T) { app := fixtureTrustApp(t, t.TempDir()) printed := make(chan struct{}) var prints atomic.Int32 app.trustReceipt = func(string) { prints.Add(1); close(printed) } writer := &trustBlockingWriter{entered: make(chan struct{}), release: make(chan struct{})} ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan struct{}) go func() { app.streamTrustPayment(writer, trustStreamRequest(false).WithContext(ctx), false); close(done) }() var once sync.Once t.Cleanup(func() { once.Do(func() { close(writer.release) }); <-done }) select { case <-writer.entered: case <-time.After(3 * time.Second): t.Fatal("handler did not reach blocked writer") } if disconnect { cancel() } select { case <-printed: case <-time.After(3 * time.Second): t.Fatal("delivery blocked provider finalization/printing") } once.Do(func() { close(writer.release) }) select { case <-done: case <-time.After(3 * time.Second): t.Fatal("handler did not finish after delivery released") } if prints.Load() != 1 { t.Errorf("prints=%d, want 1", prints.Load()) } }) } } func TestTrustDisconnectDuringProviderCallAndConcurrentAdmission(t *testing.T) { entered, release := make(chan struct{}), make(chan struct{}) var calls atomic.Int32 client, err := trustpayments.New(trustpayments.Config{BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "fixture-site", Password: "synthetic", Terminal: "fixture-ped", Currency: "GBP", Timezone: "Europe/London", Transport: trustFixtureTransport(func(r *http.Request) (*http.Response, error) { calls.Add(1) var input map[string]string if err := json.NewDecoder(r.Body).Decode(&input); err != nil { return nil, err } close(entered) <-release if r.Context().Err() != nil { t.Error("incoming disconnect cancelled admitted provider request") } body, _ := json.Marshal(map[string]string{"refid": input["refid"], "siteid": "fixture-site", "terminalserialnumber": "fixture-ped", "type": input["type"], "amount": input["amount"], "resultcode": "Approved"}) return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(body))}, nil })}) if err != nil { t.Fatal(err) } app := &trustFixtureApp{App: &App{isPayment: true, cfg: &config.ConfigRec{}}, trustReceipt: func(string) {}} app.SetTrustPayments(client) app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(s string) { app.trustReceipt(s) }})) ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan struct{}) go func() { app.streamTrustPayment(httptest.NewRecorder(), trustStreamRequest(false).WithContext(ctx), false) close(done) }() var once sync.Once t.Cleanup(func() { once.Do(func() { close(release) }); <-done }) select { case <-entered: case <-time.After(3 * time.Second): t.Fatal("provider request was not admitted") } second := httptest.NewRecorder() app.streamTrustPayment(second, trustStreamRequest(false), false) if !strings.Contains(second.Body.String(), `"httpStatus":409`) { t.Errorf("concurrent admission status=%d, want 409", second.Code) } cancel() once.Do(func() { close(release) }) select { case <-done: case <-time.After(3 * time.Second): t.Fatal("admitted provider did not finish after disconnect") } if calls.Load() != 1 { t.Errorf("financial requests=%d, want 1", calls.Load()) } } type trustFixtureApp struct { *App trustReceipt func(string) } func (a *trustFixtureApp) streamTrustPayment(w http.ResponseWriter, r *http.Request, preauth bool) { a.streamPayment(w, r, preauth) }