MediumRetrievalPython 3
Document Permission Filter
Filter retrieval chunks by public, tenant, group, and private permissions before ranking.
30m3 sample tests12 hidden tests
Filter retrieved chunks by user permissions before ranking them.
Requirements
- Define
filter_chunks(chunks, user, k). - Each chunk has
id,score,visibility, and optionaltenant,groups,owner. visibility == "public"is visible to everyone.visibility == "tenant"is visible when chunk tenant matches user tenant.visibility == "group"is visible when tenant matches and at least one group overlaps.visibility == "private"is visible only to the owner.- Missing tenant or owner identities never authorize a protected chunk.
- Unknown or missing
visibilityis denied: fail closed by omitting the chunk instead of raising. - Return selected chunk IDs sorted by score descending, then ID alphabetically.
- Return at most
kIDs. - If
k <= 0, return an empty list.
Example
python
chunks = [{"id": "a", "score": 1, "visibility": "public"}]
assert filter_chunks(chunks, {"id": "u", "tenant": "t", "groups": []}, 3) == ["a"]
protected = [{"id": "hidden", "score": 9, "visibility": "tenant"}]
assert filter_chunks(protected, {"id": "u", "tenant": None, "groups": []}, 3) == []Constraints
- Never return unauthorized chunks.
- Don't mutate input chunks.
- Missing or null group lists count as empty.
- Chunk IDs are unique, case-sensitive ASCII strings; scores are finite numbers and
kis an integer. Present tenant, owner, user and group identities are nonempty, case-sensitive strings. Group fields contain lists of those strings,None, or are absent. - User IDs are globally unique in this exercise. Private visibility checks ownership alone, even if tenant metadata differs; tenant and group visibility require the tenant check described above.
- Filter all candidates before applying the result limit. If the highest-scoring chunk is denied, a lower-scoring authorized chunk can still fill the slot.
The function receives trusted identity and permission metadata. In a real service, derive the user from authentication and obtain ACLs from an authoritative source. OWASP's authorization guidance recommends denying access by default and checking permissions on every request. This exercise models the selection step, not authentication or retrieval of protected text.
Editor