Class: RackJwtAegis::RbacManager
- Inherits:
-
Object
- Object
- RackJwtAegis::RbacManager
- Includes:
- DebugLogger
- Defined in:
- lib/rack_jwt_aegis/rbac_manager.rb
Overview
Role-Based Access Control (RBAC) manager
Handles authorization by checking user permissions against cached RBAC data. Supports both simple boolean permissions and complex permission structures. Uses a two-tier caching system for performance optimization.
Constant Summary collapse
- CACHE_TTL =
5 minutes default cache TTL
300
Instance Method Summary collapse
-
#authorize(request, payload) ⇒ Object
Authorize a request against RBAC permissions.
- #build_permission_key(user_id, request) ⇒ Object private
-
#cache_permission_match(user_id, request, _role_id, _matched_permission) ⇒ Object
private
Cache the specific permission match for faster future lookups Format: => timestamp.
- #cache_permission_result(permission_key, has_permission) ⇒ Object private
- #check_cached_permission(permission_key) ⇒ Object private
- #check_rbac_format?(user_id, request, rbac_data) ⇒ Boolean private
- #check_rbac_permission(user_id, request) ⇒ Object private
-
#check_role_permissions?(permissions, request) ⇒ Boolean
private
Check if any role permission matches the request.
-
#extract_api_path_from_request(request) ⇒ Object
private
Extract the API path portion from the full request path Removes subdomain and pathname slug parts to get the resource endpoint.
-
#extract_user_roles_from_request(request) ⇒ Object
private
Extract user roles from request context (stored by middleware).
-
#find_matching_permission(permissions, request) ⇒ Object
private
Find the first matching permission for the request (returns the permission string or nil).
-
#initialize(config) ⇒ RbacManager
constructor
Initialize the RBAC manager.
-
#method_matches?(permission_method, request_method) ⇒ Boolean
private
Check if HTTP method matches.
-
#nuke_user_permissions_cache(reason) ⇒ Object
private
Nuke (delete) the entire user permissions cache.
-
#path_matches?(permission_path, resource_path) ⇒ Boolean
private
Check if path matches (handles both literal strings and regex patterns).
-
#permission_matches?(permission, resource_path, request_method) ⇒ Boolean
private
Check if a permission string matches the request.
-
#rbac_last_update_timestamp ⇒ Object
private
Get RBAC permissions collection last_update timestamp.
-
#remove_stale_permission(permission_key, reason) ⇒ Object
private
Remove a specific stale permission.
- #setup_cache_adapters ⇒ Object private
-
#validate_rbac_cache_format(rbac_data) ⇒ Object
private
Validate RBAC cache format according to specification Expected format: { last_update: timestamp, permissions: { "role-id": ["resource-endpoint:http-method"] } }.
Methods included from DebugLogger
Constructor Details
#initialize(config) ⇒ RbacManager
Initialize the RBAC manager
25 26 27 28 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 25 def initialize(config) @config = config setup_cache_adapters end |
Instance Method Details
#authorize(request, payload) ⇒ Object
Authorize a request against RBAC permissions
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 35 def (request, payload) user_id = payload[@config.payload_key(:user_id).to_s] raise AuthorizationError, 'User ID missing from JWT payload' if user_id.nil? # Build permission key = (user_id, request) # Check cached permission first (if middleware can write to cache) if @permission_cache && @config.cache_write_enabled? = () return if == true raise AuthorizationError, 'Access denied - cached permission' if == false end # Permission not cached or cache miss - check RBAC store = (user_id, request) # Cache the result if middleware has write access (, ) return if raise AuthorizationError, 'Access denied - insufficient permissions' end |
#build_permission_key(user_id, request) ⇒ Object (private)
85 86 87 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 85 def (user_id, request) "#{user_id}:#{request.host}#{request.path}:#{request.request_method.downcase}" end |
#cache_permission_match(user_id, request, _role_id, _matched_permission) ⇒ Object (private)
Cache the specific permission match for faster future lookups Format: => timestamp
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 293 def (user_id, request, _role_id, ) return unless @permission_cache begin current_time = Time.now.to_i # Build the permission key in new format host = request.host || 'localhost' full_url = "#{host}#{request.path}" method = request.request_method.downcase = "#{user_id}:#{full_url}:#{method}" # Get existing user permissions cache or create new one = @permission_cache.read('user_permissions') || {} # Store permission with new format [] = current_time # Write back to cache @permission_cache.write('user_permissions', , expires_in: CACHE_TTL) debug_log("Cached user permission: #{} => #{current_time}") rescue CacheError => e # Log cache error but don't fail the request debug_log("RbacManager permission cache write error: #{e.}", :warn) end end |
#cache_permission_result(permission_key, has_permission) ⇒ Object (private)
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 150 def (, ) return unless @permission_cache return unless # Only cache positive permissions begin current_time = Time.now.to_i # Get existing user permissions cache or create new one = @permission_cache.read('user_permissions') || {} # Store permission with new format: {"user_id:full_url:method" => timestamp} [] = current_time # Write back to cache @permission_cache.write('user_permissions', , expires_in: CACHE_TTL) debug_log("Cached permission: #{} => #{current_time}") rescue CacheError => e # Log cache error but don't fail the request debug_log("RbacManager permission cache write error: #{e.}", :warn) end end |
#check_cached_permission(permission_key) ⇒ Object (private)
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 89 def () return nil unless @permission_cache begin # Get the cached user permissions = @permission_cache.read('user_permissions') return nil if .nil? || !.is_a?(Hash) # First check: If RBAC permissions were updated recently, nuke ALL cached permissions rbac_last_update = if rbac_last_update rbac_update_age = Time.now.to_i - rbac_last_update # If RBAC was updated within the TTL period, all cached permissions are invalid if rbac_update_age <= @config. ("RBAC permissions updated recently (#{rbac_update_age}s ago, within TTL)") return nil end end # Check if permission exists in this format: {"user_id:full_url:method" => timestamp} = [] return nil unless .is_a?(Integer) = Time.now.to_i - # Second check: TTL expiration if > @config. # This specific permission expired due to TTL (, "TTL expired (#{}s > #{@config.}s)") return nil end # Permission is fresh debug_log("Cache hit: #{} (permission age: \ #{}s, RBAC age: #{rbac_update_age || 'unknown'}s)".squeeze) true rescue CacheError => e # Log cache error but don't fail the request debug_log("RbacManager cache read error: #{e.}", :warn) nil end end |
#check_rbac_format?(user_id, request, rbac_data) ⇒ Boolean (private)
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 173 def check_rbac_format?(user_id, request, rbac_data) # Extract user roles from JWT payload user_roles = extract_user_roles_from_request(request) if user_roles.nil? || user_roles.empty? debug_log('RbacManager: No user roles found in request context', :warn) return false end # Get permissions object for direct lookup = rbac_data['permissions'] || rbac_data[:permissions] # Check permissions for each user role using direct lookup user_roles.each do |role_id| # Try both string and integer keys for role lookup = [role_id.to_s] || [role_id.to_i] next unless = (, request) next unless # Cache this specific permission match for faster future lookups if @permission_cache && @config.cache_write_enabled? (user_id, request, role_id, ) end return true end false end |
#check_rbac_permission(user_id, request) ⇒ Object (private)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 134 def (user_id, request) rbac_data = @rbac_cache.read('permissions') # Check if RBAC data exists and is valid if rbac_data.is_a?(Hash) && validate_rbac_cache_format(rbac_data) return check_rbac_format?(user_id, request, rbac_data) end # No valid RBAC data found false rescue CacheError => e # Cache error - fail secure (deny access) debug_log("RbacManager RBAC cache error: #{e.}", :warn) false end |
#check_role_permissions?(permissions, request) ⇒ Boolean (private)
Check if any role permission matches the request
264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 264 def (, request) return false unless .is_a?(Array) request_path = extract_api_path_from_request(request) request_method = request.request_method.downcase .each do || return true if (, request_path, request_method) end false end |
#extract_api_path_from_request(request) ⇒ Object (private)
Extract the API path portion from the full request path Removes subdomain and pathname slug parts to get the resource endpoint
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 323 def extract_api_path_from_request(request) path = request.path # Remove API prefix and pathname slug pattern if configured if @config.pathname_slug_pattern # Extract the resource path after the pathname slug match = path.match(@config.pathname_slug_pattern) if match&.captures&.any? # Get everything after the slug pattern slug_part = match[0] resource_path = path.sub(slug_part, '') return resource_path.start_with?('/') ? resource_path[1..] : resource_path end end # Fallback: remove common API prefixes path = path.sub(%r{^/api/v\d+/}, '') path = path.sub(%r{^/api/}, '') path.sub(%r{^/}, '') end |
#extract_user_roles_from_request(request) ⇒ Object (private)
Extract user roles from request context (stored by middleware)
258 259 260 261 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 258 def extract_user_roles_from_request(request) # Check if roles are stored in request environment by middleware request.env['rack_jwt_aegis.user_roles'] end |
#find_matching_permission(permissions, request) ⇒ Object (private)
Find the first matching permission for the request (returns the permission string or nil)
278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 278 def (, request) return nil unless .is_a?(Array) request_path = extract_api_path_from_request(request) request_method = request.request_method.downcase .each do || return if (, request_path, request_method) end nil end |
#method_matches?(permission_method, request_method) ⇒ Boolean (private)
Check if HTTP method matches
362 363 364 365 366 367 368 369 370 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 362 def method_matches?(, request_method) = .downcase # Wildcard method matches all return true if == '*' # Exact method match == request_method end |
#nuke_user_permissions_cache(reason) ⇒ Object (private)
Nuke (delete) the entire user permissions cache
246 247 248 249 250 251 252 253 254 255 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 246 def (reason) return unless @permission_cache begin @permission_cache.delete('user_permissions') debug_log("Nuked user permissions cache: #{reason}") rescue CacheError => e debug_log("RbacManager cache nuke error: #{e.}", :warn) end end |
#path_matches?(permission_path, resource_path) ⇒ Boolean (private)
Check if path matches (handles both literal strings and regex patterns)
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 373 def path_matches?(, resource_path) # Handle regex pattern format: "%r{pattern}" if .start_with?('%r{') && .end_with?('}') regex_pattern = [3..-2] # Remove %r{ and } begin regex = Regexp.new(regex_pattern) return regex.match?(resource_path) rescue RegexpError => e debug_log("RbacManager: Invalid regex pattern '#{regex_pattern}': #{e.}", :warn) return false end end # Exact string match == resource_path end |
#permission_matches?(permission, resource_path, request_method) ⇒ Boolean (private)
Check if a permission string matches the request
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 345 def (, resource_path, request_method) return false unless .is_a?(String) # Parse permission format: "resource-endpoint:http-method" parts = .split(':') return false unless parts.length == 2 , = parts # Check if method matches return false unless method_matches?(, request_method) # Check if path matches (handle both literal and regex patterns) path_matches?(, resource_path) end |
#rbac_last_update_timestamp ⇒ Object (private)
Get RBAC permissions collection last_update timestamp
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 204 def return nil unless @rbac_cache begin rbac_data = @rbac_cache.read('permissions') if rbac_data.is_a?(Hash) && (rbac_data.key?('last_update') || rbac_data.key?(:last_update)) return rbac_data['last_update'] || rbac_data[:last_update] end nil rescue CacheError => e debug_log("RbacManager RBAC last-update read error: #{e.}", :warn) nil end end |
#remove_stale_permission(permission_key, reason) ⇒ Object (private)
Remove a specific stale permission
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 221 def (, reason) return unless @permission_cache begin = @permission_cache.read('user_permissions') return unless .is_a?(Hash) # Remove the specific permission key .delete() # If no permissions remain, remove the entire cache if .empty? @permission_cache.delete('user_permissions') debug_log("Removed last permission, cleared entire cache: #{reason}") else # Update the cache with the modified permissions @permission_cache.write('user_permissions', , expires_in: CACHE_TTL) debug_log("Removed stale permission #{}: #{reason}") end rescue CacheError => e debug_log("RbacManager stale permission removal error: #{e.}", :warn) end end |
#setup_cache_adapters ⇒ Object (private)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 63 def setup_cache_adapters if @config.cache_write_enabled? && @config.cache_store # Shared cache mode - both RBAC and permission cache use same store @rbac_cache = CacheAdapter.build(@config.cache_store, @config. || {}) @permission_cache = @rbac_cache else # Separate cache mode - different stores for RBAC and permissions if @config.rbac_cache_store @rbac_cache = CacheAdapter.build(@config.rbac_cache_store, @config. || {}) end if @config. @permission_cache = CacheAdapter.build(@config., @config. || {}) end end # Ensure we have at least RBAC cache for permission lookups return if @rbac_cache raise ConfigurationError, 'RBAC cache store not configured' end |
#validate_rbac_cache_format(rbac_data) ⇒ Object (private)
Validate RBAC cache format according to specification Expected format: { last_update: timestamp, permissions: { "role-id": ["resource-endpoint:http-method"] } }
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/rack_jwt_aegis/rbac_manager.rb', line 398 def validate_rbac_cache_format(rbac_data) return false unless rbac_data.is_a?(Hash) # Check required fields return false unless rbac_data.key?('last_update') || rbac_data.key?(:last_update) return false unless rbac_data.key?('permissions') || rbac_data.key?(:permissions) # Get permissions object (now expecting a Hash, not Array) = rbac_data['permissions'] || rbac_data[:permissions] # If permissions is present but not a Hash, raise an exception to help developers if !.nil? && !.is_a?(Hash) raise ConfigurationError, "RBAC permissions must be a Hash with role-id keys, not #{.class}. " \ "Expected format: {\"role-id\": [\"resource:method\", ...]}, " \ "but got: #{.class}" end # Return false if permissions is nil (should not happen given the key check above, but defensive) return false if .nil? # Validate each role's permissions .each_value do || return false unless .is_a?(Array) # Each permission should be a string in format "endpoint:method" .each do || return false unless .is_a?(String) # Permission must include ':' (resource:method format) or '*' (wildcard) return false unless .include?(':') || .include?('*') end end true rescue ConfigurationError # Re-raise configuration errors so developers see them raise rescue StandardError => e debug_log("RbacManager: Cache format validation error: #{e.}", :warn) false end |