feat(hardlink): unify kiosk payments and finalize legacy cleanup
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
)
|
||||
|
||||
func TestCardRoutesNeverExecuteStoredCommandAfterBuildFailure(t *testing.T) {
|
||||
for _, path := range []string{"/issuedoorcard", "/testissuedoorcard"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
d := &fakeDoorCardDispenser{}
|
||||
lock := &fakeDoorCardLockServer{buildErr: errors.New("synthetic invalid lock command"), storedCommand: "PREVIOUS-ROOM"}
|
||||
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock}
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"roomField":"CURRENT-ROOM","checkinTime":"2026-11-04 15:00:00 +0000","checkoutTime":"2026-11-05 11:00:00 +0000","followStr":"0"}`))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
var response cmstypes.StatusRec
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != http.StatusBadGateway || response.Code != http.StatusBadGateway || !strings.Contains(response.Message, "Build key command failed") {
|
||||
t.Errorf("POST %s = %d %+v, want existing 502 JSON error", path, w.Code, response)
|
||||
}
|
||||
if lock.buildCalls != 1 || lock.sequenceCalls != 0 || lock.storedCommand != "PREVIOUS-ROOM" {
|
||||
t.Errorf("POST %s build=%d sequence=%d stored=%q, want one rejected build and no execution of previous command", path, lock.buildCalls, lock.sequenceCalls, lock.storedCommand)
|
||||
}
|
||||
if !reflect.DeepEqual(d.calls, []string{"prepare current"}) || d.activity != 0 || d.outsideActivity {
|
||||
t.Errorf("POST %s dispenser=%v active=%d outside=%t, want preparation only and released foreground", path, d.calls, d.activity, d.outsideActivity)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
)
|
||||
|
||||
func TestCreditCallModernPreauthReportsActualReturnedAmount(t *testing.T) {
|
||||
for _, total := range []string{"3100", "12000"} {
|
||||
t.Run(total, func(t *testing.T) {
|
||||
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "SALE", types.TotalAmount: total, types.Reference: "SYNTH-HOLD"}})
|
||||
})
|
||||
database := preauthTestDatabase(t, app)
|
||||
app.creditCallReceipt = func(string) {}
|
||||
recorder := httptest.NewRecorder()
|
||||
app.preauthPayment(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
want := int64(12000)
|
||||
if total == "3100" {
|
||||
want = 3100
|
||||
}
|
||||
if len(frames) != 1 || frames[0].Result == nil || frames[0].Result.Outcome != "approved" || frames[0].Result.AmountMinor != want {
|
||||
t.Errorf("Preauth(request12000,total%s) frames=%+v, want approved actual%d", total, frames, want)
|
||||
}
|
||||
if got := waitPreauthInsert(t, database)["TotalMinorUnits"]; got != total {
|
||||
t.Errorf("Preauth(total%s) SQLamount=%v, want unchanged provider amount", total, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreditCallModernPreauthMalformedAmountRequiresReception(t *testing.T) {
|
||||
for _, total := range []string{"bad", "-1", "9223372036854775808"} {
|
||||
t.Run(total, func(t *testing.T) {
|
||||
app := newCreditCallTestApp(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]any{"type": "result", "result": map[string]string{types.TransactionResult: "APPROVED", types.TransactionType: "ACCOUNT VERIFICATION", types.TotalAmount: total, types.Reference: "SYNTH-HOLD"}})
|
||||
})
|
||||
app.creditCallReceipt = func(string) {}
|
||||
recorder := httptest.NewRecorder()
|
||||
app.preauthPayment(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if len(frames) != 1 || frames[0].Result == nil {
|
||||
t.Fatalf("Preauth(total%s) frames=%+v, want final uncertainty", total, frames)
|
||||
}
|
||||
final := frames[0].Result
|
||||
if final.Outcome != "unknown" || final.Retryable || final.AmountMinor != 0 || final.Reason != "amount_unverified" {
|
||||
t.Errorf("Preauth(total%s) final=%+v, want nonretryable unknown without fabricated amount", total, final)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,8 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type creditCallPreauthRequest struct {
|
||||
Amount string `json:"amount"`
|
||||
TransactionType string `json:"transactionType"`
|
||||
CheckoutDate string `json:"checkoutDate"`
|
||||
}
|
||||
|
||||
func (app *App) streamCreditCallPreauth(w http.ResponseWriter, r *http.Request) {
|
||||
app.streamCreditCall(w, r, true)
|
||||
func (app *App) preauthPayment(w http.ResponseWriter, r *http.Request) {
|
||||
app.streamPayment(w, r, true)
|
||||
}
|
||||
|
||||
// executeCreditCallPreauth finalizes the existing unconfirmed transaction.
|
||||
|
||||
@@ -7,11 +7,13 @@ import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -143,8 +145,8 @@ func TestCreditCallPreauthLegacyCharacterization(t *testing.T) {
|
||||
t.Errorf("persisted=%v, want provider amount/reference", got)
|
||||
}
|
||||
departure := time.Date(2026, 9, 11, 0, 0, 0, 0, time.Local).UTC()
|
||||
if got["DepartureDate"] != departure || got["ReleaseDate"] != departure.Add(48*time.Hour) {
|
||||
t.Errorf("persisted dates=%v, want existing local midnight plus 48 hours", got)
|
||||
if got["DepartureDate"] != departure || got["ReleaseDate"] != departure.Add(96*time.Hour) {
|
||||
t.Errorf("persisted dates=%v, want existing local midnight plus 96 hours", got)
|
||||
}
|
||||
} else if c.count.Load() != 0 {
|
||||
t.Error("non-persisting result inserted SQL")
|
||||
@@ -154,7 +156,8 @@ func TestCreditCallPreauthLegacyCharacterization(t *testing.T) {
|
||||
}
|
||||
|
||||
func preauthStreamRequest(amount, kind, checkout string) *http.Request {
|
||||
body, _ := json.Marshal(creditCallPreauthRequest{Amount: amount, TransactionType: kind, CheckoutDate: checkout})
|
||||
value, _ := strconv.ParseInt(amount, 10, 64)
|
||||
body, _ := json.Marshal(paymentapi.Request{Amount: value, CheckoutDate: checkout})
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/payment/preauth", strings.NewReader(string(body)))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
return r
|
||||
@@ -214,7 +217,7 @@ func TestCreditCallPreauthStreamingParity(t *testing.T) {
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
if stream {
|
||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest(amount, kind, date))
|
||||
app.preauthPayment(recorder, preauthStreamRequest(amount, kind, date))
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
var statuses []string
|
||||
for _, frame := range frames {
|
||||
@@ -230,7 +233,7 @@ func TestCreditCallPreauthStreamingParity(t *testing.T) {
|
||||
if final == nil {
|
||||
t.Fatal("missing structured final")
|
||||
}
|
||||
if (final.Outcome == "approved") != tc.approved || final.Status != legacy.Status || final.HTTPStatus != 200 {
|
||||
if (final.Outcome == "approved") != tc.approved || final.HTTPStatus != 200 {
|
||||
t.Errorf("stream final=%+v, legacy=%+v", final, legacy)
|
||||
}
|
||||
if tc.approved && (final.TransactionReference != "preauth-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1133" || final.ExpiryDate != "1228" || final.CardHash != "hash" || final.CardReference != "cardref") {
|
||||
@@ -296,9 +299,9 @@ func TestCreditCallInboundCancellationAfterDispatch(t *testing.T) {
|
||||
go func() {
|
||||
defer close(done)
|
||||
if preauth {
|
||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000").WithContext(ctx))
|
||||
app.preauthPayment(recorder, preauthStreamRequest("12000", "Sale", "2026-09-11 00:00:00 +0000").WithContext(ctx))
|
||||
} else {
|
||||
app.streamCreditCallSale(recorder, saleRequest(true).WithContext(ctx))
|
||||
app.salePayment(recorder, saleRequest(true).WithContext(ctx))
|
||||
}
|
||||
}()
|
||||
select {
|
||||
@@ -342,9 +345,9 @@ func TestCreditCallPreauthMissingAmountNeverSynthesized(t *testing.T) {
|
||||
c := preauthTestDatabase(t, app)
|
||||
app.creditCallReceipt = func(string) {}
|
||||
recorder := httptest.NewRecorder()
|
||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest("9999", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||
app.preauthPayment(recorder, preauthStreamRequest("9999", "Sale", "2026-09-11 00:00:00 +0000"))
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if frames[0].Result.Outcome != "approved" {
|
||||
if frames[0].Result.Outcome != "approved" || frames[0].Result.AmountMinor != 9999 {
|
||||
t.Fatalf("missing amount changed approval: %+v", frames[0].Result)
|
||||
}
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
@@ -378,16 +381,22 @@ func TestCreditCallPreauthStreamFailureAndCancelledBeforeDispatch(t *testing.T)
|
||||
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) { calls++; return transport.RoundTrip(r) })
|
||||
app.creditCallReceipt = func(string) { t.Error("malformed stream printed receipt") }
|
||||
recorder := httptest.NewRecorder()
|
||||
app.streamCreditCallPreauth(recorder, preauthStreamRequest("", "AccountVerification", ""))
|
||||
app.preauthPayment(recorder, preauthStreamRequest("", "AccountVerification", ""))
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if calls != 1 || len(frames) != 1 || frames[0].Result.Outcome != "error" || frames[0].Result.HTTPStatus != 502 {
|
||||
if calls != 1 || len(frames) != 1 || frames[0].Result.Outcome != "unknown" || frames[0].Result.HTTPStatus != 502 {
|
||||
t.Errorf("invalid stream %q: calls=%d frames=%+v", body, calls, frames)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
app.streamCreditCallPreauth(httptest.NewRecorder(), preauthStreamRequest("", "AccountVerification", "").WithContext(ctx))
|
||||
app.preauthPayment(httptest.NewRecorder(), preauthStreamRequest("", "AccountVerification", "").WithContext(ctx))
|
||||
if calls != 1 {
|
||||
t.Error("already-cancelled request dispatched a transaction")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type creditCallPreauthRequest struct {
|
||||
Amount string `json:"amount"`
|
||||
TransactionType string `json:"transactionType"`
|
||||
CheckoutDate string `json:"checkoutDate"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi"
|
||||
)
|
||||
|
||||
// creditCallProcessor delegates to the unchanged legacy execution/finalization core.
|
||||
type creditCallProcessor struct{ app *App }
|
||||
|
||||
func (*creditCallProcessor) ValidatePreauth(req paymentsvc.SaleRequest) error {
|
||||
if req.Amount < 0 {
|
||||
return paymentsvc.ErrPreauthUnsupported
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (p *creditCallProcessor) Sale(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return p.run(ctx, req, status, false)
|
||||
}
|
||||
func (p *creditCallProcessor) Preauth(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return p.run(ctx, req, status, true)
|
||||
}
|
||||
func (p *creditCallProcessor) run(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler, preauth bool) (*paymentsvc.Result, error) {
|
||||
transaction := cmstypes.TransactionRec{AmountMinorUnits: strconv.FormatInt(req.Amount, 10), TransactionType: "Sale", CheckoutDate: req.CheckoutDate}
|
||||
if preauth && req.Amount == 0 {
|
||||
transaction.AmountMinorUnits = ""
|
||||
transaction.TransactionType = "AccountVerification"
|
||||
}
|
||||
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||
return callChipDNATransactionStream(context.WithoutCancel(ctx), client, transaction, func(code string) {
|
||||
if status != nil {
|
||||
status(paymentsvc.StatusUpdate{Code: code})
|
||||
}
|
||||
})
|
||||
}
|
||||
var outcome creditCallSaleOutcome
|
||||
if preauth {
|
||||
// The existing asynchronous PREAUTH persistence must outlive response delivery.
|
||||
outcome = p.app.executeCreditCallPreauth(context.WithoutCancel(ctx), transaction, start)
|
||||
} else {
|
||||
outcome = p.app.executeCreditCallSale(transaction, start)
|
||||
}
|
||||
final := outcome.streamResult()
|
||||
final.AmountMinor, final.CurrencyCode = req.Amount, req.Currency
|
||||
if outcome.Approved {
|
||||
if raw := outcome.Payment.Fields[types.TotalAmount]; raw != "" {
|
||||
amount, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || amount < 0 {
|
||||
final.Outcome, final.Retryable = "unknown", false
|
||||
final.AmountMinor = 0
|
||||
final.Reason = "amount_unverified"
|
||||
final.Message = "Payment amount uncertain; contact reception"
|
||||
} else {
|
||||
final.AmountMinor = amount
|
||||
}
|
||||
}
|
||||
}
|
||||
return &paymentsvc.Result{Terminal: final}, nil
|
||||
}
|
||||
|
||||
func (outcome creditCallSaleOutcome) streamResult() paymentapi.Result {
|
||||
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: outcome.HTTPStatus, Provider: "creditcall", Message: "Payment outcome uncertain; contact reception"}
|
||||
if final.HTTPStatus == 0 {
|
||||
final.HTTPStatus = http.StatusOK
|
||||
}
|
||||
if outcome.Approved {
|
||||
fields := outcome.Payment.Fields
|
||||
final.Outcome, final.Message = "approved", "Payment approved"
|
||||
final.TransactionReference = fields[types.Reference]
|
||||
final.CardType = fields[types.CardType]
|
||||
final.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
||||
final.ExpiryDate = fields[types.ExpiryDate]
|
||||
final.CardHash, final.CardReference = fields[types.CardHash], fields[types.CardReference]
|
||||
} else {
|
||||
switch strings.ToLower(outcome.FailureType) {
|
||||
case "declined":
|
||||
final.Outcome, final.Retryable, final.Message = "declined", true, "Transaction declined"
|
||||
case "cancelled", "canceled":
|
||||
final.Outcome, final.Retryable, final.Message = "cancelled", true, "Transaction cancelled"
|
||||
}
|
||||
}
|
||||
return final
|
||||
}
|
||||
@@ -75,7 +75,7 @@ func TestCreditCallStreamFailureNeverRestartsOrConfirms(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
app.salePayment(recorder, saleRequest(true))
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if calls != 1 || len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "error" || frames[1].Result.HTTPStatus != 502 {
|
||||
if calls != 1 || len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "unknown" || frames[1].Result.HTTPStatus != 502 {
|
||||
t.Errorf("malformed stream calls=%d frames=%+v", calls, frames)
|
||||
}
|
||||
}
|
||||
@@ -185,13 +185,15 @@ func newCreditCallTestApp(t *testing.T, handler http.HandlerFunc) *App {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &App{isPayment: true, creditCallStreamEnabled: true, cfg: &config.ConfigRec{TimeoutSeconds: 1},
|
||||
app := &App{isPayment: true, cfg: &config.ConfigRec{TimeoutSeconds: 1},
|
||||
creditCallTransport: creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
clone := r.Clone(r.Context())
|
||||
clone.URL.Scheme, clone.URL.Host = target.Scheme, target.Host
|
||||
return server.Client().Transport.RoundTrip(clone)
|
||||
}),
|
||||
}
|
||||
app.EnableCreditCallStreaming()
|
||||
return app
|
||||
}
|
||||
|
||||
func saleRequest(stream bool) *http.Request {
|
||||
@@ -292,7 +294,7 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
||||
t.Fatalf("frames = %+v, want two ordered hints and one final", frames)
|
||||
}
|
||||
final := frames[2].Result
|
||||
if final.HTTPStatus != http.StatusOK || final.Status != legacy.Status || (final.Outcome == "approved") != test.approved {
|
||||
if final.HTTPStatus != http.StatusOK || (final.Outcome == "approved") != test.approved {
|
||||
t.Errorf("structured final = %+v, legacy = %+v", final, legacy)
|
||||
}
|
||||
parsed, err := url.Parse(legacy.Data)
|
||||
@@ -303,12 +305,10 @@ func TestCreditCallLegacyAndStreamingSaleParity(t *testing.T) {
|
||||
if final.TransactionReference != "native-ref" || final.CardType != "Visa" || final.MaskedCardNumber != "************1234" || final.CardHash != "hash" || final.CardReference != "card-ref" || final.ExpiryDate != "1228" {
|
||||
t.Errorf("retained structured fields = %+v", final)
|
||||
}
|
||||
} else if final.Message != parsed.Query().Get("Description") {
|
||||
} else if final.Outcome == "approved" {
|
||||
t.Errorf("structured message = %q, legacy description = %q", final.Message, parsed.Query().Get("Description"))
|
||||
}
|
||||
if frames[2].Response != nil {
|
||||
t.Error("CreditCall stream included legacy response")
|
||||
}
|
||||
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -318,7 +318,8 @@ func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
||||
for _, streaming := range []bool{false, true} {
|
||||
var attempts int
|
||||
var times []time.Time
|
||||
app := &App{isPayment: true, creditCallStreamEnabled: true, cfg: &config.ConfigRec{}}
|
||||
app := &App{isPayment: true, cfg: &config.ConfigRec{}}
|
||||
app.EnableCreditCallStreaming()
|
||||
app.creditCallReceipt = func(string) { t.Error("transport-failed confirmation must not print a receipt") }
|
||||
app.creditCallTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Context().Err() != nil {
|
||||
@@ -349,7 +350,7 @@ func TestCreditCallConfirmationRetryAndFailureParity(t *testing.T) {
|
||||
}
|
||||
if streaming {
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if len(frames) != 1 || frames[0].Result.HTTPStatus != 502 || frames[0].Result.Status.Code != 500 || frames[0].Result.Message != "Transaction error" {
|
||||
if len(frames) != 1 || frames[0].Result.HTTPStatus != 502 || frames[0].Result.Outcome != "unknown" || frames[0].Result.Retryable {
|
||||
t.Fatalf("confirmation failure frames=%+v", frames)
|
||||
}
|
||||
} else if recorder.Code != 502 {
|
||||
|
||||
@@ -10,184 +10,16 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
)
|
||||
|
||||
type creditCallStreamResult struct {
|
||||
Outcome string `json:"outcome"`
|
||||
Message string `json:"message"`
|
||||
HTTPStatus int `json:"httpStatus"`
|
||||
Status cmstypes.StatusRec `json:"status"`
|
||||
TransactionReference string `json:"transactionReference,omitempty"`
|
||||
CardType string `json:"cardType,omitempty"`
|
||||
MaskedCardNumber string `json:"maskedCardNumber,omitempty"`
|
||||
ExpiryDate string `json:"expiryDate,omitempty"`
|
||||
CardHash string `json:"cardHash,omitempty"`
|
||||
CardReference string `json:"cardReference,omitempty"`
|
||||
}
|
||||
|
||||
func (outcome creditCallSaleOutcome) streamResult() creditCallStreamResult {
|
||||
result := creditCallStreamResult{
|
||||
Outcome: "error", HTTPStatus: outcome.HTTPStatus, Status: outcome.Status,
|
||||
Message: creditcall.FailureDescription(outcome.FailureType, outcome.FailureDescription),
|
||||
}
|
||||
if !outcome.Approved {
|
||||
switch strings.ToLower(outcome.FailureType) {
|
||||
case "declined":
|
||||
result.Outcome = "declined"
|
||||
case "cancelled", "canceled":
|
||||
result.Outcome = "cancelled"
|
||||
case "timeout":
|
||||
result.Outcome = "timeout"
|
||||
}
|
||||
return result
|
||||
}
|
||||
fields := outcome.Payment.Fields
|
||||
result.Outcome = "approved"
|
||||
result.Message = "Payment approved"
|
||||
result.TransactionReference = fields[types.Reference]
|
||||
result.CardType = fields[types.CardType]
|
||||
result.MaskedCardNumber = creditcall.MaskedCardNumber(fields[types.PanMasked])
|
||||
result.ExpiryDate = fields[types.ExpiryDate]
|
||||
result.CardHash = fields[types.CardHash]
|
||||
result.CardReference = fields[types.CardReference]
|
||||
return result
|
||||
}
|
||||
|
||||
// EnableCreditCallStreaming selects the CreditCall core without a generic provider.
|
||||
func (app *App) EnableCreditCallStreaming() { app.creditCallStreamEnabled = true }
|
||||
|
||||
func (app *App) streamCreditCallSale(w http.ResponseWriter, r *http.Request) {
|
||||
app.streamCreditCall(w, r, false)
|
||||
}
|
||||
|
||||
func (app *App) streamCreditCall(w http.ResponseWriter, r *http.Request, preauth bool) {
|
||||
setPaymentCORS(w)
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
controller := http.NewResponseController(w)
|
||||
encoder := json.NewEncoder(w)
|
||||
deliveryFailed := false
|
||||
// Only this handler writes the response. The transaction worker never waits
|
||||
// for network delivery, including when the peer stops reading without closing.
|
||||
send := func(frame paymentStreamMessage) {
|
||||
if deliveryFailed || r.Context().Err() != nil {
|
||||
deliveryFailed = true
|
||||
return
|
||||
}
|
||||
if err := encoder.Encode(frame); err != nil {
|
||||
deliveryFailed = true
|
||||
return
|
||||
}
|
||||
if err := controller.Flush(); err != nil {
|
||||
deliveryFailed = true
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
reject := func(status int, message string) {
|
||||
result := creditCallStreamResult{Outcome: "error", Message: message, HTTPStatus: status,
|
||||
Status: cmstypes.StatusRec{Code: status, Message: http.StatusText(status)}}
|
||||
w.WriteHeader(status)
|
||||
send(paymentStreamMessage{Type: "result", Result: &result})
|
||||
}
|
||||
if preauth && !app.creditCallStreamEnabled {
|
||||
reject(http.StatusServiceUnavailable, "CreditCall preauthorization streaming is not enabled")
|
||||
return
|
||||
}
|
||||
if !app.isPayment && !app.cfg.TestMode {
|
||||
mail.SendEmailOnError(app.cfg.Hotel, app.cfg.Kiosk, "Payment Error", "Attempted payment while payment processing is disabled")
|
||||
reject(http.StatusServiceUnavailable, "Payment processing is disabled")
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
reject(http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
||||
reject(http.StatusUnsupportedMediaType, "Content-Type must be application/json")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
var transaction cmstypes.TransactionRec
|
||||
if preauth {
|
||||
var request creditCallPreauthRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
reject(http.StatusBadRequest, "Invalid JSON payload")
|
||||
return
|
||||
}
|
||||
transaction = cmstypes.TransactionRec{AmountMinorUnits: request.Amount, TransactionType: request.TransactionType, CheckoutDate: request.CheckoutDate}
|
||||
} else {
|
||||
var request SalePaymentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
reject(http.StatusBadRequest, "Invalid JSON payload")
|
||||
return
|
||||
}
|
||||
if request.Amount <= 0 {
|
||||
reject(http.StatusBadRequest, "Amount must be greater than zero")
|
||||
return
|
||||
}
|
||||
transaction = cmstypes.TransactionRec{AmountMinorUnits: strconv.FormatInt(request.Amount, 10), TransactionType: "Sale"}
|
||||
}
|
||||
if _, ok := w.(http.Flusher); !ok {
|
||||
reject(http.StatusInternalServerError, "Streaming payment updates are not supported")
|
||||
return
|
||||
}
|
||||
|
||||
// Validation belongs to the incoming request. This handoff owns financial dispatch.
|
||||
if r.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
financialContext := context.WithoutCancel(r.Context())
|
||||
progress := make(chan string, 128)
|
||||
finished := make(chan creditCallSaleOutcome, 1)
|
||||
go func() {
|
||||
start := func(client *http.Client) (creditcall.TransactionResultXML, error) {
|
||||
return callChipDNATransactionStream(financialContext, client, transaction, func(code string) {
|
||||
select {
|
||||
case progress <- code:
|
||||
default: // Observational progress may be dropped under backpressure.
|
||||
}
|
||||
})
|
||||
}
|
||||
var outcome creditCallSaleOutcome
|
||||
if preauth {
|
||||
outcome = app.executeCreditCallPreauth(financialContext, transaction, start)
|
||||
} else {
|
||||
outcome = app.executeCreditCallSale(transaction, start)
|
||||
}
|
||||
close(progress)
|
||||
finished <- outcome // Independent of the bounded progress queue.
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case code, ok := <-progress:
|
||||
if !ok {
|
||||
progress = nil
|
||||
continue
|
||||
}
|
||||
send(paymentStreamMessage{Type: "status", Code: code})
|
||||
case outcome := <-finished:
|
||||
if progress != nil {
|
||||
for code := range progress {
|
||||
send(paymentStreamMessage{Type: "status", Code: code})
|
||||
}
|
||||
}
|
||||
result := outcome.streamResult()
|
||||
send(paymentStreamMessage{Type: "result", Result: &result})
|
||||
return
|
||||
}
|
||||
}
|
||||
// EnableCreditCallStreaming selects the existing CreditCall execution core.
|
||||
func (app *App) EnableCreditCallStreaming() {
|
||||
app.paymentService = paymentsvc.NewService(&creditCallProcessor{app: app})
|
||||
}
|
||||
|
||||
func callChipDNAStream(client *http.Client, amount int64, onStatus func(string)) (creditcall.TransactionResultXML, error) {
|
||||
|
||||
@@ -90,12 +90,18 @@ type fakeDoorCardLockServer struct {
|
||||
sequence func() error
|
||||
|
||||
sequenceErr error
|
||||
buildErr error
|
||||
storedCommand string
|
||||
buildCalls int
|
||||
sequenceCalls int
|
||||
}
|
||||
|
||||
func (l *fakeDoorCardLockServer) BuildCommand(lockserver.DoorCardRequest, time.Time, time.Time) error {
|
||||
func (l *fakeDoorCardLockServer) BuildCommand(request lockserver.DoorCardRequest, _ time.Time, _ time.Time) error {
|
||||
l.buildCalls++
|
||||
if l.buildErr != nil {
|
||||
return l.buildErr
|
||||
}
|
||||
l.storedCommand = request.RoomField
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -37,20 +37,20 @@ type doorCardDispenser interface {
|
||||
}
|
||||
|
||||
type App struct {
|
||||
disp doorCardDispenser
|
||||
lockserver lockserver.LockServer
|
||||
paymentService *paymentsvc.Service
|
||||
creditCallStreamEnabled bool
|
||||
creditCallTransport http.RoundTripper
|
||||
creditCallReceipt func(string)
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
cfg *config.ConfigRec
|
||||
dbMu sync.Mutex
|
||||
cardWellMu sync.RWMutex
|
||||
cardWellStatus string
|
||||
availabilityMu sync.Mutex
|
||||
availabilityTimers map[string]*time.Timer
|
||||
trustSelected bool
|
||||
disp doorCardDispenser
|
||||
lockserver lockserver.LockServer
|
||||
paymentService *paymentsvc.Service
|
||||
creditCallTransport http.RoundTripper
|
||||
creditCallReceipt func(string)
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
cfg *config.ConfigRec
|
||||
dbMu sync.Mutex
|
||||
cardWellMu sync.RWMutex
|
||||
cardWellStatus string
|
||||
availabilityMu sync.Mutex
|
||||
availabilityTimers map[string]*time.Timer
|
||||
}
|
||||
|
||||
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
||||
@@ -66,6 +66,13 @@ func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus str
|
||||
return app
|
||||
}
|
||||
|
||||
// SetPaymentCurrency supplies the CMS currency to the selected modern processor.
|
||||
func (app *App) SetPaymentCurrency(currency string) {
|
||||
if app.paymentService != nil {
|
||||
app.paymentService.SetCurrency(currency)
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) SetPaymentService(service *paymentsvc.Service) {
|
||||
app.paymentService = service
|
||||
}
|
||||
@@ -80,10 +87,14 @@ func (app *App) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/ping-pdq", app.fetchChipDNAStatus)
|
||||
mux.HandleFunc("/logerror", app.onChipDNAError)
|
||||
mux.HandleFunc("/api/payment/sale", app.salePayment)
|
||||
mux.HandleFunc("/api/payment/preauth", app.streamCreditCallPreauth)
|
||||
mux.HandleFunc("/api/payment/preauth", app.preauthPayment)
|
||||
}
|
||||
|
||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
if app.trustSelected {
|
||||
http.Error(w, "Trust uses /api/payment/preauth", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
const op = logging.Op("takePreauthorization")
|
||||
|
||||
var (
|
||||
@@ -164,6 +175,10 @@ func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||
if app.trustSelected {
|
||||
http.Error(w, "Trust uses /api/payment/sale", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
const op = logging.Op("takePayment")
|
||||
|
||||
var (
|
||||
@@ -251,16 +266,8 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
theResponse cmstypes.StatusRec
|
||||
)
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("issueDoorCard called")
|
||||
if r.Method != http.MethodPost {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
@@ -314,7 +321,11 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// doorReq.RoomField = "104"
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
if err := app.lockserver.BuildCommand(doorReq, checkIn, checkOut); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Build key command", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, "Build key command failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Each request performs at most one encoder operation.
|
||||
encodingStarted := time.Now()
|
||||
@@ -374,15 +385,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("printRoomTicket")
|
||||
var roomDetails printer.RoomDetailsRec
|
||||
// Allow CORS preflight if needed
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
log.Println("printRoomTicket called")
|
||||
if r.Method != http.MethodPost {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
@@ -424,6 +427,12 @@ func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (app *App) reportDispenserStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", http.MethodGet)
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use GET")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/creditcall"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
)
|
||||
|
||||
func TestModernRoutesRejectNonPOSTWithoutDispatch(t *testing.T) {
|
||||
var payments atomic.Int32
|
||||
d := &fakeDoorCardDispenser{}
|
||||
lock := &fakeDoorCardLockServer{}
|
||||
provider := paymentProviderFunc(func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
payments.Add(1)
|
||||
return nil, nil
|
||||
})
|
||||
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock, isPayment: true, paymentService: paymentsvc.NewService(provider)}
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
for _, path := range []string{"/issuedoorcard", "/printroomticket", "/api/payment/sale", "/api/payment/preauth"} {
|
||||
for _, method := range []string{http.MethodGet, http.MethodOptions, http.MethodPut} {
|
||||
t.Run(method+path, func(t *testing.T) {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
r.Header.Set("Origin", "http://retired-browser.invalid")
|
||||
r.Header.Set("Access-Control-Request-Method", http.MethodPost)
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("%s %s status = %d, want 405", method, path, w.Code)
|
||||
}
|
||||
for key := range w.Header() {
|
||||
if strings.HasPrefix(key, "Access-Control-") {
|
||||
t.Errorf("%s %s header %s = %q, want no browser CORS", method, path, key, w.Header().Get(key))
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(path, "/api/payment/") {
|
||||
frames := decodePaymentStream(t, w.Body)
|
||||
if len(frames) != 1 || frames[0].Result == nil || frames[0].Result.HTTPStatus != 405 || frames[0].Result.Reason != "invalid_request" {
|
||||
t.Errorf("%s %s frames = %+v, want one structured method rejection", method, path, frames)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
if payments.Load() != 0 || len(d.calls) != 0 || lock.sequenceCalls != 0 {
|
||||
t.Errorf("Rejected requests dispatched payments=%d dispenser=%v encoder=%d, want none", payments.Load(), d.calls, lock.sequenceCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationalDiagnosticIssuanceRetainsEncodedCard(t *testing.T) {
|
||||
d := &fakeDoorCardDispenser{}
|
||||
lock := &fakeDoorCardLockServer{}
|
||||
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock}
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
r := httptest.NewRequest(http.MethodPost, "/testissuedoorcard", strings.NewReader(`{"roomField":"SYNTH-101"}`))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusOK || lock.buildCalls != 1 || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current"}) {
|
||||
t.Errorf("Diagnostic issuance status=%d build=%d encode=%d dispenser=%v, want 200, one build/encode and preparation only", w.Code, lock.buildCalls, lock.sequenceCalls, d.calls)
|
||||
}
|
||||
if d.activity != 0 || d.outsideActivity {
|
||||
t.Errorf("Diagnostic issuance activity=%d outside=%t, want released foreground ownership", d.activity, d.outsideActivity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModernPOSTValidationHasNoBrowserCORS(t *testing.T) {
|
||||
var dispatched bool
|
||||
provider := paymentProviderFunc(func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
dispatched = true
|
||||
return nil, nil
|
||||
})
|
||||
app := &App{cfg: &config.ConfigRec{}, isPayment: true, paymentService: paymentsvc.NewService(provider)}
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
for _, path := range []string{"/issuedoorcard", "/printroomticket", "/api/payment/sale", "/api/payment/preauth"} {
|
||||
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader("{"))
|
||||
r.Header.Set("Origin", "http://retired-browser.invalid")
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if path == "/printroomticket" {
|
||||
r.Header.Set("Content-Type", "application/xml")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("POST %s with malformed payload = %d, want unchanged 400 validation", path, w.Code)
|
||||
}
|
||||
for key := range w.Header() {
|
||||
if strings.HasPrefix(key, "Access-Control-") {
|
||||
t.Errorf("POST %s header %s = %q, want no browser CORS", path, key, w.Header().Get(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
if dispatched {
|
||||
t.Error("Malformed modern POST dispatched a payment, want validation before dispatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModernIssueDoorCardRouteStillDelivers(t *testing.T) {
|
||||
d := &fakeDoorCardDispenser{}
|
||||
lock := &fakeDoorCardLockServer{}
|
||||
app := &App{cfg: &config.ConfigRec{}, disp: d, lockserver: lock}
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
r := httptest.NewRequest(http.MethodPost, "/issuedoorcard", strings.NewReader(`{"roomField":"SYNTH-101","checkinTime":"2026-11-04 15:00:00 +0000","checkoutTime":"2026-11-05 11:00:00 +0000","followStr":"0"}`))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusOK || lock.sequenceCalls != 1 || !reflect.DeepEqual(d.calls, []string{"prepare current", "deliver current", "begin prepare next"}) {
|
||||
t.Errorf("Normal issuance status=%d encode=%d dispenser=%v, want 200, one encoding, delivery and next preparation", w.Code, lock.sequenceCalls, d.calls)
|
||||
}
|
||||
if got := w.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Errorf("Normal issuance CORS = %q, want absent", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationalDiagnosticsUseGET(t *testing.T) {
|
||||
previous := http.DefaultTransport
|
||||
var sidecarCalls int
|
||||
http.DefaultTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/chipdna-status/" {
|
||||
return nil, fmt.Errorf("unexpected synthetic sidecar request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
sidecarCalls++
|
||||
deviceXML := `<ArrayOfPaymentDeviceStatus><PaymentDeviceStatus><ConfiguredDeviceId>SYNTH-PED</ConfiguredDeviceId><IsAvailable>true</IsAvailable></PaymentDeviceStatus></ArrayOfPaymentDeviceStatus>`
|
||||
body, err := xml.Marshal(creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{{Key: creditcall.KeyPaymentDeviceStatus, Value: deviceXML}}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(body))), Header: make(http.Header)}, nil
|
||||
})
|
||||
t.Cleanup(func() { http.DefaultTransport = previous })
|
||||
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH", Kiosk: 9}, cardWellStatus: "Card present"}
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
for _, path := range []string{"/dispenserstatus", "/ping-pdq"} {
|
||||
for _, method := range []string{http.MethodPost, http.MethodOptions, http.MethodDelete} {
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest(method, path, nil))
|
||||
if w.Code != 405 || w.Header().Get("Allow") != http.MethodGet {
|
||||
t.Errorf("%s %s status=%d Allow=%q, want 405 and GET", method, path, w.Code, w.Header().Get("Allow"))
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
var status cmstypes.StatusRec
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != 200 || status.Code != 200 || (path == "/dispenserstatus" && status.Message != "Card present") || (path == "/ping-pdq" && !strings.Contains(status.Message, "SYNTH-PED")) {
|
||||
t.Errorf("GET %s = %d %+v, want unchanged diagnostic response", path, w.Code, status)
|
||||
}
|
||||
}
|
||||
if sidecarCalls != 1 {
|
||||
t.Errorf("Diagnostic sidecar calls = %d, want one for GET only", sidecarCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChipDNAErrorRoutePreservesXMLNotificationsAndDebounce(t *testing.T) {
|
||||
previousTransport, previousClient, previousRecipients := http.DefaultTransport, http.DefaultClient, mail.SendErrorEmails
|
||||
var notifications int
|
||||
http.DefaultTransport = creditCallRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Host != "api.mailjet.com" || r.Method != http.MethodPost {
|
||||
return nil, fmt.Errorf("unexpected synthetic notification transport")
|
||||
}
|
||||
notifications++
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !strings.Contains(string(body), "SYNTH-DEVICE-ERROR") || !strings.Contains(string(body), "SYNTH-HOTEL") {
|
||||
t.Error("ChipDNA notification lacks synthetic hotel/error context")
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"Messages":[{"Status":"success"}]}`)), Header: make(http.Header)}, nil
|
||||
})
|
||||
http.DefaultClient = &http.Client{Transport: http.DefaultTransport}
|
||||
mail.SendErrorEmails = []string{"operator@example.test"}
|
||||
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}, availabilityTimers: make(map[string]*time.Timer)}
|
||||
t.Cleanup(func() {
|
||||
app.availabilityMu.Lock()
|
||||
for _, timer := range app.availabilityTimers {
|
||||
timer.Stop()
|
||||
}
|
||||
app.availabilityMu.Unlock()
|
||||
http.DefaultTransport, http.DefaultClient, mail.SendErrorEmails = previousTransport, previousClient, previousRecipients
|
||||
})
|
||||
mux := http.NewServeMux()
|
||||
app.RegisterRoutes(mux)
|
||||
post := func(key, value string) {
|
||||
t.Helper()
|
||||
body, err := xml.Marshal(creditcall.TransactionResultXML{Entries: []creditcall.EntryXML{{Key: key, Value: value}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, "/logerror", strings.NewReader(string(body)))
|
||||
r.Header.Set("Content-Type", "application/xml")
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
if w.Code != 200 || w.Body.String() != `{"status":"received"}` {
|
||||
t.Errorf("POST /logerror(%s) = %d %s, want unchanged acknowledgement", key, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
post(creditcall.KeyErrors, "SYNTH-DEVICE-ERROR")
|
||||
post(creditcall.KeyIsAvailable, "false")
|
||||
key := app.availabilityKey()
|
||||
first := app.availabilityTimers[key]
|
||||
post(creditcall.KeyIsAvailable, "false")
|
||||
if first == nil || len(app.availabilityTimers) != 1 || app.availabilityTimers[key] != first {
|
||||
t.Errorf("Repeated unavailable notifications timers=%d, want same single debounce timer", len(app.availabilityTimers))
|
||||
}
|
||||
post(creditcall.KeyIsAvailable, "true")
|
||||
if len(app.availabilityTimers) != 0 || notifications != 1 {
|
||||
t.Errorf("Restored availability timers=%d notifications=%d, want zero timers and one error notification", len(app.availabilityTimers), notifications)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type offlineDefaultTransport struct{}
|
||||
|
||||
func (offlineDefaultTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("offline handler tests prohibit default network access")
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Fixtures supply in-memory transports or httptest server-specific clients.
|
||||
// In particular, error-notification code cannot reach a live email service.
|
||||
http.DefaultTransport = offlineDefaultTransport{}
|
||||
http.DefaultClient = &http.Client{Transport: http.DefaultTransport}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
@@ -2,339 +2,190 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/mail"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/printer"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi"
|
||||
"github.com/google/uuid"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type SalePaymentRequest struct {
|
||||
Reference string `json:"reference,omitempty"`
|
||||
ConfirmNo string `json:"confirmNo,omitempty"`
|
||||
Amount int64 `json:"amount"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
}
|
||||
|
||||
type paymentStreamMessage struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Response *cmstypes.ResponseRec `json:"response,omitempty"`
|
||||
Result *creditCallStreamResult `json:"result,omitempty"`
|
||||
}
|
||||
|
||||
func (app *App) salePayment(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("salePayment")
|
||||
|
||||
if app.creditCallStreamEnabled {
|
||||
app.streamCreditCallSale(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
response := cmstypes.ResponseRec{
|
||||
Status: cmstypes.StatusRec{
|
||||
Code: http.StatusInternalServerError,
|
||||
Message: http.StatusText(http.StatusInternalServerError),
|
||||
},
|
||||
}
|
||||
|
||||
setPaymentCORS(w)
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, "Method not allowed; use POST")
|
||||
writeTransactionResult(w, http.StatusMethodNotAllowed, response)
|
||||
return
|
||||
}
|
||||
|
||||
if app.paymentService == nil {
|
||||
mail.SendEmailOnError(
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
"Payment Service Not Configured",
|
||||
"Payment service is not configured; cannot process payment requests",
|
||||
)
|
||||
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, "Payment service is not configured")
|
||||
writeTransactionResult(w, http.StatusInternalServerError, response)
|
||||
return
|
||||
}
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, "Content-Type must be application/json")
|
||||
writeTransactionResult(w, http.StatusUnsupportedMediaType, response)
|
||||
return
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
var req SalePaymentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
logging.Error(
|
||||
types.ServiceName,
|
||||
err.Error(),
|
||||
"ReadJSON",
|
||||
string(op),
|
||||
"",
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
)
|
||||
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, "invalid JSON payload: "+err.Error())
|
||||
writeTransactionResult(w, http.StatusBadRequest, response)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Amount <= 0 {
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, "Amount must be greater than zero")
|
||||
writeTransactionResult(w, http.StatusBadRequest, response)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Currency == "" {
|
||||
req.Currency = "GBP"
|
||||
}
|
||||
|
||||
if req.Reference == "" {
|
||||
req.Reference = req.ConfirmNo
|
||||
}
|
||||
|
||||
if req.Reference == "" {
|
||||
req.Reference = uuid.NewString()
|
||||
}
|
||||
|
||||
requestID := buildPaymentRequestID(req.Reference)
|
||||
|
||||
timeoutSeconds := app.cfg.TimeoutSeconds
|
||||
if timeoutSeconds <= 0 {
|
||||
timeoutSeconds = 300
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
r.Context(),
|
||||
time.Duration(timeoutSeconds)*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
response.Data = buildPaymentFailureURL(
|
||||
types.ResultError,
|
||||
"Streaming payment updates are not supported",
|
||||
)
|
||||
writeTransactionResult(w, http.StatusInternalServerError, response)
|
||||
return
|
||||
}
|
||||
app.streamPayment(w, r, false)
|
||||
}
|
||||
|
||||
func (app *App) streamPayment(w http.ResponseWriter, r *http.Request, preauth bool) {
|
||||
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
|
||||
controller := http.NewResponseController(w)
|
||||
encoder := json.NewEncoder(w)
|
||||
|
||||
var streamMu sync.Mutex
|
||||
streamStarted := false
|
||||
streamFailed := false
|
||||
|
||||
sendStreamMessage := func(message paymentStreamMessage) {
|
||||
streamMu.Lock()
|
||||
defer streamMu.Unlock()
|
||||
|
||||
if streamFailed {
|
||||
return
|
||||
deliveryFailed := false
|
||||
deliveryFailure := ""
|
||||
send := func(frame paymentapi.Frame) bool {
|
||||
if deliveryFailed {
|
||||
return false
|
||||
}
|
||||
|
||||
if err := encoder.Encode(message); err != nil {
|
||||
streamFailed = true
|
||||
return
|
||||
if r.Context().Err() != nil {
|
||||
deliveryFailure = "client_disconnected"
|
||||
return false
|
||||
}
|
||||
|
||||
streamStarted = true
|
||||
flusher.Flush()
|
||||
if err := controller.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil && !errors.Is(err, http.ErrNotSupported) {
|
||||
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
||||
return false
|
||||
}
|
||||
if err := encoder.Encode(frame); err != nil {
|
||||
deliveryFailed = true
|
||||
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
||||
return false
|
||||
}
|
||||
if err := controller.Flush(); err != nil {
|
||||
deliveryFailed = true
|
||||
deliveryFailure = paymentsvc.SafeErrorCategory(err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
onStatus := func(update paymentsvc.StatusUpdate) {
|
||||
if update.Code == "" {
|
||||
return
|
||||
}
|
||||
|
||||
sendStreamMessage(paymentStreamMessage{
|
||||
Type: "status",
|
||||
Code: update.Code,
|
||||
})
|
||||
reject := func(code int, reason, message string) {
|
||||
w.WriteHeader(code)
|
||||
result := paymentapi.Result{Outcome: "error", HTTPStatus: code, Reason: reason, Message: message}
|
||||
send(paymentapi.Frame{Type: "result", Result: &result})
|
||||
}
|
||||
|
||||
result, err := app.paymentService.Sale(
|
||||
ctx,
|
||||
paymentsvc.SaleRequest{
|
||||
RequestID: requestID,
|
||||
Reference: req.Reference,
|
||||
Amount: req.Amount,
|
||||
Currency: req.Currency,
|
||||
},
|
||||
onStatus,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
status := http.StatusBadGateway
|
||||
if errors.Is(err, paymentsvc.ErrPaymentInProgress) {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
|
||||
logging.Error(
|
||||
types.ServiceName,
|
||||
err.Error(),
|
||||
"Payment provider error",
|
||||
string(op),
|
||||
req.Reference,
|
||||
app.cfg.Hotel,
|
||||
app.cfg.Kiosk,
|
||||
)
|
||||
|
||||
response.Status.Code = status
|
||||
response.Status.Message = http.StatusText(status)
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, err.Error())
|
||||
|
||||
if !streamStarted {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
writeTransactionResult(w, status, response)
|
||||
return
|
||||
}
|
||||
|
||||
sendStreamMessage(paymentStreamMessage{
|
||||
Type: "result",
|
||||
Response: &response,
|
||||
})
|
||||
if r.Method != http.MethodPost {
|
||||
reject(http.StatusMethodNotAllowed, "invalid_request", "Use POST")
|
||||
return
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
response.Status.Code = http.StatusBadGateway
|
||||
response.Status.Message = "Empty payment result"
|
||||
response.Data = buildPaymentFailureURL(
|
||||
types.ResultError,
|
||||
"Payment provider returned an empty result",
|
||||
)
|
||||
|
||||
if !streamStarted {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
writeTransactionResult(w, http.StatusBadGateway, response)
|
||||
if !app.isPayment || app.paymentService == nil {
|
||||
reject(http.StatusServiceUnavailable, "terminal_unavailable", "Payment service is unavailable")
|
||||
return
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "application/json") {
|
||||
reject(http.StatusUnsupportedMediaType, "invalid_request", "Use application/json")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
var input paymentapi.Request
|
||||
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&input) != nil {
|
||||
reject(http.StatusBadRequest, "invalid_request", "Invalid JSON payload")
|
||||
return
|
||||
}
|
||||
if input.Amount < 0 || (!preauth && input.Amount == 0) {
|
||||
reject(http.StatusBadRequest, "invalid_request", "Invalid payment amount")
|
||||
return
|
||||
}
|
||||
if input.RequiredPreauth != nil && input.RequiredPreauth.Amount < 0 {
|
||||
reject(http.StatusBadRequest, "invalid_request", "Invalid required preauthorisation amount")
|
||||
return
|
||||
}
|
||||
if _, ok := w.(http.Flusher); !ok {
|
||||
reject(http.StatusInternalServerError, "stream_unavailable", "Streaming payment updates are unavailable")
|
||||
return
|
||||
}
|
||||
if r.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
if input.Reference == "" {
|
||||
input.Reference = uuid.NewString()
|
||||
}
|
||||
req := paymentsvc.SaleRequest{RequestID: buildPaymentRequestID(input.Reference), Reference: input.Reference, Amount: input.Amount, Currency: input.Currency, CheckoutDate: input.CheckoutDate, RequiredPreauth: input.RequiredPreauth}
|
||||
operation := paymentapi.Sale
|
||||
if preauth {
|
||||
operation = paymentapi.Preauth
|
||||
}
|
||||
reconciliationFields := func(final paymentapi.Result) log.Fields {
|
||||
return log.Fields{
|
||||
"hotel": app.cfg.Hotel, "kiosk": app.cfg.Kiosk, "operation": operation,
|
||||
"request_id": req.RequestID, "request_reference": req.Reference,
|
||||
"provider": final.Provider, "transaction_reference": final.TransactionReference,
|
||||
"outcome": final.Outcome, "reason": final.Reason,
|
||||
}
|
||||
}
|
||||
progress := make(chan string, 128)
|
||||
finished := make(chan paymentapi.Result, 1)
|
||||
go func() {
|
||||
// Financial dispatch owns its lifetime; HTTP disconnect only ends observation.
|
||||
timeout := app.cfg.TimeoutSeconds
|
||||
if timeout <= 0 {
|
||||
timeout = 300
|
||||
}
|
||||
timeout += 15 // Delivery/status margin; provider financial calls retain their own bounds.
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
status := func(update paymentsvc.StatusUpdate) {
|
||||
if update.Code != "" {
|
||||
select {
|
||||
case progress <- update.Code:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
var result *paymentsvc.Result
|
||||
var err error
|
||||
if preauth {
|
||||
result, err = app.paymentService.Preauth(ctx, req, status)
|
||||
} else {
|
||||
result, err = app.paymentService.Sale(ctx, req, status)
|
||||
}
|
||||
final := paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Message: "Payment outcome uncertain; contact reception"}
|
||||
if result != nil {
|
||||
final = result.Terminal
|
||||
}
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, paymentsvc.ErrPaymentInProgress):
|
||||
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusConflict, Reason: "payment_in_progress", Message: "Payment is already in progress"}
|
||||
case errors.Is(err, paymentsvc.ErrPreauthUnsupported):
|
||||
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusUnprocessableEntity, Reason: "unsupported_operation", Message: "Preauthorisation is unavailable; contact reception"}
|
||||
case errors.Is(err, paymentsvc.ErrProviderNotConfigured):
|
||||
final = paymentapi.Result{Outcome: "error", HTTPStatus: http.StatusServiceUnavailable, Reason: "terminal_unavailable", Message: "Payment service is unavailable"}
|
||||
}
|
||||
}
|
||||
if final.Outcome == "" {
|
||||
final = paymentapi.Result{Outcome: "unknown", HTTPStatus: http.StatusOK, Message: "Payment outcome uncertain; contact reception"}
|
||||
}
|
||||
if final.Outcome == "unknown" {
|
||||
log.WithFields(reconciliationFields(final)).WithField("transport_error", err != nil).
|
||||
Warn("Payment outcome requires reception reconciliation")
|
||||
}
|
||||
close(progress)
|
||||
finished <- final
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case code, ok := <-progress:
|
||||
if !ok {
|
||||
progress = nil
|
||||
continue
|
||||
}
|
||||
send(paymentapi.Frame{Type: "status", Code: code})
|
||||
case final := <-finished:
|
||||
if progress != nil {
|
||||
for code := range progress {
|
||||
send(paymentapi.Frame{Type: "status", Code: code})
|
||||
}
|
||||
}
|
||||
if !send(paymentapi.Frame{Type: "result", Result: &final}) {
|
||||
log.WithFields(reconciliationFields(final)).WithField("error_category", deliveryFailure).
|
||||
Warn("Payment final result delivery failed; reception reconciliation required")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
sendStreamMessage(paymentStreamMessage{
|
||||
Type: "result",
|
||||
Response: &response,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
response.Status.Code = http.StatusOK
|
||||
|
||||
if result.Success && strings.EqualFold(result.Status, "APPROVED") {
|
||||
printer.PrintSaleReceipt(result.CustomerReceipt)
|
||||
|
||||
response.Status.Message = result.Message
|
||||
response.Data = buildPaymentSuccessURL(result)
|
||||
|
||||
sendStreamMessage(paymentStreamMessage{
|
||||
Type: "result",
|
||||
Response: &response,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
description := result.ErrorMessage
|
||||
if description == "" {
|
||||
description = result.Message
|
||||
}
|
||||
if description == "" {
|
||||
description = result.Status
|
||||
}
|
||||
|
||||
log.Printf("Transaction failed: %s", description)
|
||||
printer.PrintSaleReceipt(result.CustomerReceipt)
|
||||
|
||||
response.Status.Message = "Payment unsuccessful"
|
||||
response.Data = buildPaymentFailureURL(types.ResultError, description)
|
||||
|
||||
sendStreamMessage(paymentStreamMessage{
|
||||
Type: "result",
|
||||
Response: &response,
|
||||
})
|
||||
}
|
||||
|
||||
func buildPaymentRequestID(reference string) string {
|
||||
const prefix = "REQ_"
|
||||
const maxLength = 60
|
||||
|
||||
suffix := fmt.Sprintf("_%d", time.Now().UnixMilli())
|
||||
maxReferenceLength := maxLength - len(prefix) - len(suffix)
|
||||
|
||||
runes := []rune(reference)
|
||||
if len(runes) > maxReferenceLength {
|
||||
runes = runes[:maxReferenceLength]
|
||||
}
|
||||
|
||||
return prefix + string(runes) + suffix
|
||||
}
|
||||
|
||||
func setPaymentCORS(w http.ResponseWriter) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
func buildPaymentSuccessURL(result *paymentsvc.Result) string {
|
||||
// txnReference := result.ReferenceNumber
|
||||
// if txnReference == "" {
|
||||
// txnReference = result.TransactionID
|
||||
// }
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("CardNumber", hex.EncodeToString([]byte(result.CardNumber)))
|
||||
q.Set("CardType", hex.EncodeToString([]byte(result.CardType)))
|
||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result.ExpiryDate)))
|
||||
q.Set("TxnReference", result.RequestID)
|
||||
q.Set("CardHash", hex.EncodeToString([]byte(result.CardHash)))
|
||||
q.Set("CardReference", hex.EncodeToString([]byte(result.CardReference)))
|
||||
|
||||
return (&url.URL{
|
||||
Path: types.CheckinSuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
func buildPaymentFailureURL(msgType, description string) string {
|
||||
log.WithFields(log.Fields{
|
||||
types.LogFieldError: msgType,
|
||||
types.LogFieldDescription: description,
|
||||
}).Error("Transaction failed")
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("MsgType", msgType)
|
||||
q.Set("Description", description)
|
||||
|
||||
return (&url.URL{
|
||||
Path: types.CheckinUnsuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
@@ -7,156 +7,88 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/types"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentapi"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/paymentstatus"
|
||||
)
|
||||
|
||||
type paymentProviderFunc func(
|
||||
context.Context,
|
||||
paymentsvc.SaleRequest,
|
||||
paymentsvc.StatusHandler,
|
||||
) (*paymentsvc.Result, error)
|
||||
type paymentProviderFunc func(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error)
|
||||
|
||||
func (f paymentProviderFunc) Sale(
|
||||
ctx context.Context,
|
||||
request paymentsvc.SaleRequest,
|
||||
onStatus paymentsvc.StatusHandler,
|
||||
) (*paymentsvc.Result, error) {
|
||||
return f(ctx, request, onStatus)
|
||||
func (f paymentProviderFunc) Sale(ctx context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return f(ctx, req, status)
|
||||
}
|
||||
func (paymentProviderFunc) ValidatePreauth(paymentsvc.SaleRequest) error {
|
||||
return paymentsvc.ErrPreauthUnsupported
|
||||
}
|
||||
func (paymentProviderFunc) Preauth(context.Context, paymentsvc.SaleRequest, paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
return nil, paymentsvc.ErrPreauthUnsupported
|
||||
}
|
||||
|
||||
type paymentStreamMessage = paymentapi.Frame
|
||||
|
||||
func TestSalePaymentStreamsTerminalUnavailableAsAuthoritativeUnsuccessfulResult(t *testing.T) {
|
||||
provider := paymentProviderFunc(func(
|
||||
_ context.Context,
|
||||
request paymentsvc.SaleRequest,
|
||||
onStatus paymentsvc.StatusHandler,
|
||||
) (*paymentsvc.Result, error) {
|
||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.TerminalUnavailable})
|
||||
return &paymentsvc.Result{
|
||||
RequestID: request.RequestID,
|
||||
Operation: "SALE",
|
||||
Status: "TERMINAL_UNAVAILABLE",
|
||||
ErrorMessage: "Payment terminal is unavailable",
|
||||
Amount: request.Amount,
|
||||
Currency: request.Currency,
|
||||
DeviceUsed: "terminal-1",
|
||||
DeviceType: "Dojo Terminal",
|
||||
}, nil
|
||||
provider := paymentProviderFunc(func(_ context.Context, req paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
status(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
||||
status(paymentsvc.StatusUpdate{Code: paymentstatus.TerminalUnavailable})
|
||||
return &paymentsvc.Result{Terminal: paymentapi.Result{Outcome: "error", HTTPStatus: 200, Reason: "terminal_unavailable", Message: "Payment terminal is unavailable"}}, nil
|
||||
})
|
||||
|
||||
recorder := performSalePaymentRequest(t, provider)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("outer status = %d, want %d", recorder.Code, http.StatusOK)
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if recorder.Code != 200 || len(frames) != 3 || frames[0].Code != paymentstatus.Starting || frames[1].Code != paymentstatus.TerminalUnavailable || frames[2].Result == nil {
|
||||
t.Fatalf("SalePayment() HTTP/frames=%d/%+v, want 200 and two statuses plus final", recorder.Code, frames)
|
||||
}
|
||||
messages := decodePaymentStream(t, recorder.Body)
|
||||
if len(messages) != 3 {
|
||||
t.Fatalf("stream messages = %#v, want two statuses and one result", messages)
|
||||
final := frames[2].Result
|
||||
if final.Outcome != "error" || final.Reason != "terminal_unavailable" || final.Retryable {
|
||||
t.Errorf("SalePayment() final=%+v, want definite nonretryable terminal unavailability", final)
|
||||
}
|
||||
if messages[0].Type != "status" || messages[0].Code != paymentstatus.Starting ||
|
||||
messages[1].Type != "status" || messages[1].Code != paymentstatus.TerminalUnavailable {
|
||||
t.Fatalf("status frames = %#v", messages[:2])
|
||||
}
|
||||
final := messages[2]
|
||||
if final.Type != "result" || final.Response == nil {
|
||||
t.Fatalf("final frame = %#v", final)
|
||||
}
|
||||
if final.Response.Status.Code != http.StatusOK {
|
||||
t.Fatalf("nested status = %d, want %d", final.Response.Status.Code, http.StatusOK)
|
||||
}
|
||||
resultURL, err := url.Parse(final.Response.Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resultURL.Path != types.CheckinUnsuccessfulEndpoint {
|
||||
t.Fatalf("result path = %q, want %q", resultURL.Path, types.CheckinUnsuccessfulEndpoint)
|
||||
}
|
||||
if got := resultURL.Query().Get("Description"); got != "Payment terminal is unavailable" {
|
||||
t.Fatalf("Description = %q", got)
|
||||
}
|
||||
|
||||
body := recorder.Body.String()
|
||||
for _, forbidden := range []string{
|
||||
"Dojo returned HTTP 409",
|
||||
"offline or currently in use",
|
||||
"traceId",
|
||||
"docs.dojo.tech",
|
||||
} {
|
||||
if strings.Contains(body, forbidden) {
|
||||
t.Fatalf("stream exposed %q: %s", forbidden, body)
|
||||
for _, forbidden := range []string{"Dojo returned HTTP 409", "offline or currently in use", "traceId", "docs.dojo.tech", "\"response\""} {
|
||||
if strings.Contains(recorder.Body.String(), forbidden) {
|
||||
t.Errorf("SalePayment() leaked %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSalePaymentRetainsNestedBadGatewayForProviderErrorsAfterStreamingStarts(t *testing.T) {
|
||||
provider := paymentProviderFunc(func(
|
||||
_ context.Context,
|
||||
_ paymentsvc.SaleRequest,
|
||||
onStatus paymentsvc.StatusHandler,
|
||||
) (*paymentsvc.Result, error) {
|
||||
onStatus(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
||||
return nil, errors.New("provider failed")
|
||||
func TestSalePaymentRetainsUncertaintyForProviderErrorsAfterStreamingStarts(t *testing.T) {
|
||||
provider := paymentProviderFunc(func(_ context.Context, _ paymentsvc.SaleRequest, status paymentsvc.StatusHandler) (*paymentsvc.Result, error) {
|
||||
status(paymentsvc.StatusUpdate{Code: paymentstatus.Starting})
|
||||
return nil, errors.New("raw secret provider error")
|
||||
})
|
||||
|
||||
recorder := performSalePaymentRequest(t, provider)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("outer status = %d, want streaming status %d", recorder.Code, http.StatusOK)
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if len(frames) != 2 || frames[1].Result == nil || frames[1].Result.Outcome != "unknown" || frames[1].Result.Retryable {
|
||||
t.Fatalf("SalePayment() frames=%+v, want progress then nonretryable uncertainty", frames)
|
||||
}
|
||||
messages := decodePaymentStream(t, recorder.Body)
|
||||
if len(messages) != 2 || messages[1].Type != "result" || messages[1].Response == nil {
|
||||
t.Fatalf("stream messages = %#v", messages)
|
||||
}
|
||||
if messages[1].Response.Status.Code != http.StatusBadGateway {
|
||||
t.Fatalf("nested status = %d, want %d", messages[1].Response.Status.Code, http.StatusBadGateway)
|
||||
}
|
||||
resultURL, err := url.Parse(messages[1].Response.Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resultURL.Path != types.CheckinUnsuccessfulEndpoint {
|
||||
t.Fatalf("result path = %q, want %q", resultURL.Path, types.CheckinUnsuccessfulEndpoint)
|
||||
if strings.Contains(recorder.Body.String(), "secret") {
|
||||
t.Error("SalePayment() exposed raw provider diagnostics")
|
||||
}
|
||||
}
|
||||
|
||||
func performSalePaymentRequest(t *testing.T, provider paymentsvc.Provider) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
app := &App{
|
||||
paymentService: paymentsvc.NewService(provider),
|
||||
cfg: &config.ConfigRec{
|
||||
Hotel: "HOTEL",
|
||||
Kiosk: 7,
|
||||
TimeoutSeconds: 5,
|
||||
},
|
||||
}
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/payment/sale",
|
||||
strings.NewReader(`{"reference":"BOOKING-123","amount":10852,"currency":"GBP"}`),
|
||||
)
|
||||
app := &App{isPayment: true, paymentService: paymentsvc.NewService(provider), cfg: &config.ConfigRec{TimeoutSeconds: 1}}
|
||||
request := httptest.NewRequest(http.MethodPost, paymentapi.SalePath, strings.NewReader(`{"amount":1234,"currency":"GBP","reference":"SYNTH"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
app.salePayment(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func decodePaymentStream(t *testing.T, body io.Reader) []paymentStreamMessage {
|
||||
func decodePaymentStream(t *testing.T, body io.Reader) []paymentapi.Frame {
|
||||
t.Helper()
|
||||
var frames []paymentapi.Frame
|
||||
decoder := json.NewDecoder(body)
|
||||
var messages []paymentStreamMessage
|
||||
for {
|
||||
var message paymentStreamMessage
|
||||
if err := decoder.Decode(&message); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return messages
|
||||
}
|
||||
t.Fatal(err)
|
||||
var frame paymentapi.Frame
|
||||
err := decoder.Decode(&frame)
|
||||
if err == io.EOF {
|
||||
return frames
|
||||
}
|
||||
messages = append(messages, message)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodePaymentStream() error=%v, want valid frames", err)
|
||||
}
|
||||
frames = append(frames, frame)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,11 @@ func (app *App) testIssueDoorCard(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
if err := app.lockserver.BuildCommand(doorReq, checkIn, checkOut); err != nil {
|
||||
logging.Error(types.ServiceName, err.Error(), "Build key command", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, "Build key command failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// lock server sequence
|
||||
if err := app.lockserver.LockSequence(); err != nil {
|
||||
@@ -90,8 +94,14 @@ func (app *App) fetchChipDNAStatus(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("fetchChipDNAStatus")
|
||||
var theResponse cmstypes.StatusRec
|
||||
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", http.MethodGet)
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use GET")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
status, err := creditcall.ReadPdqStatus(app.cfg.Hotel, app.cfg.Kiosk)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type failedDiagnosticWriter struct{ header http.Header }
|
||||
|
||||
func (w *failedDiagnosticWriter) Header() http.Header { return w.header }
|
||||
func (*failedDiagnosticWriter) WriteHeader(int) {}
|
||||
func (*failedDiagnosticWriter) Flush() {}
|
||||
func (*failedDiagnosticWriter) Write([]byte) (int, error) {
|
||||
return 0, errors.New("https://user:WRITE_PRIVATE_MARKER@gateway.invalid/4111111111111111")
|
||||
}
|
||||
|
||||
func TestTrustReconciliationLogsPreserveIdentityAndFinancialOutcome(t *testing.T) {
|
||||
for _, preauth := range []bool{false, true} {
|
||||
for _, mode := range []string{"unknown", "unknown-transport", "unknown-write-failure", "approved-client-closed", "approved-write-failure"} {
|
||||
operation := "sale"
|
||||
if preauth {
|
||||
operation = "preauth"
|
||||
}
|
||||
t.Run(operation+"/"+mode, func(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
logger := log.StandardLogger()
|
||||
oldOutput, oldFormatter := logger.Out, logger.Formatter
|
||||
logger.SetOutput(&output)
|
||||
logger.SetFormatter(&log.JSONFormatter{})
|
||||
t.Cleanup(func() { logger.SetOutput(oldOutput); logger.SetFormatter(oldFormatter) })
|
||||
unknown := strings.HasPrefix(mode, "unknown")
|
||||
financial, lookups, prints := 0, 0, 0
|
||||
var ref string
|
||||
var tokens []string
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
client, err := trustpayments.New(trustpayments.Config{
|
||||
BaseURL: "https://sandbox.link.trustpayments.com/trustpayments/rest/", SiteID: "SYNTH-SITE", Password: "PASSWORD_PRIVATE_MARKER", Terminal: "SYNTH-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
|
||||
}
|
||||
tokens = append(tokens, r.Header.Get("token"))
|
||||
if strings.HasSuffix(r.URL.Path, "/status") {
|
||||
lookups++
|
||||
if input["refid"] != ref {
|
||||
t.Errorf("Status RefID=%q, want original %q", input["refid"], ref)
|
||||
}
|
||||
} else {
|
||||
financial++
|
||||
ref = input["refid"]
|
||||
if !strings.HasSuffix(r.URL.Path, "/"+operation) || input["type"] != operation {
|
||||
t.Errorf("Financial request path/type=%s/%s, want %s", r.URL.Path, input["type"], operation)
|
||||
}
|
||||
if mode == "approved-client-closed" {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
if mode == "unknown-transport" {
|
||||
return nil, errors.New("https://user:PASSWORD_PRIVATE_MARKER@gateway.invalid/4111111111111111/JWT_PRIVATE_MARKER")
|
||||
}
|
||||
body := map[string]any{"refid": ref, "siteid": "SYNTH-SITE", "terminalserialnumber": "SYNTH-PED", "type": operation, "amount": "25.00", "finalamount": "25.00", "resultcode": "Approved", "authcode": "AUTH_PRIVATE_MARKER", "cardtype": "Visa", "last4": "1133", "receipt": "PAN: 4111111111111111\nRAW_PRIVATE_MARKER"}
|
||||
if unknown {
|
||||
body["errorcode"], body["errormessage"] = 2003, "RAW_PRIVATE_MARKER JWT_PRIVATE_MARKER"
|
||||
}
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(encoded)), Header: make(http.Header)}, nil
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app := &App{cfg: &config.ConfigRec{Hotel: "SYNTH-HOTEL", Kiosk: 9}, isPayment: true}
|
||||
app.SetPaymentService(paymentsvc.NewService(&trustpayments.Processor{Client: client, PrintReceipt: func(string) { prints++ }}))
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/payment/"+operation, strings.NewReader(`{"reference":"SYNTH-BOOK","amount":2500,"currency":"GBP"}`)).WithContext(ctx)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
var writer http.ResponseWriter = recorder
|
||||
if strings.Contains(mode, "write-failure") {
|
||||
writer = &failedDiagnosticWriter{header: make(http.Header)}
|
||||
}
|
||||
app.streamPayment(writer, request, preauth)
|
||||
wantLookups, wantPrints, wantOutcome := 0, 1, "approved"
|
||||
if unknown {
|
||||
wantLookups, wantPrints, wantOutcome = 1, 0, "unknown"
|
||||
}
|
||||
if financial != 1 || lookups != wantLookups || prints != wantPrints || len(ref) != 32 {
|
||||
t.Fatalf("Trust(%s) financial/status/prints/ref=%d/%d/%d/%q, want 1/%d/%d and original RefID", mode, financial, lookups, prints, ref, wantLookups, wantPrints)
|
||||
}
|
||||
if unknown && !strings.Contains(mode, "write-failure") {
|
||||
frames := decodePaymentStream(t, recorder.Body)
|
||||
if len(frames) == 0 {
|
||||
t.Fatal("Unknown payment stream is empty, want final result")
|
||||
}
|
||||
final := frames[len(frames)-1].Result
|
||||
if final == nil || final.Outcome != wantOutcome || final.Retryable || final.TransactionReference != ref {
|
||||
t.Errorf("Unknown terminal result=%+v, want unchanged nonretryable outcome and RefID %s", final, ref)
|
||||
}
|
||||
}
|
||||
var requestID string
|
||||
warnings := 0
|
||||
decoder := json.NewDecoder(strings.NewReader(output.String()))
|
||||
for {
|
||||
var entry map[string]any
|
||||
if err := decoder.Decode(&entry); err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if entry["level"] != "warning" {
|
||||
continue
|
||||
}
|
||||
warnings++
|
||||
id, _ := entry["request_id"].(string)
|
||||
if requestID == "" {
|
||||
requestID = id
|
||||
}
|
||||
if id == "" || id != requestID || entry["request_reference"] != "SYNTH-BOOK" || entry["transaction_reference"] != ref || entry["provider"] != "TrustPayments" || entry["operation"] != operation || entry["outcome"] != wantOutcome {
|
||||
t.Errorf("Reconciliation warning=%v, want same request ID, Trust RefID, provider, operation and financial outcome", entry)
|
||||
}
|
||||
}
|
||||
wantWarnings := 0
|
||||
if unknown {
|
||||
wantWarnings = 2
|
||||
}
|
||||
if strings.Contains(mode, "write-failure") || mode == "approved-client-closed" {
|
||||
wantWarnings++
|
||||
}
|
||||
if warnings != wantWarnings {
|
||||
t.Errorf("Trust(%s) reconciliation warnings=%d, want %d", mode, warnings, wantWarnings)
|
||||
}
|
||||
for _, secret := range append(tokens, "PASSWORD_PRIVATE_MARKER", "AUTH_PRIVATE_MARKER", "RAW_PRIVATE_MARKER", "JWT_PRIVATE_MARKER", "WRITE_PRIVATE_MARKER", "4111111111111111") {
|
||||
if secret != "" && strings.Contains(output.String(), secret) {
|
||||
t.Errorf("Trust(%s) diagnostics contain private fixture data", mode)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/trustpayments"
|
||||
)
|
||||
|
||||
// SetTrustPayments selects Trust while preserving the deprecated endpoint guard.
|
||||
func (app *App) SetTrustPayments(client *trustpayments.Client) {
|
||||
app.trustSelected = true
|
||||
app.paymentService = paymentsvc.NewService(&trustpayments.Processor{Client: client})
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
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/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/internal/paymentsvc"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/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)
|
||||
}
|
||||
Reference in New Issue
Block a user