Files
GuwandykA 323e131216
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
changed role permission
2026-09-26 16:34:28 +05:00

359 lines
9.5 KiB
Go

package rbac
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/identity/rbac/perm"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/sirupsen/logrus"
)
const (
contextPrincipal = "rbacPrincipal"
contextService = "rbacService"
)
// Public: no token (login, register, payment callback).
func Public() Policy {
return Policy{name: "public", read: rule{kind: rulePublic}, write: rule{kind: rulePublic}}
}
// Authenticated: any logged-in user, clients included (profile, file).
func Authenticated() Policy {
return Policy{name: "authenticated", read: rule{kind: ruleAuthenticated}, write: rule{kind: ruleAuthenticated}}
}
// 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}}
}
// 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 || 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
}
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
}
c.Set("id", strconv.FormatInt(userID, 10))
c.Set(contextPrincipal, principal)
c.Set(contextService, service)
c.Next()
}
}
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
}
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()
}
}
// 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
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 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 pinOwnBody(c *gin.Context, userID int64) bool {
if !isWrite(c.Request.Method) || c.Request.Method == http.MethodDelete {
return true
}
body, ok := readBody(c)
if !ok {
return false
}
if len(bytes.TrimSpace(body)) == 0 {
return true
}
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err != nil {
return true
}
payload["userId"] = userID
payload["user_id"] = userID
payload["createdBy"] = userID
payload["created_by"] = userID
rewritten, err := json.Marshal(payload)
if err != nil {
return true
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(rewritten))
c.Request.ContentLength = int64(len(rewritten))
return true
}
func branchWriteAllowed(c *gin.Context, branchIDs []int64) bool {
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
return true
}
body, ok := readBody(c)
if !ok {
return false
}
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 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) {
if id, ok := parseContextUserID(c); ok {
return id, true
}
token := bearerToken(c.GetHeader("Authorization"))
if token == "" {
return 0, false
}
claims, err := appresult.TokenClaims(token, config.GetConfig().JwtKey)
if err != nil {
return 0, false
}
return claimUserID(claims)
}
func parseContextUserID(c *gin.Context) (int64, bool) {
rawID, exists := c.Get("id")
if !exists {
return 0, false
}
switch id := rawID.(type) {
case int64:
return id, id > 0
case int:
return int64(id), id > 0
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}
func claimUserID(claims jwt.MapClaims) (int64, bool) {
switch id := claims["id"].(type) {
case float64:
return int64(id), id > 0
case int64:
return id, id > 0
case int:
return int64(id), id > 0
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}
func bearerToken(header string) string {
const prefix = "Bearer "
if strings.HasPrefix(header, prefix) {
return strings.TrimSpace(header[len(prefix):])
}
return strings.TrimSpace(header)
}