PythiloLesson 1 of 12 · progress kept in this browser

Practice in Lab: Filter retrieval permissions before selecting context →

Filter retrieval permissions before selecting context

Retrieved documents are data, and their contents cannot grant the caller access to other tenants. Apply authorization from trusted metadata before ranking or returning context. Filtering only after taking a global top-k can both expose content in logs and starve an authorized user's results.

The exercise performs a real permission-aware selection over a local document collection. Scores are supplied by a retriever so the authorization policy can be tested independently of embedding quality. A production search index must enforce the same tenant and ACL rules at every retrieval, reranking and cache boundary.

docs=[{"id":"a","tenant":"one","score":.2},{"id":"b","tenant":"two","score":.9}]
print([d["id"] for d in docs if d["tenant"]=="one"])
Your task

Implement authorized_topk(docs,tenant,roles,k). Each doc has id,tenant,roles (empty means tenant-public),score,text. Keep same-tenant docs whose roles intersect caller roles or are empty; rank by descending score then id; return at most k ids. Reject k<0. Do not mutate docs.