ch logika
This commit is contained in:
1 parent
e0d03730de
commit
d3e188affe
28 files changed
+405
-656
No files matched your search
@@ -18,14 +18,15 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
guardWeb = "web"
|
||||
guardOperator = "operator"
|
||||
guardAdmin = "admin"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextGuard = "guard"
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
roleSuperadmin = "superadmin"
|
||||
guardWeb = "web"
|
||||
guardOperator = "operator"
|
||||
guardAdmin = "admin"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextGuard = "guard"
|
||||
)
|
||||
|
||||
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
|
||||
@@ -96,12 +97,52 @@ func Guard(service Authorizer) gin.HandlerFunc {
|
||||
c.Next()
|
||||
return
|
||||
default:
|
||||
c.Next()
|
||||
enforceAdmin(c, service, userID, code)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// enforceAdmin gates the admin guard: only the superadmin role code is
|
||||
// unconditionally trusted (kept as one deliberately unrestricted role by
|
||||
// design). Every other admin-guard role (admin, manager, currency_maintainer,
|
||||
// or any future role with guard_name=admin) is checked against its actual
|
||||
// permission_role grants, mirroring enforceOperator's module/code checks —
|
||||
// so who can do what is decided by role/permission assignment (managed by
|
||||
// superadmin via the Role/Permission/Permission-Role APIs), not by role code.
|
||||
func enforceAdmin(c *gin.Context, service Authorizer, userID int64, code string) {
|
||||
if strings.EqualFold(strings.TrimSpace(code), roleSuperadmin) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
if module := operatorPathModule(c.Request.Method, c.Request.URL.Path); module != "" {
|
||||
granted, err := service.HasModuleAccess(c.Request.Context(), userID, module)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !granted {
|
||||
abortForbidden(c, "missing module access for admin path", logrus.Fields{"userId": userID, "module": module})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if perm := adminPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" {
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !granted {
|
||||
abortForbidden(c, "missing permission for admin path", logrus.Fields{"userId": userID, "permission": perm})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
|
||||
ids, err := service.BranchIDs(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
@@ -120,6 +161,18 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
|
||||
return
|
||||
}
|
||||
|
||||
if module := operatorPathModule(c.Request.Method, c.Request.URL.Path); module != "" {
|
||||
granted, err := service.HasModuleAccess(c.Request.Context(), userID, module)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !granted {
|
||||
abortForbidden(c, "missing module access for operator path", logrus.Fields{"userId": userID, "module": module})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if perm := operatorPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" {
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
|
||||
if err != nil {
|
||||
@@ -485,10 +538,13 @@ func adminREST(path string) string {
|
||||
return rest
|
||||
}
|
||||
|
||||
// operatorPathPermission returns "cards" or "loans" for saha endpoints.
|
||||
// Empty string: shared catalog (profile, file, dashboard, branches, provinces,
|
||||
// users/clients, currencies read) — any operator may call it.
|
||||
func operatorPathPermission(method, path string) string {
|
||||
// operatorPathModule returns the permission module ("cards" or "loans") that
|
||||
// guards a saha endpoint. Matching by module rather than a fixed code lets an
|
||||
// admin grant access under a new permission code created in that module
|
||||
// (via the existing Permission/Permission-Role APIs) without a code change
|
||||
// here. Shared by both enforceOperator and enforceAdmin — the cards/loans
|
||||
// grouping is the same regardless of which guard is calling.
|
||||
func operatorPathModule(_, path string) string {
|
||||
rest := adminREST(path)
|
||||
|
||||
switch {
|
||||
@@ -512,7 +568,19 @@ func operatorPathPermission(method, path string) string {
|
||||
"/loans-documents",
|
||||
}):
|
||||
return "loans"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// operatorPathPermission returns the exact permission code required for
|
||||
// endpoints that distinguish view vs. manage access. Empty string: shared
|
||||
// catalog (profile, file, dashboard, branches, provinces, users/clients,
|
||||
// currencies read) — any operator may call it.
|
||||
func operatorPathPermission(method, path string) string {
|
||||
rest := adminREST(path)
|
||||
|
||||
switch {
|
||||
case matchesPrefix(rest, []string{"/users/clients"}):
|
||||
return ""
|
||||
|
||||
@@ -526,6 +594,46 @@ func operatorPathPermission(method, path string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// adminPathPermission returns the "<module>.view"/"<module>.manage" code
|
||||
// required for admin-guard saha that split read vs. write access (unlike
|
||||
// cards/loans, which stay module-based via operatorPathModule). Empty
|
||||
// string: no permission required (dashboard, profile, file, public routes).
|
||||
func adminPathPermission(method, path string) string {
|
||||
rest := adminREST(path)
|
||||
|
||||
switch {
|
||||
case matchesPrefix(rest, []string{"/users", "/branch-users"}):
|
||||
return viewOrManage(method, "users")
|
||||
|
||||
case matchesPrefix(rest, []string{"/roles", "/permissions", "/permission-roles", "/role-users"}):
|
||||
return viewOrManage(method, "roles")
|
||||
|
||||
case matchesPrefix(rest, []string{"/branches"}):
|
||||
return viewOrManage(method, "branches")
|
||||
|
||||
case matchesPrefix(rest, []string{"/provinces"}):
|
||||
return viewOrManage(method, "provinces")
|
||||
|
||||
case matchesPrefix(rest, []string{"/activity-logs"}):
|
||||
return "activity-logs.view"
|
||||
|
||||
case matchesPrefix(rest, []string{"/backups"}):
|
||||
return viewOrManage(method, "backups")
|
||||
|
||||
case matchesPrefix(rest, []string{"/currencies"}):
|
||||
return viewOrManage(method, "currencies")
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func viewOrManage(method, module string) string {
|
||||
if method == http.MethodGet {
|
||||
return module + ".view"
|
||||
}
|
||||
return module + ".manage"
|
||||
}
|
||||
|
||||
var operatorWritePrefixes = []string{
|
||||
"/profile",
|
||||
"/file",
|
||||
|
||||
@@ -160,10 +160,10 @@ func TestOperatorCardsAndLoansSahalar(t *testing.T) {
|
||||
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden {
|
||||
t.Fatalf("loans GET balances=%d", status)
|
||||
}
|
||||
if got := operatorPathPermission(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
|
||||
if got := operatorPathModule(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
|
||||
t.Fatalf("card-balances path=%q", got)
|
||||
}
|
||||
if got := operatorPathPermission(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
|
||||
if got := operatorPathModule(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
|
||||
t.Fatalf("card-orders path=%q", got)
|
||||
}
|
||||
}
|
||||
@@ -187,22 +187,22 @@ func TestAllCardAndLoanRoutesMapped(t *testing.T) {
|
||||
"/api/admin/loans-documents",
|
||||
}
|
||||
for _, path := range cardPaths {
|
||||
if got := operatorPathPermission(http.MethodGet, path); got != "cards" {
|
||||
t.Errorf("GET %s perm=%q, want cards", path, got)
|
||||
if got := operatorPathModule(http.MethodGet, path); got != "cards" {
|
||||
t.Errorf("GET %s module=%q, want cards", path, got)
|
||||
}
|
||||
if got := operatorPathPermission(http.MethodPost, path); got != "cards" {
|
||||
t.Errorf("POST %s perm=%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 := operatorPathPermission(http.MethodGet, path); got != "loans" {
|
||||
t.Errorf("GET %s perm=%q, want loans", path, got)
|
||||
if got := operatorPathModule(http.MethodGet, path); got != "loans" {
|
||||
t.Errorf("GET %s module=%q, want loans", path, got)
|
||||
}
|
||||
if got := operatorPathPermission(http.MethodPost, path); got != "loans" {
|
||||
t.Errorf("POST %s perm=%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)
|
||||
@@ -378,6 +378,72 @@ func TestGuardMatrix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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/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}
|
||||
@@ -655,6 +721,13 @@ func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool,
|
||||
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
|
||||
}
|
||||
|
||||
@@ -22,35 +22,20 @@ type Authorizer interface {
|
||||
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error)
|
||||
BranchIDs(ctx context.Context, userID int64) ([]int64, error)
|
||||
HasPermission(ctx context.Context, userID int64, code string) (bool, error)
|
||||
HasModuleAccess(ctx context.Context, userID int64, module string) (bool, error)
|
||||
UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error)
|
||||
}
|
||||
|
||||
// HasPermission checks the role's baseline grant, then lets a per-user
|
||||
// permission_user override win: an explicit "deny" always wins (even over
|
||||
// another allow), an explicit "allow" grants a permission the role does
|
||||
// not, and no override falls back to the role.
|
||||
// HasPermission checks whether the user's role grants the exact permission code.
|
||||
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
|
||||
const query = `
|
||||
SELECT
|
||||
CASE
|
||||
WHEN EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
||||
) THEN false
|
||||
WHEN EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
||||
) THEN true
|
||||
ELSE EXISTS (
|
||||
SELECT 1
|
||||
FROM role_user ru
|
||||
JOIN permission_role pr ON pr.role_id = ru.role_id
|
||||
JOIN permissions p ON p.id = pr.permission_id
|
||||
WHERE ru.user_id = $1 AND p.code = $2 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL
|
||||
)
|
||||
END`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM role_user ru
|
||||
JOIN permission_role pr ON pr.role_id = ru.role_id
|
||||
JOIN permissions p ON p.id = pr.permission_id
|
||||
WHERE ru.user_id = $1 AND p.code = $2 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL
|
||||
)`
|
||||
|
||||
var granted bool
|
||||
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
|
||||
@@ -59,6 +44,26 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string)
|
||||
return granted, nil
|
||||
}
|
||||
|
||||
// HasModuleAccess is HasPermission matched against a permission's module
|
||||
// instead of its exact code, so a new permission code created under an
|
||||
// existing module (e.g. "loans") is recognized without a code change here.
|
||||
func (s *Service) HasModuleAccess(ctx context.Context, userID int64, module string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM role_user ru
|
||||
JOIN permission_role pr ON pr.role_id = ru.role_id
|
||||
JOIN permissions p ON p.id = pr.permission_id
|
||||
WHERE ru.user_id = $1 AND p.module = $2 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL
|
||||
)`
|
||||
|
||||
var granted bool
|
||||
if err := s.client.QueryRow(ctx, query, userID, module).Scan(&granted); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return granted, nil
|
||||
}
|
||||
|
||||
func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) {
|
||||
const query = `
|
||||
SELECT r.code, r.guard_name
|
||||
|
||||
Reference in new issue
Block a user