Build a Rule-Based Access Control Evaluator with Expression Parsing
Data Structure DesignModel answerLast updated
Design and implement an access decision engine that evaluates ordered security rules with conditions expressed in a custom expression language.
You're building an access control system for authentication requests. The system receives login attempts as dictionaries of attributes and must evaluate them against a sequence of security rules.
def decide(attempt: dict, policies: list[tuple[str, str]]) -> str:
...
Inputs:
attempt: dictionary mapping attribute names to values (strings or booleans)policies: ordered list of(verdict, condition)tuples where verdict is"allow"or"deny"
Behavior:
- Evaluate rules in order; the first matching condition determines the outcome
- If no rule matches, default to
"allow" - All conditions are guaranteed to be syntactically correct
Expression Language Rules:
Literals and Identifiers:
- String constants use single quotes:
'US' - Escape sequences:
\'for quote,\\for backslash - Identifiers match
[A-Za-z_][A-Za-z0-9_]*and reference attempt attributes - Attributes absent from
attemptcause any expression using them to evaluate false
Phase 1: Equality Comparisons
Support operand = operand where operands are attributes or string literals in any order.
attempt = {"country": "US", "client": "mobile"}
policies = [
("deny", "country = 'CN'"),
("allow", "'mobile' = client"),
("deny", "client = 'mobile'")
]
decide(attempt, policies) # "allow" - second rule matches first
Phase 2: Boolean Logic
Attributes can be boolean. A standalone identifier evaluates true when its value is exactly True. Add and / or operators (lowercase keywords), where and has higher precedence.
attempt = {"country": "US", "suspicious": True, "verified": False}
decide(attempt, [
("deny", "suspicious and verified or country = 'IR'"),
("deny", "country = 'US' and suspicious")
]) # "deny" - second rule matches
The first condition parses as (suspicious and verified) or country = 'IR' and evaluates false.
Phase 3: Complete Expression Support
Add parentheses for grouping, prefix not operator (higher precedence than and), and != for inequality. Inequality also returns false when either operand is missing.
attempt = {"country": "FR", "suspicious": True, "verified": False, "client": "web"}
decide(attempt, [
("deny", "suspicious and not (verified or client = 'kiosk')"),
("allow", "missing_field"),
]) # "deny"
decide({"country": "FR", "client": "it\'s"}, [
("deny", r"client = 'it\'s' and country != 'DE'")
]) # "deny"
Performance Consideration: Expect thousands of rules checked against many requests. Consider what preprocessing can be done once per rule.
Hints
Hint 1
Separate tokenization from parsing from evaluation - only one of these depends on the request data
Hint 2
Handle missing attributes with a sentinel value that makes comparisons return false consistently
Hint 3
Use recursive descent parsing with one function per precedence level to handle operator priority naturally
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution separates concerns into three stages: tokenization, parsing, and evaluation. Since rule conditions are static, we parse each once and cache the result, evaluating the pre-built structure against each request.
Tokenization
Build a lexer that recognizes:
- String literals (everything between single quotes, handling escapes)
- Operators:
=,!=,(,) - Keywords:
and,or,not - Identifiers (attribute names)
Use a single regex with named groups to match all token types. Process escape sequences during tokenization so the parser sees clean strings.
TOKEN_RE = re.compile(r"""
\s*(?:
(?P<str>'(?:[^'\\]|\\.)*')
| (?P<op>!=|=|\(|\))
| (?P<word>[A-Za-z_][A-Za-z0-9_]*)
)""", re.X)
Parsing: Recursive Descent
Model the grammar with precedence levels (lowest to highest):
orexpressionsandexpressionsnotprefix- Primary: parenthesized expressions, comparisons, or flags
- Operands: identifiers and string literals
Each precedence level is a function that calls the next higher level. This naturally encodes precedence without extra logic.
or_expr := and_expr ("or" and_expr)*
and_expr := unary ("and" unary)*
unary := "not" unary | primary
primary := "(" or_expr ")" | operand (("=" | "!=") operand)?
operand := IDENT | STRING
Build an abstract syntax tree (AST) as nested tuples: ("and", [left, right]), ("=", left_operand, right_operand), etc.
Missing Attributes
Use a sentinel object MISSING = object() as the result when accessing absent attributes. Any comparison involving MISSING returns False, including !=. This correctly implements "missing attributes fail all checks" semantics.
For not, be careful: not country = 'FR' means "it's not true that country equals FR" and correctly returns True when country is missing.
Evaluation
Walk the AST recursively:
and/or: short-circuit evaluationnot: boolean negation (but comparison results are already correct for missing values)flag: true only if the valueis True(not just truthy)=/!=: compare values, returnFalseif either isMISSING
Caching
Use functools.lru_cache on the compile function. Parse each distinct condition string once, reuse the AST for all requests.
Code
import re
from functools import lru_cache
TOKEN_RE = re.compile(r"""
\s*(?:
(?P<str>'(?:[^'\\]|\\.)*')
| (?P<op>!=|=|\(|\))
| (?P<word>[A-Za-z_][A-Za-z0-9_]*)
)""", re.X)
KEYWORDS = {"and", "or", "not"}
MISSING = object()
def tokenize(src):
tokens, pos = [], 0
src = src.rstrip()
while pos < len(src):
m = TOKEN_RE.match(src, pos)
if not m or m.end() == pos:
raise SyntaxError(f"bad input at {pos}")
pos = m.end()
if m.group("str"):
raw = m.group("str")[1:-1]
tokens.append(("STR", re.sub(r"\\(.)", r"\1", raw)))
elif m.group("op"):
tokens.append(("OP", m.group("op")))
else:
w = m.group("word")
tokens.append(("KW", w) if w in KEYWORDS else ("ID", w))
return tokens
class Parser:
def __init__(self, tokens):
self.tokens, self.pos = tokens, 0
def current(self):
return self.tokens[self.pos] if self.pos < len(self.tokens) else (None, None)
def consume(self, kind=None, value=None):
tok = self.current()
if (kind and tok[0] != kind) or (value and tok[1] != value):
raise SyntaxError(f"expected {value or kind}")
self.pos += 1
return tok
def parse(self):
ast = self.or_expr()
if self.pos != len(self.tokens):
raise SyntaxError("unexpected tokens at end")
return ast
def or_expr(self):
terms = [self.and_expr()]
while self.current() == ("KW", "or"):
self.consume()
terms.append(self.and_expr())
return terms[0] if len(terms) == 1 else ("or", terms)
def and_expr(self):
terms = [self.unary()]
while self.current() == ("KW", "and"):
self.consume()
terms.append(self.unary())
return terms[0] if len(terms) == 1 else ("and", terms)
def unary(self):
if self.current() == ("KW", "not"):
self.consume()
return ("not", self.unary())
return self.primary()
def primary(self):
if self.current() == ("OP", "("):
self.consume()
expr = self.or_expr()
self.consume("OP", ")")
return expr
left = self.operand()
if self.current() in (("OP", "="), ("OP", "!=")):
op = self.consume()[1]
return (op, left, self.operand())
if left[0] != "id":
raise SyntaxError("literal without comparison")
return ("flag", left)
def operand(self):
kind, val = self.current()
if kind == "ID":
self.consume()
return ("id", val)
if kind == "STR":
self.consume()
return ("lit", val)
raise SyntaxError("expected operand")
@lru_cache(maxsize=None)
def compile_condition(src):
return Parser(tokenize(src)).parse()
def get_value(operand, attempt):
kind, val = operand
return val if kind == "lit" else attempt.get(val, MISSING)
def evaluate(ast, attempt):
op = ast[0]
if op == "or":
return any(evaluate(child, attempt) for child in ast[1])
if op == "and":
return all(evaluate(child, attempt) for child in ast[1])
if op == "not":
return not evaluate(ast[1], attempt)
if op == "flag":
return get_value(ast[1], attempt) is True
left, right = get_value(ast[1], attempt), get_value(ast[2], attempt)
if left is MISSING or right is MISSING:
return False
return left == right if op == "=" else left != right
def decide(attempt, policies):
for verdict, condition in policies:
if evaluate(compile_condition(condition), attempt):
return verdict
return "allow"
Complexity
Time: Tokenizing and parsing are O(n) where n is condition length, done once per unique condition. Evaluation is O(m) where m is AST node count, with short-circuit optimization for boolean operators.
Space: O(n) for tokens, O(m) for AST nodes.
For k policies checked before a match, total evaluation cost is O(k × m). Caching ensures parsing doesn't repeat.
Common Mistakes
- String splitting instead of tokenizing: Breaks when literals contain operator keywords like
'and'or'or' - Wrong precedence: Forgetting
andbinds tighter thanor, or thatnotbinds tightest - Missing attribute handling: Treating missing as empty string, or making
!=return true for missing values - Flag evaluation: Accepting any truthy value instead of requiring exactly
True - Not caching: Re-parsing conditions for every request causes unnecessary overhead
- Comparison symmetry: Hard-coding which operand is the attribute vs literal instead of detecting during tokenization