Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesAI Engineering with PythonModule 3 · RAG (Retrieval-Augmented Generation)Metadata filteringwrite39 / 105
+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.
✏️ Write your code here
🐍
Loading Python...
One-time download (~1 MB). Then it runs instantly.
📊 Result
Press Run to see result...

💬 Discussion

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