package rbac import ( "bytes" "context" "encoding/json" "errors" "io" "net/http" "net/http/httptest" "strings" "testing" "online-back/internal/identity/rbac/perm" "github.com/gin-gonic/gin" ) func principal(scope Scope, codes ...perm.Code) *Principal { p := &Principal{UserID: 7, RoleID: 70, Scope: scope, Perms: map[perm.Code]struct{}{}} for _, code := range codes { p.Perms[code] = struct{}{} } if scope == ScopeBranch { p.BranchIDs = []int64{3} } return p } type fakeAuthorizer struct { principals map[int64]*Principal visible bool loadErr error } func (f *fakeAuthorizer) Load(_ context.Context, id int64) (*Principal, error) { return f.principals[id], f.loadErr } func (f *fakeAuthorizer) BranchIDs(context.Context, int64) ([]int64, error) { return nil, nil } func (f *fakeAuthorizer) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) { return f.visible, nil } // runPolicy sends one request through p's group middleware with caller // already in the context (as Guard would leave it). func runPolicy(t *testing.T, p Policy, caller *Principal, method, target, body string) (int, *http.Request) { t.Helper() gin.SetMode(gin.TestMode) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = httptest.NewRequest(method, target, strings.NewReader(body)) if caller != nil { c.Set(contextPrincipal, caller) } c.Set(contextService, &fakeAuthorizer{visible: false}) p.handler()(c) if c.IsAborted() { return w.Code, c.Request } return http.StatusOK, c.Request } func TestCan(t *testing.T) { p := principal(ScopeAll, perm.Loans) if !p.Can(perm.Loans) || p.Can(perm.Cards) { t.Fatal("Can should follow the permission set") } if !(&Principal{IsSuper: true}).Can(perm.Backups) { t.Fatal("superadmin holds every permission") } if (*Principal)(nil).Can(perm.Loans) { t.Fatal("nil principal holds nothing") } } func TestPermCodesFollowCatalogOrder(t *testing.T) { p := principal(ScopeAll, perm.Loans, perm.Dashboard, perm.Cards) got := p.PermCodes() want := []perm.Code{perm.Dashboard, perm.Cards, perm.Loans} if len(got) != len(want) { t.Fatalf("got %v", got) } for i := range want { if got[i] != want[i] { t.Fatalf("got %v, want %v", got, want) } } } func TestCanGrant(t *testing.T) { admin := principal(ScopeAll, perm.Cards, perm.Loans, perm.Users) manager := principal(ScopeBranch, perm.Cards, perm.Users) cases := []struct { name string caller *Principal target RoleInfo want error }{ {"super grants anything", &Principal{IsSuper: true, Scope: ScopeAll}, RoleInfo{IsSuper: true, Scope: ScopeAll}, nil}, {"admin cannot grant superadmin", admin, RoleInfo{IsSuper: true, Scope: ScopeAll}, ErrSuperOnly}, {"admin grants loan head", admin, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Loans}}, nil}, {"admin lacks backups", admin, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Backups}}, ErrPermissionHeld}, {"manager cannot grant all scope", manager, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Cards}}, ErrScopeTooWide}, {"manager grants card operator", manager, RoleInfo{Scope: ScopeBranch, Perms: []perm.Code{perm.Cards}}, nil}, {"manager lacks loans", manager, RoleInfo{Scope: ScopeBranch, Perms: []perm.Code{perm.Loans}}, ErrPermissionHeld}, {"own-scope role skips the permission check", manager, RoleInfo{Scope: ScopeOwn, Perms: []perm.Code{perm.Cards, perm.Loans}}, nil}, {"nil caller", nil, RoleInfo{Scope: ScopeOwn}, ErrSuperOnly}, } for _, tc := range cases { if got := tc.caller.CanGrant(tc.target); !errors.Is(got, tc.want) { t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) } } } func TestCanSaveRole(t *testing.T) { admin := principal(ScopeAll, perm.Cards, perm.Loans, perm.Roles) super := &Principal{IsSuper: true, Scope: ScopeAll} if err := admin.CanSaveRole(nil, RoleInfo{Scope: "global"}); !errors.Is(err, ErrInvalidScope) { t.Errorf("invalid scope: got %v", err) } if err := admin.CanSaveRole(nil, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{"nope"}}); !errors.Is(err, ErrUnknownPerm) { t.Errorf("unknown perm: got %v", err) } system := &RoleInfo{Scope: ScopeOwn, IsSystem: true} if err := super.CanSaveRole(system, RoleInfo{Scope: ScopeBranch}); !errors.Is(err, ErrSystemRole) { t.Errorf("system role scope change: got %v", err) } if err := super.CanSaveRole(system, RoleInfo{Scope: ScopeOwn, Perms: []perm.Code{perm.Cards}}); err != nil { t.Errorf("system role perms may change: got %v", err) } superRole := &RoleInfo{Scope: ScopeAll, IsSuper: true, IsSystem: true} if err := admin.CanSaveRole(superRole, RoleInfo{Scope: ScopeAll}); !errors.Is(err, ErrSuperOnly) { t.Errorf("admin editing superadmin role: got %v", err) } // A role already out of reach cannot be stripped either. backups := &RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Backups}} if err := admin.CanSaveRole(backups, RoleInfo{Scope: ScopeAll}); !errors.Is(err, ErrPermissionHeld) { t.Errorf("admin editing role with backups: got %v", err) } } func TestPolicyMatrix(t *testing.T) { client := principal(ScopeOwn, perm.Cards, perm.Loans) operator := principal(ScopeBranch, perm.Cards) loanHead := principal(ScopeAll, perm.Loans) cases := []struct { name string policy Policy caller *Principal method string want int }{ {"client reads own cards", Require(perm.Cards), client, http.MethodGet, 200}, {"operator lacks loans", Require(perm.Loans), operator, http.MethodGet, 403}, {"loan head reads loans", Require(perm.Loans), loanHead, http.MethodGet, 200}, {"loan head has no cards", Require(perm.Cards), loanHead, http.MethodGet, 403}, {"client blocked from staff module", RequireStaff(perm.Cards), client, http.MethodGet, 403}, {"operator on staff module", RequireStaff(perm.Cards), operator, http.MethodGet, 200}, {"client reads catalog", Catalog(perm.Loans), client, http.MethodGet, 200}, {"client cannot write catalog", Catalog(perm.Loans), client, http.MethodPost, 403}, {"operator cannot write loans catalog", Catalog(perm.Loans), operator, http.MethodPost, 403}, {"loan head writes loans catalog", Catalog(perm.Loans), loanHead, http.MethodPost, 200}, {"staff read for operator", StaffRead(perm.PaymentSettings), operator, http.MethodGet, 200}, {"staff read blocks client", StaffRead(perm.PaymentSettings), client, http.MethodGet, 403}, {"staff write needs perm", StaffRead(perm.PaymentSettings), operator, http.MethodPut, 403}, {"staff blocks client", Staff(), client, http.MethodGet, 403}, {"authenticated lets client in", Authenticated(), client, http.MethodPut, 200}, {"no principal", Authenticated(), nil, http.MethodGet, 403}, } for _, tc := range cases { if got, _ := runPolicy(t, tc.policy, tc.caller, tc.method, "/api/admin/x", ""); got != tc.want { t.Errorf("%s: got %d, want %d", tc.name, got, tc.want) } } } func TestBranchScopeWithoutBranchesIsDenied(t *testing.T) { p := principal(ScopeBranch, perm.Cards) p.BranchIDs = nil if got, _ := runPolicy(t, Require(perm.Cards), p, http.MethodGet, "/api/admin/cards", ""); got != 403 { t.Fatalf("got %d, want 403", got) } } func TestOwnScopePinsQueryAndBody(t *testing.T) { client := principal(ScopeOwn, perm.Cards) _, req := runPolicy(t, Require(perm.Cards), client, http.MethodGet, "/api/admin/card-orders?user_id=99", "") if req.URL.Query().Get("user_id") != "7" || req.URL.Query().Get("created_by") != "7" { t.Fatalf("list not pinned to caller: %s", req.URL.RawQuery) } _, req = runPolicy(t, Require(perm.Cards), client, http.MethodPost, "/api/admin/card-orders", `{"userId":99,"branchId":1}`) body, _ := io.ReadAll(req.Body) var payload map[string]interface{} if err := json.Unmarshal(body, &payload); err != nil { t.Fatal(err) } for _, key := range []string{"userId", "user_id", "createdBy", "created_by"} { if payload[key] != float64(7) { t.Fatalf("%s = %v, want 7", key, payload[key]) } } if payload["branchId"] != float64(1) { t.Fatal("other fields must survive the rewrite") } } func TestBranchScopeWrites(t *testing.T) { operator := principal(ScopeBranch, perm.Cards) cases := []struct { name string method string body string want int }{ {"own branch", http.MethodPost, `{"branchId":3}`, 200}, {"other branch", http.MethodPost, `{"branchId":4}`, 403}, {"create for new customer", http.MethodPost, `{"branchId":3,"userId":50}`, 200}, {"reassign to invisible user", http.MethodPut, `{"branchId":3,"userId":50}`, 403}, {"no body", http.MethodPut, ``, 200}, } for _, tc := range cases { if got, _ := runPolicy(t, Require(perm.Cards), operator, tc.method, "/api/admin/card-orders/1", tc.body); got != tc.want { t.Errorf("%s: got %d, want %d", tc.name, got, tc.want) } } } func TestRegistryLookupAndVerify(t *testing.T) { routes.reset() defer routes.reset() gin.SetMode(gin.TestMode) engine := gin.New() admin := engine.Group("/api/admin") Group(admin, "/users", RequireStaff(perm.Users)).GET("/:id", func(*gin.Context) {}) Group(admin, "/users/clients", Staff()).GET("", func(*gin.Context) {}) Group(admin, "/login", Public()).POST("", func(*gin.Context) {}) if p, _ := routes.lookup("/api/admin/users/clients"); p.name != "staff" { t.Fatalf("longest prefix should win, got %s", p.name) } if p, _ := routes.lookup("/api/admin/users/:id"); p.name != "require-staff:users" { t.Fatalf("got %s", p.name) } if _, ok := routes.lookup("/api/admin/usersx"); ok { t.Fatal("prefix must match whole path segments") } if err := VerifyRoutes(engine.Routes(), "/api/admin"); err != nil { t.Fatalf("all routes declared: %v", err) } admin.GET("/forgotten", func(*gin.Context) {}) err := VerifyRoutes(engine.Routes(), "/api/admin") if err == nil || !strings.Contains(err.Error(), "GET /api/admin/forgotten") { t.Fatalf("undeclared route must be reported, got %v", err) } } func TestRegistryRejectsConflictingPolicies(t *testing.T) { routes.reset() defer routes.reset() engine := gin.New() Group(engine.Group("/api/admin"), "/cards", Require(perm.Cards)) Group(engine.Group("/api/admin"), "/cards", Require(perm.Cards)) // same policy twice is fine defer func() { if recover() == nil { t.Fatal("expected panic for conflicting policy") } }() Group(engine.Group("/api/admin"), "/cards", Catalog(perm.Cards)) } func TestGuardEndToEnd(t *testing.T) { routes.reset() defer routes.reset() gin.SetMode(gin.TestMode) auth := &fakeAuthorizer{principals: map[int64]*Principal{7: principal(ScopeAll, perm.Loans)}} engine := gin.New() admin := engine.Group("/api/admin") // Stand-in for JwtTokenCheck: Guard reads the id from the context first. admin.Use(func(c *gin.Context) { if id := c.GetHeader("X-User"); id != "" { c.Set("id", id) } }, Guard(auth)) ok := func(c *gin.Context) { c.Status(http.StatusOK) } admin.Group("/loan-orders", Require(perm.Loans).handler()).GET("", ok) routes.add("/api/admin/loan-orders", Require(perm.Loans)) admin.Group("/cards", Require(perm.Cards).handler()).GET("", ok) routes.add("/api/admin/cards", Require(perm.Cards)) admin.GET("/undeclared", ok) do := func(path, user string) int { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, path, &bytes.Buffer{}) if user != "" { req.Header.Set("X-User", user) } engine.ServeHTTP(w, req) return w.Code } if got := do("/api/admin/loan-orders", "7"); got != 200 { t.Errorf("loan head on loans: %d", got) } if got := do("/api/admin/cards", "7"); got != 403 { t.Errorf("loan head on cards: %d", got) } if got := do("/api/admin/loan-orders", "8"); got != 403 { t.Errorf("unknown user: %d", got) } if got := do("/api/admin/undeclared", "7"); got != 403 { t.Errorf("undeclared route must be denied: %d", got) } auth.loadErr = errors.New("db down") if got := do("/api/admin/loan-orders", "7"); got != 500 { t.Errorf("load error: %d", got) } } func TestScopeHelpers(t *testing.T) { gin.SetMode(gin.TestMode) ctx := func(p *Principal) *gin.Context { c, _ := gin.CreateTestContext(httptest.NewRecorder()) c.Request = httptest.NewRequest(http.MethodGet, "/", nil) c.Set(contextPrincipal, p) c.Set(contextService, &fakeAuthorizer{visible: true}) return c } all := ctx(principal(ScopeAll)) if !HasAllScope(all) || !SkipRecordGuard(all) || BranchIDsFrom(all) != nil || !AllowsBranch(all, 99) { t.Error("all scope sees everything") } branch := ctx(principal(ScopeBranch)) if !HasBranchScope(branch) || SkipRecordGuard(branch) || AllowsBranch(branch, 99) || !AllowsBranch(branch, 3) { t.Error("branch scope is limited to its branches") } var ids []int64 BindBranchIDs(branch, &ids) if len(ids) != 1 || ids[0] != 3 { t.Errorf("BindBranchIDs = %v", ids) } own := ctx(principal(ScopeOwn)) if !IsOwnScope(own) || SkipRecordGuard(own) { t.Error("own scope must be guarded") } mine, other := int64(7), int64(8) if !GuardOwned(own, &mine) || GuardOwned(ctx(principal(ScopeOwn)), &other) { t.Error("GuardOwned follows the owner id") } if id, ok := CurrentUserID(own); !ok || id != 7 { t.Errorf("CurrentUserID = %d, %v", id, ok) } } func TestUserInBranchSQLIncludesOrderTables(t *testing.T) { sql := UserInBranchSQL("u.id", 2) 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("UserInBranchSQL missing %s", table) } } }