Design:
a. Policy Representation:
- Policies could be represented as a set of rules (conditions) that are combined (AND/OR) and may include placeholders for user attributes.
- Example rule for RLS:
Rule: {
name: "user_data_access",
condition: "tenant_id = :tenant_id AND (role = 'admin' OR user_id = :current_user_id)"
}
- The evaluator would replace :tenant_id and :current_user_id with the actual values.
b. Cache Design:
- Two levels of cache:
- Policy cache: keyed by tenant_id and user_roles (or a policy version). Value: the compiled filter (with placeholders replaced) for the user/tenant.
- Query result cache: keyed by (tenant_id, user_identifier, query_hash, policy_version). But note: the same query might produce different results for different users because of RLS. So we must include the policy version or the actual filter in the key.
Alternatively, we can avoid caching query results at this layer and rely on the database cache or an external cache that is already tenant-aware. However, if we do cache at this layer, we must be very careful.
c. Implementation:
Let's assume we have an interceptor that runs before the query is sent to the database.
Pseudocode for the interceptor:
function interceptQuery(originalQuery, tenantContext, userContext):
// tenantContext: { tenant_id, ... }
// userContext: { user_id, roles, attributes, ... }
// Step 1: Get policy filter
policyFilter = getPolicyFilter(tenantContext, userContext)
// Step 2: Apply the filter to the original query
// This could be done by modifying the WHERE clause, or by adding a condition to the JOIN, etc.
// We assume we have a way to transform the query (e.g., using an ORM hook or by building a new query string).
modifiedQuery = applyFilterToQuery(originalQuery, policyFilter)
return modifiedQuery
function getPolicyFilter(tenantContext, userContext):
cacheKey = generatePolicyCacheKey(tenantContext, userContext.roles)
cachedPolicy = policyCache.get(cacheKey)
if cachedPolicy:
return cachedPolicy
// Fetch policies from PolicyStore for this tenant and user's roles
policies = policyStore.getPolicies(tenantContext.tenant_id, userContext.roles)
// Evaluate the policies to produce a filter
// This might involve combining multiple conditions with AND/OR.
filter = evaluatePolicies(policies, tenantContext, userContext)
// Cache the filter for this tenant and user roles (note: if user attributes change, the cache might be stale. We can use a shorter TTL or invalidate on policy change.)
policyCache.set(cacheKey, filter, ttl=300) // 5 minutes?
return filter
function evaluatePolicies(policies, tenantContext, userContext):
// We assume policies are stored as strings that can be parsed and then filled with context.
// Example: policy.condition might be "tenant_id = {tenant_id} AND (role = '{role}' OR user_id = {user_id})"
// We replace the placeholders with actual values.
conditions = []
for policy in policies:
condition = policy.condition
// Replace placeholders. We can use a simple template replacement.
// But note: we must be cautious of SQL injection. The values should be properly escaped or parameterized.
// Alternatively, we can build the condition with parameters and then pass them separately.
// For simplicity, let's assume we are building a string and then parameterizing the query separately.
// Actually, we should not build raw SQL with string concatenation. Instead, we should generate a parameterized condition.
// We can have a function that returns a condition string and a list of parameters.
(conditionStr, params) = fillPlaceholders(condition, tenantContext, userContext)
conditions.append(conditionStr)
// Combine conditions with AND (or OR? depends on policy logic). We assume AND for simplicity.
combinedCondition = " AND ".join(conditions)
// But note: we also have to combine with the existing conditions in the query. We'll do that in applyFilterToQuery.
return (combinedCondition, params) // We return both the condition string and the parameters to avoid SQL injection.
However, note that the original query might already have parameters. We must merge the parameters.
Alternatively, we can design the policy to be a function that returns a condition and parameters, and then we add that to the query.
But let's think about the database: if the database supports RLS (like PostgreSQL), we might not need to modify the query at all. Instead, we set the session variables and let the database apply the RLS policies.
There are two approaches:
Approach 1: Modify the query by appending the condition.
Approach 2: Use database-native RLS (if supported) and set the session context (tenant_id, user_id, etc.) and let the database apply the policies.
Approach 2 is cleaner and more secure because the database handles the RLS and we don't risk messing up the query.
So let's adjust:
Instead of modifying the query, we set the database session context (if supported) and then run the query as is.
Steps for Approach 2:
- For each connection, set the session variables (e.g., SET app.tenant_id = '...', SET app.user_id = '...').
- The database has RLS policies defined that use these session variables.
Then, our engine becomes:
function interceptQuery(originalQuery, tenantContext, userContext):
// Set the session context in the database connection (if not already set for this request)
setSessionContext(tenantContext, userContext)
// Then just run the originalQuery, and the database will apply the RLS.
return originalQuery
But note: we still need to cache the policy? Actually, the policies are defined in the database and cached by the database. So we don't need to cache them in our app.
However, we might have dynamic policies that are not in the database? Then we might need to set the session context and also modify the query? Not necessarily.
Let's stick to the database RLS if possible.
But the requirement says "evaluating Row Level Security, tenancy filters, and caching". So we are building the engine, not necessarily the RLS in the database.
Given the complexity of modifying queries and the risk of errors, using database RLS is preferred if the database supports it.
However, if we are using a database that doesn't support RLS (like MySQL) or we have complex policies that are hard to express in RLS, then we have to modify the query.
So let's design for both:
We can have a strategy:
- If the database supports RLS (and we have defined the policies in the database), then we use session context.
- Else, we use query modification.
But note: the requirement says "architect a data access policy engine", so we are building the engine that can work with or without database RLS.
We can design the engine to be pluggable:
interface PolicyEnforcementStrategy {
enforce(tenantContext, userContext, query): query
}
Then we have:
class DatabaseRlsStrategy implements PolicyEnforcementStrategy {
enforce(tenantContext, userContext, query):
setSessionContext(tenantContext, userContext)
return query
}
class QueryModificationStrategy implements PolicyEnforcementStrategy {
enforce(tenantContext, userContext, query):
filter = getPolicyFilter(tenantContext, userContext)
return applyFilterToQuery(query, filter)
}
Then the engine can be configured to use one of these strategies.
But note: the tenancy filter is part of the RLS? Yes, we can include the tenant_id condition in the RLS policy.
So in the RLS policy, we would have:
CREATE POLICY tenant_isolation_policy ON table_name
USING (tenant_id = current_setting('app.tenant_id')::uuid);
And for user-specific:
CREATE POLICY user_data_policy ON table_name
USING (user_id = current_setting('app.user_id')::uuid OR current_setting('app.role') = 'admin');
Then our job is just to set the session variables.
However, if we have multiple tables and complex conditions, we might need to set multiple session variables and have multiple policies.
Alternatively, we can have a single policy that uses a function that evaluates based on session variables.
But let's assume we go with the session context approach.
Then our engine becomes very simple:
- For each request, extract tenant and user context.
- Set the session context (if not already set for this connection).
- Then run the query.
But what about caching?
We can cache the policy definitions (if we are generating them on the fly) but if we are using database RLS, the policies are in the database and cached by the database.
However, if we have a dynamic policy store (not in the database) then we need to translate that into RLS policies? That's complex.
Given the requirement of caching, we might want to cache the session context? No, that's per request.
Alternatively, we might want to cache the results of the query? But that is separate.
Let's break down:
The requirement: "caching" - it could mean caching of policy rules (to avoid fetching from a policy store) or caching of query results.
In the session context approach, we don't have a policy store in the app. The policies are in the database.
So if we are using database RLS, we don't need to cache policies in the app.
But if we are using query modification, then we do.
So to cover both, let's design:
- We have a PolicyStore that can be either the database (for RLS policies) or an external store (for dynamic policies).
- We have a PolicyEvaluator that evaluates the policies and produces a filter (for query modification) or a set of session variables (for RLS).
Actually, for the RLS strategy, we don't need a PolicyEvaluator because the policies are in the database. We just set the session variables and let the database do the rest.
So the engine can be:
class DataAccessPolicyEngine:
def __init__(self, strategy, policy_store=None):
self.strategy = strategy
self.policy_store = policy_store # only needed for query modification strategy
def enforce(self, tenant_context, user_context, query):
return self.strategy.enforce(tenant_context, user_context, query)
Then:
- DatabaseRlsStrategy:
def enforce(self, tenant_context, user_context, query):
self.set_session_context(tenant_context, user_context)
return query
- QueryModificationStrategy:
def enforce(self, tenant_context, user_context, query):
policy_filter = self.get_policy_filter(tenant_context, user_context)
return self.apply_filter(query, policy_filter)
And the get_policy_filter uses the policy_store and caches the result.
But note: the policy_store might be the same as the database? Then we are fetching policies from the same database we are going to query? That's a circular dependency? Not necessarily, but we must be cautious of recursive queries.
Alternatively, we can have a separate database for policy store? Or we can have the policies in a configuration that is loaded at startup.
Given the complexity, let's assume:
- For the RLS strategy, we don't use the policy_store in the app. The policies are in the database and we just set the context.
- For the query modification strategy, we use the policy_store (which could be the same database or a different one) to get the policies and then cache them.
But wait: the requirement says "caching". So we want to cache the policies in the app for the query modification strategy.
So:
In the QueryModificationStrategy, we have:
class QueryModificationStrategy:
def __init__(self, policy_store, policy_cache_ttl=300):
self.policy_store = policy_store
self.policy_cache = {} # or use a proper cache like Redis
self.policy_cache_ttl = policy_cache_ttl
def get_policy_filter(self, tenant_context, user_context):
cache_key = f"{tenant_context.tenant_id}:{':'.join(sorted(user_context.roles))}"
if cache_key in self.policy_cache:
return self.policy_cache[cache_key]
policies = self.policy_store.get_policies(tenant_context.tenant_id, user_context.roles)
filter = self.evaluate_policies(policies, tenant_context, user_context)
self.policy_cache[cache_key] = filter
return filter
But note: user_context might have attributes that are not just roles. So we need to include more in the cache key? Or we can have a more fine-grained cache.
Alternatively, we can cache the policy rules (the raw policies) and then evaluate them for each request? But evaluation might be cheap.
But if the policies are complex, we might want to cache the evaluated filter (which is a string and parameters) for a given set of roles and tenant.
However, if the user has attributes that are not in the roles (like user_id, department, etc.) then the filter might change per user.
So we have two options:
1. Cache the policy rules (raw) and then evaluate them for each request (with the user attributes). This is safe but might be slower if evaluation is heavy.
2. Cache the evaluated filter per user? That would be a lot of cache entries.
Alternatively, we can design the policies to be role-based and then the only per-user variable is the user_id (or similar). Then we can have:
policy.condition: "tenant_id = :tenant_id AND (role = 'admin' OR user_id = :user_id)"
Then we can cache the policy string and then replace :tenant_id and :user_id for each request. That is cheap.
So let's assume:
- Policies are stored as strings with placeholders.
- We cache the policy string for a given tenant and role set (without the user-specific placeholders? But note: the condition might have :user_id and :tenant_id, which are per user and per tenant).
Actually, the tenant_id is per tenant, so for a given tenant and set of roles, the condition string is the same, but we have to replace :tenant_id and :user_id.
So we can cache the condition string and then do the replacement at request time.
Then:
cache_key = f"{tenant_id}:{':'.join(roles)}"
condition_template = cache.get(cache_key)
if not condition_template:
condition_template = self.policy_store.get_condition_template(tenant_id, roles)
cache.set(cache_key, condition_template)
Then we replace the placeholders in condition_template with the actual values (tenant_id and user_id) and then apply to query.
But note: the condition might have more placeholders (like :department, etc.). Then we need to pass all user attributes.
So the evaluation function might be:
def evaluate_policies(policies, tenant_context, user_context):
conditions = []
parameters = {}
for policy in policies:
condition = policy.condition
# Replace placeholders in condition with values from tenant_context and user_context
# We assume placeholders are in the form :placeholder
# We can use a template engine or simple string replacement, but we must also build a parameter list for the query.
# Example: condition = "tenant_id = :tenant_id AND user_id = :user_id"
# We replace :tenant_id with the value, but we want to parameterize the query to avoid SQL injection.
# Instead, we should return the condition with named placeholders and a dictionary of parameters.
# But note: the original query might have its own parameters. We are going to merge.
# We can do:
# condition_str = condition
# for key, value in {**tenant_context.__dict__, **user_context.__dict__}.items():
# condition_str = condition_str.replace(f":{key}", str(value))
# But that is dangerous because we are building a string. We want to use parameterized queries.
# Alternatively, we can return a condition string with placeholders and a parameters dict, and then when we apply to the query, we merge the parameters.
# However, the query might already have parameters. We must merge without conflict.
# Alternatively, we can avoid named placeholders and use positional? That might be easier.
# Given the complexity, let's assume we are building a condition string and then we will use the database driver's parameterization for the entire query.
# But if we are building the condition string by replacing with values, we risk SQL injection if the values are not escaped.
# So we must escape the values? Or use the database driver's parameterization for the condition too.
# We can do:
# condition_str = "tenant_id = %s AND user_id = %s"
# params = [tenant_id, user_id]
# But then we have to merge with the original query's parameters.
# Since we are modifying the query, we are essentially building a new query. We can:
# 1. Parse the original query to get the condition and parameters? That's complex.
# 2. Alternatively, we can use an ORM that handles this.
# Since this is an architecture, we can assume we have a way to safely build the query.
# Let's assume we are using a query builder that accepts conditions and parameters separately.
# For simplicity, let's assume we are using an ORM like SQLAlchemy, and we can add filters to the query.
# Then we don't need to build strings. We can have:
# from sqlalchemy import and_
# conditions = []
# for policy in policies:
# condition = evaluate_policy_to_sqlalchemy_condition(policy, tenant_context, user_context)
# conditions.append(condition)
# combined_condition = and_(*conditions)
# query = query.filter(combined_condition)
# This way, the ORM handles the parameters.
# So we need to convert the policy condition (which might be a string) into a SQLAlchemy condition.
# But if the policy condition is a string, we can use `text` and then parameters.
# Alternatively, we can define policies in a structured format (like JSON) that can be converted to ORM conditions.
# Given the time, let's assume we have a function that takes a policy string and context and returns a SQLAlchemy condition.
# But note: the requirement is to architect, not implement. So we can leave the implementation of the evaluator abstract.
# So in the engine, we have:
# filter_condition = policy_evaluator.evaluate(tenant_context, user_context)
# and then we apply that condition to the query.
# The policy_evaluator can be implemented in various ways.
# Given the above, let's define:
# class PolicyEvaluator:
# def evaluate(self, tenant_context, user_context) -> Condition:
# pass
# And then the QueryModificationStrategy uses the PolicyEvaluator.
So to summarize:
We have:
- DataAccessPolicyEngine with a strategy (DatabaseRlsStrategy or QueryModificationStrategy).
- For DatabaseRlsStrategy, we set session variables and run the query.
- For QueryModificationStrategy, we use a PolicyEvaluator to get a condition (and parameters) and then apply to the query.
And for QueryModificationStrategy, we cache the policy rules (or the evaluated condition template) per tenant and roles.
But note: the user_context might have attributes that are not in the roles. So we might need to include more in the cache key? Or we can cache the policy rules and then evaluate with the user attributes.
Let's decide:
We cache the policy rules (the raw condition templates) for a given tenant and set of roles. Then for each request, we evaluate the condition templates with the user attributes.
This way, if the user attributes change (but roles remain the same), we still get the correct condition.
So:
cache_key = (tenant_id, frozenset(roles))
condition_templates = cache.get(cache_key)
if not condition_templates:
condition_templates = policy_store.get_condition_templates(tenant_id, roles)
cache.set(cache_key, condition_templates)
Then for the request, we evaluate condition_templates with tenant_context and user_context to get the actual condition.
This evaluation must be done for each request because user_context (like user_id) changes per request.
But if the condition_templates are just strings with placeholders, then replacing placeholders is cheap.
So we can do:
condition = condition_template.replace(":tenant_id", tenant_id).replace(":user_id", user_id) ... but that is not safe for SQL injection.
So we must use parameterization.
Therefore, we return the condition template (with named placeholders) and a parameters dict, and then we merge with the original query's parameters.
But again, if we are using an ORM, we can build the condition with the ORM's expression language.
Given the complexity of the query building, it might be better to let the ORM handle the condition building if we have a structured policy format.
Alternatively, we can define policies as expressions in the ORM's language? That would be powerful but then the policy store would have to store ORM-specific expressions.
Given the time, I propose:
We design the engine to be flexible and let the implementation of the PolicyEvaluator decide how to evaluate.
We can have:
interface PolicyEvaluator:
evaluate(tenant_context, user_context) -> (condition, parameters)
And then the QueryModificationStrategy uses that to modify the query.
But note: the condition must be in a form that can be added to the query. If we are using raw SQL, we might return a string and a dict of parameters, and then we have to merge with the original query.
If we are using an ORM, we return an ORM condition object.
So the engine must be aware of the query type? Not necessarily. We can have adapters for different query builders.
This is getting complex.
Let's simplify:
We assume we are using an ORM (like SQLAlchemy) and we can modify the query by adding a filter condition.
Then:
class QueryModificationStrategy:
def __init__(self, policy_store, policy_cache_ttl=300):
self.policy_store = policy_store
self.policy_cache = {}
self.policy_cache_ttl = policy_cache_ttl
def enforce(self, tenant_context, user_context, query):
# query is an ORM query object (e.g., SQLAlchemy Query)
condition = self.get_condition(tenant_context, user_context)
return query.filter(condition)
def get_condition(self, tenant_context, user_context):
cache_key = (tenant_context.tenant_id, frozenset(user_context.roles))
if cache_key in self.policy_cache:
condition_template = self.policy_cache[cache_key]
else:
condition_template = self.policy_store.get_condition_template(tenant_context.tenant_id, user_context.roles)
self.policy_cache[cache_key] = condition_template
# Now evaluate the condition_template with the user_context
# condition_template is a string with placeholders like :tenant_id, :user_id, etc.
# We want to build a SQLAlchemy condition. We can use `text` and then parameters, but then we have to merge parameters.
# Alternatively, we can parse the condition_template and build the condition using SQLAlchemy expressions.
# Given the time, we assume we have a function that does that.
condition = evaluate_condition_template(condition_template, tenant_context, user_context)
return condition
But note: the condition_template might be a complex expression with AND/OR, etc. We need a parser.
Alternatively, we can store the policies as a JSON structure that can be converted to SQLAlchemy conditions.
Example:
policy = {
"operator": "and",
"conditions": [
{"column": "tenant_id", "operator": "=", "value": ":tenant_id"},
{
"operator": "or",
"conditions": [
{"column": "role", "operator": "=", "value": "'admin'"},
{"column": "user_id", "operator": "=", "value": ":user_id"}
]
}
]
}
Then we can convert this to a SQLAlchemy condition by recursively building.
But then the policy store must store in this format.
Given the open-endedness, we can leave the implementation of the PolicyEvaluator abstract.
However, for the purpose of this architecture, we can define:
The PolicyStore returns a list of policies in a structured format (or string format) that the PolicyEvaluator can evaluate.
The PolicyEvaluator is responsible for converting the policies into a condition that can be applied to the query.
And the QueryModificationStrategy uses the PolicyEvaluator.
So:
class QueryModificationStrategy:
def __init__(self, policy_store, policy_evaluator, policy_cache_ttl=300):
self.policy_store = policy_store
self.policy_evaluator = policy_evaluator
self.policy_cache = {}
self.policy_cache_ttl = policy_cache_ttl
def enforce(self, tenant_context, user_context, query):
condition = self.get_condition(tenant_context, user_context)
return query.filter(condition)
def get_condition(self, tenant_context, user_context):
cache_key = (tenant_context.tenant_id, frozenset(user_context.roles))
if cache_key in self.policy_cache:
policies = self.policy_cache[cache_key]
else:
policies = self.policy_store.get_policies(tenant_context.tenant_id, user_context.roles)
self.policy_cache[cache_key] = policies
return self.policy_evaluator.evaluate(policies, tenant_context, user_context)
Now, the DatabaseRlsStrategy:
class DatabaseRlsStrategy:
def __init__(self, session_setter):
self.session_setter = session_setter # function that sets the session context
def enforce(self, tenant_context, user_context, query):
self.session_setter.set(tenant_context, user_context)
return query
The session_setter might be a class that knows how to set the session variables for the current database connection.
Now, the engine:
class DataAccessPolicyEngine:
def __init__(self, strategy):
self.strategy = strategy
def enforce(self, tenant_context, user_context, query):
return self.strategy.enforce(tenant_context, user_context, query)
Then, in the application, we would do:
engine = DataAccessPolicyEngine(strategy)
query = ... # original query
query = engine.enforce(tenant_context, user_context, query)
results = query.execute()
For caching query results:
We can have a separate cache for query results. The cache key should be:
- The SQL string (or its hash) after the policy has been applied? But note: the policy is applied by the engine, so the query that is executed is already filtered.
However, if we are using the RLS strategy, the query string is the same, but the results are different because of the session context. So we cannot cache by query string alone.
We must include the tenant and user (or the session context) in the cache key.
So for query result caching, we can do:
cache_key = f"{tenant_id}:{user_id}:{query_hash}"
But note: the user_id might be the same for multiple requests? Then we can cache per user.
But also, the policy might change, so we need to include a policy version? Or we can set a TTL.
Alternatively, we can have the engine invalidate the query cache when policies change.
But query caching might be handled at a different layer (like a Redis cache of query results). The engine might not be responsible for that.
The requirement says "caching", so we must consider it. But the engine might not be the one caching the query results. It might be that the database cache or an external cache is used.
However, the engine can be responsible for cache invalidation when policies change.
So:
- We have a QueryResultCache that caches the results of queries, with a key that includes the tenant, user, and the query (with the policy applied?).
But wait: if we are using RLS, the same query string for the same tenant but different users returns different results. So the cache key must include the user.
And if the policy changes for that user, we must invalidate.
How do we know when a policy changes? We can have the PolicyStore emit events when policies are updated, and then the engine (or the cache) can invalidate.
Alternatively, we can include a policy version in the cache key. The policy version can be stored in the PolicyStore and incremented on change.
Then:
cache_key = f"{tenant_id}:{user_id}:{query_hash}:{policy_version}"
The policy_version can be per tenant? Or per user? We can have a version for the tenant's policies.
Then when we fetch policies, we get the version and include it in the cache key for query results.
But note: the query result cache is at the query level, and the policy is applied by the engine. The engine doesn't know about the query result cache.
So we need to coordinate.
Alternatively, we can have the engine provide a cache key for the query that includes the policy context.
Then the application can use that key to cache the query results.
So:
The engine, when enforcing, can return not only the modified query but also a cache key (or cache context) that the application can use for caching.
But that might be too invasive.
Given the complexity, and since the requirement is to "architect", we can note that:
- For RLS strategy: the cache key for query results must include the tenant_id and user_id (or session identifier) and the query string (without the session context because the session context is set separately). But note: the same query string for the same user will always return the same result until the data or policy changes.
- For query modification strategy: the cache key must include the tenant_id, user_id, and the original query string (because the modified query depends on the policy which depends on the user's roles and attributes). But if we cache the policy per tenant and roles, then for the same tenant and roles and same original query, the modified query is the same. Then we can cache by (tenant_id, roles, original_query_hash). But note: the user_id might be different for the same roles? Then the condition might be different if the policy uses :user_id.
So we must include the user_id in the cache key for query results if the policy uses user_id.
Therefore, the safe way is to include the user_id in the cache key for query results.
And for policy changes, we can have a TTL on the query result cache, or we can have a way to invalidate by tenant.
Given the complexity, we might decide that query result caching is out of scope for the engine and is handled by the application.
But the requirement says "caching", so we must at least design for policy caching.
So let's focus on policy caching and leave query result caching as an exercise.
Summary:
We have:
- DataAccessPolicyEngine with a strategy.
- Two strategies: DatabaseRlsStrategy and QueryModificationStrategy.
- For QueryModificationStrategy, we cache policy templates (condition templates) per tenant and roles.
- For each request, we evaluate the condition templates with the user attributes to get the condition and then apply to the query.
We also consider that the policy store might be separate and we need to fetch policies.
We also consider cache invalidation: when policies change, we invalidate the policy cache for the affected tenant and roles.
We can have a policy version or a last_updated timestamp in the policy store, and then include that in the cache key.
Alternatively, we can use a time-based TTL.
For real-time invalidation, we can have a message queue that notifies the engine of policy changes.
Given the time, we'll leave cache invalidation as an advanced topic.
This is a high-level architecture. We can adjust based on the actual database and requirements.
Let's write the code structure:
We'll define:
class TenantContext:
tenant_id: str
class UserContext:
user_id: str
roles: List[str]
attributes: Dict[str, any]
class PolicyStore(ABC):
@abstractmethod
def get_condition_templates(self, tenant_id: str, roles: List[str]) -> List[str]:
# returns a list of condition templates (strings) for the given tenant and roles.
pass
class PolicyEvaluator(ABC):
@abstractmethod
def evaluate(self, condition_templates: List[str], tenant_context: TenantContext, user_context: UserContext) -> Condition:
# returns a condition (ORM condition) that can be applied to the query.
pass
class QueryModificationStrategy:
def __init__(self, policy_store: PolicyStore, policy_evaluator: PolicyEvaluator, policy_cache_ttl: int = 300):
self.policy_store = policy_store
self.policy_evaluator = policy_evaluator
self.policy_cache = {}
self.policy_cache_ttl = policy_cache_ttl
def enforce(self, tenant_context: TenantContext, user_context: UserContext, query):
condition = self.get_condition(tenant_context, user_context)
return query.filter(condition)
def get_condition(self, tenant_context: TenantContext, user_context: UserContext):
cache_key = (tenant_context.tenant_id, frozenset(user_context.roles))
if cache_key in self.policy_cache:
condition_templates = self.policy_cache[cache_key]
else:
condition_templates = self.policy_store.get_condition_templates(tenant_context.tenant_id, user_context.roles)
self.policy_cache[cache_key] = condition_templates
return self.policy_evaluator.evaluate(condition_templates, tenant_context, user_context)
class DatabaseRlsStrategy:
def __init__(self, session_setter):
self.session_setter = session_setter
def enforce(self, tenant_context: TenantContext, user_context: UserContext, query):
self.session_setter.set(tenant_context, user_context)
return query
class SessionSetter(ABC):
@abstractmethod
def set(self, tenant_context: TenantContext, user_context: UserContext):
# set the session variables in the current database connection
pass
class DataAccessPolicyEngine:
def __init__(self, strategy):
self.strategy = strategy
def enforce(self, tenant_context: TenantContext, user_context: UserContext, query):
return self.strategy.enforce(tenant_context, user_context, query)
Then, in the application, we would:
engine = DataAccessPolicyEngine(strategy)
query = session.query(MyModel) # SQLAlchemy example
query = engine.enforce(tenant_context, user_context, query)
results = query.all()
For the DatabaseRlsStrategy, we must set the session context before executing the query. We can do that in the strategy.
But note: the session_setter must be called for each request? And we must reset after? We can set the context at the beginning of the request and reset at the end? Or set per query?
If we set per query, then for multiple queries in the same request, we set the context multiple times? That might be okay.
Alternatively, we can set the context once per connection and then reuse the connection? But in a web app, we might use connection pooling.
So we must set the context for each connection we use.
This can be done by an event listener in SQLAlchemy, for example.
But in our strategy, we set the context and then run the query. That should be okay.
For the QueryModificationStrategy, we modify the query and then run it.
This is a basic architecture. We can extend it as needed.
Let me know if you have any questions or need more details.</think>