896 lines
32 KiB
Go
896 lines
32 KiB
Go
package rbac
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt"
|
|
)
|
|
|
|
func TestUserRoleAllows(t *testing.T) {
|
|
tests := []struct {
|
|
method, path string
|
|
want bool
|
|
}{
|
|
{http.MethodGet, "/api/admin/currencies", true},
|
|
{http.MethodGet, "/api/admin/currencies/3", true},
|
|
{http.MethodPost, "/api/admin/currencies", false},
|
|
{http.MethodPut, "/api/admin/currencies/3", false},
|
|
{http.MethodDelete, "/api/admin/currencies/3", false},
|
|
{http.MethodGet, "/api/admin/backups", false},
|
|
{http.MethodGet, "/api/admin/backups/1", false},
|
|
{http.MethodPost, "/api/admin/backups", false},
|
|
{http.MethodGet, "/api/admin/cards", true},
|
|
{http.MethodPost, "/api/admin/cards", true},
|
|
{http.MethodPut, "/api/admin/cards/9", true},
|
|
{http.MethodDelete, "/api/admin/cards/9", true},
|
|
{http.MethodGet, "/api/admin/card-orders/9", true},
|
|
{http.MethodPost, "/api/admin/card-orders", true},
|
|
{http.MethodPut, "/api/admin/loan-orders/2", true},
|
|
{http.MethodDelete, "/api/admin/loan-orders/2", true},
|
|
{http.MethodGet, "/api/admin/card-balances", true},
|
|
{http.MethodPost, "/api/admin/card-balances", true},
|
|
{http.MethodPut, "/api/admin/card-balances/9", true},
|
|
{http.MethodDelete, "/api/admin/card-balances/9", true},
|
|
{http.MethodGet, "/api/admin/profile", true},
|
|
{http.MethodPut, "/api/admin/profile", true},
|
|
{http.MethodPost, "/api/admin/file", true},
|
|
{http.MethodDelete, "/api/admin/profile", false},
|
|
{http.MethodGet, "/api/admin/users", false},
|
|
{http.MethodGet, "/api/admin/activity-logs", false},
|
|
{http.MethodGet, "/api/admin/provinces", true},
|
|
{http.MethodPost, "/api/admin/provinces", false},
|
|
{http.MethodGet, "/api/admin/branches", true},
|
|
{http.MethodPost, "/api/admin/branches", false},
|
|
{http.MethodGet, "/api/admin/users/clients", true},
|
|
{http.MethodPost, "/api/admin/users", false},
|
|
{http.MethodGet, "/api/admin/loan-types", true},
|
|
{http.MethodPost, "/api/admin/loan-types", false},
|
|
{http.MethodPost, "/api/admin/loan-orders", true},
|
|
{http.MethodGet, "/api/admin/loans-repayment", true},
|
|
{http.MethodPost, "/api/admin/loans-repayment", true},
|
|
{http.MethodDelete, "/api/admin/loan-paid-off-letters/4", true},
|
|
{http.MethodPatch, "/api/admin/cards/9", true},
|
|
}
|
|
for _, tt := range tests {
|
|
if got := userRoleAllows(tt.method, tt.path); got != tt.want {
|
|
t.Errorf("userRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestOperatorRoleAllows(t *testing.T) {
|
|
tests := []struct {
|
|
method, path string
|
|
want bool
|
|
}{
|
|
{http.MethodGet, "/api/admin/currencies", true},
|
|
{http.MethodGet, "/api/admin/currencies/1", true},
|
|
{http.MethodPost, "/api/admin/currencies", false},
|
|
{http.MethodPut, "/api/admin/currencies/1", false},
|
|
{http.MethodDelete, "/api/admin/currencies/1", false},
|
|
{http.MethodGet, "/api/admin/backups", false},
|
|
{http.MethodPost, "/api/admin/backups", false},
|
|
{http.MethodGet, "/api/admin/card-orders", true},
|
|
{http.MethodPost, "/api/admin/card-orders", true},
|
|
{http.MethodDelete, "/api/admin/card-orders/2", true},
|
|
{http.MethodGet, "/api/admin/dashboard", true},
|
|
{http.MethodGet, "/api/admin/users", true},
|
|
{http.MethodGet, "/api/admin/users/clients", true},
|
|
{http.MethodPost, "/api/admin/users", true},
|
|
{http.MethodGet, "/api/admin/activity-logs", false},
|
|
{http.MethodGet, "/api/admin/provinces", true},
|
|
{http.MethodPost, "/api/admin/provinces", false},
|
|
{http.MethodGet, "/api/admin/card-balances", true},
|
|
{http.MethodPost, "/api/admin/card-balances", true},
|
|
}
|
|
for _, tt := range tests {
|
|
if got := operatorRoleAllows(tt.method, tt.path); got != tt.want {
|
|
t.Errorf("operatorRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestOperatorClientsListNeedsNoPermission(t *testing.T) {
|
|
if got := operatorPathPermission(http.MethodGet, "/api/admin/users/clients"); got != "" {
|
|
t.Fatalf("clients GET perm=%q, want none", got)
|
|
}
|
|
if got := operatorPathPermission(http.MethodGet, "/api/admin/users"); got != "users.view" {
|
|
t.Fatalf("users GET perm=%q, want users.view", got)
|
|
}
|
|
|
|
auth := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{}}
|
|
if status := serveGuard(auth, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("clients status=%d", status)
|
|
}
|
|
if status := serveGuard(auth, http.MethodGet, "/api/admin/users", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("users list status=%d", status)
|
|
}
|
|
noBranch := &stubAuth{role: roleOperator, perms: map[string]bool{}}
|
|
if status := serveGuard(noBranch, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("no-branch clients status=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestOperatorCardsAndLoansSahalar(t *testing.T) {
|
|
cardsOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true}}
|
|
loansOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"loans": true}}
|
|
both := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true, "loans": true}}
|
|
|
|
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("cards GET orders=%d", status)
|
|
}
|
|
if status := serveGuard(cardsOnly, http.MethodPost, "/api/admin/card-pin-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("cards POST pin=%d", status)
|
|
}
|
|
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/visa-master-payment-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("cards GET visa=%d", status)
|
|
}
|
|
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("cards GET loans=%d", status)
|
|
}
|
|
|
|
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("loans GET orders=%d", status)
|
|
}
|
|
if status := serveGuard(loansOnly, http.MethodPut, "/api/admin/loan-paid-off-letters/1", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("loans PUT letter=%d", status)
|
|
}
|
|
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("loans GET cards=%d", status)
|
|
}
|
|
|
|
if status := serveGuard(both, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("both GET cards=%d", status)
|
|
}
|
|
if status := serveGuard(both, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("both GET loans=%d", status)
|
|
}
|
|
|
|
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("cards GET balances=%d", status)
|
|
}
|
|
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("loans GET balances=%d", status)
|
|
}
|
|
if got := operatorPathModule(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
|
|
t.Fatalf("card-balances path=%q", got)
|
|
}
|
|
if got := operatorPathModule(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
|
|
t.Fatalf("card-orders path=%q", got)
|
|
}
|
|
}
|
|
|
|
func TestAllCardAndLoanRoutesMapped(t *testing.T) {
|
|
cardPaths := []string{
|
|
"/api/admin/cards",
|
|
"/api/admin/card-balances",
|
|
"/api/admin/card-orders",
|
|
"/api/admin/card-pin-orders",
|
|
"/api/admin/card-rekwizit-orders",
|
|
"/api/admin/visa-master-payment-orders",
|
|
"/api/admin/payment-cards",
|
|
"/api/admin/reasons-cards",
|
|
}
|
|
loanPaths := []string{
|
|
"/api/admin/loan-orders",
|
|
"/api/admin/loans-repayment",
|
|
"/api/admin/loan-paid-off-letters",
|
|
"/api/admin/loan-types",
|
|
"/api/admin/loans-documents",
|
|
}
|
|
for _, path := range cardPaths {
|
|
if got := operatorPathModule(http.MethodGet, path); got != "cards" {
|
|
t.Errorf("GET %s module=%q, want cards", path, got)
|
|
}
|
|
if got := operatorPathModule(http.MethodPost, path); got != "cards" {
|
|
t.Errorf("POST %s module=%q, want cards", path, got)
|
|
}
|
|
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
|
|
t.Errorf("%s not on operator allowlist", path)
|
|
}
|
|
}
|
|
for _, path := range loanPaths {
|
|
if got := operatorPathModule(http.MethodGet, path); got != "loans" {
|
|
t.Errorf("GET %s module=%q, want loans", path, got)
|
|
}
|
|
if got := operatorPathModule(http.MethodPost, path); got != "loans" {
|
|
t.Errorf("POST %s module=%q, want loans", path, got)
|
|
}
|
|
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
|
|
t.Errorf("%s not on operator allowlist", path)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) {
|
|
if matchesPrefix("/card-balances", []string{"/cards"}) {
|
|
t.Fatal("/cards prefix must not match /card-balances")
|
|
}
|
|
if !matchesPrefix("/card-balances", userOwnedPrefixes) {
|
|
t.Fatal("/card-balances must be granted via its own entry in userOwnedPrefixes")
|
|
}
|
|
}
|
|
|
|
func TestIsPublicAdminPath(t *testing.T) {
|
|
public := []string{
|
|
"/api/admin/login",
|
|
"/api/admin/token",
|
|
"/api/admin/register",
|
|
"/api/admin/register/verify",
|
|
"/api/admin/forgot-password",
|
|
"/api/admin/forgot-password/verify",
|
|
"/api/admin/login/",
|
|
}
|
|
for _, path := range public {
|
|
if !isPublicAdminPath(path) {
|
|
t.Errorf("expected public %s", path)
|
|
}
|
|
}
|
|
private := []string{"/api/admin/currencies", "/api/admin/backups", "/api/admin/users"}
|
|
for _, path := range private {
|
|
if isPublicAdminPath(path) {
|
|
t.Errorf("expected private %s", path)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestAdminREST(t *testing.T) {
|
|
if got := adminREST("/api/admin/currencies/4"); got != "/currencies/4" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
if got := adminREST("/api/admin/currencies/"); got != "/currencies" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
if got := adminREST("/api/admin"); got != "" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestScopeOwnedListsInjectsUserID(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
paths := []string{
|
|
"/api/admin/cards?page=1",
|
|
"/api/admin/loan-orders",
|
|
"/api/admin/loans-repayment",
|
|
"/api/admin/loan-paid-off-letters",
|
|
"/api/admin/card-balances",
|
|
}
|
|
for _, path := range paths {
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, path, nil)
|
|
scopeOwnedLists(c, 42)
|
|
if got := c.Request.URL.Query().Get("user_id"); got != "42" {
|
|
t.Errorf("%s user_id=%q", path, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestScopeOwnedListsInjectsCreatedByForCardBalances(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/card-balances?status=pending", nil)
|
|
|
|
scopeOwnedLists(c, 42)
|
|
if got := c.Request.URL.Query().Get("created_by"); got != "42" {
|
|
t.Fatalf("card-balances created_by=%q, want 42", got)
|
|
}
|
|
if got := c.Request.URL.Query().Get("status"); got != "pending" {
|
|
t.Fatalf("existing query params must be preserved, status=%q", got)
|
|
}
|
|
}
|
|
|
|
func TestScopeOwnedListsSkipsReferenceData(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/currencies", nil)
|
|
|
|
scopeOwnedLists(c, 42)
|
|
if got := c.Request.URL.Query().Get("user_id"); got != "" {
|
|
t.Fatalf("currencies must not be scoped by user_id, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestGuardMatrix(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
tests := []struct {
|
|
name string
|
|
role string
|
|
branches []int64
|
|
method string
|
|
path string
|
|
want int
|
|
}{
|
|
{"user GET currencies", roleUser, nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
|
|
{"user POST currencies", roleUser, nil, http.MethodPost, "/api/admin/currencies", http.StatusForbidden},
|
|
{"user GET backups", roleUser, nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
|
|
{"user GET cards", roleUser, nil, http.MethodGet, "/api/admin/cards", http.StatusOK},
|
|
{"user POST cards", roleUser, nil, http.MethodPost, "/api/admin/cards", http.StatusOK},
|
|
{"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK},
|
|
{"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK},
|
|
{"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK},
|
|
{"user GET card-balances", roleUser, nil, http.MethodGet, "/api/admin/card-balances", http.StatusOK},
|
|
{"user POST card-balances", roleUser, nil, http.MethodPost, "/api/admin/card-balances", http.StatusOK},
|
|
{"user DELETE card-balances", roleUser, nil, http.MethodDelete, "/api/admin/card-balances/3", http.StatusOK},
|
|
{"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK},
|
|
{"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK},
|
|
{"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK},
|
|
{"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden},
|
|
{"user GET users/clients", roleUser, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK},
|
|
{"user GET branches", roleUser, nil, http.MethodGet, "/api/admin/branches", http.StatusOK},
|
|
{"user GET provinces", roleUser, nil, http.MethodGet, "/api/admin/provinces", http.StatusOK},
|
|
{"user POST branches", roleUser, nil, http.MethodPost, "/api/admin/branches", http.StatusForbidden},
|
|
{"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
|
|
{"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
|
|
|
|
{"operator GET currencies", roleOperator, []int64{1}, http.MethodGet, "/api/admin/currencies", http.StatusOK},
|
|
{"operator POST currencies", roleOperator, []int64{1}, http.MethodPost, "/api/admin/currencies", http.StatusForbidden},
|
|
{"operator GET backups", roleOperator, []int64{1}, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
|
|
{"operator GET card-orders", roleOperator, []int64{1}, http.MethodGet, "/api/admin/card-orders", http.StatusOK},
|
|
{"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK},
|
|
{"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden},
|
|
{"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK},
|
|
{"operator no branch GET users/clients", roleOperator, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK},
|
|
|
|
{"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
|
|
{"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK},
|
|
{"superadmin DELETE backups", "superadmin", nil, http.MethodDelete, "/api/admin/backups/1", http.StatusOK},
|
|
{"manager GET backups", "manager", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
status := serveGuard(&stubAuth{role: tt.role, branches: tt.branches}, tt.method, tt.path, "7", nil)
|
|
if status != tt.want {
|
|
t.Fatalf("status=%d want=%d", status, tt.want)
|
|
}
|
|
})
|
|
}
|
|
|
|
if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodPost, "/api/admin/cards", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("web guard custom role status=%d", status)
|
|
}
|
|
if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("web guard backups status=%d", status)
|
|
}
|
|
if status := serveGuard(&stubAuth{role: "teller", guard: guardOperator, branches: []int64{1}}, http.MethodPost, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("operator guard custom role status=%d", status)
|
|
}
|
|
if status := serveGuard(&stubAuth{role: "auditor", guard: guardAdmin}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("admin guard custom role status=%d", status)
|
|
}
|
|
if status := serveGuard(&stubAuth{role: roleOperator, guard: guardAdmin, branches: []int64{1}}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("legacy operator+admin guard must stay operator, status=%d", status)
|
|
}
|
|
if status := serveGuard(&stubAuth{role: "superadmin", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("superadmin code must stay admin even if guard is web, status=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestAdminPathPermission(t *testing.T) {
|
|
tests := []struct {
|
|
method, path string
|
|
want string
|
|
}{
|
|
{http.MethodGet, "/api/admin/users", "users.view"},
|
|
{http.MethodPost, "/api/admin/users", "users.manage"},
|
|
{http.MethodGet, "/api/admin/branch-users", "users.view"},
|
|
{http.MethodGet, "/api/admin/roles", "roles.view"},
|
|
{http.MethodPost, "/api/admin/roles", "roles.manage"},
|
|
{http.MethodGet, "/api/admin/permissions", "roles.view"},
|
|
{http.MethodPost, "/api/admin/permission-roles", "roles.manage"},
|
|
{http.MethodDelete, "/api/admin/role-users/1", "roles.manage"},
|
|
{http.MethodGet, "/api/admin/branches", "branches.view"},
|
|
{http.MethodPost, "/api/admin/branches", "branches.manage"},
|
|
{http.MethodGet, "/api/admin/provinces", "provinces.view"},
|
|
{http.MethodPost, "/api/admin/provinces", "provinces.manage"},
|
|
{http.MethodGet, "/api/admin/activity-logs", "activity-logs.view"},
|
|
{http.MethodGet, "/api/admin/backups", "backups.view"},
|
|
{http.MethodPost, "/api/admin/backups", "backups.manage"},
|
|
{http.MethodGet, "/api/admin/currencies", "currencies.view"},
|
|
{http.MethodPost, "/api/admin/currencies", "currencies.manage"},
|
|
{http.MethodGet, "/api/admin/payment-settings", "payment-settings.view"},
|
|
{http.MethodPut, "/api/admin/payment-settings", "payment-settings.manage"},
|
|
{http.MethodGet, "/api/admin/dashboard", ""},
|
|
{http.MethodGet, "/api/admin/profile", ""},
|
|
{http.MethodPost, "/api/admin/file", ""},
|
|
}
|
|
for _, tt := range tests {
|
|
if got := adminPathPermission(tt.method, tt.path); got != tt.want {
|
|
t.Errorf("adminPathPermission(%s %s)=%q want %q", tt.method, tt.path, got, tt.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestEnforceAdminSuperadminBypassesEverything(t *testing.T) {
|
|
// perms is a non-nil empty map, so every HasPermission/HasModuleAccess
|
|
// lookup would deny — superadmin must still pass without ever checking.
|
|
auth := &stubAuth{role: roleSuperadmin, perms: map[string]bool{}}
|
|
|
|
if status := serveGuard(auth, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("superadmin GET backups=%d", status)
|
|
}
|
|
if status := serveGuard(auth, http.MethodDelete, "/api/admin/users/1", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("superadmin DELETE users=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestEnforceAdminChecksPermission(t *testing.T) {
|
|
admin := &stubAuth{role: "admin", perms: map[string]bool{}}
|
|
if status := serveGuard(admin, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("admin without grant GET backups=%d", status)
|
|
}
|
|
|
|
adminWithGrant := &stubAuth{role: "admin", perms: map[string]bool{"backups.view": true}}
|
|
if status := serveGuard(adminWithGrant, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("admin with grant GET backups=%d", status)
|
|
}
|
|
|
|
manager := &stubAuth{role: "manager", perms: map[string]bool{"cards": true}}
|
|
if status := serveGuard(manager, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("manager GET card-orders=%d", status)
|
|
}
|
|
if status := serveGuard(manager, http.MethodGet, "/api/admin/currencies", "7", nil); status != http.StatusForbidden {
|
|
t.Fatalf("manager without currencies grant GET currencies=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestGuardOptionsAndPublicSkipAuthz(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
auth := &stubAuth{role: roleUser}
|
|
|
|
if status := serveGuard(auth, http.MethodOptions, "/api/admin/backups", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("OPTIONS status=%d", status)
|
|
}
|
|
if status := serveGuard(auth, http.MethodGet, "/api/admin/login", "7", nil); status != http.StatusOK {
|
|
t.Fatalf("public login status=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestGuardWithoutUserPassesThrough(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(Guard(&stubAuth{role: roleUser}))
|
|
r.GET("/api/admin/backups", func(c *gin.Context) { c.Status(http.StatusOK) })
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/api/admin/backups", nil)
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("status=%d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestGuardRoleLookupError(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
status := serveGuard(&stubAuth{roleErr: errors.New("db down")}, http.MethodGet, "/api/admin/currencies", "7", nil)
|
|
if status != http.StatusInternalServerError {
|
|
t.Fatalf("status=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestOperatorWriteAllowedBranchScope(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
auth := &stubAuth{role: roleOperator, branches: []int64{1, 2}, visible: true}
|
|
|
|
allowed := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":1}`))
|
|
if allowed != http.StatusOK {
|
|
t.Fatalf("own branch status=%d", allowed)
|
|
}
|
|
|
|
denied := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":99}`))
|
|
if denied != http.StatusForbidden {
|
|
t.Fatalf("foreign branch status=%d", denied)
|
|
}
|
|
}
|
|
|
|
func TestOperatorWriteAllowedUserVisibility(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
okAuth := &stubAuth{role: roleOperator, branches: []int64{1}, visible: true}
|
|
if status := serveGuard(okAuth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK {
|
|
t.Fatalf("visible user status=%d", status)
|
|
}
|
|
|
|
// Creating a brand-new order for a customer who has no prior record in
|
|
// the branch must still succeed — the branchId check alone scopes a
|
|
// create to the operator's own branch.
|
|
hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false}
|
|
if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK {
|
|
t.Fatalf("new customer create status=%d", status)
|
|
}
|
|
|
|
// Reassigning an existing order's customer still enforces visibility.
|
|
if status := serveGuard(hidden, http.MethodPut, "/api/admin/card-orders/1", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden {
|
|
t.Fatalf("update hidden user status=%d", status)
|
|
}
|
|
}
|
|
|
|
func TestRequirePermission(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
c.Set("id", "3")
|
|
c.Next()
|
|
})
|
|
r.GET("/x", RequirePermission(&stubAuth{perms: map[string]bool{"currencies.view": true}}, "currencies.view"), okHandler)
|
|
r.POST("/x", RequirePermission(&stubAuth{perms: map[string]bool{}}, "currencies.manage"), okHandler)
|
|
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/x", nil))
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("granted status=%d", w.Code)
|
|
}
|
|
|
|
w = httptest.NewRecorder()
|
|
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", nil))
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("denied status=%d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestAllowsBranchAndGuardUser(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
|
if !AllowsBranch(c, 1) {
|
|
t.Fatal("no scope should allow any branch")
|
|
}
|
|
if !GuardUser(c, 9) {
|
|
t.Fatal("no scope should allow any user")
|
|
}
|
|
|
|
c.Set(contextBranchIDs, []int64{1, 2})
|
|
if !AllowsBranch(c, 2) {
|
|
t.Fatal("expected branch 2 allowed")
|
|
}
|
|
if AllowsBranch(c, 9) {
|
|
t.Fatal("expected branch 9 denied")
|
|
}
|
|
|
|
c.Set(contextService, &stubAuth{visible: true})
|
|
if !GuardUser(c, 15) {
|
|
t.Fatal("expected visible user allowed")
|
|
}
|
|
c.Set(contextService, &stubAuth{visible: false})
|
|
if GuardUser(c, 15) {
|
|
t.Fatal("expected hidden user denied")
|
|
}
|
|
}
|
|
|
|
func TestGuardNewBranchAssignment(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
|
|
|
// No branch scope (admin caller): always allowed.
|
|
if !GuardNewBranchAssignment(c, 42) {
|
|
t.Fatal("admin caller should be able to assign any user")
|
|
}
|
|
|
|
// Operator scoped to branch 1.
|
|
c.Set(contextBranchIDs, []int64{1})
|
|
|
|
// Target has no existing branch: first-time assignment is allowed.
|
|
c.Set(contextService, &stubAuth{branches: nil})
|
|
if !GuardNewBranchAssignment(c, 42) {
|
|
t.Fatal("unbranched target should be assignable")
|
|
}
|
|
|
|
// Target already belongs to the operator's own branch: no-op re-assignment is allowed.
|
|
c.Set(contextService, &stubAuth{branches: []int64{1}})
|
|
if !GuardNewBranchAssignment(c, 42) {
|
|
t.Fatal("target already in caller's branch should be assignable")
|
|
}
|
|
|
|
// Target belongs to a different branch: reject cross-branch poaching.
|
|
c.Set(contextService, &stubAuth{branches: []int64{2}})
|
|
if GuardNewBranchAssignment(c, 42) {
|
|
t.Fatal("target from a foreign branch must not be assignable")
|
|
}
|
|
}
|
|
|
|
func TestBindBranchIDs(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
var dest []int64
|
|
BindBranchIDs(c, &dest)
|
|
if dest != nil {
|
|
t.Fatalf("expected empty dest, got %v", dest)
|
|
}
|
|
|
|
c.Set(contextBranchIDs, []int64{4, 5})
|
|
BindBranchIDs(c, &dest)
|
|
if len(dest) != 2 || dest[0] != 4 {
|
|
t.Fatalf("dest=%v", dest)
|
|
}
|
|
}
|
|
|
|
func TestClaimAndContextUserID(t *testing.T) {
|
|
if id, ok := claimUserID(jwt.MapClaims{"id": float64(12)}); !ok || id != 12 {
|
|
t.Fatalf("float id=%d ok=%v", id, ok)
|
|
}
|
|
if id, ok := claimUserID(jwt.MapClaims{"id": "8"}); !ok || id != 8 {
|
|
t.Fatalf("string id=%d ok=%v", id, ok)
|
|
}
|
|
if _, ok := claimUserID(jwt.MapClaims{"id": 0}); ok {
|
|
t.Fatal("zero id should fail")
|
|
}
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Set("id", "21")
|
|
if id, ok := parseContextUserID(c); !ok || id != 21 {
|
|
t.Fatalf("context id=%d ok=%v", id, ok)
|
|
}
|
|
}
|
|
|
|
func TestBearerToken(t *testing.T) {
|
|
if got := bearerToken("Bearer abc"); got != "abc" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
if got := bearerToken("abc"); got != "abc" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestUserInBranchSQLIncludesNewOrderTables(t *testing.T) {
|
|
sql := UserInBranchSQL("c.user_id", 3)
|
|
for _, table := range []string{
|
|
"branch_user", "card_orders", "loan_orders", "card_pin_orders",
|
|
"card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters",
|
|
"card_balances",
|
|
} {
|
|
if !strings.Contains(sql, table) {
|
|
t.Errorf("missing %s", table)
|
|
}
|
|
}
|
|
if strings.Count(sql, "$3") != 8 {
|
|
t.Fatalf("$3 count=%d", strings.Count(sql, "$3"))
|
|
}
|
|
}
|
|
|
|
func serveGuard(auth Authorizer, method, path, userID string, body []byte) int {
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
c.Set("id", userID)
|
|
c.Next()
|
|
})
|
|
r.Use(Guard(auth))
|
|
handler := func(c *gin.Context) { c.Status(http.StatusOK) }
|
|
r.GET("/api/admin/*rest", handler)
|
|
r.POST("/api/admin/*rest", handler)
|
|
r.PUT("/api/admin/*rest", handler)
|
|
r.PATCH("/api/admin/*rest", handler)
|
|
r.DELETE("/api/admin/*rest", handler)
|
|
r.OPTIONS("/api/admin/*rest", handler)
|
|
|
|
var req *http.Request
|
|
if body != nil {
|
|
req = httptest.NewRequest(method, path, bytes.NewReader(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
} else {
|
|
req = httptest.NewRequest(method, path, nil)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
return w.Code
|
|
}
|
|
|
|
func okHandler(c *gin.Context) { c.Status(http.StatusOK) }
|
|
|
|
type stubAuth struct {
|
|
role string
|
|
guard string
|
|
roleErr error
|
|
branches []int64
|
|
visible bool
|
|
visibleErr error
|
|
perms map[string]bool
|
|
}
|
|
|
|
func (s *stubAuth) RoleLookup(context.Context, int64) (string, string, error) {
|
|
return s.role, s.guard, s.roleErr
|
|
}
|
|
|
|
func (s *stubAuth) BranchIDs(context.Context, int64) ([]int64, error) {
|
|
return s.branches, nil
|
|
}
|
|
|
|
func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) {
|
|
if s.perms == nil {
|
|
return true, nil
|
|
}
|
|
return s.perms[code], nil
|
|
}
|
|
|
|
func (s *stubAuth) HasModuleAccess(_ context.Context, _ int64, module string) (bool, error) {
|
|
if s.perms == nil {
|
|
return true, nil
|
|
}
|
|
return s.perms[module], nil
|
|
}
|
|
|
|
func (s *stubAuth) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) {
|
|
return s.visible, s.visibleErr
|
|
}
|
|
|
|
var _ Authorizer = (*stubAuth)(nil)
|
|
var _ Authorizer = (*Service)(nil)
|
|
|
|
func TestEffectiveGuard(t *testing.T) {
|
|
tests := []struct {
|
|
code, guard, want string
|
|
}{
|
|
{roleUser, guardWeb, guardWeb},
|
|
{roleOperator, guardOperator, guardOperator},
|
|
{"admin", guardAdmin, guardAdmin},
|
|
{"customer", guardWeb, guardWeb},
|
|
{"teller", guardOperator, guardOperator},
|
|
{"auditor", guardAdmin, guardAdmin},
|
|
{roleUser, "", guardWeb},
|
|
{roleOperator, "", guardOperator},
|
|
{"admin", "", guardAdmin},
|
|
{"", "", guardWeb},
|
|
{roleOperator, guardAdmin, guardOperator},
|
|
{roleOperator, guardWeb, guardOperator},
|
|
{"operatot", guardWeb, guardOperator},
|
|
{"superadmin", guardWeb, guardAdmin},
|
|
{"admin", guardWeb, guardAdmin},
|
|
{"manager", guardOperator, guardAdmin},
|
|
}
|
|
for _, tt := range tests {
|
|
if got := effectiveGuard(tt.code, tt.guard); got != tt.want {
|
|
t.Errorf("effectiveGuard(%q, %q)=%q want %q", tt.code, tt.guard, got, tt.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestContainsInt64(t *testing.T) {
|
|
if !containsInt64([]int64{1, 2, 3}, 2) {
|
|
t.Fatal("expected 2")
|
|
}
|
|
if containsInt64([]int64{1, 2, 3}, 9) {
|
|
t.Fatal("did not expect 9")
|
|
}
|
|
}
|
|
|
|
func TestHasBranchScope(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
|
if HasBranchScope(c) {
|
|
t.Fatal("expected no scope")
|
|
}
|
|
c.Set(contextBranchIDs, []int64{1})
|
|
if !HasBranchScope(c) {
|
|
t.Fatal("expected scope")
|
|
}
|
|
}
|
|
|
|
func TestEnforceOwnWritesRewritesUserID(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
c.Set("id", "7")
|
|
c.Next()
|
|
})
|
|
r.Use(Guard(&stubAuth{role: roleUser}))
|
|
r.POST("/api/admin/cards", func(c *gin.Context) {
|
|
body, _ := io.ReadAll(c.Request.Body)
|
|
c.String(http.StatusOK, string(body))
|
|
})
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodPost, "/api/admin/cards", bytes.NewReader([]byte(`{"userId":99,"number":"1"}`)))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("status=%d", w.Code)
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"userId":7`) {
|
|
t.Fatalf("userId not rewritten: %s", w.Body.String())
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"user_id":7`) {
|
|
t.Fatalf("user_id not rewritten: %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestEnforceOwnWritesRewritesCreatedByForCardBalances(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
c.Set("id", "7")
|
|
c.Next()
|
|
})
|
|
r.Use(Guard(&stubAuth{role: roleUser}))
|
|
r.POST("/api/admin/card-balances", func(c *gin.Context) {
|
|
body, _ := io.ReadAll(c.Request.Body)
|
|
c.String(http.StatusOK, string(body))
|
|
})
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-balances", bytes.NewReader([]byte(`{"createdBy":99,"cardNumber":"4111111111111111"}`)))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("status=%d", w.Code)
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"createdBy":7`) {
|
|
t.Fatalf("createdBy not rewritten: %s", w.Body.String())
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"created_by":7`) {
|
|
t.Fatalf("created_by not rewritten: %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestGuardOwnedOwnScope(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
|
c.Set(contextRole, roleUser)
|
|
c.Set(contextGuard, guardWeb)
|
|
c.Set("id", "7")
|
|
|
|
own := int64(7)
|
|
if !GuardOwned(c, &own) {
|
|
t.Fatal("own record should pass")
|
|
}
|
|
other := int64(9)
|
|
if GuardOwned(c, &other) {
|
|
t.Fatal("foreign record should fail")
|
|
}
|
|
if GuardOwned(c, nil) {
|
|
t.Fatal("nil owner should fail")
|
|
}
|
|
if GuardUser(c, 9) {
|
|
t.Fatal("GuardUser should deny other users")
|
|
}
|
|
if !GuardUser(c, 7) {
|
|
t.Fatal("GuardUser should allow current user")
|
|
}
|
|
}
|
|
|
|
func TestSkipRecordGuard(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
if !SkipRecordGuard(c) {
|
|
t.Fatal("admin with no role/branches should skip")
|
|
}
|
|
c.Set(contextRole, roleUser)
|
|
c.Set(contextGuard, guardWeb)
|
|
if SkipRecordGuard(c) {
|
|
t.Fatal("user must not skip record guard")
|
|
}
|
|
c.Set(contextRole, roleOperator)
|
|
c.Set(contextGuard, guardOperator)
|
|
c.Set(contextBranchIDs, []int64{1})
|
|
if SkipRecordGuard(c) {
|
|
t.Fatal("operator with branches must not skip")
|
|
}
|
|
}
|