We are going to design a composable authorization engine that supports RBAC, ABAC, and ReBAC.
We'll also consider caching and audit logging.
Components:
Policy Engine: Core that can evaluate policies (RBAC, ABAC, ReBAC).
Policy Store: Where policies are stored (could be database, file, etc.). We'll abstract this.
Cache: To cache policy evaluations for performance.
Audit Logger: To log authorization decisions for audit.
We'll design with the following in mind:
Composable: We can combine multiple models (e.g., RBAC and ABAC) in a single policy.
Extensible: Easy to add new policy models or data sources.
Steps for evaluation:
Given a subject (user), resource, and action, we want to know if it's allowed.
We may have multiple policies (from different models) that apply.
We combine the results (usually any allow, but we can have a combining algorithm).
Let's define:
Policy:
- type: "rbac", "abac", "rebac"
- rule: a function that takes (subject, resource, action) and returns true/false.
- (For ReBAC, the rule might involve graph relationships)
Policy Store:
- get_policies(subject, resource, action) -> returns list of policies that might be relevant.
- We can also have a way to add/update policies.
Cache:
- cache_key: hash of (subject, resource, action) -> decision (and maybe timestamp, policy version?).
- We must invalidate cache when policies change.
We'll create an AuthorizationEngine class that uses these components.
Steps in engine:
Check cache for (subject, resource, action). If hit, return cached decision (but still audit? maybe we audit the cached decision too?).
If cache miss, get relevant policies from policy store.
Evaluate each policy (in order? or we can have a combining algorithm, like "any" or "all").
Combine the results (by default, we'll use "any" - if any policy allows, then allow).
Cache the result (with an appropriate TTL or until invalidated).
Log the decision (including which policies were evaluated and their results?).
We must consider:
Policy evaluation order? Usually, we don't care about order if using "any", but if using "all" then order doesn't matter either. However, some policies might have conditions that short-circuit? We can leave it to the policy rule.
We might also pass a context (like current time, request parameters, etc.)
For ReBAC, the rule might look up relationships in a graph. We can have a separate GraphStore.
We'll design the policy store to return policies that are potentially relevant. We can have a method that does a pre-filter (like by subject roles, resource types, etc.) to reduce the number of policies to evaluate.
However, in a simple implementation, we might just return all policies and let the rule function decide if it applies. But that's inefficient.
Alternatively, we can have:
code
Policy:
- subjects: list of subject patterns (or roles, for RBAC)
- resources: list of resource patterns (or types, for ReBAC)
- actions: list of actions
Then the policy store can index by these and return only policies that match the subject, resource, action.
But for ABAC, the conditions might be more complex and not easily indexed. So we might have to return more and let the rule filter.
We can have two stages:
code
Stage 1: Index-based filtering (using pre-defined attributes in the policy, like roles, resource types, actions).
Stage 2: Rule-based evaluation (the actual condition).
We'll design the Policy class to have:
code
class Policy:
id: str
type: str
subjects: list # or pattern, e.g., "user:*", "role:admin"
resources: list # e.g., "document:*", "document:123"
actions: list # e.g., "read", "write"
rule: callable # (subject, resource, action, context) -> bool
Then, the policy store can have an index on (subjects, resources, actions) to quickly find candidate policies.
However, note that for ReBAC, the resource might be a specific node in a graph, and the condition might be about the relationship. So we might not be able to index by resource string. We might have to store the graph separately and the rule function will query the graph.
Given the complexity, we might let the policy store return all policies of a given type (or all) and then the rule function does the rest. But that's not scalable.
Alternatively, we can have:
code
For RBAC: index by role (subject's role) and resource type, action.
For ABAC: index by resource type and action? But the condition can be arbitrary.
For ReBAC: index by resource type? and then the rule does graph traversal.
We'll design the policy store to be pluggable. For simplicity in this design, we'll assume the policy store can return a set of candidate policies based on a simple filter (subject, resource, action) that matches the policy's subjects, resources, actions (using pattern matching or exact match). Then the rule function will do the rest.
Steps:
code
candidate_policies = policy_store.get_policies(subject, resource, action)
Then for each policy in candidate_policies:
if policy.rule(subject, resource, action, context) is True:
allow = True (if combining is "any") and break? or collect all.
But if we are using "all", we have to evaluate all and if any fails, then deny.
We can have a policy combining algorithm per policy set? Or global? Let's make it configurable per policy store or per request.
We'll define:
code
combining_algorithm: "any" (default) or "all"
Then:
code
if combining_algorithm == "any":
for policy in candidate_policies:
if policy.rule(...):
return allow
return deny
if combining_algorithm == "all":
for policy in candidate_policies:
if not policy.rule(...):
return deny
return allow # if no policy, then deny? or we can have a default.
But note: what if there are no candidate policies? We should have a default decision (usually deny).
We can also have priority on policies? Maybe, but let's keep it simple.
Now, caching:
code
We want to cache the final decision (allow/deny) for a given (subject, resource, action, context?) but context might change (like time). So we need to be careful.
We can cache by (subject, resource, action) and also by some context hash if the rule uses context. But that might be too many keys.
Alternatively, we can set a TTL on the cache (e.g., 5 minutes) and then invalidate on policy change.
We'll design the cache to be a simple key-value store with TTL and invalidation on policy update.
The engine will:
cache_key = hash(subject, resource, action) # and maybe context if we want to include it? but then cache hits less.
We can let the user decide the cache key function? Or we can include a context hash if provided.
We'll assume the context is not part of the cache key by default, but if the user wants, they can provide a custom cache key function.
Alternatively, we can have the policy rule indicate whether it uses context that changes? Not easy.
We'll go with: cache by (subject, resource, action) and set a TTL. And on any policy change (add, update, delete) we invalidate the entire cache? Or we can try to invalidate by subject/resource/action if we know which policies changed? That's complex.
Simpler: when a policy changes, we clear the entire cache. Or we can use a version number for the policy set and include that in the cache key.
Let's do:
cache_key = (subject, resource, action, policy_store_version)
Then when policy_store changes, we increment the version and the old cache entries will not be used.
How to get version? The policy store can have a version (like a timestamp or incrementing integer) that changes on any policy change.
Then the engine:
version = policy_store.get_version()
cache_key = (subject, resource, action, version)
Then cache lookup and store with that key.
Audit:
code
We'll log:
- timestamp
- subject, resource, action
- decision (allow/deny)
- policies evaluated (list of policy ids and their results) or at least the ones that matched?
- cache hit or miss?
We can have an audit logger that is called after the decision.
Let's code the engine:
code
But note: in the "any" algorithm, we break at the first allow. So we don't evaluate all policies. But for audit, we might want to know which policies were evaluated until the decision? Or just the candidate set?
We can change _evaluate_policies to return (decision, policy_results) where policy_results is a list of (policy_id, result) for the policies that were evaluated? But then we break early, so we don't evaluate all.
Alternatively, we can have two modes:
- For performance, we break early.
- For audit, we might want to evaluate all? But that would be slower.
Let's keep it simple and just log the candidate policies (the ones returned by policy_store). Then the auditor can see which policies were considered.
But if we break early, the auditor doesn't know which policy caused the allow. We can change:
code
In _evaluate_policies for "any", we can evaluate all and then if any true, then allow? But that's less efficient.
Alternatively, we can collect the results of the policies we evaluate until we break? But then we don't evaluate all.
We can change the engine to always evaluate all policies? That might be expensive.
Let's assume that for audit we want to know the result of every candidate policy? Then we have to evaluate all even in "any".
We can have a flag in the engine: evaluate_all_for_audit? But that would change the performance.
Alternatively, we can have the policy rule itself log? Not good.
Let's change the engine to always evaluate all policies and then combine? That way we have the results of all.
But note: some policies might have side effects? We assume they are pure.
We'll change:
code
def _evaluate_policies(self, policies, subject, resource, action, context):
results = []
for policy in policies:
result = policy.rule(subject, resource, action, context)
results.append((policy.id, result))
if self.combining_algorithm == "any":
return any(result for _, result in results), results
elif self.combining_algorithm == "all":
return all(result for _, result in results), results
else:
...
Then in the main function:
decision, policy_results = self._evaluate_policies(...)
Then in audit, we log policy_results.
But note: if there are no policies, then results is empty and any([]) is False, all([]) is True? Actually, all([]) is True by definition. But we want default deny? So we have to handle no policies separately.
We'll adjust:
code
if not policies:
return False, [] # no policies, so deny, and no results.
Then for combining:
if self.combining_algorithm == "any":
decision = any(result for _, result in results)
elif self.combining_algorithm == "all":
decision = all(result for _, result in results)
But note: all([]) returns True, but we already handled no policies? Actually, if policies is empty, we return (False, []). So we don't get to the combining algorithm.
Alternatively, we can let the combining algorithm handle empty list? But then for "all", empty list returns True, which we don't want.
So we keep the early return for no policies.
Now, the policy store:
code
class PolicyStore:
def get_policies(self, subject, resource, action) -> List[Policy]:
raise NotImplementedError
def get_version(self) -> int:
raise NotImplementedError
# We also need methods to add, update, delete policies and then update the version.
We can have a simple in-memory policy store for testing.
class AuditLogger:
def log(self, entry):
raise NotImplementedError
Now, let's consider ReBAC:
code
For ReBAC, we might have a graph of relationships. The policy rule might be:
def rebac_rule(subject, resource, action, context):
# subject and resource are nodes in the graph. We need to check if there is a path from subject to resource with a certain relationship type?
# But the policy might define the relationship type and maybe the action is mapped to a relationship.
We can have a GraphStore that the rule function uses.
We can design the rule function to have access to the graph store? Or we can pass the graph store as part of the context?
Let's assume the context has a `graph_store` attribute.
Alternatively, we can have the rule function be a method of a class that has the graph store.
We'll design the policy rule as a callable that takes (subject, resource, action, context). The context can be a dictionary that includes the graph store.
Example:
context = {
"graph_store": graph_store,
"time": datetime.now(),
...
}
Then the rebac rule:
def rebac_rule(subject, resource, action, context):
graph_store = context["graph_store"]
# Check if subject has a relationship to resource that is allowed for the action.
# We might have a mapping from action to relationship type? Or the policy might specify the relationship.
# Let's assume the policy has an attribute `relationship` that says what relationship to check.
But our Policy class already has a rule function. So we can create a policy with:
rule = lambda s, r, a, ctx: check_relationship(s, r, a, ctx, relationship="viewer")
But we want to reuse the same function for multiple policies? We can create a function that returns a rule.
Example:
def make_rebac_rule(relationship):
def rule(subject, resource, action, context):
graph_store = context["graph_store"]
# Check if there is a path from subject to resource with the given relationship? Or direct?
# We can have a method in graph_store: has_relationship(subject, resource, relationship)
return graph_store.has_relationship(subject, resource, relationship)
return rule
Then create policy:
policy = Policy(
id="rebac1",
type="rebac",
subjects=["user:*"],
resources=["document:*"],
actions=["read"],
rule=make_rebac_rule("viewer")
)
This way, the rule function is created with the relationship type.
Now, for ABAC:
code
The rule can be any condition based on subject, resource, action, and context.
Example:
def abac_rule(subject, resource, action, context):
# subject might have attributes, resource has attributes, etc.
# We can have a way to access these? Maybe the subject and resource are objects with attributes.
# Or we can have the context include a dictionary of attributes.
We can design the subject and resource to be dictionaries or objects. We'll leave it flexible.
For RBAC:
code
We can have a rule that checks the subject's role against a list of allowed roles.
def rbac_rule(allowed_roles):
def rule(subject, resource, action, context):
# subject might be a user object with a role attribute, or a dictionary.
# We assume subject is a dictionary with key 'role'
return subject.get('role') in allowed_roles
return rule
But note: the policy store might index by role? We can have the policy's `subjects` field be a list of roles? Then we can pre-filter by role.
Actually, for RBAC, we can have the policy store index by role. So when we call get_policies(subject, resource, action), we can pass the subject's role and get policies that have that role in their subjects.
We can design the policy store to use the subject's role (if it's a dictionary) to filter.
But we want to be generic. So let's assume the policy store's get_policies does:
For each policy, check if the subject matches any of the policy's subjects (which could be a pattern, e.g., "role:admin", or a specific user id).
We can have a matching function:
def matches(subject, subject_pattern):
# subject_pattern could be:
# - exact string: then subject must be exactly that.
# - "role:*": then subject must have a role that matches the pattern?
# We can use glob patterns?
But that might be heavy.
Alternatively, we can have the policy store use the subject's attributes to filter. We can define that the subject is a dictionary and the policy's subjects is a list of conditions on the subject dictionary.
However, to keep it simple, we'll assume that the policy store does a simple string matching (exact or prefix) and the rule function does the rest.
Given the complexity, we might leave the policy store implementation to be a simple in-memory list that filters by:
code
for policy in policies:
for s in policy.subjects:
if subject matches s? (we can do: if subject == s, or if s.endswith('*') and subject.startswith(s[:-1]))
similarly for resources and actions.
Then return the policies that match at least one subject, one resource, and one action.
But note: the policy might have multiple subjects, resources, actions. We want to check if the given (subject, resource, action) is covered by any of the policy's subjects, resources, actions.
Example:
code
policy.subjects = ["user:alice", "role:admin"]
policy.resources = ["document:*"]
policy.actions = ["read", "write"]
Then if subject="user:alice", resource="document:123", action="read", it matches.
We can do:
code
subject_match = any(_match(subject, s) for s in policy.subjects)
resource_match = any(_match(resource, r) for r in policy.resources)
action_match = any(_match(action, a) for a in policy.actions)
if subject_match and resource_match and action_match:
candidate_policies.append(policy)
Where _match does:
code
def _match(value, pattern):
if pattern.endswith('*'):
return value.startswith(pattern[:-1])
else:
return value == pattern
But this is very simple. We might want more advanced pattern matching (like regex) but that's expensive.
We'll stick with simple prefix matching.
Now, let's code the in-memory policy store:
code
class InMemoryPolicyStore(PolicyStore):
def __init__(self):
self.policies = [] # list of Policy
self.version = 0
def add_policy(self, policy):
self.policies.append(policy)
self.version += 1
def remove_policy(self, policy_id):
self.policies = [p for p in self.policies if p.id != policy_id]
self.version += 1
def update_policy(self, policy):
# remove old and add new? or update in place?
self.remove_policy(policy.id)
self.add_policy(policy)
def get_policies(self, subject, resource, action):
result = []
for policy in self.policies:
if (any(self._match(subject, s) for s in policy.subjects) and
any(self._match(resource, r) for r in policy.resources) and
any(self._match(action, a) for a in policy.actions)):
result.append(policy)
return result
def get_version(self):
return self.version
def _match(self, value, pattern):
if pattern.endswith('*'):
return value.startswith(pattern[:-1])
else:
return value == pattern
Now, we have the components.
We can also have a way to load policies from a file or database.
Let's write an example of how to use:
code
However, note that the pattern matching in the policy store is on the subject string. So if we have an RBAC policy with subjects=["role:admin"] and the subject is "user:alice" (with role admin) but the string is "user:alice", it won't match. So we must set the subject string to be the role? Or we need to have a way to map the user to a role.
This is a limitation of our simple design.
To fix this, we can have the subject be a dictionary and the policy's subjects be patterns on the dictionary? But then the pattern matching would be more complex.
Alternatively, we can have the subject be an object and the policy's subjects be a function that extracts the role? Not easy.
We can change the policy store's get_policies to take the subject as a dictionary and then the policy's subjects can be a list of roles? But then we lose the ability to have patterns.
Given the complexity, we might assume that the subject is a string that already encodes the role (like "role:admin") for RBAC. For ABAC, we can have the subject be a dictionary and the rule function can use the dictionary.
But then we have two different representations for subject? That's not good.
Let's decide: the subject, resource, action are strings. For RBAC, the subject string is the role (or user with role?).
Alternatively, we can have the subject be a dictionary and the policy's subjects be a list of conditions on the dictionary. We can do:
code
For each policy, the subjects is a list of conditions. Each condition is a dictionary that must be a subset of the subject dictionary? Or we can have a pattern on a specific attribute.
Example:
policy.subjects = [{"role": "admin"}]
Then we check if the subject dictionary has role="admin".
But then we need to know which attribute to check? We can have the condition be a key-value pair that must match.
Then:
subject = {"role": "admin", "name": "Alice"}
policy.subjects = [{"role": "admin"}] -> matches.
We can also have:
policy.subjects = [{"role": "admin", "name": "Alice"}] -> must match exactly.
But what if we want to match any admin? Then we only specify {"role": "admin"}.
We can implement:
def _match_subject(subject_dict, condition):
for key, value in condition.items():
if key not in subject_dict or subject_dict[key] != value:
return False
return True
Then for a policy, we check if any of the conditions in policy.subjects matches the subject_dict.
Similarly for resources and actions? But actions are usually strings, so we might keep actions as strings.
This way, we can have:
RBAC:
subject_dict = {"role": "admin"}
policy.subjects = [{"role": "admin"}]
ABAC:
we can have more complex conditions in the rule function, but the pattern matching on subject_dict can be a pre-filter.
ReBAC:
the subject might be a node in a graph, so we might have subject_dict = {"id": "user:123", "type": "user"} and the policy's subjects might be [{"type": "user"}]?
But then the rule function for ReBAC would use the graph store and the subject's id.
This seems more flexible.
Let's change the design:
code
The subject, resource, action are dictionaries? But then the action might be a string. We can have:
subject: dict
resource: dict
action: str (or we can have action as dict too? but usually actions are simple strings)
But then the policy's subjects, resources, actions are lists of conditions (dicts) that must be a subset of the given subject/resource dict.
For actions, we can have a list of strings? Or a list of conditions on a dict? Let's keep actions as strings and the policy's actions as a list of strings (exact match or pattern?).
We'll change:
Policy:
subjects: list[dict] # each dict is a condition (subset match)
resources: list[dict] # same
actions: list[str] # exact match? or pattern? We can do pattern matching on the action string.
But then the policy store's get_policies would do:
for policy in self.policies:
subject_match = any(self._dict_subset_match(subject, cond) for cond in policy.subjects)
resource_match = any(self._dict_subset_match(resource, cond) for cond in policy.resources)
action_match = any(self._match_string(action, a) for a in policy.actions) # using the same pattern matching as before.
Then if all three match, include the policy.
This way, we can have:
RBAC policy:
subjects = [{"role": "admin"}]
resources = [{"type": "document"}] # or [{"type": "document", "owner": "user:alice"}]?
actions = ["read", "write"]
Then the rule function can be the default (True) because the pattern matching already did the job.
But note: the rule function can still add additional conditions. For example, an RBAC policy that only allows during business hours? Then we need a rule.
So the rule function is still needed for any additional condition that cannot be expressed by the subset matching.
The subset matching is just a pre-filter to reduce the number of policies.
Let's adjust the Policy class:
code
class Policy:
def __init__(self, id, type, subjects, resources, actions, rule=None):
self.id = id
self.type = type
self.subjects = subjects # list of dicts
self.resources = resources # list of dicts
self.actions = actions # list of strings (with pattern matching)
self.rule = rule
if self.rule is None:
if type == "rbac":
self.rule = self._default_rule
else:
raise ValueError(f"Policy type {type} requires a rule")
def _default_rule(self, subject, resource, action, context):
return True
Now, the in-memory policy store's _match_string for actions and _dict_subset_match for subjects and resources.
code
def _dict_subset_match(self, d, condition):
for key, value in condition.items():
if key not in d or d[key] != value:
return False
return True
And for actions, we use the same pattern matching as before.
But note: the subject and resource are now dictionaries. So we have to change the engine's is_allowed to accept dictionaries.
Let's adjust the engine:
code
def is_allowed(self, subject, resource, action, context=None):
# subject, resource are dicts, action is string.
And the cache key: we need to hash the dictionaries. We can convert to a frozenset of items? But order might matter? We can use json.dumps with sort_keys=True.
code
def _make_cache_key(self, subject, resource, action, version, context):
# Convert subject and resource to a hashable representation.
subject_key = json.dumps(subject, sort_keys=True)
resource_key = json.dumps(resource, sort_keys=True)
return (subject_key, resource_key, action, version)
But note: the context might affect the decision, but we are not including it in the cache key. We can include a hash of the context if needed.
Now, let's consider the audit: we want to log the subject and resource as they are (dicts) but we might want to avoid logging sensitive information. We can have the audit logger filter? That's up to the implementation.
This design is getting complex, but it's flexible.
Let's summarize:
code
- Policy:
id, type, subjects (list of dict conditions), resources (list of dict conditions), actions (list of string patterns), rule (callable)
- PolicyStore:
get_policies(subject_dict, resource_dict, action_string) -> list of policies that match the pre-filter.
get_version() -> int
- Cache:
get(key) -> value or None
set(key, value, ttl)
- AuditLogger:
log(entry)
- AuthorizationEngine:
is_allowed(subject_dict, resource_dict, action_string, context=None) -> bool
The engine:
1. Compute cache key (using cache_key_func)
2. Check cache
3. If cache hit, audit and return.
4. Else, get policies from store.
5. Evaluate policies (all, and collect results).
6. Combine results (any/all).
7. Cache the decision.
8. Audit with policy results.
Now, let's code the engine with these changes.
We'll also change the in-memory policy store to use the new matching.
policy = Policy(
id="abac1",
type="abac",
subjects=[{"role": "user"}],
resources=[{"type": "document"}],
actions=["read"],
rule=lambda s, r, a, ctx: r.get('owner') == s.get('id') # only the owner can read
)
For ReBAC:
code
We assume the subject and resource have an "id" field that we can use in the graph.
policy = Policy(
id="rebac1",
type="rebac",
subjects=[{"type": "user"}],
resources=[{"type": "document"}],
actions=["read"],
rule=lambda s, r, a, ctx: ctx['graph_store'].has_permission(s['id'], r['id'], a)
)
But note: the rule function for ReBAC might be more complex, but this is the idea.
We must make sure the context has the graph_store.
Now, let's write the code accordingly.
We'll write:
code
class Policy:
...
class InMemoryPolicyStore:
...
class AuthorizationEngine:
...
And then an example.
But note: the policy store's get_policies must return policies that match the subject, resource, action pre-filter.
We'll adjust InMemoryPolicyStore:
code
def get_policies(self, subject, resource, action):
result = []
for policy in self.policies:
subject_match = any(self._dict_subset_match(subject, cond) for cond in policy.subjects)
resource_match = any(self._dict_subset_match(resource, cond) for cond in policy.resources)
action_match = any(self._match_string(action, pattern) for pattern in policy.actions)
if subject_match and resource_match and action_match:
result.append(policy)
return result
def _dict_subset_match(self, d, condition):
for key, value in condition.items():
if key not in d or d[key] != value:
return False
return True
def _match_string(self, value, pattern):
if pattern.endswith('*'):
return value.startswith(pattern[:-1])
else:
return value == pattern
This should work.
Now, let's code the engine with the cache key function and audit.
We'll also add a way to clear the cache? The cache is external, so we can just rely on TTL and version.
Let's write the code.
Note: We are using json.dumps for cache key, so the subject and resource must be JSON serializable.
We'll write the code accordingly.
Let's code.
I'll design a composable, multi-model authorization engine with pluggable policies, caching, and audit. This follows the Open Policy Agent (OPA)/ Cedar-inspired approach with clean separation of concerns.
class PolicyEvaluator(ABC):
"""Abstract base for policy evaluators"""
@abstractmethod
def evaluate(
self,
request: Request,
policies: List[Policy],
cache: Optional['CacheBackend'] = None
) -> EvaluationResult:
"""Evaluate request against policies"""
pass
@abstractmethod
def can_evaluate(self, policy: Policy) -> bool:
"""Check if this evaluator can handle the policy model"""
pass
class CompositeEvaluator:
"""Orchestrates multiple evaluators with priority ordering"""
def __init__(self, evaluators: List[PolicyEvaluator]):
self.evaluators = sorted(evaluators, key=lambda e: getattr(e, 'priority', 0))
self.evaluator_map = {e.__class__.__name__: e for e in evaluators}
def evaluate(
self,
request: Request,
policies: List[Policy],
cache: Optional['CacheBackend'] = None,
strategy: str = "ANY_ALLOW" # or "ALL_DENY", "FIRST_MATCH"
) -> EvaluationResult:
"""Evaluate using configured strategy"""
enabled_policies = [p for p in policies if p.enabled]
sorted_policies = sorted(enabled_policies, key=lambda p: p.priority, reverse=True)
# Group by model
policies_by_model = {}
for policy in sorted_policies:
policies_by_model.setdefault(policy.model, []).append(policy)
results = []
start_time = datetime.utcnow()
# Evaluate with each evaluator
for model, model_policies in policies_by_model.items():
evaluator = self.evaluator_map.get(f"{model.title()}Evaluator")
if evaluator and evaluator.can_evaluate(model_policies[0]):
result = evaluator.evaluate(request, model_policies, cache)
results.append(result)
# Combine results based on strategy
if strategy == "ANY_ALLOW":
allow_results = [r for r in results if r.decision == Decision.ALLOW]
final_decision = Decision.ALLOW if allow_results else Decision.DENY
elif strategy == "ALL_DENY":
deny_results = [r for r in results if r.decision == Decision.DENY]
final_decision = Decision.DENY if deny_results else Decision.ALLOW
elif strategy == "FIRST_MATCH":
# Use highest priority policy that matches
final_decision = Decision.DENY
final_policy = None
for result in sorted(results, key=lambda r: r.policy_priority if hasattr(r, 'policy_priority') else 0, reverse=True):
if result.decision in [Decision.ALLOW, Decision.DENY]:
final_decision = result.decision
final_policy = result.policy_id
break
duration = (datetime.utcnow() - start_time).total_seconds() * 1000
return EvaluationResult(
decision=final_decision,
matching_policies=[r.policy_id for r in results if r.policy_id],
evaluation_time_ms=duration,
model="composite"
)
3. Model-Specific Evaluators
python
4. Caching Layer
python
class CacheBackend(ABC):
"""Abstract cache interface"""
@abstractmethod
def get(self, key: str) -> Optional[Any]:
pass
@abstractmethod
def set(self, key: str, value: Any, ttl: int = 300):
pass
@abstractmethod
def invalidate(self, pattern: str):
"""Invalidate all keys matching pattern"""
pass
@abstractmethod
def clear(self):
pass
class MemoryCache(CacheBackend):
"""Simple in-memory cache"""
def __init__(self, max_size: int = 10000):
self.cache: Dict[str, Tuple[Any, datetime]] = {}
self.max_size = max_size
def get(self, key: str) -> Optional[Any]:
if key in self.cache:
value, expiry = self.cache[key]
if datetime.utcnow() < expiry:
return value
del self.cache[key]
return None
def set(self, key: str, value: Any, ttl: int = 300):
if len(self.cache) >= self.max_size:
# Simple LRU: remove oldest
oldest = min(self.cache.items(), key=lambda x: x[1][1])[0]
del self.cache[oldest]
expiry = datetime.utcnow().timestamp() + ttl
self.cache[key] = (value, expiry)
def invalidate(self, pattern: str):
# Pattern matching - simple implementation
keys_to_remove = [k for k in self.cache if pattern in k]
for key in keys_to_remove:
del self.cache[key]
def clear(self):
self.cache.clear()
class RedisCache(CacheBackend):
"""Redis-backed cache with pub/sub for invalidation"""
def __init__(self, redis_client, prefix: str = "authz:"):
self.redis = redis_client
self.prefix = prefix
def _key(self, key: str) -> str:
return f"{self.prefix}{key}"
def get(self, key: str) -> Optional[Any]:
value = self.redis.get(self._key(key))
return json.loads(value) if value else None
def set(self, key: str, value: Any, ttl: int = 300):
self.redis.setex(
self._key(key),
ttl,
json.dumps(value, default=str)
)
def invalidate(self, pattern: str):
pattern = self._key(f"*{pattern}*")
keys = self.redis.keys(pattern)
if keys:
self.redis.delete(*keys)
def clear(self):
pattern = self._key("*")
keys = self.redis.keys(pattern)
if keys:
self.redis.delete(*keys)
5. Graph Store for ReBAC
python
6. Policy Store & Management
python
class PolicyStore(ABC):
"""Abstract policy storage"""
@abstractmethod
def get_policies(
self,
model: Optional[str] = None,
enabled_only: bool = True
) -> List[Policy]:
pass
@abstractmethod
def add_policy(self, policy: Policy):
pass
@abstractmethod
def update_policy(self, policy: Policy):
pass
@abstractmethod
def remove_policy(self, policy_id: str):
pass
@abstractmethod
def get_policy(self, policy_id: str) -> Optional[Policy]:
pass
class InMemoryPolicyStore(PolicyStore):
"""In-memory policy store with indexing"""
def __init__(self):
self.policies: Dict[str, Policy] = {}
self.index: Dict[str, Set[str]] = {} # model -> set of policy_ids
self.version = 0
def get_policies(
self,
model: Optional[str] = None,
enabled_only: bool = True
) -> List[Policy]:
policies = []
for policy in self.policies.values():
if model and policy.model != model:
continue
if enabled_only and not policy.enabled:
continue
policies.append(policy)
return sorted(policies, key=lambda p: p.priority, reverse=True)
def add_policy(self, policy: Policy):
self.policies[policy.id] = policy
self.index.setdefault(policy.model, set()).add(policy.id)
self.version += 1
def update_policy(self, policy: Policy):
if policy.id not in self.policies:
raise ValueError(f"Policy {policy.id} not found")
old_policy = self.policies[policy.id]
if old_policy.model != policy.model:
self.index[old_policy.model].remove(policy.id)
self.index.setdefault(policy.model, set()).add(policy.id)
self.policies[policy.id] = policy
self.version += 1
def remove_policy(self, policy_id: str):
if policy_id in self.policies:
policy = self.policies[policy_id]
del self.policies[policy_id]
self.index[policy.model].remove(policy_id)
self.version += 1
def get_policy(self, policy_id: str) -> Optional[Policy]:
return self.policies.get(policy_id)
def get_version(self) -> int:
return self.version
# 1. Rate Limiting Integration
class RateLimitedEngine(AuthorizationEngine):
def __init__(self, *args, rate_limiter, **kwargs):
super().__init__(*args, **kwargs)
self.rate_limiter = rate_limiter
def check(self, *args, **kwargs):
if not self.rate_limiter.allow(request.subject.id):
return EvaluationResult(
decision=Decision.DENY,
reason="Rate limit exceeded"
)
return super().check(*args, **kwargs)
# 2. Policy Templates
class PolicyTemplate:
"""Reusable policy templates"""
@staticmethod
def ownership_policy(resource_type: str) -> Policy:
return Policy(
id=f"owner_{resource_type}",
model="abac",
attributes={
"resource.owner_id": "subject.id",
"subject.role": "owner"
},
effect=Decision.ALLOW
)
# 3. Batch Evaluation
def batch_check(
engine: AuthorizationEngine,
requests: List[Request]
) -> List[EvaluationResult]:
"""Batch evaluation with shared cache lookups"""
results = []
cache_keys = [engine._get_cache_key(r) for r in requests]
# Batch cache lookup if supported
if engine.cache and hasattr(engine.cache, 'batch_get'):
cached_results = engine.cache.batch_get(cache_keys)
for request in requests:
result = engine.check(
subject=request.subject,
resource=request.resource,
action=request.action,
context=request.context,
bypass_cache=bool(cached_results.get(engine._get_cache_key(request)))
)
results.append(result)
return results
# 4. Dynamic Policy Loading
class DynamicPolicyLoader:
"""Load policies from external sources (K8s OPA, databases, etc.)"""
def __init__(self, policy_store: PolicyStore, source: str):
self.policy_store = policy_store
self.source = source
def sync(self):
"""Sync policies from external source"""
# Implementation depends on source
# Could watch for changes via webhook, poll, etc.
pass
11. Production Considerations
python
# metrics.py
from prometheus_client import Counter, Histogram, Gauge
AUTHZ_REQUESTS = Counter('authz_requests_total', 'Total authorization requests', ['model', 'decision'])
AUTHZ_DURATION = Histogram('authz_duration_seconds', 'Authorization duration', ['model'])
CACHE_HITS = Counter('authz_cache_hits_total', 'Cache hits')
POLICIES_LOADED = Gauge('authz_policies_loaded', 'Number of loaded policies')
# Wrap engine with metrics
class MonitoredEngine(AuthorizationEngine):
def check(self, *args, **kwargs):
with AUTHZ_DURATION.labels(model='composite').time():
result = super().check(*args, **kwargs)
AUTHZ_REQUESTS.labels(
model=result.model or 'unknown',
decision=result.decision.value
).inc()
return result
# health.py
class HealthChecker:
def __init__(self, engine: AuthorizationEngine):
self.engine = engine
def check(self) -> Dict[str, Any]:
return {
"status": "healthy",
"policies_count": len(self.engine.policy_store.get_policies()),
"cache_size": len(self.engine.cache.cache) if hasattr(self.engine.cache, 'cache') else 0,
"timestamp": datetime.utcnow().isoformat()
}
Key Design Decisions:
Policy-First Design: Policies are first-class citizens with explicit models
Composable Evaluators: Each model (RBAC/ABAC/ReBAC) has dedicated evaluator
Cache Hierarchy: Multi-level caching (policy result + relationship caching)
Structured Audit: Complete audit trail with request context
Pluggable Backends: All components (store, cache, audit, graph) are abstracted
Priority & Strategy: Policies evaluated by priority, combined by strategy
Cache Invalidation: Version-based or pattern-based invalidation
Thread-Safe: All implementations should be thread-safe for production
Scalability Considerations:
Shard by resource type for policy storage
Distributed cache (Redis) for multi-instance deployments
Policy pre-compilation for complex ABAC expressions
Warm cache on startup for common policies
Async audit logging to avoid blocking
Circuit breakers for external graph stores
This design provides a flexible, production-ready authorization engine that can:
Run standalone or as a service (gRPC/REST wrapper)
Integrate with existing IAM systems (LDAP, SAML, OIDC)
Handle complex hierarchical relationships (ReBAC)
Support dynamic policies without restarts
Provide complete audit trails for compliance
Scale horizontally with shared cache
Hot-reload policies from external sources
class AuthorizationEngine:
def __init__(self, policy_store, cache, audit_logger, combining_algorithm="any", cache_ttl=300):
self.policy_store = policy_store
self.cache = cache
self.audit_logger = audit_logger
self.combining_algorithm = combining_algorithm
self.cache_ttl = cache_ttl
def is_allowed(self, subject, resource, action, context=None):
# Step 1: Check cache
version = self.policy_store.get_version()
cache_key = self._make_cache_key(subject, resource, action, version, context)
cached_decision = self.cache.get(cache_key)
if cached_decision is not None:
self._audit(subject, resource, action, cached_decision, cache_hit=True, context=context)
return cached_decision
# Step 2: Get candidate policies
policies = self.policy_store.get_policies(subject, resource, action)
# Step 3: Evaluate
decision = self._evaluate_policies(policies, subject, resource, action, context)
# Step 4: Cache
self.cache.set(cache_key, decision, self.cache_ttl)
# Step 5: Audit
self._audit(subject, resource, action, decision, cache_hit=False, context=context, policies=policies)
return decision
def _make_cache_key(self, subject, resource, action, version, context):
# We'll use a tuple that is hashable. But subject, resource, action might be complex objects.
# We assume they are strings or have a consistent __str__ or we use their string representation.
# For context, we might not include it in the key by default? But then if the rule uses context, we might get wrong cache hit.
# Let's not include context in the key by default, but if the user wants, they can override this method.
return (str(subject), str(resource), str(action), version)
def _evaluate_policies(self, policies, subject, resource, action, context):
if not policies:
return False # default deny
if self.combining_algorithm == "any":
for policy in policies:
if policy.rule(subject, resource, action, context):
return True
return False
elif self.combining_algorithm == "all":
for policy in policies:
if not policy.rule(subject, resource, action, context):
return False
return True
else:
raise ValueError(f"Unknown combining algorithm: {self.combining_algorithm}")
def _audit(self, subject, resource, action, decision, cache_hit, context, policies=None):
audit_entry = {
"timestamp": datetime.utcnow().isoformat(),
"subject": subject,
"resource": resource,
"action": action,
"decision": decision,
"cache_hit": cache_hit,
"context": context,
}
if policies is not None:
# We can log the policy ids and their individual decisions? But we don't have that in _evaluate_policies for "any" (we break early).
# So we need to change _evaluate_policies to return more info? Or we can log the policies that were evaluated (the candidate set) and then the decision.
# Let's change: we want to log which policies were evaluated and their results? But that might be too much.
# Alternatively, we can log the list of policy ids that were considered (candidate policies) and the final decision.
audit_entry["policy_ids"] = [p.id for p in policies]
# We don't have the results of each policy unless we change _evaluate_policies to return a list of results.
# For audit, we might want the results. Let's change the engine to collect results for audit.
self.audit_logger.log(audit_entry)
# Create policy store
store = InMemoryPolicyStore()
# Create an RBAC policy
rbac_policy = Policy(
id="rbac1",
type="rbac",
subjects=["role:admin"],
resources=["document:*"],
actions=["read", "write"],
rule=lambda s, r, a, ctx: s.get('role') == 'admin' # but note: we already filtered by subject pattern, so we know the subject is "role:admin"?
# Actually, the subject pattern is "role:admin", so the subject string must be exactly "role:admin"?
# But our subject might be a dictionary. We have to be consistent.
We have a problem: the subject we pass to is_allowed might be a dictionary (with role) but the policy's subjects are strings.
We need to decide on the subject representation.
Let's assume the subject is a string that represents the user, e.g., "user:alice" or "role:admin". Then the RBAC policy's subjects would be ["role:admin"] and the rule would check the subject string?
Alternatively, we can have the subject be an object and the policy's subjects be patterns that match the string representation of the subject.
We'll change: the subject, resource, action are strings. Then the rule function can parse them? Or we can have a context that has the parsed attributes.
For RBAC, we can have:
subject = "user:alice" and the policy's subjects = ["role:admin"] -> won't match.
So we need to have the subject be the role? Or we need to have a way to extract the role from the subject.
Alternatively, we can have the subject be a dictionary and the policy's subjects be patterns on the dictionary? That's more complex.
Let's stick to strings for subject, resource, action. Then for RBAC, we can have:
subject = "role:admin" and the policy's subjects = ["role:admin"]
Then the rule function can just check the subject string? But then the rule function for RBAC is trivial: if the subject string is in the list of allowed roles? But we already did the pattern matching.
Actually, the pattern matching in the policy store already ensures that the subject string matches one of the patterns. So for RBAC, the rule function might just return True? Because the pattern matching already ensured the subject is one of the allowed roles.
But what if the policy has multiple subjects and we want to allow any of them? Then the pattern matching already did that.
So for RBAC, we might not need a rule function? We can have a policy type that doesn't require a rule? But our Policy class requires a rule.
We can have a default rule for RBAC that returns True? Because the pattern matching already did the job.
Alternatively, we can change the policy store to not require a rule for RBAC? But then we have to handle different policy types differently.
We can have:
class Policy:
def __init__(self, id, type, subjects, resources, actions, rule=None):
self.id = id
self.type = type
self.subjects = subjects
self.resources = resources
self.actions = actions
self.rule = rule
if self.rule is None:
if type == "rbac":
self.rule = self._rbac_default_rule
elif type == "abac":
raise ValueError("ABAC requires a rule")
elif type == "rebac":
raise ValueError("ReBAC requires a rule")
def _rbac_default_rule(self, subject, resource, action, context):
return True # because the pattern matching already ensured the subject is in the list.
Then for RBAC, we don't need to provide a rule.
But wait, what if we want to have an RBAC policy that also has an additional condition? Then we need a rule.
So we leave it as: if the user provides a rule, use it; else, for RBAC, use the default (which is always allow if the pattern matched). For ABAC and ReBAC, rule is required.
class RBACEvaluator(PolicyEvaluator):
"""Role-Based Access Control evaluator"""
priority = 10
def can_evaluate(self, policy: Policy) -> bool:
return policy.model == "rbac"
def evaluate(
self,
request: Request,
policies: List[Policy],
cache: Optional['CacheBackend'] = None
) -> EvaluationResult:
user_roles = request.subject.attributes.get("roles", [])
resource_roles = request.resource.attributes.get("required_roles", [])
for policy in policies:
# Check role overlap
user_has_role = any(role in user_roles for role in policy.roles)
resource_needs_role = any(role in resource_roles for role in policy.roles)
if user_has_role and (not resource_needs_role or policy.effect == Decision.ALLOW):
return EvaluationResult(
decision=policy.effect,
policy_id=policy.id,
reason=f"User has role {policy.roles}",
model="rbac"
)
return EvaluationResult(decision=Decision.DENY, model="rbac")
class ABACEvaluator(PolicyEvaluator):
"""Attribute-Based Access Control evaluator"""
priority = 20
def can_evaluate(self, policy: Policy) -> bool:
return policy.model == "abac"
def evaluate(
self,
request: Request,
policies: List[Policy],
cache: Optional['CacheBackend'] = None
) -> EvaluationResult:
for policy in policies:
# Build evaluation context
ctx = {
"subject": request.subject.attributes,
"resource": request.resource.attributes,
"action": request.action.id,
"request": request.context,
"time": datetime.utcnow().isoformat()
}
# Evaluate conditions (simplified - in reality use actual parser)
if self._evaluate_conditions(policy.attributes, ctx):
return EvaluationResult(
decision=policy.effect,
policy_id=policy.id,
reason=f"ABAC conditions matched: {policy.attributes}",
model="abac"
)
return EvaluationResult(decision=Decision.DENY, model="abac")
def _evaluate_conditions(self, conditions: Dict, ctx: Dict) -> bool:
"""Simple condition evaluator - replace with real parser (CEL, Rego, etc.)"""
# This is simplified - use real expression language in production
for key, expected in conditions.items():
actual = ctx.get(key)
if actual != expected:
return False
return True
class ReBACEvaluator(PolicyEvaluator):
"""Relationship-Based Access Control evaluator"""
priority = 15
def __init__(self, graph_store: 'GraphStore'):
self.graph_store = graph_store
def can_evaluate(self, policy: Policy) -> bool:
return policy.model == "rebac"
def evaluate(
self,
request: Request,
policies: List[Policy],
cache: Optional['CacheBackend'] = None
) -> EvaluationResult:
for policy in policies:
# Check all relations in policy
all_relations_match = True
for subj_rel_obj in policy.relations:
subj_type, relation, obj_type = subj_rel_obj
# Build cache key for relationship check
cache_key = f"rebac:{request.subject.id}:{relation}:{request.resource.id}"
if cache:
cached = cache.get(cache_key)
if cached is not None:
if not cached:
all_relations_match = False
break
continue
# Check relationship in graph
has_relation = self.graph_store.has_relationship(
subject_id=request.subject.id,
relation=relation,
object_id=request.resource.id
)
if cache:
cache.set(cache_key, has_relation, ttl=300)
if not has_relation:
all_relations_match = False
break
if all_relations_match:
return EvaluationResult(
decision=policy.effect,
policy_id=policy.id,
reason=f"ReBAC relations matched: {policy.relations}",
model="rebac"
)
return EvaluationResult(decision=Decision.DENY, model="rebac")
class GraphStore(ABC):
"""Abstract graph storage for ReBAC relationships"""
@abstractmethod
def add_relationship(
self,
subject_id: str,
relation: str,
object_id: str,
metadata: Optional[Dict] = None
):
pass
@abstractmethod
def remove_relationship(
self,
subject_id: str,
relation: str,
object_id: str
):
pass
@abstractmethod
def has_relationship(
self,
subject_id: str,
relation: str,
object_id: str,
transitive: bool = False
) -> bool:
"""Check if relationship exists (direct or transitive)"""
pass
@abstractmethod
def get_relationships(
self,
subject_id: str,
relation: Optional[str] = None
) -> List[Tuple[str, str]]:
"""Get all (relation, object_id) for subject"""
pass
class InMemoryGraphStore(GraphStore):
"""Simple in-memory graph implementation"""
def __init__(self):
# (subject_id, relation) -> set of object_ids
self.graph: Dict[Tuple[str, str], Set[str]] = {}
# For transitive queries
self.transitive_cache: Dict[Tuple[str, str, str], bool] = {}
def add_relationship(
self,
subject_id: str,
relation: str,
object_id: str,
metadata: Optional[Dict] = None
):
key = (subject_id, relation)
if key not in self.graph:
self.graph[key] = set()
self.graph[key].add(object_id)
self.transitive_cache.clear() # Invalidate transitive cache
def remove_relationship(
self,
subject_id: str,
relation: str,
object_id: str
):
key = (subject_id, relation)
if key in self.graph and object_id in self.graph[key]:
self.graph[key].remove(object_id)
self.transitive_cache.clear()
def has_relationship(
self,
subject_id: str,
relation: str,
object_id: str,
transitive: bool = False
) -> bool:
# Direct relationship
direct_key = (subject_id, relation)
if direct_key in self.graph and object_id in self.graph[direct_key]:
return True
if transitive:
cache_key = (subject_id, relation, object_id)
if cache_key in self.transitive_cache:
return self.transitive_cache[cache_key]
# Simple DFS for transitive closure
visited = set()
stack = [(subject_id, relation)]
while stack:
current, rel = stack.pop()
if (current, rel) in self.graph:
for obj in self.graph[(current, rel)]:
if obj == object_id:
self.transitive_cache[cache_key] = True
return True
if (obj, rel) not in visited:
visited.add((obj, rel))
stack.append((obj, rel))
self.transitive_cache[cache_key] = False
return False
return False
def get_relationships(
self,
subject_id: str,
relation: Optional[str] = None
) -> List[Tuple[str, str]]:
results = []
for (subj, rel), objects in self.graph.items():
if subj == subject_id and (relation is None or rel == relation):
for obj in objects:
results.append((rel, obj))
return results
class AuthorizationEngine:
"""
Composable authorization engine with:
- Multi-model support (RBAC/ABAC/ReBAC/Custom)
- Pluggable caching
- Audit logging
- Policy management
"""
def __init__(
self,
policy_store: PolicyStore,
evaluators: List[PolicyEvaluator],
cache: Optional[CacheBackend] = None,
audit_logger: Optional[AuditBackend] = None,
default_strategy: str = "ANY_ALLOW",
cache_ttl: int = 300
):
self.policy_store = policy_store
self.composite_evaluator = CompositeEvaluator(evaluators)
self.cache = cache
self.audit_logger = audit_logger
self.default_strategy = default_strategy
self.cache_ttl = cache_ttl
self.request_counter = 0
# Cache invalidation on policy changes
self._setup_policy_invalidation()
def _setup_policy_invalidation(self):
"""Setup cache invalidation on policy changes"""
if hasattr(self.policy_store, 'version'):
# Track version for cache invalidation
self.current_version = self.policy_store.get_version()
else:
# Subscribe to policy change events if your store supports it
pass
def _generate_request_id(self) -> str:
self.request_counter += 1
return f"req_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}_{self.request_counter}"
def _get_cache_key(self, request: Request) -> str:
"""Generate cache key from request"""
key_data = {
"subject": f"{request.subject.type}:{request.subject.id}",
"resource": f"{request.resource.type}:{request.resource.id}",
"action": request.action.id,
"context": request.context
}
key_str = json.dumps(key_data, sort_keys=True, default=str)
return f"authz:{hashlib.md5(key_str.encode()).hexdigest()}"
def check(
self,
subject: Entity,
resource: Entity,
action: Entity,
context: Optional[Dict] = None,
strategy: Optional[str] = None,
bypass_cache: bool = False
) -> EvaluationResult:
"""
Main authorization check
Args:
subject: Who is making the request
resource: What is being accessed
action: What operation
context: Additional context (time, IP, etc.)
strategy: Override default strategy
bypass_cache: Skip cache lookup
Returns:
EvaluationResult with decision and metadata
"""
request = Request(
subject=subject,
resource=resource,
action=action,
context=context or {},
request_id=self._generate_request_id()
)
start_time = datetime.utcnow()
cache_key = self._get_cache_key(request)
cache_hit = False
# 1. Check cache (if enabled and not bypassed)
if self.cache and not bypass_cache:
cached = self.cache.get(cache_key)
if cached is not None:
cache_hit = True
duration = (datetime.utcnow() - start_time).total_seconds() * 1000
if self.audit_logger:
self.audit_logger.log(AuditEntry(
timestamp=datetime.utcnow(),
request_id=request.request_id,
subject=subject,
resource=resource,
action=action,
decision=cached.decision,
policies_evaluated=[],
final_policy=None,
context=context or {},
cache_hit=True,
duration_ms=duration
))
return cached
# 2. Get policies
policies = self.policy_store.get_policies()
# 3. Evaluate
result = self.composite_evaluator.evaluate(
request=request,
policies=policies,
cache=self.cache,
strategy=strategy or self.default_strategy
)
# 4. Cache result (if allowed)
if self.cache and result.decision == Decision.ALLOW:
self.cache.set(cache_key, result, ttl=self.cache_ttl)
# 5. Audit
duration = (datetime.utcnow() - start_time).total_seconds() * 1000
if self.audit_logger:
self.audit_logger.log(AuditEntry(
timestamp=datetime.utcnow(),
request_id=request.request_id,
subject=subject,
resource=resource,
action=action,
decision=result.decision,
policies_evaluated=result.matching_policies,
final_policy=result.policy_id,
context=context or {},
cache_hit=cache_hit,
duration_ms=duration
))
return result
def invalidate_cache_for(
self,
subject: Optional[Entity] = None,
resource: Optional[Entity] = None,
action: Optional[Entity] = None
):
"""Invalidate cache for specific entities"""
if not self.cache:
return
pattern = "authz:"
if subject:
pattern += f"*{subject.type}:{subject.id}*"
if resource:
pattern += f"*{resource.type}:{resource.id}*"
if action:
pattern += f"*{action.id}*"
self.cache.invalidate(pattern)
def reload_policies(self):
"""Reload policies from store (useful if external changes)"""
if hasattr(self.policy_store, 'version'):
self.current_version = self.policy_store.get_version()
# Additional reload logic as needed