changed role permission
This commit is contained in:
1 parent
f0ecf23879
commit
323e131216
74 files changed
+2915
-4713
No files matched your search
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -18,291 +19,176 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
roleSuperadmin = "superadmin"
|
||||
guardWeb = "web"
|
||||
guardOperator = "operator"
|
||||
guardAdmin = "admin"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextGuard = "guard"
|
||||
contextPrincipal = "rbacPrincipal"
|
||||
contextService = "rbacService"
|
||||
)
|
||||
|
||||
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Public: no token (login, register, payment callback).
|
||||
func Public() Policy {
|
||||
return Policy{name: "public", read: rule{kind: rulePublic}, write: rule{kind: rulePublic}}
|
||||
}
|
||||
|
||||
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Authenticated: any logged-in user, clients included (profile, file).
|
||||
func Authenticated() Policy {
|
||||
return Policy{name: "authenticated", read: rule{kind: ruleAuthenticated}, write: rule{kind: ruleAuthenticated}}
|
||||
}
|
||||
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
||||
if err != nil || !granted {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Staff: any logged-in user whose role scope is not own.
|
||||
func Staff() Policy {
|
||||
return Policy{name: "staff", read: rule{kind: ruleStaff}, write: rule{kind: ruleStaff}}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
// Require: code for every method. Own-scope callers are limited to their
|
||||
// own records, branch-scope callers to their branches.
|
||||
func Require(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code)}
|
||||
return Policy{name: "require:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// RequireStaff: Require, but never for own-scope callers.
|
||||
func RequireStaff(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code), staffOnly: true}
|
||||
return Policy{name: "require-staff:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// Catalog: reference data every logged-in user reads (loan types, branches,
|
||||
// currencies, ...); writes need code and a staff scope.
|
||||
func Catalog(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "catalog:" + string(code),
|
||||
read: rule{kind: ruleAuthenticated},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// StaffRead: any staff member reads, writes need code.
|
||||
func StaffRead(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "staff-read:" + string(code),
|
||||
read: rule{kind: ruleStaff},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// Guard runs on every /api/admin request before the route's group
|
||||
// middleware: it resolves the route's policy (deny if none), and for
|
||||
// non-public routes loads the caller's principal into the context.
|
||||
func Guard(service Authorizer) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) {
|
||||
if c.Request.Method == http.MethodOptions || c.FullPath() == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
policy, ok := routes.lookup(c.FullPath())
|
||||
if !ok {
|
||||
abortForbidden(c, "route has no rbac policy", nil)
|
||||
return
|
||||
}
|
||||
if policy.public() {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := requestUserID(c)
|
||||
if !ok {
|
||||
// The group's JwtTokenCheck answers with the proper 401/403.
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
code, guardName, err := service.RoleLookup(c.Request.Context(), userID)
|
||||
principal, err := service.Load(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
logging.GetLogger().Errorf("rbac: load principal %d failed: %v", userID, err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if principal == nil {
|
||||
abortForbidden(c, "user or role not found", logrus.Fields{"userId": userID})
|
||||
return
|
||||
}
|
||||
|
||||
guard := effectiveGuard(code, guardName)
|
||||
c.Set("id", strconv.FormatInt(userID, 10))
|
||||
c.Set(contextRole, code)
|
||||
c.Set(contextGuard, guard)
|
||||
c.Set(contextPrincipal, principal)
|
||||
c.Set(contextService, service)
|
||||
|
||||
switch guard {
|
||||
case guardOperator:
|
||||
enforceOperator(c, service, userID)
|
||||
return
|
||||
case guardWeb:
|
||||
if code == "" {
|
||||
c.Set(contextRole, roleUser)
|
||||
}
|
||||
if !userRoleAllows(c.Request.Method, c.Request.URL.Path) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
scopeOwnedLists(c, userID)
|
||||
if !enforceOwnWrites(c, userID) {
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
return
|
||||
default:
|
||||
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 {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
c.Set(contextBranchIDs, ids)
|
||||
|
||||
if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) {
|
||||
abortForbidden(c, "route not in operator allow-list", logrus.Fields{"userId": userID})
|
||||
return
|
||||
}
|
||||
|
||||
if !operatorProfileOrFile(c.Request.URL.Path) && !operatorClientsList(c.Request.URL.Path) && len(ids) == 0 {
|
||||
abortForbidden(c, "operator has no assigned branches", logrus.Fields{"userId": userID})
|
||||
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)
|
||||
func (p Policy) handler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
r := p.ruleFor(c.Request.Method)
|
||||
principal := PrincipalFrom(c)
|
||||
if principal == nil {
|
||||
abortForbidden(c, "no principal", nil)
|
||||
return
|
||||
}
|
||||
if !granted {
|
||||
abortForbidden(c, "missing module access for operator path", logrus.Fields{"userId": userID, "module": module})
|
||||
|
||||
switch r.kind {
|
||||
case ruleAuthenticated:
|
||||
case ruleStaff:
|
||||
if principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID})
|
||||
return
|
||||
}
|
||||
case rulePermission:
|
||||
if !principal.Can(perm.Code(r.perm)) {
|
||||
abortForbidden(c, "missing permission", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if r.staffOnly && principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if !enforceScope(c, principal) {
|
||||
return
|
||||
}
|
||||
default:
|
||||
abortForbidden(c, "unknown rule", nil)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
|
||||
if perm := operatorPathPermission(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 operator path", logrus.Fields{"userId": userID, "permission": perm})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if !operatorWriteAllowed(c, service, ids) {
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// abortForbidden logs why a request was denied (method, path, and any extra
|
||||
// fields the caller passes) before writing the 403, since appresult.ErrForbidden
|
||||
// alone gives the client and the logs no way to tell which rbac check failed.
|
||||
func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) {
|
||||
entry := logging.GetLogger().WithFields(logrus.Fields{
|
||||
"method": c.Request.Method,
|
||||
"path": c.Request.URL.Path,
|
||||
})
|
||||
for k, v := range fields {
|
||||
entry = entry.WithField(k, v)
|
||||
}
|
||||
entry.Warn("rbac forbidden: " + reason)
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
|
||||
// EffectiveGuard resolves the guard a role with the given code/guard_name
|
||||
// would run requests under - the same resolution Guard() applies to the
|
||||
// caller on every request. Exposed so callers that grant a role (e.g. the
|
||||
// user handler) can ask "would this reach guardAdmin?" against the role's
|
||||
// real guard_name instead of matching against a hardcoded list of role
|
||||
// names, which drifts the moment a new role is added.
|
||||
func EffectiveGuard(code, guardName string) string {
|
||||
return effectiveGuard(code, guardName)
|
||||
}
|
||||
|
||||
func effectiveGuard(code, guardName string) string {
|
||||
code = strings.ToLower(strings.TrimSpace(code))
|
||||
guard := strings.ToLower(strings.TrimSpace(guardName))
|
||||
|
||||
switch code {
|
||||
case "admin", "superadmin", "manager":
|
||||
return guardAdmin
|
||||
case roleOperator, "operatot":
|
||||
return guardOperator
|
||||
}
|
||||
|
||||
switch guard {
|
||||
case guardWeb, guardOperator, guardAdmin:
|
||||
return guard
|
||||
}
|
||||
|
||||
if code == roleUser || code == "" {
|
||||
return guardWeb
|
||||
}
|
||||
return guardAdmin
|
||||
}
|
||||
|
||||
func isPublicAdminPath(path string) bool {
|
||||
switch strings.TrimSuffix(path, "/") {
|
||||
case adminPrefix + "/login",
|
||||
adminPrefix + "/token",
|
||||
adminPrefix + "/register",
|
||||
adminPrefix + "/register/verify",
|
||||
adminPrefix + "/forgot-password",
|
||||
adminPrefix + "/forgot-password/verify",
|
||||
adminPrefix + "/visa-master-payment-orders/callback":
|
||||
// enforceScope applies the role's data scope to a permission-gated request.
|
||||
// own: list queries and write bodies are pinned to the caller's user id.
|
||||
// branch: the caller must have branches, and write bodies may only name
|
||||
// those branches (and, on update, users visible in them).
|
||||
func enforceScope(c *gin.Context, p *Principal) bool {
|
||||
switch p.Scope {
|
||||
case ScopeAll:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func userRoleAllows(method, path string) bool {
|
||||
rest := adminREST(path)
|
||||
if rest == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if matchesPrefix(rest, userCatalogPrefixes) {
|
||||
return method == http.MethodGet
|
||||
}
|
||||
if matchesPrefix(rest, userSelfPrefixes) {
|
||||
if rest == "/profile" || strings.HasPrefix(rest, "/profile/") {
|
||||
return method == http.MethodGet || method == http.MethodPut || method == http.MethodPatch
|
||||
}
|
||||
return method == http.MethodGet || method == http.MethodPost
|
||||
}
|
||||
if matchesPrefix(rest, userOwnedPrefixes) {
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
case ScopeOwn:
|
||||
pinOwnQuery(c, p.UserID)
|
||||
return pinOwnBody(c, p.UserID)
|
||||
case ScopeBranch:
|
||||
if len(p.BranchIDs) == 0 {
|
||||
abortForbidden(c, "branch scope without assigned branches", logrus.Fields{"userId": p.UserID})
|
||||
return false
|
||||
}
|
||||
return branchWriteAllowed(c, p.BranchIDs)
|
||||
}
|
||||
abortForbidden(c, "unknown scope", logrus.Fields{"userId": p.UserID, "scope": p.Scope})
|
||||
return false
|
||||
}
|
||||
|
||||
func matchesPrefix(rest string, prefixes []string) bool {
|
||||
for _, prefix := range prefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
func pinOwnQuery(c *gin.Context, userID int64) {
|
||||
query := c.Request.URL.Query()
|
||||
id := strconv.FormatInt(userID, 10)
|
||||
query.Set("user_id", id)
|
||||
query.Set("created_by", id)
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
}
|
||||
|
||||
func enforceOwnWrites(c *gin.Context, userID int64) bool {
|
||||
if !matchesPrefix(adminREST(c.Request.URL.Path), userOwnedPrefixes) {
|
||||
func pinOwnBody(c *gin.Context, userID int64) bool {
|
||||
if !isWrite(c.Request.Method) || c.Request.Method == http.MethodDelete {
|
||||
return true
|
||||
}
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
@@ -324,30 +210,92 @@ func enforceOwnWrites(c *gin.Context, userID int64) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func scopeOwnedLists(c *gin.Context, userID int64) {
|
||||
rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/")
|
||||
if rest == "" {
|
||||
return
|
||||
func branchWriteAllowed(c *gin.Context, branchIDs []int64) bool {
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
if !strings.HasPrefix(rest, "/") {
|
||||
rest = "/" + rest
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
owned := false
|
||||
for _, prefix := range userOwnedPrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
var payload struct {
|
||||
BranchId *int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
}
|
||||
if !owned {
|
||||
return
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
query := c.Request.URL.Query()
|
||||
query.Set("user_id", strconv.FormatInt(userID, 10))
|
||||
query.Set("created_by", strconv.FormatInt(userID, 10))
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
|
||||
abortForbidden(c, "payload branchId not in caller's branches", logrus.Fields{
|
||||
"requestedBranchId": *payload.BranchId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
// A new order's customer has no record in the branch yet; the branchId
|
||||
// check above already scopes the create, so only reassignment (PUT/PATCH)
|
||||
// has to name a user visible in the caller's branches.
|
||||
if c.Request.Method == http.MethodPost || payload.UserId == nil || *payload.UserId <= 0 {
|
||||
return true
|
||||
}
|
||||
service := serviceFrom(c)
|
||||
if service == nil {
|
||||
abortForbidden(c, "no rbac service", nil)
|
||||
return false
|
||||
}
|
||||
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
if !visible {
|
||||
abortForbidden(c, "payload userId not visible in caller's branches", logrus.Fields{
|
||||
"requestedUserId": *payload.UserId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func readBody(c *gin.Context) ([]byte, bool) {
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return nil, false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
return body, true
|
||||
}
|
||||
|
||||
func isWrite(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// abortForbidden logs which rbac check denied the request before writing the
|
||||
// 403, since appresult.ErrForbidden alone doesn't say.
|
||||
func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) {
|
||||
entry := logging.GetLogger().WithFields(logrus.Fields{
|
||||
"method": c.Request.Method,
|
||||
"path": c.Request.URL.Path,
|
||||
})
|
||||
for k, v := range fields {
|
||||
entry = entry.WithField(k, v)
|
||||
}
|
||||
entry.Warn("rbac forbidden: " + reason)
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
|
||||
func requestUserID(c *gin.Context) (int64, bool) {
|
||||
@@ -408,278 +356,3 @@ func bearerToken(header string) string {
|
||||
}
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
|
||||
var userCatalogPrefixes = []string{
|
||||
"/payment-cards",
|
||||
"/reasons-cards",
|
||||
"/loan-types",
|
||||
"/loans-documents",
|
||||
"/currencies",
|
||||
"/branches",
|
||||
"/provinces",
|
||||
"/users/clients",
|
||||
}
|
||||
|
||||
var userSelfPrefixes = []string{
|
||||
"/profile",
|
||||
"/file",
|
||||
}
|
||||
|
||||
var userOwnedPrefixes = []string{
|
||||
"/cards",
|
||||
"/card-balances",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/card-rekwizit-orders",
|
||||
"/visa-master-payment-orders",
|
||||
"/loan-orders",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
}
|
||||
|
||||
func operatorRoleAllows(method, path string) bool {
|
||||
rest := adminREST(path)
|
||||
if rest == "" {
|
||||
return false
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
for _, prefix := range operatorGetPrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, prefix := range operatorWritePrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func operatorProfileOrFile(path string) bool {
|
||||
rest := adminREST(path)
|
||||
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
|
||||
}
|
||||
|
||||
func operatorClientsList(path string) bool {
|
||||
rest := adminREST(path)
|
||||
return rest == "/users/clients" || strings.HasPrefix(rest, "/users/clients/")
|
||||
}
|
||||
|
||||
func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64) bool {
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
if operatorProfileOrFile(c.Request.URL.Path) || len(branchIDs) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
BranchId *int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
|
||||
abortForbidden(c, "payload branchId not in operator's assigned branches", logrus.Fields{
|
||||
"requestedBranchId": *payload.BranchId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
// A new order's customer has no prior record in the branch to be
|
||||
// "visible" through yet — the branchId check above already scopes the
|
||||
// create to the operator's own branch, so only enforce user visibility
|
||||
// when reassigning an existing record (PUT/PATCH).
|
||||
if c.Request.Method == http.MethodPost {
|
||||
return true
|
||||
}
|
||||
|
||||
if payload.UserId != nil && *payload.UserId > 0 {
|
||||
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
if !visible {
|
||||
abortForbidden(c, "payload userId not visible in operator's branches", logrus.Fields{
|
||||
"requestedUserId": *payload.UserId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func adminREST(path string) string {
|
||||
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
|
||||
if rest == "" {
|
||||
return ""
|
||||
}
|
||||
if !strings.HasPrefix(rest, "/") {
|
||||
rest = "/" + rest
|
||||
}
|
||||
return rest
|
||||
}
|
||||
|
||||
// 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 {
|
||||
case matchesPrefix(rest, []string{
|
||||
"/cards",
|
||||
"/card-balances",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/card-rekwizit-orders",
|
||||
"/visa-master-payment-orders",
|
||||
"/payment-history",
|
||||
"/payment-cards",
|
||||
"/reasons-cards",
|
||||
}):
|
||||
return "cards"
|
||||
|
||||
case matchesPrefix(rest, []string{
|
||||
"/loan-orders",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
"/loan-types",
|
||||
"/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 ""
|
||||
|
||||
case matchesPrefix(rest, []string{"/users", "/branch-users"}):
|
||||
if method == http.MethodGet {
|
||||
return "users.view"
|
||||
}
|
||||
return "users.manage"
|
||||
}
|
||||
|
||||
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")
|
||||
|
||||
case matchesPrefix(rest, []string{"/payment-settings"}):
|
||||
return viewOrManage(method, "payment-settings")
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func viewOrManage(method, module string) string {
|
||||
if method == http.MethodGet {
|
||||
return module + ".view"
|
||||
}
|
||||
return module + ".manage"
|
||||
}
|
||||
|
||||
var operatorWritePrefixes = []string{
|
||||
"/profile",
|
||||
"/file",
|
||||
"/users",
|
||||
"/branch-users",
|
||||
"/cards",
|
||||
"/card-balances",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/card-rekwizit-orders",
|
||||
"/visa-master-payment-orders",
|
||||
"/payment-cards",
|
||||
"/reasons-cards",
|
||||
"/loan-orders",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
"/loan-types",
|
||||
"/loans-documents",
|
||||
}
|
||||
|
||||
var operatorGetPrefixes = []string{
|
||||
"/profile",
|
||||
"/file",
|
||||
"/dashboard",
|
||||
"/users",
|
||||
"/cards",
|
||||
"/card-balances",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/card-rekwizit-orders",
|
||||
"/payment-cards",
|
||||
"/reasons-cards",
|
||||
"/visa-master-payment-orders",
|
||||
"/payment-history",
|
||||
"/loan-orders",
|
||||
"/loan-types",
|
||||
"/loans-documents",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
"/provinces",
|
||||
"/branches",
|
||||
"/currencies",
|
||||
"/payment-settings",
|
||||
}
|
||||
@@ -1,895 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Package perm is the single source of truth for permission codes. One code
|
||||
// per module: holding it grants every action (read and write) in that module;
|
||||
// which records the caller sees is decided by the role's scope, not here.
|
||||
//
|
||||
// The admin UI can only assign these codes to roles - it cannot create,
|
||||
// rename or delete them. Sync writes this list into the permissions table on
|
||||
// startup so role_permissions' foreign key always matches the code.
|
||||
package perm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"online-back/pkg/client/postgresql"
|
||||
)
|
||||
|
||||
type Code string
|
||||
|
||||
const (
|
||||
Dashboard Code = "dashboard"
|
||||
Cards Code = "cards"
|
||||
Loans Code = "loans"
|
||||
Users Code = "users"
|
||||
Roles Code = "roles"
|
||||
Branches Code = "branches"
|
||||
Provinces Code = "provinces"
|
||||
Currencies Code = "currencies"
|
||||
PaymentSettings Code = "payment-settings"
|
||||
Backups Code = "backups"
|
||||
ActivityLogs Code = "activity-logs"
|
||||
)
|
||||
|
||||
type Def struct {
|
||||
Code Code `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// All is also the display order for the admin UI and the profile.
|
||||
var All = []Def{
|
||||
{Dashboard, "Dashboard"},
|
||||
{Cards, "Cards"},
|
||||
{Loans, "Loans"},
|
||||
{Users, "Users"},
|
||||
{Roles, "Roles"},
|
||||
{Branches, "Branches"},
|
||||
{Provinces, "Provinces"},
|
||||
{Currencies, "Currencies"},
|
||||
{PaymentSettings, "Payment settings"},
|
||||
{Backups, "Backups"},
|
||||
{ActivityLogs, "Activity logs"},
|
||||
}
|
||||
|
||||
var known = func() map[Code]struct{} {
|
||||
m := make(map[Code]struct{}, len(All))
|
||||
for _, d := range All {
|
||||
m[d.Code] = struct{}{}
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
func Valid(code Code) bool {
|
||||
_, ok := known[code]
|
||||
return ok
|
||||
}
|
||||
|
||||
func Codes() []Code {
|
||||
out := make([]Code, len(All))
|
||||
for i, d := range All {
|
||||
out[i] = d.Code
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Sync upserts All into the permissions table and removes codes no longer
|
||||
// in the catalog (role_permissions rows go with them via ON DELETE CASCADE).
|
||||
func Sync(ctx context.Context, client postgresql.Client) error {
|
||||
tx, err := client.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
codes := make([]string, len(All))
|
||||
names := make([]string, len(All))
|
||||
for i, d := range All {
|
||||
codes[i] = string(d.Code)
|
||||
names[i] = d.Name
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO permissions (code, name)
|
||||
SELECT * FROM unnest($1::varchar[], $2::varchar[])
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name`, codes, names); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM permissions WHERE NOT (code = ANY($1::varchar[]))`, codes); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
)
|
||||
|
||||
// Scope decides which records a role's permissions apply to. It is the only
|
||||
// data-visibility knob: "what can I do" is the permission list, "on whose
|
||||
// records" is the scope.
|
||||
type Scope string
|
||||
|
||||
const (
|
||||
ScopeOwn Scope = "own" // only records the caller owns (clients)
|
||||
ScopeBranch Scope = "branch" // records of the caller's branch_user branches
|
||||
ScopeAll Scope = "all" // every branch
|
||||
)
|
||||
|
||||
func (s Scope) Valid() bool {
|
||||
return s == ScopeOwn || s == ScopeBranch || s == ScopeAll
|
||||
}
|
||||
|
||||
func (s Scope) rank() int {
|
||||
switch s {
|
||||
case ScopeBranch:
|
||||
return 1
|
||||
case ScopeAll:
|
||||
return 2
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Principal is the caller as rbac sees it, loaded once per request (cached
|
||||
// across requests, see Service.Load). Treat it as read-only.
|
||||
type Principal struct {
|
||||
UserID int64
|
||||
RoleID int64
|
||||
RoleCode string
|
||||
Scope Scope
|
||||
IsSuper bool
|
||||
Perms map[perm.Code]struct{}
|
||||
BranchIDs []int64
|
||||
}
|
||||
|
||||
func (p *Principal) Can(code perm.Code) bool {
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
if p.IsSuper {
|
||||
return true
|
||||
}
|
||||
_, ok := p.Perms[code]
|
||||
return ok
|
||||
}
|
||||
|
||||
// PermCodes lists the caller's effective permissions in catalog order.
|
||||
func (p *Principal) PermCodes() []perm.Code {
|
||||
out := []perm.Code{}
|
||||
for _, code := range perm.Codes() {
|
||||
if p.Can(code) {
|
||||
out = append(out, code)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RoleInfo is what the grant/edit rules need to know about a role.
|
||||
type RoleInfo struct {
|
||||
ID int64
|
||||
Code string
|
||||
Scope Scope
|
||||
IsSuper bool
|
||||
IsSystem bool
|
||||
Perms []perm.Code
|
||||
}
|
||||
|
||||
var (
|
||||
ErrSuperOnly = errors.New("only a superadmin can grant or change a superadmin role")
|
||||
ErrScopeTooWide = errors.New("role scope is wider than the caller's own scope")
|
||||
ErrPermissionHeld = errors.New("role holds a permission the caller does not have")
|
||||
ErrSystemRole = errors.New("system role scope cannot be changed")
|
||||
ErrUnknownPerm = errors.New("unknown permission code")
|
||||
ErrInvalidScope = errors.New("invalid scope")
|
||||
)
|
||||
|
||||
// CanGrant reports whether the caller may give target to a user - or, the
|
||||
// same question, manage a user who already holds target. A caller can only
|
||||
// hand out what they themselves hold: no wider scope, no permission they
|
||||
// lack, and superadmin only from a superadmin. Own-scope roles (clients)
|
||||
// skip the permission check: they only ever reach the holder's own records,
|
||||
// so a cards-only operator can still register a cards+loans client.
|
||||
func (p *Principal) CanGrant(target RoleInfo) error {
|
||||
if p == nil {
|
||||
return ErrSuperOnly
|
||||
}
|
||||
if p.IsSuper {
|
||||
return nil
|
||||
}
|
||||
if target.IsSuper {
|
||||
return ErrSuperOnly
|
||||
}
|
||||
if target.Scope.rank() > p.Scope.rank() {
|
||||
return ErrScopeTooWide
|
||||
}
|
||||
if target.Scope == ScopeOwn {
|
||||
return nil
|
||||
}
|
||||
for _, code := range target.Perms {
|
||||
if !p.Can(code) {
|
||||
return ErrPermissionHeld
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CanSaveRole checks a role create (existing == nil) or update. The caller
|
||||
// must be able to grant both the role as it is now and as it will be, so
|
||||
// they can neither widen a role past their own rights nor strip one that is
|
||||
// already out of their reach.
|
||||
func (p *Principal) CanSaveRole(existing *RoleInfo, next RoleInfo) error {
|
||||
if !next.Scope.Valid() {
|
||||
return ErrInvalidScope
|
||||
}
|
||||
for _, code := range next.Perms {
|
||||
if !perm.Valid(code) {
|
||||
return ErrUnknownPerm
|
||||
}
|
||||
}
|
||||
if existing != nil {
|
||||
if existing.IsSystem && next.Scope != existing.Scope {
|
||||
return ErrSystemRole
|
||||
}
|
||||
if err := p.CanGrant(*existing); err != nil {
|
||||
return err
|
||||
}
|
||||
next.IsSuper = existing.IsSuper
|
||||
}
|
||||
return p.CanGrant(next)
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ruleKind int
|
||||
|
||||
const (
|
||||
rulePublic ruleKind = iota // no token needed
|
||||
ruleAuthenticated // any logged-in user
|
||||
ruleStaff // any logged-in user whose scope is not own
|
||||
rulePermission // perm required (+ scope enforcement)
|
||||
)
|
||||
|
||||
type rule struct {
|
||||
kind ruleKind
|
||||
perm string
|
||||
staffOnly bool
|
||||
}
|
||||
|
||||
// Policy is the access rule of a route group: one rule for reads (GET/HEAD)
|
||||
// and one for writes. Build it with Public, Authenticated, Staff, Require,
|
||||
// RequireStaff, Catalog or StaffRead.
|
||||
type Policy struct {
|
||||
name string
|
||||
read rule
|
||||
write rule
|
||||
}
|
||||
|
||||
func (p Policy) String() string { return p.name }
|
||||
|
||||
func (p Policy) public() bool { return p.read.kind == rulePublic && p.write.kind == rulePublic }
|
||||
|
||||
func (p Policy) ruleFor(method string) rule {
|
||||
if method == http.MethodGet || method == http.MethodHead {
|
||||
return p.read
|
||||
}
|
||||
return p.write
|
||||
}
|
||||
|
||||
// registry maps full route prefixes (e.g. "/api/admin/card-orders") to the
|
||||
// policy declared for them. Guard resolves a request's policy from it by
|
||||
// longest prefix, and VerifyRoutes fails startup for any route with none.
|
||||
type registry struct {
|
||||
mu sync.RWMutex
|
||||
policies map[string]Policy
|
||||
}
|
||||
|
||||
var routes = ®istry{policies: make(map[string]Policy)}
|
||||
|
||||
func (r *registry) add(prefix string, p Policy) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if existing, ok := r.policies[prefix]; ok && existing.name != p.name {
|
||||
panic(fmt.Sprintf("rbac: %s registered with policy %s and %s", prefix, existing.name, p.name))
|
||||
}
|
||||
r.policies[prefix] = p
|
||||
}
|
||||
|
||||
func (r *registry) lookup(fullPath string) (Policy, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
best := ""
|
||||
var found Policy
|
||||
ok := false
|
||||
for prefix, p := range r.policies {
|
||||
if (fullPath == prefix || strings.HasPrefix(fullPath, prefix+"/")) && len(prefix) >= len(best) {
|
||||
best, found, ok = prefix, p, true
|
||||
}
|
||||
}
|
||||
return found, ok
|
||||
}
|
||||
|
||||
func (r *registry) reset() {
|
||||
r.mu.Lock()
|
||||
r.policies = make(map[string]Policy)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// Group creates a route group under parent at relativePath and declares its
|
||||
// policy. Every /api/admin route must be registered through Group - see
|
||||
// VerifyRoutes.
|
||||
func Group(parent *gin.RouterGroup, relativePath string, p Policy) *gin.RouterGroup {
|
||||
full := joinPath(parent.BasePath(), relativePath)
|
||||
routes.add(full, p)
|
||||
if p.public() {
|
||||
return parent.Group(relativePath)
|
||||
}
|
||||
return parent.Group(relativePath, appresult.JwtTokenCheck(), p.handler())
|
||||
}
|
||||
|
||||
// VerifyRoutes returns an error naming every route under prefix that has no
|
||||
// policy. Call it after all handlers are registered.
|
||||
func VerifyRoutes(all gin.RoutesInfo, prefix string) error {
|
||||
var missing []string
|
||||
for _, route := range all {
|
||||
if route.Path != prefix && !strings.HasPrefix(route.Path, prefix+"/") {
|
||||
continue
|
||||
}
|
||||
if _, ok := routes.lookup(route.Path); !ok {
|
||||
missing = append(missing, route.Method+" "+route.Path)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.Strings(missing)
|
||||
return fmt.Errorf("rbac: routes without a policy (use rbac.Group): %s", strings.Join(missing, ", "))
|
||||
}
|
||||
|
||||
func joinPath(base, rel string) string {
|
||||
if rel == "" {
|
||||
return strings.TrimSuffix(base, "/")
|
||||
}
|
||||
return strings.TrimSuffix(path.Join(base, rel), "/")
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
// RoleInfoSelect selects the columns ScanRoleInfo reads from roles r; append
|
||||
// the WHERE clause (it must keep r.deleted_at IS NULL).
|
||||
const RoleInfoSelect = `SELECT r.id, r.code, r.scope, r.is_super, r.is_system,
|
||||
ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id ORDER BY 1)
|
||||
FROM roles r `
|
||||
|
||||
// ScanRoleInfo scans one RoleInfoSelect row; a missing row is (nil, nil).
|
||||
func ScanRoleInfo(row genericrepo.Scanner) (*RoleInfo, error) {
|
||||
var info RoleInfo
|
||||
var scope string
|
||||
var codes []string
|
||||
err := row.Scan(&info.ID, &info.Code, &scope, &info.IsSuper, &info.IsSystem, &codes)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info.Scope = Scope(scope)
|
||||
info.Perms = make([]perm.Code, len(codes))
|
||||
for i, code := range codes {
|
||||
info.Perms[i] = perm.Code(code)
|
||||
}
|
||||
return &info, nil
|
||||
}
|
||||
@@ -5,61 +5,69 @@ import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// The three valid guard names. Use these constants when validating
|
||||
// the guardName field in role/permission DTOs.
|
||||
const (
|
||||
GuardWeb = guardWeb
|
||||
GuardOperator = guardOperator
|
||||
GuardAdmin = guardAdmin
|
||||
)
|
||||
|
||||
const (
|
||||
contextBranchIDs = "branchIds"
|
||||
contextService = "rbacService"
|
||||
)
|
||||
|
||||
func BranchIDsFrom(c *gin.Context) []int64 {
|
||||
raw, ok := c.Get(contextBranchIDs)
|
||||
// PrincipalFrom returns the caller loaded by Guard, or nil on public routes.
|
||||
func PrincipalFrom(c *gin.Context) *Principal {
|
||||
raw, ok := c.Get(contextPrincipal)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
ids, _ := raw.([]int64)
|
||||
return ids
|
||||
p, _ := raw.(*Principal)
|
||||
return p
|
||||
}
|
||||
|
||||
func serviceFrom(c *gin.Context) Authorizer {
|
||||
raw, ok := c.Get(contextService)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
service, _ := raw.(Authorizer)
|
||||
return service
|
||||
}
|
||||
|
||||
// Can reports whether the caller holds code (always true for superadmin).
|
||||
func Can(c *gin.Context, code perm.Code) bool {
|
||||
return PrincipalFrom(c).Can(code)
|
||||
}
|
||||
|
||||
// BranchIDsFrom returns the caller's branches when their scope is branch,
|
||||
// nil otherwise (all and own scopes are not narrowed by branch).
|
||||
func BranchIDsFrom(c *gin.Context) []int64 {
|
||||
p := PrincipalFrom(c)
|
||||
if p == nil || p.Scope != ScopeBranch {
|
||||
return nil
|
||||
}
|
||||
return p.BranchIDs
|
||||
}
|
||||
|
||||
func HasBranchScope(c *gin.Context) bool {
|
||||
return len(BranchIDsFrom(c)) > 0
|
||||
}
|
||||
|
||||
func RoleFrom(c *gin.Context) string {
|
||||
raw, _ := c.Get(contextRole)
|
||||
role, _ := raw.(string)
|
||||
return role
|
||||
}
|
||||
|
||||
func GuardFrom(c *gin.Context) string {
|
||||
raw, _ := c.Get(contextGuard)
|
||||
guard, _ := raw.(string)
|
||||
return guard
|
||||
}
|
||||
|
||||
func IsOwnScope(c *gin.Context) bool {
|
||||
return GuardFrom(c) == guardWeb
|
||||
p := PrincipalFrom(c)
|
||||
return p != nil && p.Scope == ScopeOwn
|
||||
}
|
||||
|
||||
func IsAdminGuard(c *gin.Context) bool {
|
||||
return GuardFrom(c) == guardAdmin
|
||||
func HasAllScope(c *gin.Context) bool {
|
||||
p := PrincipalFrom(c)
|
||||
return p != nil && p.Scope == ScopeAll
|
||||
}
|
||||
|
||||
// SkipRecordGuard: all-scope callers see every record, so handlers can skip
|
||||
// the extra owner/branch lookup.
|
||||
func SkipRecordGuard(c *gin.Context) bool {
|
||||
return !HasBranchScope(c) && !IsOwnScope(c)
|
||||
return HasAllScope(c)
|
||||
}
|
||||
|
||||
func CurrentUserID(c *gin.Context) (int64, bool) {
|
||||
if p := PrincipalFrom(c); p != nil {
|
||||
return p.UserID, true
|
||||
}
|
||||
return parseContextUserID(c)
|
||||
}
|
||||
|
||||
@@ -116,12 +124,7 @@ func GuardNewBranchAssignment(c *gin.Context, targetUserID int64) bool {
|
||||
if !HasBranchScope(c) {
|
||||
return true
|
||||
}
|
||||
raw, ok := c.Get(contextService)
|
||||
if !ok {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
}
|
||||
service, _ := raw.(Authorizer)
|
||||
service := serviceFrom(c)
|
||||
if service == nil {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
@@ -149,12 +152,7 @@ func GuardUser(c *gin.Context, userID int64) bool {
|
||||
if len(ids) == 0 {
|
||||
return true
|
||||
}
|
||||
raw, ok := c.Get(contextService)
|
||||
if !ok {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
}
|
||||
service, _ := raw.(Authorizer)
|
||||
service := serviceFrom(c)
|
||||
if service == nil {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
|
||||
@@ -3,82 +3,137 @@ package rbac
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/client/postgresql"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
client postgresql.Client
|
||||
}
|
||||
|
||||
func NewService(client postgresql.Client) *Service {
|
||||
return &Service{client: client}
|
||||
}
|
||||
|
||||
// Authorizer is the lookup Guard, RequirePermission and GuardUser need.
|
||||
// Authorizer is what the middleware and the scope helpers need.
|
||||
type Authorizer interface {
|
||||
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error)
|
||||
// Load returns the caller's principal, or nil when the user or their
|
||||
// role no longer exists.
|
||||
Load(ctx context.Context, userID int64) (*Principal, 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 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 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
|
||||
)`
|
||||
const (
|
||||
principalTTL = time.Minute
|
||||
versionCheckEvery = 2 * time.Second
|
||||
principalCacheLimit = 10000
|
||||
)
|
||||
|
||||
var granted bool
|
||||
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return granted, nil
|
||||
type cachedPrincipal struct {
|
||||
principal *Principal
|
||||
loadedAt time.Time
|
||||
}
|
||||
|
||||
// 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
|
||||
)`
|
||||
// Service loads principals and caches them per user. The rbac_version row
|
||||
// is bumped by DB triggers whenever roles, role_permissions, users.role_id
|
||||
// or branch_user change; seeing a new version drops the whole cache, so a
|
||||
// permission change takes effect within versionCheckEvery.
|
||||
type Service struct {
|
||||
client postgresql.Client
|
||||
now func() time.Time
|
||||
|
||||
var granted bool
|
||||
if err := s.client.QueryRow(ctx, query, userID, module).Scan(&granted); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return granted, nil
|
||||
mu sync.Mutex
|
||||
cache map[int64]cachedPrincipal
|
||||
version int64
|
||||
checkedAt time.Time
|
||||
}
|
||||
|
||||
func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) {
|
||||
const query = `
|
||||
SELECT r.code, r.guard_name
|
||||
FROM role_user ru
|
||||
JOIN roles r ON r.id = ru.role_id
|
||||
WHERE ru.user_id = $1 AND ru.deleted_at IS NULL AND r.deleted_at IS NULL
|
||||
ORDER BY ru.id
|
||||
LIMIT 1`
|
||||
func NewService(client postgresql.Client) *Service {
|
||||
return &Service{client: client, now: time.Now, cache: make(map[int64]cachedPrincipal)}
|
||||
}
|
||||
|
||||
var code, guardName string
|
||||
err := s.client.QueryRow(ctx, query, userID).Scan(&code, &guardName)
|
||||
func (s *Service) Load(ctx context.Context, userID int64) (*Principal, error) {
|
||||
if err := s.syncVersion(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
s.mu.Lock()
|
||||
entry, ok := s.cache[userID]
|
||||
s.mu.Unlock()
|
||||
if ok && now.Sub(entry.loadedAt) < principalTTL {
|
||||
return entry.principal, nil
|
||||
}
|
||||
|
||||
p, err := s.loadPrincipal(ctx, userID)
|
||||
if err != nil || p == nil {
|
||||
return p, err
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
if len(s.cache) >= principalCacheLimit {
|
||||
s.cache = make(map[int64]cachedPrincipal)
|
||||
}
|
||||
s.cache[userID] = cachedPrincipal{principal: p, loadedAt: now}
|
||||
s.mu.Unlock()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *Service) syncVersion(ctx context.Context) error {
|
||||
now := s.now()
|
||||
s.mu.Lock()
|
||||
fresh := now.Sub(s.checkedAt) < versionCheckEvery
|
||||
s.mu.Unlock()
|
||||
if fresh {
|
||||
return nil
|
||||
}
|
||||
|
||||
var version int64
|
||||
if err := s.client.QueryRow(ctx, `SELECT version FROM rbac_version WHERE id = 1`).Scan(&version); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
if version != s.version {
|
||||
s.cache = make(map[int64]cachedPrincipal)
|
||||
s.version = version
|
||||
}
|
||||
s.checkedAt = now
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
const principalQuery = `
|
||||
SELECT r.id, r.code, r.scope, r.is_super,
|
||||
ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id),
|
||||
ARRAY(
|
||||
SELECT bu.branch_id
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id AND b.deleted_at IS NULL
|
||||
WHERE bu.user_id = u.id AND bu.deleted_at IS NULL
|
||||
ORDER BY bu.id
|
||||
)
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL
|
||||
WHERE u.id = $1 AND u.deleted_at IS NULL`
|
||||
|
||||
func (s *Service) loadPrincipal(ctx context.Context, userID int64) (*Principal, error) {
|
||||
p := &Principal{UserID: userID}
|
||||
var scope string
|
||||
var codes []string
|
||||
err := s.client.QueryRow(ctx, principalQuery, userID).Scan(
|
||||
&p.RoleID, &p.RoleCode, &scope, &p.IsSuper, &codes, &p.BranchIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", "", nil
|
||||
return nil, nil
|
||||
}
|
||||
return code, guardName, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Scope = Scope(scope)
|
||||
p.Perms = make(map[perm.Code]struct{}, len(codes))
|
||||
for _, code := range codes {
|
||||
p.Perms[perm.Code(code)] = struct{}{}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) {
|
||||
|
||||
Reference in new issue
Block a user