1
0
forked from baron/baron-sso
Files
baron-sso/backend/internal/middleware/rbac.go

158 lines
4.9 KiB
Go

package middleware
import (
"baron-sso-backend/internal/domain"
"baron-sso-backend/internal/service"
"fmt"
"log/slog"
"github.com/gofiber/fiber/v2"
)
// RBACConfig defines the configuration for RBAC middleware
type RBACConfig struct {
AllowedRoles []string
AuthHandler AuthProfileProvider
KetoService service.KetoService
}
// AuthProfileProvider는 미들웨어에서 사용자 정보를 조회하기 위한 최소 인터페이스입니다.
type AuthProfileProvider interface {
GetEnrichedProfile(c *fiber.Ctx) (*domain.UserProfileResponse, error)
}
// RequireKetoPermission enforces permissions using Ory Keto (ReBAC)
func RequireKetoPermission(config RBACConfig, namespace, relation string) fiber.Handler {
return func(c *fiber.Ctx) error {
profile, err := config.AuthHandler.GetEnrichedProfile(c)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "인증에 실패했습니다. (rbac_keto)"})
}
// Store profile in locals for further use in handlers
c.Locals("user_profile", profile)
// Super Admin bypass
if profile.Role == domain.RoleSuperAdmin {
return c.Next()
}
// Get object ID from path (e.g., tenant ID)
objectID := c.Params("id")
if objectID == "" {
objectID = c.Params("tenantId")
}
if objectID == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "권한 검증을 위한 대상 ID가 누락되었습니다."})
}
// Set tenant_id for audit logging if namespace is Tenant
if namespace == "Tenant" {
c.Locals("tenant_id", objectID)
}
// Check with Keto
allowed, err := config.KetoService.CheckPermission(c.Context(), profile.ID, namespace, objectID, relation)
if err != nil || !allowed {
slog.Warn("Keto permission denied", "userID", profile.ID, "namespace", namespace, "objectID", objectID, "relation", relation)
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": fmt.Sprintf("접근 권한이 없습니다. 현재 '%s' 권한으로는 요청하신 리소스에 대한 상세 권한(Keto)이 부족합니다. 관리자에게 문의하세요.", profile.Role),
})
}
return c.Next()
}
}
// RequireRole enforces that the user has one of the allowed roles
func RequireRole(config RBACConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
// Bypass if already authenticated via API Key
if c.Locals("apiKeyName") != nil {
return c.Next()
}
profile, err := config.AuthHandler.GetEnrichedProfile(c)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "인증 정보 조회에 실패했습니다: " + err.Error(),
})
}
// Store profile in locals for further use in handlers
c.Locals("user_profile", profile)
// Super Admin always has access
if profile.Role == domain.RoleSuperAdmin {
return c.Next()
}
// Check if user's role is in allowed roles
roleAllowed := false
for _, role := range config.AllowedRoles {
if profile.Role == role {
roleAllowed = true
break
}
}
if !roleAllowed {
slog.Warn("RBAC access denied",
"userID", profile.ID,
"userRole", profile.Role,
"allowedRoles", config.AllowedRoles,
"path", c.Path(),
)
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": fmt.Sprintf("접근 권한이 없습니다. 현재 '%s' 권한으로는 이 기능을 사용할 수 없습니다. 관리자에게 문의하여 'rp_admin' 이상의 권한을 확보하세요.", profile.Role),
})
}
// Store profile in locals for further use in handlers
c.Locals("user_profile", profile)
return c.Next()
}
}
// RequireTenantMatch enforces that a Tenant Admin can only access their own tenant's data
func RequireTenantMatch(config RBACConfig) fiber.Handler {
return func(c *fiber.Ctx) error {
// Bypass if already authenticated via API Key (System-wide for now)
if c.Locals("apiKeyName") != nil {
return c.Next()
}
profile, err := config.AuthHandler.GetEnrichedProfile(c)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "인증에 실패했습니다. (rbac_match)"})
}
// Store profile in locals for further use in handlers
c.Locals("user_profile", profile)
// Super Admin bypass
if profile.Role == domain.RoleSuperAdmin {
return c.Next()
}
// Tenant Admin check
if profile.Role == domain.RoleTenantAdmin {
targetTenantID := c.Params("tenantId")
if targetTenantID == "" {
targetTenantID = c.Params("id") // common for /tenants/:id
}
if profile.TenantID == nil || *profile.TenantID != targetTenantID {
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": fmt.Sprintf("해당 테넌트에 대한 접근 권한이 없습니다. 사용자님의 '%s' 권한은 소속된 테넌트의 리소스만 관리할 수 있습니다.", profile.Role),
})
}
return c.Next()
}
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "요청하신 리소스에 접근할 수 없습니다."})
}
}