The exercise
Implement authorization filtering before ranking retrieved records. Prove with tests that cross-tenant and unauthorized documents never enter the model context.
- Before looking at the solution
Write down the invariant the code must preserve and one failure case that could violate it.
- Run the reference implementation
Download the single-file lab and run
python tenant-safe-retrieval.py. It uses Python's built-inunittestand needs no network or API key. - Read each test as a requirement
Identify what the test proves, what it does not prove, and which production boundary remains trusted.
- Modify one condition
Add a test for cancellation, concurrent requests, revocation, or a corrupted evaluation case. Explain how the design changes.
Download runnable lab and tests ↗
Reference solution
Show the complete solution and tests
def retrieve_for(principal: dict, documents: list[dict], query: str) -> list[dict]:
tenant = principal["tenant_id"]
roles = set(principal.get("roles", []))
allowed = [d for d in documents if d["tenant_id"] == tenant and set(d["required_roles"]).issubset(roles)]
terms = set(query.lower().split())
return sorted(allowed, key=lambda d: len(terms & set(d["text"].lower().split())), reverse=True)
if __name__ == "__main__":
import unittest
class RetrievalTests(unittest.TestCase):
def setUp(self):
self.docs = [
{"id":"a", "tenant_id":"acme", "required_roles":[], "text":"refund policy"},
{"id":"b", "tenant_id":"other", "required_roles":[], "text":"refund policy"},
{"id":"c", "tenant_id":"acme", "required_roles":["finance"], "text":"refund limits"},
]
def test_isolates_tenant(self):
got = retrieve_for({"tenant_id":"acme"}, self.docs, "refund policy")
self.assertEqual({d["id"] for d in got}, {"a"})
def test_enforces_roles(self):
got = retrieve_for({"tenant_id":"acme", "roles":["finance"]}, self.docs, "refund")
self.assertEqual({d["id"] for d in got}, {"a", "c"})
def test_ranks_matching_terms(self):
got = retrieve_for({"tenant_id":"acme", "roles":["finance"]}, self.docs, "refund policy")
self.assertEqual(got[0]["id"], "a")
unittest.main()The mental model
Authorization is a prerequisite to retrieval, not a ranking preference. The model should only receive records already authorized for the authenticated principal.
Limits and production extensions
The example uses trusted principal data and simple term overlap. Production authorization must use authoritative policy, account for revocation and cache invalidation, and avoid exposing denied records in logs or debug output.
Explain it in an interview
Follow-up prompts
- What race or failure does this example still permit?
- How would you make the result observable without logging secrets?
- Which property belongs in a unit test, integration test, or production alert?