Files
hardlink/internal/handlers/modern_routes_test.go

232 lines
10 KiB
Go

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/v2/config"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/creditcall"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/internal/mail"
"gitea.futuresens.co.uk/futuresens/hardlink/v2/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)
}
}