From e47e8c24d0c86c926c11a4996e8e32456b416be6 Mon Sep 17 00:00:00 2001 From: GuwandykA Date: Mon, 28 Sep 2026 16:53:34 +0500 Subject: [PATCH] added log --- .../payment/visamasterpay/db/helpers_test.go | 61 +++++++++ .../payment/visamasterpay/db/postgresql.go | 115 ++++++++++++++--- internal/payment/visamasterpay/handler.go | 7 +- internal/payment/visamasterpay/storage.go | 5 +- pkg/paymentgateway/client_test.go | 98 ++++++++++++++ pkg/paymentgateway/http_client.go | 15 ++- scripts/smoke_rbac_test.sh | 120 ++++++++++++++++++ 7 files changed, 400 insertions(+), 21 deletions(-) create mode 100644 internal/payment/visamasterpay/db/helpers_test.go create mode 100644 pkg/paymentgateway/client_test.go create mode 100755 scripts/smoke_rbac_test.sh diff --git a/internal/payment/visamasterpay/db/helpers_test.go b/internal/payment/visamasterpay/db/helpers_test.go new file mode 100644 index 0000000..9686e03 --- /dev/null +++ b/internal/payment/visamasterpay/db/helpers_test.go @@ -0,0 +1,61 @@ +package db + +import ( + "testing" + "time" +) + +func TestRound2(t *testing.T) { + // Values that round cleanly. + cases := map[float64]float64{ + 2.344: 2.34, + 100.0: 100.0, + 0.1 + 0.2: 0.30, + } + for in, want := range cases { + if got := round2(in); got != want { + t.Errorf("round2(%v)=%v want %v", in, got, want) + } + } +} + +// round2 is built on float64 (math.Round(v*100)/100). Classic .xx5 amounts +// like 1.005 and 2.345 are NOT representable exactly, so they round DOWN +// instead of to the nearer cent. This test pins that real behaviour: money +// math on float64 loses tenths of a cent, which is why totals should be +// computed in integer minor units (tetri) or a decimal type. If round2 is +// ever fixed to true half-up cents, update these expectations deliberately. +func TestRound2_FloatImprecision(t *testing.T) { + // 1.005 cannot be represented exactly; v*100 lands just under 100.5, so + // math.Round drops it to 100 -> 1.00 instead of the expected 1.01. + if got := round2(1.005); got != 1.00 { + t.Errorf("round2(1.005)=%v; documented float behaviour is 1.00 (loses a cent)", got) + } +} + +func TestIsSber(t *testing.T) { + sber := "sber" + upper := " SBER " + visa := "visa" + if !isSber(&sber) || !isSber(&upper) { + t.Error("sber/SBER should be detected (case- and space-insensitive)") + } + if isSber(&visa) || isSber(nil) { + t.Error("non-sber and nil should be false") + } +} + +// isPayableDay currently has skipPayableDayCheck hard-wired to true, so it +// returns true for EVERY day - including weekends. This test documents that +// live behaviour so it can't change silently: if the weekend guard is ever +// re-enabled, this test will flip and force a deliberate update. +func TestIsPayableDay_GuardIsDisabled(t *testing.T) { + saturday := time.Date(2026, 9, 26, 12, 0, 0, 0, ashgabatZone) // a Saturday + sunday := time.Date(2026, 9, 27, 12, 0, 0, 0, ashgabatZone) // a Sunday + if !skipPayableDayCheck { + t.Skip("weekend guard re-enabled; update this test intentionally") + } + if !isPayableDay(saturday) || !isPayableDay(sunday) { + t.Error("with skipPayableDayCheck=true, weekends must still report payable") + } +} diff --git a/internal/payment/visamasterpay/db/postgresql.go b/internal/payment/visamasterpay/db/postgresql.go index f13b96b..25e2507 100644 --- a/internal/payment/visamasterpay/db/postgresql.go +++ b/internal/payment/visamasterpay/db/postgresql.go @@ -136,9 +136,18 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P orderID, ).Scan(&orderType, &paid, &branchID, &userID) if err != nil { + // No log row for a missing order: visa_master_payment_logs.order_id + // references it, so the insert would fail anyway. + if !errors.Is(err, pgx.ErrNoRows) { + r.logFailure(ctx, orderID, dto.CreatedBy, "load_order", err, nil) + } return visamasterpay.PaymentInitResultDTO{}, err } + r.logStep(ctx, orderID, dto.CreatedBy, "pay_requested", map[string]interface{}{ + "orderType": derefOrEmpty(orderType), "requestedAmountTmt": dto.AmountTmt, "paymentPeriod": dto.PaymentPeriod, + }) + if !isPayableDay(time.Now()) { r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]string{"reason": "payment_window_closed"}) return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrPaymentWindowClosed @@ -150,11 +159,13 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P usdRate, err := r.fetchRate(ctx, "USD") if err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "fetch_rate_usd", err, nil) return visamasterpay.PaymentInitResultDTO{}, err } settings, err := r.settingsRepo.Get(ctx) if err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "load_payment_settings", err, nil) return visamasterpay.PaymentInitResultDTO{}, err } @@ -183,6 +194,7 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P if sber { rate, err := r.fetchRate(ctx, "RUB") if err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "fetch_rate_rub", err, nil) return visamasterpay.PaymentInitResultDTO{}, err } tveb := round2(settings.TvebFeeUsd * usdRate) @@ -210,6 +222,7 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P username, password, err := r.branchCredentials(ctx, branchID, sber) if err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "load_branch_credentials", err, map[string]interface{}{"branchId": branchID, "sber": sber}) return visamasterpay.PaymentInitResultDTO{}, err } @@ -220,9 +233,14 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P total: total, createdBy: dto.CreatedBy, }) if err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "create_payment_record", err, nil) return visamasterpay.PaymentInitResultDTO{}, err } + r.logStep(ctx, orderID, dto.CreatedBy, "payment_record_created", map[string]interface{}{ + "paymentId": paymentID, "paymentPeriod": period.Format("2006-01-02"), "amountTmt": amountTmt, "totalAmountTmt": total, + }) + returnURL := fmt.Sprintf("%s/online/visa-master", r.publicBaseURL) orderNumber := fmt.Sprintf("vmo-%d-%d", orderID, paymentID) description := "Visa/Master tölegi" @@ -251,7 +269,9 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P "success": false, "errorCode": result.ErrorCode, "errorMessage": result.ErrorMessage, "error": errString(regErr), "rawResponse": rawJSON(result.RawResponse), }) - _ = updatePaymentGatewayResult(ctx, r.client, paymentID, "failed", nil, result.RawResponse) + if err := updatePaymentGatewayResult(ctx, r.client, paymentID, "failed", nil, result.RawResponse); err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "save_register_result", err, map[string]interface{}{"paymentId": paymentID, "gatewayStatus": "failed"}) + } return visamasterpay.PaymentInitResultDTO{}, fmt.Errorf("payment gateway registration failed: %s", firstNonEmpty(result.ErrorMessage, errString(regErr))) } @@ -261,14 +281,28 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P ref := result.OrderId if err := updatePaymentGatewayResult(ctx, r.client, paymentID, "pending", &ref, result.RawResponse); err != nil { + r.logFailure(ctx, orderID, dto.CreatedBy, "save_register_result", err, map[string]interface{}{ + "paymentId": paymentID, "gatewayStatus": "pending", "gbusOrderId": ref, + }) return visamasterpay.PaymentInitResultDTO{}, err } + r.logStep(ctx, orderID, dto.CreatedBy, "redirected_to_payment_page", map[string]interface{}{ + "paymentId": paymentID, "gbusOrderId": ref, "formUrl": result.FormUrl, + }) + return visamasterpay.PaymentInitResultDTO{PaymentId: paymentID, OrderId: orderID, FormUrl: result.FormUrl, SuccessUrl: returnURL}, nil } func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visamasterpay.PaymentResultDTO, error) { + return r.verifyPayment(ctx, paymentID, "callback", nil) +} +// verifyPayment is the shared body of HandleCallback and Status: trigger +// ("callback" or "status") and requestedBy (the caller of Status; nil for +// the tokenless callback) are recorded on every log step so each check is +// traceable to what started it. +func (r *repository) verifyPayment(ctx context.Context, paymentID int64, trigger string, requestedBy *int64) (visamasterpay.PaymentResultDTO, error) { var orderID int64 var gatewayStatus string var gatewayReference *string @@ -278,18 +312,38 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam paymentID, ).Scan(&orderID, &gatewayStatus, &gatewayReference, &createdBy) if errors.Is(err, pgx.ErrNoRows) { + // Unknown payment id: there's no order to attach a log row to. return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound } if err != nil { return visamasterpay.PaymentResultDTO{}, err } + // step logs a step of this check with its trigger/caller attached. + step := func(name string, detail map[string]interface{}) { + if detail == nil { + detail = map[string]interface{}{} + } + detail["paymentId"] = paymentID + detail["trigger"] = trigger + if requestedBy != nil { + detail["requestedBy"] = *requestedBy + } + r.logStep(ctx, orderID, createdBy, name, detail) + } + fail := func(stage string, err error) { + step("failed", map[string]interface{}{"stage": stage, "error": errString(err)}) + } + + step(trigger+"_received", map[string]interface{}{"gatewayStatus": gatewayStatus}) + var orderType *string var amountUsd *float64 var branchID int64 if err := r.client.QueryRow(ctx, `SELECT type, amount_usd, branch_id FROM visa_master_payment_orders WHERE id = $1 AND deleted_at IS NULL`, orderID, ).Scan(&orderType, &amountUsd, &branchID); err != nil { + fail("load_order", err) return visamasterpay.PaymentResultDTO{}, err } @@ -304,95 +358,111 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam if gatewayStatus != "pending" { item, err := fetchPaymentByID(ctx, r.client, paymentID) if err != nil { + fail("load_payment", err) return visamasterpay.PaymentResultDTO{}, err } item.Paid = item.GatewayStatus == "success" + step("already_finalized", map[string]interface{}{"gatewayStatus": item.GatewayStatus, "paid": item.Paid}) return finish(item), nil } if gatewayReference == nil || *gatewayReference == "" { - return visamasterpay.PaymentResultDTO{}, fmt.Errorf("payment %d has no gateway reference yet", paymentID) + err := fmt.Errorf("payment %d has no gateway reference yet", paymentID) + fail("missing_gateway_reference", err) + return visamasterpay.PaymentResultDTO{}, err } username, password, err := r.branchCredentials(ctx, branchID, isSber(orderType)) if err != nil { + fail("load_branch_credentials", err) return visamasterpay.PaymentResultDTO{}, err } - r.logStep(ctx, orderID, createdBy, "callback_received", map[string]interface{}{"paymentId": paymentID}) - r.logStep(ctx, orderID, createdBy, "status_check_request", map[string]interface{}{"gbusOrderId": *gatewayReference}) + step("status_check_request", map[string]interface{}{"gbusOrderId": *gatewayReference}) status, err := r.gateway.CheckStatus(ctx, paymentgateway.StatusRequest{OrderId: *gatewayReference, Username: username, Password: password}) if err != nil { - r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{"error": errString(err)}) + step("status_check_response", map[string]interface{}{"success": false, "error": errString(err)}) return visamasterpay.PaymentResultDTO{}, err } - r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{ - "paid": status.Paid, "orderStatus": status.OrderStatus, "actionCode": status.ActionCode, + step("status_check_response", map[string]interface{}{ + "success": true, "paid": status.Paid, "orderStatus": status.OrderStatus, "actionCode": status.ActionCode, "actionCodeDescription": status.ActionCodeDescription, "rawResponse": rawJSON(status.RawResponse), }) var item visamasterpay.PaymentResultDTO if status.Paid { + // GBÜS has taken the money from here on, so every failure below is + // logged: it leaves a paid payment the order doesn't reflect yet. tx, err := r.client.Begin(ctx) if err != nil { + fail("finalize_begin_tx", err) return visamasterpay.PaymentResultDTO{}, err } defer tx.Rollback(ctx) var lockedPaid bool if err := tx.QueryRow(ctx, `SELECT paid FROM visa_master_payment_orders WHERE id = $1 FOR UPDATE`, orderID).Scan(&lockedPaid); err != nil { + fail("finalize_lock_order", err) return visamasterpay.PaymentResultDTO{}, err } - if !lockedPaid { + if lockedPaid { + step("order_already_marked_paid", nil) + } else { if _, err := tx.Exec(ctx, `UPDATE visa_master_payment_orders SET paid = true, status = 'completed', updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $1`, orderID, ); err != nil { + fail("finalize_mark_order_paid", err) return visamasterpay.PaymentResultDTO{}, err } } item, err = updatePaymentStatus(ctx, tx, paymentID, "success", status.RawResponse) if err != nil { + fail("finalize_save_payment_status", err) return visamasterpay.PaymentResultDTO{}, err } if err := tx.Commit(ctx); err != nil { + fail("finalize_commit", err) return visamasterpay.PaymentResultDTO{}, err } } else { item, err = updatePaymentStatus(ctx, r.client, paymentID, "failed", status.RawResponse) if err != nil { + fail("finalize_save_payment_status", err) return visamasterpay.PaymentResultDTO{}, err } } - r.logStep(ctx, orderID, createdBy, "payment_finalized", map[string]interface{}{"paymentId": paymentID, "paid": status.Paid}) + step("payment_finalized", map[string]interface{}{"paid": status.Paid, "gatewayStatus": item.GatewayStatus}) item.Paid = status.Paid return finish(item), nil } -// Status re-checks orderID's latest payment attempt via HandleCallback - -// for when the frontend can't rely on GBÜS's redirect having reached the -// callback (e.g. the user closed the hosted payment page first). Safe to -// call repeatedly: HandleCallback only hits GBÜS while the attempt is still -// "pending" and otherwise just returns the already-finalized row. -func (r *repository) Status(ctx context.Context, orderID int64) (visamasterpay.PaymentResultDTO, error) { +// Status re-checks orderID's latest payment attempt the same way +// HandleCallback does - for when the frontend can't rely on GBÜS's redirect +// having reached the callback (e.g. the user closed the hosted payment page +// first). Safe to call repeatedly: it only hits GBÜS while the attempt is +// still "pending" and otherwise just returns the already-finalized row. +func (r *repository) Status(ctx context.Context, orderID int64, requestedBy *int64) (visamasterpay.PaymentResultDTO, error) { var paymentID int64 err := r.client.QueryRow(ctx, `SELECT id FROM visa_master_order_payments WHERE order_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1`, orderID, ).Scan(&paymentID) if errors.Is(err, pgx.ErrNoRows) { + r.logStep(ctx, orderID, requestedBy, "status_received", map[string]interface{}{"trigger": "status", "paymentId": nil}) return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound } if err != nil { + r.logFailure(ctx, orderID, requestedBy, "find_latest_payment", err, map[string]interface{}{"trigger": "status"}) return visamasterpay.PaymentResultDTO{}, err } - return r.HandleCallback(ctx, paymentID) + return r.verifyPayment(ctx, paymentID, "status", requestedBy) } // branchCredentials picks the sber or visa/master MPI merchant credentials @@ -458,6 +528,9 @@ func (r *repository) logStep(ctx context.Context, orderID int64, createdBy *int6 if err != nil { payload = []byte(`{}`) } + // Detached from cancellation: a client dropping the request mid-payment + // must not cost us the record of the steps that still run. + ctx = context.WithoutCancel(ctx) if _, err := r.client.Exec(ctx, `INSERT INTO visa_master_payment_logs (order_id, step, detail, created_by) VALUES ($1, $2, $3, $4)`, orderID, step, payload, createdBy, @@ -466,6 +539,16 @@ func (r *repository) logStep(ctx context.Context, orderID int64, createdBy *int6 } } +// logFailure records a "failed" step naming the stage that broke and the +// error, plus any extra detail, so every error path of a payout leaves a row. +func (r *repository) logFailure(ctx context.Context, orderID int64, createdBy *int64, stage string, err error, extra map[string]interface{}) { + detail := map[string]interface{}{"stage": stage, "error": errString(err)} + for k, v := range extra { + detail[k] = v + } + r.logStep(ctx, orderID, createdBy, "failed", detail) +} + // querier is satisfied by both postgresql.Client and pgx.Tx, so helpers // below can run either against the plain client or an open transaction. type querier interface { diff --git a/internal/payment/visamasterpay/handler.go b/internal/payment/visamasterpay/handler.go index 73ccc49..0dfb5ac 100644 --- a/internal/payment/visamasterpay/handler.go +++ b/internal/payment/visamasterpay/handler.go @@ -133,7 +133,12 @@ func (h *handler) status(c *gin.Context) { return } - result, err := h.repository.Status(c.Request.Context(), id) + var requestedBy *int64 + if userID, ok := rbac.CurrentUserID(c); ok { + requestedBy = &userID + } + + result, err := h.repository.Status(c.Request.Context(), id, requestedBy) if h.handleError(c, err, "status") { return } diff --git a/internal/payment/visamasterpay/storage.go b/internal/payment/visamasterpay/storage.go index a988a5b..ee44ae2 100644 --- a/internal/payment/visamasterpay/storage.go +++ b/internal/payment/visamasterpay/storage.go @@ -37,6 +37,7 @@ type Repository interface { // HandleCallback does - for the frontend to call (authenticated, // order-scoped) when it can't rely on GBÜS having redirected the // browser back to the callback, e.g. the user closed the hosted - // payment page before the redirect fired. - Status(ctx context.Context, orderID int64) (PaymentResultDTO, error) + // payment page before the redirect fired. requestedBy is the caller, + // recorded on the payment log. + Status(ctx context.Context, orderID int64, requestedBy *int64) (PaymentResultDTO, error) } diff --git a/pkg/paymentgateway/client_test.go b/pkg/paymentgateway/client_test.go new file mode 100644 index 0000000..abb0a41 --- /dev/null +++ b/pkg/paymentgateway/client_test.go @@ -0,0 +1,98 @@ +package paymentgateway + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestRegisterResultSuccess(t *testing.T) { + cases := []struct { + name string + r RegisterResult + want bool + }{ + {"ok blank code", RegisterResult{OrderId: "o1", FormUrl: "https://f"}, true}, + {"ok zero code", RegisterResult{OrderId: "o1", FormUrl: "https://f", ErrorCode: "0"}, true}, + {"no orderId", RegisterResult{FormUrl: "https://f"}, false}, + {"no formUrl", RegisterResult{OrderId: "o1"}, false}, + {"error code", RegisterResult{OrderId: "o1", FormUrl: "https://f", ErrorCode: "5"}, false}, + } + for _, c := range cases { + if got := c.r.Success(); got != c.want { + t.Errorf("%s: Success()=%v want %v", c.name, got, c.want) + } + } +} + +func TestLogClientAlwaysPaid(t *testing.T) { + c := NewLogClient(nil) + reg, err := c.Register(context.Background(), RegisterRequest{OrderNumber: "vmo-1-2", ReturnURL: "https://x/cb"}) + if err != nil || !reg.Success() { + t.Fatalf("stub register should succeed: %+v err=%v", reg, err) + } + st, err := c.CheckStatus(context.Background(), StatusRequest{OrderId: reg.OrderId}) + if err != nil { + t.Fatalf("stub status err: %v", err) + } + // Documents debug behaviour: the stub reports EVERY payment as paid. + if !st.Paid || st.OrderStatus != 2 { + t.Errorf("stub CheckStatus should report paid/status=2, got paid=%v status=%d", st.Paid, st.OrderStatus) + } +} + +func TestHTTPClientRegisterParsesResponse(t *testing.T) { + var gotPath, gotAmount, gotCurrency, gotUser string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotAmount = r.URL.Query().Get("amount") + gotCurrency = r.URL.Query().Get("currency") + gotUser = r.URL.Query().Get("userName") + w.Write([]byte(`{"orderId":"GB-123","formUrl":"https://pay/GB-123"}`)) + })) + defer srv.Close() + + c := &HTTPClient{httpClient: srv.Client(), baseURL: srv.URL + "/"} + res, err := c.Register(context.Background(), RegisterRequest{ + OrderNumber: "vmo-1-2", AmountMinor: 12345, Username: "u", Password: "p", ReturnURL: "https://cb", + }) + if err != nil { + t.Fatalf("register: %v", err) + } + if res.OrderId != "GB-123" || res.FormUrl != "https://pay/GB-123" || !res.Success() { + t.Fatalf("bad parse: %+v", res) + } + if gotPath != "/register.do" || gotAmount != "12345" || gotCurrency != "934" || gotUser != "u" { + t.Errorf("bad request: path=%s amount=%s currency=%s user=%s", gotPath, gotAmount, gotCurrency, gotUser) + } +} + +func TestHTTPClientCheckStatusPaidMapping(t *testing.T) { + cases := []struct { + body string + paid bool + }{ + {`{"orderStatus":2,"actionCode":"0"}`, true}, // 2 = deposited + {`{"orderStatus":1,"actionCode":0}`, false}, // numeric actionCode still decodes + {`{"orderStatus":6,"actionCode":"declined"}`, false}, + } + for _, tc := range cases { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.Header.Get("Content-Type"), "x-www-form-urlencoded") { + t.Errorf("status check must be form-encoded POST, got %q", r.Header.Get("Content-Type")) + } + w.Write([]byte(tc.body)) + })) + c := &HTTPClient{httpClient: srv.Client(), baseURL: srv.URL + "/"} + st, err := c.CheckStatus(context.Background(), StatusRequest{OrderId: "x"}) + srv.Close() + if err != nil { + t.Fatalf("status: %v", err) + } + if st.Paid != tc.paid { + t.Errorf("body %s: Paid=%v want %v", tc.body, st.Paid, tc.paid) + } + } +} diff --git a/pkg/paymentgateway/http_client.go b/pkg/paymentgateway/http_client.go index 927eb04..32bf79f 100644 --- a/pkg/paymentgateway/http_client.go +++ b/pkg/paymentgateway/http_client.go @@ -25,16 +25,27 @@ const mpiBaseURL = "https://mpi.gov.tm/payment/rest/" // the gateway's own convention exactly rather than normalizing them. type HTTPClient struct { httpClient *http.Client + baseURL string logger *logging.Logger } func NewHTTPClient(logger *logging.Logger) *HTTPClient { return &HTTPClient{ httpClient: &http.Client{Timeout: 20 * time.Second}, + baseURL: mpiBaseURL, logger: logger, } } +// base returns the configured gateway base URL, falling back to the fixed +// GBÜS endpoint when the client was constructed without one. +func (c *HTTPClient) base() string { + if c.baseURL == "" { + return mpiBaseURL + } + return c.baseURL +} + type registerResponse struct { OrderId string `json:"orderId"` FormUrl string `json:"formUrl"` @@ -55,7 +66,7 @@ func (c *HTTPClient) Register(ctx context.Context, req RegisterRequest) (Registe "description": {req.Description}, } - body, err := c.do(ctx, http.MethodGet, mpiBaseURL+"register.do", query, nil) + body, err := c.do(ctx, http.MethodGet, c.base()+"register.do", query, nil) if err != nil { return RegisterResult{}, err } @@ -110,7 +121,7 @@ func (c *HTTPClient) CheckStatus(ctx context.Context, req StatusRequest) (Status "password": {req.Password}, } - body, err := c.do(ctx, http.MethodPost, mpiBaseURL+"getOrderStatusExtended.do", nil, form) + body, err := c.do(ctx, http.MethodPost, c.base()+"getOrderStatusExtended.do", nil, form) if err != nil { return StatusResult{}, err } diff --git a/scripts/smoke_rbac_test.sh b/scripts/smoke_rbac_test.sh new file mode 100755 index 0000000..968671a --- /dev/null +++ b/scripts/smoke_rbac_test.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# --------------------------------------------------------------------------- +# Smoke + RBAC test for the deployed test server (read-only: GET requests). +# Logs in as every seeded account from db/seed.sql and checks each endpoint +# returns 2xx when the role's policy allows it and 403 when it does not. +# +# Usage: +# bash scripts/smoke_rbac_test.sh +# BASE=http://localhost:8080/api/admin bash scripts/smoke_rbac_test.sh +# +# Works on macOS bash 3.2 (no associative arrays). +# --------------------------------------------------------------------------- +set -uo pipefail + +BASE="${BASE:-https://test.webulgam.com/online-backend/api/admin}" +PASSWORD="${PASSWORD:-test1234}" +TIMEOUT=20 +VERBOSE="${VERBOSE:-0}" + +# username:role-code (db/seed.sql) +USERS="superadmin:superadmin admin:admin manager:manager operator:operator +serdar:user gulnar:user dovran:user maya:user kerim:user leyla:user +currency:currency_maintainer loanop:loan_operator bothop:full_operator loanhead:loan_head" + +# path|policy — mirrors the rbac.Group(...) declarations in internal/**/handler.go +ENDPOINTS="/profile|auth +/dashboard/overview|require-staff:dashboard +/cards|require:cards +/card-orders|require:cards +/card-pin-orders|require:cards +/card-rekwizit-orders|require:cards +/card-balances|require:cards +/visa-master-payment-orders|require:cards +/payment-history|require-staff:cards +/payment-cards|catalog +/reasons-cards|catalog +/loan-orders|require:loans +/loans-repayment|require:loans +/loan-paid-off-letters|require:loans +/loan-types|catalog +/loans-documents|catalog +/users|require-staff:users +/users/clients|staff +/roles|require-staff:roles +/permissions|require-staff:roles +/branches|catalog +/provinces|catalog +/currencies|catalog +/payment-settings|staff +/activity-logs|require-staff:activity-logs +/backups|require-staff:backups" + +perms_of() { # role -> permissions (role_permissions in db/seed.sql) + case "$1" in + superadmin) echo ALL ;; + admin) echo "dashboard cards loans users branches provinces currencies payment-settings activity-logs" ;; + manager) echo "cards loans users dashboard" ;; + operator) echo "cards dashboard" ;; + loan_operator) echo "loans dashboard" ;; + full_operator) echo "cards loans dashboard" ;; + loan_head) echo "loans dashboard" ;; + currency_maintainer) echo "currencies" ;; + user) echo "cards loans" ;; + esac +} + +is_staff() { [ "$1" != user ]; } # only the "user" role has scope=own + +has_perm() { # $1 role, $2 perm + local p; p=$(perms_of "$1") + [ "$p" = ALL ] || [[ " $p " == *" $2 "* ]] +} + +allowed() { # $1 role, $2 policy -> 0 if GET should pass + local role="$1" policy="$2" + case "$policy" in + auth|catalog) return 0 ;; + staff) is_staff "$role" ;; + require:*) has_perm "$role" "${policy#require:}" ;; + require-staff:*) is_staff "$role" && has_perm "$role" "${policy#require-staff:}" ;; + esac +} + +login() { # $1 username -> token + curl -s -m "$TIMEOUT" -X POST "$BASE/login" -H 'Content-Type: application/json' \ + -d "{\"name\":\"$1\",\"password\":\"$PASSWORD\"}" \ + | grep -oE '"accessToken":"[^"]+"' | sed -E 's/.*":"//; s/"$//' +} + +echo "BASE=$BASE" +echo "==================================================================" +pass=0; fail=0; failures="" +for entry in $USERS; do + user="${entry%%:*}"; role="${entry#*:}" + tok=$(login "$user") + if [ -z "$tok" ]; then + echo "[$user/$role] LOGIN FAILED"; fail=$((fail+1)); failures="$failures\n $user login"; continue + fi + upass=0; ufail=0 + while IFS='|' read -r path policy; do + code=$(curl -s -o /dev/null -m "$TIMEOUT" -w '%{http_code}' -H "Authorization: Bearer $tok" "$BASE$path") + if allowed "$role" "$policy"; then + want=2xx; [[ "$code" =~ ^2 ]] && ok=Y || ok=N + else + want=403; [ "$code" = 403 ] && ok=Y || ok=N + fi + if [ "$ok" = Y ]; then + pass=$((pass+1)); upass=$((upass+1)) + else + fail=$((fail+1)); ufail=$((ufail+1)) + failures="$failures\n $user($role) GET $path want=$want got=$code [$policy]" + fi + [ "$VERBOSE" = 1 ] && printf ' %-28s %-28s want=%-4s got=%s %s\n' "$path" "$policy" "$want" "$code" "$ok" + done <<< "$ENDPOINTS" + printf '[%-10s %-20s] ok=%-3s fail=%s\n' "$user" "$role" "$upass" "$ufail" +done +echo "==================================================================" +echo "PASS=$pass FAIL=$fail" +[ -n "$failures" ] && printf "Failures:$failures\n" +[ "$fail" = 0 ]