Skip to main content
← CoursesAI Engineering with PythonModule 3 · RAG (Retrieval-Augmented Generation)Metadata filteringwrite38 / 101
💬 Discuss🧪 Playground+75 XP
Task
📝 **Question:** **Write the function** \`safe_search(query, filter)\` that protects a multi-tenant RAG against the #1 leak class — a missing \`tenant_id\` filter. Rules: - If \`filter\` isn't a dict → raise \`ValueError("filter must be a dict")\`. - If \`tenant_id\` is absent OR empty/falsy → raise \`ValueError("SECURITY: tenant_id filter is mandatory and non-empty")\`. - Otherwise return \`f"OK | {query!r} scoped to tenant {filter['tenant_id']!r}"\`. Then run it against four request shapes (two real, two unsafe): \`\`\` OK | 'refund policy' scoped to tenant 'acme' BLOCKED | 'salary table' | SECURITY: tenant_id filter is mandatory and non-empty OK | 'order history' scoped to tenant 'globex' BLOCKED | 'API keys' | SECURITY: tenant_id filter is mandatory and non-empty \`\`\` The empty-string case is the sneaky one — \`"tenant_id" in filter\` would pass, but \`filter.get("tenant_id")\` returns falsy. **Always check truthy, never just key-presence.** A misconfigured frontend defaulting \`tenant_id\` to \`""\` has caused real-world cross-tenant leaks. 📋 Pick the right answer. 💡 **Hint:** Re-read the theory above if unsure.

Keep going

✏️ Write your code here
🐍
Loading Python...
First visit only — ~5-10s. Stays cached afterward.
📊 Result
Press Run to see result...
📣 Help someone learn PythonShare this lesson with a friend — the first 15 are free, no signup.Tweet

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…