[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792ATHGGRPZXHADXAHV0DRV":3,"skill-same:01M792ATHGGRPZXHADXAHV0DRV":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":6,"ownerHtmlUrl":44,"ownerBlogUrl":45,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M792ATHGGRPZXHADXAHV0DRV","langchain-enterprise-rbac",null,"Enforce tenant isolation and role-based access across LangChain 1.0 chains and\nLangGraph 1.0 agents — per-request retriever construction, tenant-scoped rate\nlimits, role-scoped tool allowlists, and structured audit logs. Use when\nbuilding multi-tenant saas, passing soc2 review, or debugging cross-tenant\nleak. Trigger with \"langchain multi-tenant\", \"langchain tenant isolation\",\n\"langchain rbac\", \"langchain row-level security\", \"langchain audit log\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-enterprise-rbac\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-enterprise-rbac\ndescription: |\n  Enforce tenant isolation and role-based access across LangChain 1.0 chains and\n  LangGraph 1.0 agents — per-request retriever construction, tenant-scoped rate\n  limits, role-scoped tool allowlists, and structured audit logs. Use when\n  building multi-tenant saas, passing soc2 review, or debugging cross-tenant\n  leak. Trigger with \"langchain multi-tenant\", \"langchain tenant isolation\",\n  \"langchain rbac\", \"langchain row-level security\", \"langchain audit log\".\nallowed-tools: Read, Write, Edit, Bash(python:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, multi-tenant, rbac, enterprise, security]\ncompatible-with: claude-code, codex\n---\n\n# LangChain Enterprise RBAC (Python)\n\n## Overview\n\nA B2B SaaS team shipped their first RAG feature for two tenants. The factory\ncode looked innocent: build `PineconeVectorStore` once at module import with\n`namespace=\"acme-corp\"` (the first tenant), convert it to a retriever, store\nit in a module global, reuse on every request. Six weeks later tenant \"Initech\"\nwent live. Their first search returned three documents from Acme Corp.\n\nThe singleton retriever had captured the Acme namespace at process start.\n`RunnableConfig.configurable[\"tenant_id\"]` was being passed in — but the\nretriever never read it, because the filter was baked in. Every request for\nevery tenant hit the same Pinecone namespace. Security review caught it three\ndays later and put a hold on the SOC2 renewal. This is pain-catalog entry\n**P33**, the single most common cause of cross-tenant leak in LangChain 1.0\nproduction.\n\nThis skill fixes it with four workstreams:\n\n- **P33 — retriever-per-request factory** — build the retriever inside the\n  chain or agent invocation, keyed by `tenant_id` from `RunnableConfig`. Never\n  at module scope. Unit-test with two tenants and assert non-overlap.\n- **Role-scoped tool allowlist** — build the agent per-request with only the\n  tools the current user's role permits. Forbidden tools are not passed to\n  `create_agent` at all, so the model cannot call them even if it tries.\n- **Per-tenant rate limit + budget** — scope the `InMemoryRateLimiter` (or a\n  Redis-backed equivalent) by `tenant_id`, and check a per-tenant USD budget\n  before invoking the model.\n- **Structured audit log** — JSON log with `user_id`, `tenant_id`,\n  `chain_name`, `tools_called`, `cost_usd`, `outcome`, emitted in both success\n  and failure paths. Ships to SIEM or BigQuery.\n\nTwo failure patterns anchor this skill: **import-time retriever binding (P33)**\nand **missing audit log on tool failure** (the `try` block logs on success but\nthe `except` branch re-raises without emitting, so incident response has no\nrecord of denied tool calls). Pinned: `langchain-core 1.0.x`,\n`langgraph 1.0.x`, `langchain-anthropic 1.0.x`, `langchain-openai 1.0.x`,\n`langchain-postgres 0.0.15+` (for PGVector RLS), `pinecone-client 5.x`,\n`chromadb 0.5.x`. Pain-catalog anchors: **P33 primary**, P18, P24, P31, P37.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`, `langgraph >= 1.0, \u003C 2.0`\n- At least one vector-store backend: `pinecone-client`, `langchain-postgres`\n  (PGVector), `chromadb`, or `faiss-cpu` (single-tenant only — see §Step 2)\n- A structured logging sink: stdout JSON for local, Cloud Logging \u002F Datadog \u002F\n  Splunk HEC \u002F BigQuery streaming insert for production\n- A tenant authorization claim in every request (JWT `tid` claim, session\n  cookie, or header — the auth boundary is out of scope for this skill but\n  assumed correct)\n\n## Instructions\n\n### Step 1 — Build the retriever per-request, never at import\n\nMove retriever construction inside the chain or agent invocation, keyed by\n`config[\"configurable\"][\"tenant_id\"]`.\n\n```python\nfrom langchain_core.runnables import RunnableConfig, RunnableLambda\nfrom langchain_pinecone import PineconeVectorStore\n\n# WRONG — retriever bound at import time with first tenant's namespace.\n# RETRIEVER = PineconeVectorStore(index_name=\"rag\", namespace=\"acme-corp\",\n#     embedding=emb).as_retriever(search_kwargs={\"k\": 4})\n\n# RIGHT — factory called per-request, reads tenant from RunnableConfig.\ndef retriever_for(config: RunnableConfig):\n    tenant_id = config[\"configurable\"][\"tenant_id\"]  # required, no default\n    if not tenant_id:\n        raise PermissionError(\"tenant_id missing from RunnableConfig\")\n    store = PineconeVectorStore(\n        index_name=\"rag\",\n        namespace=tenant_id,   # P33 fix — namespace per-invocation\n        embedding=emb,\n    )\n    return store.as_retriever(search_kwargs={\"k\": 4})\n\ndef retrieve(inputs: dict, config: RunnableConfig):\n    return retriever_for(config).invoke(inputs[\"query\"])\n\nchain = RunnableLambda(retrieve) | prompt | model\nresult = chain.invoke({\"query\": \"...\"},\n    config={\"configurable\": {\"tenant_id\": \"initech\"}})\n```\n\nNo default on `tenant_id` — a missing tenant must be a hard error, not a silent\nfallback. See [Retriever-per-request](references\u002Fretriever-per-request.md) for\nfactory lifecycle and PGVector RLS \u002F Chroma \u002F FAISS adapters.\n\n### Step 2 — Pick a vector-store isolation primitive\n\n| Store | Isolation primitive | Per-tenant latency | Max tenants | Safety notes |\n|---|---|---|---|---|\n| **Pinecone** | `namespace=tenant_id` per query | ~40ms p50 (shared index) | 100,000+ per index | Namespace is the documented isolation boundary; still apply metadata `{\"tenant_id\": tid}` as defense in depth |\n| **PGVector** | Postgres row-level security (RLS) on `tenant_id` column | ~20ms p50 (HNSW index) | Bounded by Postgres row count | Use `SET LOCAL app.tenant_id = :tid` per transaction; RLS policy `USING (tenant_id = current_setting('app.tenant_id'))` |\n| **Chroma** | Collection-per-tenant (`get_or_create_collection(name=tid)`) | ~30ms p50 | ~1,000 before metadata overhead | Good isolation at small scale; collection creation is synchronous — provision lazily but cache the handle per-request |\n| **FAISS** | In-process index-per-tenant | ~5ms p50 (in-memory) | 10-50 practical limit | Poor fit for multi-tenant SaaS — cannot shard across processes, reloads on every deploy, no durable filter. Use for single-tenant evaluation only |\n\nPinecone scales highest. PGVector with RLS is the strongest primitive when\nisolation must be auditable at the database layer (RLS is enforced by the\nserver even if application code is bypassed). Chroma is fine for ≤1,000\ntenants. FAISS is not a multi-tenant production choice — document so future\nengineers do not adopt it. See\n[Vector-store isolation](references\u002Fvector-store-isolation.md) for the PGVector\nRLS DDL and Chroma lifecycle.\n\n### Step 3 — Build the agent per-request with a role-scoped tool allowlist\n\nNever bind every tool to every agent and trust the model to pick the right one.\nBuild the agent inside the request handler with only the tools the user's role\npermits.\n\n```python\nfrom langgraph.prebuilt import create_agent\n\n# Map role -> allowed tool names. Owned by IAM config, not the skill.\nROLE_TOOLS: dict[str, set[str]] = {\n    \"viewer\": {\"search_docs\"},\n    \"editor\": {\"search_docs\", \"create_note\"},\n    \"admin\":  {\"search_docs\", \"create_note\", \"delete_note\", \"export_audit\"},\n}\nALL_TOOLS = {t.name: t for t in [search_docs, create_note, delete_note, export_audit]}\n\ndef agent_for(user_role: str, tenant_id: str):\n    allowed = ROLE_TOOLS.get(user_role, set())\n    tools = [ALL_TOOLS[n] for n in allowed if n in ALL_TOOLS]\n    # Forbidden tools are not passed in — the model never sees them.\n    return create_agent(model, tools=tools)\n\nagent = agent_for(user_role=\"viewer\", tenant_id=\"initech\")\n# viewer has no delete_note -> the agent cannot call it.\n```\n\nAdd a denylist for dangerous argument patterns (SQL with `DROP` \u002F `TRUNCATE`,\nshell with `rm -rf` \u002F `sudo`, URLs to internal metadata endpoints) via a\n`pre_model_hook` or tool wrapper — allowlist bounds *which* tools run,\ndenylist bounds *what arguments* they accept. See\n[Role-scoped tool allowlist](references\u002Frole-scoped-tool-allowlist.md).\n\n### Step 4 — Scope rate limits and budgets by tenant\n\nPer-tenant limits prevent one tenant's runaway job from exhausting shared model\ncapacity. Rate-limit detail is covered in `langchain-rate-limits`; cost-budget\ndetail in `langchain-cost-tuning`. The only RBAC-specific requirement here:\n**limiter key must include `tenant_id`** — never a process-global singleton.\n\n```python\n# Sketch only — see langchain-rate-limits for production implementation.\n_limiters: dict[str, InMemoryRateLimiter] = {}\n\ndef limiter_for(tenant_id: str) -> InMemoryRateLimiter:\n    if tenant_id not in _limiters:\n        # Tier lookup — different plans get different budgets.\n        rps = TENANT_TIER_LIMITS.get(tenant_id, 1.0)  # 1.0 rps = free-tier default\n        _limiters[tenant_id] = InMemoryRateLimiter(requests_per_second=rps)\n    return _limiters[tenant_id]\n```\n\nFor multi-process deployments use a Redis-backed limiter — `InMemoryRateLimiter`\nis per-process only, so 1 rps × 8 workers = 8 rps aggregate.\n\n### Step 5 — Emit a structured audit log on every invocation\n\nThe audit log is the record of truth during an incident. Emit on both success\nand failure paths. The common bug is logging in the `try` block only — when a\ntool raises, the `except` branch re-raises without emitting, so the incident\nresponder has no record of the denied call.\n\n```python\nimport json\nimport time\nimport uuid\nfrom contextlib import contextmanager\n\n@contextmanager\ndef audit(ctx: dict):\n    started = time.monotonic()\n    trace_id = str(uuid.uuid4())\n    record = {**ctx, \"trace_id\": trace_id, \"outcome\": \"pending\"}\n    try:\n        yield record\n        record[\"outcome\"] = record.get(\"outcome\", \"success\")\n    except Exception as exc:\n        record[\"outcome\"] = \"error\"\n        record[\"error_class\"] = type(exc).__name__\n        record[\"error_message\"] = str(exc)[:500]  # truncate — no PII leakage\n        raise\n    finally:\n        record[\"latency_ms\"] = int((time.monotonic() - started) * 1000)  # 1000 ms per second\n        print(json.dumps(record))  # or a SIEM \u002F BigQuery client\n\nctx = {\n    \"user_id\": \"u_42\",\n    \"tenant_id\": \"initech\",\n    \"chain_name\": \"rag-qa-v3\",\n    \"role\": \"viewer\",\n}\nwith audit(ctx) as record:\n    result = chain.invoke(inputs, config={\"configurable\": ctx})\n    record[\"tools_called\"] = [m.name for m in result.get(\"tool_calls\", [])]\n    record[\"input_tokens\"]  = result[\"usage\"][\"input_tokens\"]\n    record[\"output_tokens\"] = result[\"usage\"][\"output_tokens\"]\n    record[\"cost_usd\"]      = cost_of(result[\"usage\"])\n```\n\nThe `try \u002F finally` pattern guarantees emission even when the chain raises.\nRequired fields: `user_id`, `tenant_id`, `chain_name`, `outcome`, `latency_ms`,\n`trace_id`. Recommended: `tools_called`, `input_tokens`, `output_tokens`,\n`cost_usd`, `role`. See [Audit-log schema](references\u002Faudit-log-schema.md) for\nthe full catalog, JSON example, SIEM \u002F BigQuery ingestion, and query recipes.\n\n### Step 6 — Two-tenant regression test for cross-tenant leak\n\nThe test that would have caught P33 on day one. Seed two tenants with distinct\ndocuments, run a golden query as each, assert non-overlap on retrieved IDs.\n\n```python\nimport pytest\n\n@pytest.fixture\ndef two_tenant_store():\n    seed(\"acme\",    [\"acme-doc-1\",    \"acme-doc-2\"])\n    seed(\"initech\", [\"initech-doc-1\", \"initech-doc-2\"])\n    yield\n    cleanup([\"acme\", \"initech\"])\n\ndef test_tenant_isolation(two_tenant_store):\n    acme_hits    = chain.invoke({\"query\": \"q\"}, config={\"configurable\": {\"tenant_id\": \"acme\"}})\n    initech_hits = chain.invoke({\"query\": \"q\"}, config={\"configurable\": {\"tenant_id\": \"initech\"}})\n    acme_ids    = {d.id for d in acme_hits[\"documents\"]}\n    initech_ids = {d.id for d in initech_hits[\"documents\"]}\n    assert acme_ids.isdisjoint(initech_ids), \\\n        f\"CROSS-TENANT LEAK: overlap={acme_ids & initech_ids}\"\n    assert all(\"acme\"    in doc_id for doc_id in acme_ids)\n    assert all(\"initech\" in doc_id for doc_id in initech_ids)\n```\n\nRun in CI on every PR. A regression to import-time retriever binding fails\nimmediately. See\n[Multi-tenant regression tests](references\u002Fmulti-tenant-regression-tests.md)\nfor fixtures covering tool-allowlist violation, audit-log completeness, and\nrate-limiter scoping.\n\n## Output\n\n- Retriever factory keyed by `RunnableConfig.configurable[\"tenant_id\"]`\n- Vector-store choice made against the 4-row isolation table, not by defaults\n- Agent constructed per-request with a role-scoped tool allowlist (not a\n  deny-all at tool-call time)\n- Rate limiter and cost budget keyed by `tenant_id`, never a process global\n- Structured audit log emitted on both success and failure paths with\n  required fields (`user_id`, `tenant_id`, `chain_name`, `outcome`,\n  `latency_ms`, `trace_id`)\n- Two-tenant pytest fixture in CI that asserts cross-tenant non-overlap\n\n## Error Handling\n\n| Error \u002F symptom | Cause | Fix |\n|---|---|---|\n| Tenant A's docs returned to Tenant B after deploy | Singleton retriever bound at import (P33) | Move to per-request factory keyed by `config[\"configurable\"][\"tenant_id\"]` (Step 1) |\n| `KeyError: 'tenant_id'` in retriever factory | Caller forgot to pass `configurable` | Fail fast with `PermissionError`; never default to a tenant |\n| `permission denied for relation documents` on PGVector | RLS policy enabled but session variable not set | `SET LOCAL app.tenant_id = :tid` inside the transaction |\n| Agent calls a tool the user's role should not have | Every tool bound at agent construction | Build agent per-request with only role-permitted tools (Step 3) |\n| Audit log missing entries for errored invocations | Log emitted inside `try` only, not `finally` | Move emit to `finally` block (Step 5) |\n| Shared rate limit trips all tenants when one misbehaves | Process-global `InMemoryRateLimiter` | Key limiter by `tenant_id`; use Redis-backed for multi-process (Step 4) |\n| Cross-tenant leak regression ships to prod | No two-tenant CI test | Add the Step 6 fixture; run on every PR |\n| Audit log contains raw PII from prompts | Logging `inputs` verbatim | Log field names \u002F token counts \u002F IDs only; never log raw message content |\n\n## Examples\n\n### Full multi-tenant RAG agent, end-to-end\n\nCombines all six steps: retriever-per-request, Pinecone namespace isolation,\nrole-scoped tools, per-tenant rate limit, audit-log context manager, regression\ntest. Assembly is ~80 lines. See\n[Retriever-per-request](references\u002Fretriever-per-request.md).\n\n### Migrating from a shared singleton to per-request\n\nWrap the old singleton, add the factory alongside, route by feature flag, ship\nthe regression test first, flip the flag, delete the singleton. Typical\nmigration window: 1-2 sprints. See\n[Multi-tenant regression tests](references\u002Fmulti-tenant-regression-tests.md).\n\n### Exporting audit log to BigQuery for compliance queries\n\nStream each record to BigQuery per the\n[Audit-log schema](references\u002Faudit-log-schema.md). Recipes: \"tool calls by\nuser X in last 24h\", \"tenants with >1% error rate\", \"highest-spend tenants\".\n\n## Resources\n\n- [LangChain Python: `RunnableConfig`](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Frunnables\u002F#runnableconfig)\n- [LangChain Python: Multiple retrievers](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fmultiple_queries\u002F)\n- [LangGraph: `create_agent`](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fagents\u002Fagents\u002F)\n- [Pinecone: Namespaces](https:\u002F\u002Fdocs.pinecone.io\u002Fguides\u002Findexes\u002Fuse-namespaces)\n- [PGVector: Row-level security](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fddl-rowsecurity.html)\n- [SOC2 CC6.1 — logical access controls](https:\u002F\u002Fwww.aicpa-cima.com\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (primary P33; adjacent P18, P24, P31, P37)\n- Sibling skills: `langchain-rate-limits` (per-tenant limiters), `langchain-cost-tuning` (per-tenant budgets), `langchain-security-basics` (input redaction upstream of audit log)\n","# LangChain Enterprise RBAC (Python)\n\n## Overview\n\nA B2B SaaS team shipped their first RAG feature for two tenants. The factory\ncode looked innocent: build `PineconeVectorStore` once at module import with\n`namespace=\"acme-corp\"` (the first tenant), convert it to a retriever, store\nit in a module global, reuse on every request. Six weeks later tenant \"Initech\"\nwent live. Their first search returned three documents from Acme Corp.\n\nThe singleton retriever had captured the Acme namespace at process start.\n`RunnableConfig.configurable[\"tenant_id\"]` was being passed in — but the\nretriever never read it, because the filter was baked in. Every request for\nevery tenant hit the same Pinecone namespace. Security review caught it three\ndays later and put a hold on the SOC2 renewal. This is pain-catalog entry\n**P33**, the single most common cause of cross-tenant leak in LangChain 1.0\nproduction.\n\nThis skill fixes it with four workstreams:\n\n- **P33 — retriever-per-request factory** — build the retriever inside the\n  chain or agent invocation, keyed by `tenant_id` from `RunnableConfig`. Never\n  at module scope. Unit-test with two tenants and assert non-overlap.\n- **Role-scoped tool allowlist** — build the agent per-request with only the\n  tools the current user's role permits. Forbidden tools are not passed to\n  `create_agent` at all, so the model cannot call them even if it tries.\n- **Per-tenant rate limit + budget** — scope the `InMemoryRateLimiter` (or a\n  Redis-backed equivalent) by `tenant_id`, and check a per-tenant USD budget\n  before invoking the model.\n- **Structured audit log** — JSON log with `user_id`, `tenant_id`,\n  `chain_name`, `tools_called`, `cost_usd`, `outcome`, emitted in both success\n  and failure paths. Ships to SIEM or BigQuery.\n\nTwo failure patterns anchor this skill: **import-time retriever binding (P33)**\nand **missing audit log on tool failure** (the `try` block logs on success but\nthe `except` branch re-raises without emitting, so incident response has no\nrecord of denied tool calls). Pinned: `langchain-core 1.0.x`,\n`langgraph 1.0.x`, `langchain-anthropic 1.0.x`, `langchain-openai 1.0.x`,\n`langchain-postgres 0.0.15+` (for PGVector RLS), `pinecone-client 5.x`,\n`chromadb 0.5.x`. Pain-catalog anchors: **P33 primary**, P18, P24, P31, P37.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`, `langgraph >= 1.0, \u003C 2.0`\n- At least one vector-store backend: `pinecone-client`, `langchain-postgres`\n  (PGVector), `chromadb`, or `faiss-cpu` (single-tenant only — see §Step 2)\n- A structured logging sink: stdout JSON for local, Cloud Logging \u002F Datadog \u002F\n  Splunk HEC \u002F BigQuery streaming insert for production\n- A tenant authorization claim in every request (JWT `tid` claim, session\n  cookie, or header — the auth boundary is out of scope for this skill but\n  assumed correct)\n\n## Instructions\n\n### Step 1 — Build the retriever per-request, never at import\n\nMove retriever construction inside the chain or agent invocation, keyed by\n`config[\"configurable\"][\"tenant_id\"]`.\n\n```python\nfrom langchain_core.runnables import RunnableConfig, RunnableLambda\nfrom langchain_pinecone import PineconeVectorStore\n\n# WRONG — retriever bound at import time with first tenant's namespace.\n# RETRIEVER = PineconeVectorStore(index_name=\"rag\", namespace=\"acme-corp\",\n#     embedding=emb).as_retriever(search_kwargs={\"k\": 4})\n\n# RIGHT — factory called per-request, reads tenant from RunnableConfig.\ndef retriever_for(config: RunnableConfig):\n    tenant_id = config[\"configurable\"][\"tenant_id\"]  # required, no default\n    if not tenant_id:\n        raise PermissionError(\"tenant_id missing from RunnableConfig\")\n    store = PineconeVectorStore(\n        index_name=\"rag\",\n        namespace=tenant_id,   # P33 fix — namespace per-invocation\n        embedding=emb,\n    )\n    return store.as_retriever(search_kwargs={\"k\": 4})\n\ndef retrieve(inputs: dict, config: RunnableConfig):\n    return retriever_for(config).invoke(inputs[\"query\"])\n\nchain = RunnableLambda(retrieve) | prompt | model\nresult = chain.invoke({\"query\": \"...\"},\n    config={\"configurable\": {\"tenant_id\": \"initech\"}})\n```\n\nNo default on `tenant_id` — a missing tenant must be a hard error, not a silent\nfallback. See [Retriever-per-request](references\u002Fretriever-per-request.md) for\nfactory lifecycle and PGVector RLS \u002F Chroma \u002F FAISS adapters.\n\n### Step 2 — Pick a vector-store isolation primitive\n\n| Store | Isolation primitive | Per-tenant latency | Max tenants | Safety notes |\n|---|---|---|---|---|\n| **Pinecone** | `namespace=tenant_id` per query | ~40ms p50 (shared index) | 100,000+ per index | Namespace is the documented isolation boundary; still apply metadata `{\"tenant_id\": tid}` as defense in depth |\n| **PGVector** | Postgres row-level security (RLS) on `tenant_id` column | ~20ms p50 (HNSW index) | Bounded by Postgres row count | Use `SET LOCAL app.tenant_id = :tid` per transaction; RLS policy `USING (tenant_id = current_setting('app.tenant_id'))` |\n| **Chroma** | Collection-per-tenant (`get_or_create_collection(name=tid)`) | ~30ms p50 | ~1,000 before metadata overhead | Good isolation at small scale; collection creation is synchronous — provision lazily but cache the handle per-request |\n| **FAISS** | In-process index-per-tenant | ~5ms p50 (in-memory) | 10-50 practical limit | Poor fit for multi-tenant SaaS — cannot shard across processes, reloads on every deploy, no durable filter. Use for single-tenant evaluation only |\n\nPinecone scales highest. PGVector with RLS is the strongest primitive when\nisolation must be auditable at the database layer (RLS is enforced by the\nserver even if application code is bypassed). Chroma is fine for ≤1,000\ntenants. FAISS is not a multi-tenant production choice — document so future\nengineers do not adopt it. See\n[Vector-store isolation](references\u002Fvector-store-isolation.md) for the PGVector\nRLS DDL and Chroma lifecycle.\n\n### Step 3 — Build the agent per-request with a role-scoped tool allowlist\n\nNever bind every tool to every agent and trust the model to pick the right one.\nBuild the agent inside the request handler with only the tools the user's role\npermits.\n\n```python\nfrom langgraph.prebuilt import create_agent\n\n# Map role -> allowed tool names. Owned by IAM config, not the skill.\nROLE_TOOLS: dict[str, set[str]] = {\n    \"viewer\": {\"search_docs\"},\n    \"editor\": {\"search_docs\", \"create_note\"},\n    \"admin\":  {\"search_docs\", \"create_note\", \"delete_note\", \"export_audit\"},\n}\nALL_TOOLS = {t.name: t for t in [search_docs, create_note, delete_note, export_audit]}\n\ndef agent_for(user_role: str, tenant_id: str):\n    allowed = ROLE_TOOLS.get(user_role, set())\n    tools = [ALL_TOOLS[n] for n in allowed if n in ALL_TOOLS]\n    # Forbidden tools are not passed in — the model never sees them.\n    return create_agent(model, tools=tools)\n\nagent = agent_for(user_role=\"viewer\", tenant_id=\"initech\")\n# viewer has no delete_note -> the agent cannot call it.\n```\n\nAdd a denylist for dangerous argument patterns (SQL with `DROP` \u002F `TRUNCATE`,\nshell with `rm -rf` \u002F `sudo`, URLs to internal metadata endpoints) via a\n`pre_model_hook` or tool wrapper — allowlist bounds *which* tools run,\ndenylist bounds *what arguments* they accept. See\n[Role-scoped tool allowlist](references\u002Frole-scoped-tool-allowlist.md).\n\n### Step 4 — Scope rate limits and budgets by tenant\n\nPer-tenant limits prevent one tenant's runaway job from exhausting shared model\ncapacity. Rate-limit detail is covered in `langchain-rate-limits`; cost-budget\ndetail in `langchain-cost-tuning`. The only RBAC-specific requirement here:\n**limiter key must include `tenant_id`** — never a process-global singleton.\n\n```python\n# Sketch only — see langchain-rate-limits for production implementation.\n_limiters: dict[str, InMemoryRateLimiter] = {}\n\ndef limiter_for(tenant_id: str) -> InMemoryRateLimiter:\n    if tenant_id not in _limiters:\n        # Tier lookup — different plans get different budgets.\n        rps = TENANT_TIER_LIMITS.get(tenant_id, 1.0)  # 1.0 rps = free-tier default\n        _limiters[tenant_id] = InMemoryRateLimiter(requests_per_second=rps)\n    return _limiters[tenant_id]\n```\n\nFor multi-process deployments use a Redis-backed limiter — `InMemoryRateLimiter`\nis per-process only, so 1 rps × 8 workers = 8 rps aggregate.\n\n### Step 5 — Emit a structured audit log on every invocation\n\nThe audit log is the record of truth during an incident. Emit on both success\nand failure paths. The common bug is logging in the `try` block only — when a\ntool raises, the `except` branch re-raises without emitting, so the incident\nresponder has no record of the denied call.\n\n```python\nimport json\nimport time\nimport uuid\nfrom contextlib import contextmanager\n\n@contextmanager\ndef audit(ctx: dict):\n    started = time.monotonic()\n    trace_id = str(uuid.uuid4())\n    record = {**ctx, \"trace_id\": trace_id, \"outcome\": \"pending\"}\n    try:\n        yield record\n        record[\"outcome\"] = record.get(\"outcome\", \"success\")\n    except Exception as exc:\n        record[\"outcome\"] = \"error\"\n        record[\"error_class\"] = type(exc).__name__\n        record[\"error_message\"] = str(exc)[:500]  # truncate — no PII leakage\n        raise\n    finally:\n        record[\"latency_ms\"] = int((time.monotonic() - started) * 1000)  # 1000 ms per second\n        print(json.dumps(record))  # or a SIEM \u002F BigQuery client\n\nctx = {\n    \"user_id\": \"u_42\",\n    \"tenant_id\": \"initech\",\n    \"chain_name\": \"rag-qa-v3\",\n    \"role\": \"viewer\",\n}\nwith audit(ctx) as record:\n    result = chain.invoke(inputs, config={\"configurable\": ctx})\n    record[\"tools_called\"] = [m.name for m in result.get(\"tool_calls\", [])]\n    record[\"input_tokens\"]  = result[\"usage\"][\"input_tokens\"]\n    record[\"output_tokens\"] = result[\"usage\"][\"output_tokens\"]\n    record[\"cost_usd\"]      = cost_of(result[\"usage\"])\n```\n\nThe `try \u002F finally` pattern guarantees emission even when the chain raises.\nRequired fields: `user_id`, `tenant_id`, `chain_name`, `outcome`, `latency_ms`,\n`trace_id`. Recommended: `tools_called`, `input_tokens`, `output_tokens`,\n`cost_usd`, `role`. See [Audit-log schema](references\u002Faudit-log-schema.md) for\nthe full catalog, JSON example, SIEM \u002F BigQuery ingestion, and query recipes.\n\n### Step 6 — Two-tenant regression test for cross-tenant leak\n\nThe test that would have caught P33 on day one. Seed two tenants with distinct\ndocuments, run a golden query as each, assert non-overlap on retrieved IDs.\n\n```python\nimport pytest\n\n@pytest.fixture\ndef two_tenant_store():\n    seed(\"acme\",    [\"acme-doc-1\",    \"acme-doc-2\"])\n    seed(\"initech\", [\"initech-doc-1\", \"initech-doc-2\"])\n    yield\n    cleanup([\"acme\", \"initech\"])\n\ndef test_tenant_isolation(two_tenant_store):\n    acme_hits    = chain.invoke({\"query\": \"q\"}, config={\"configurable\": {\"tenant_id\": \"acme\"}})\n    initech_hits = chain.invoke({\"query\": \"q\"}, config={\"configurable\": {\"tenant_id\": \"initech\"}})\n    acme_ids    = {d.id for d in acme_hits[\"documents\"]}\n    initech_ids = {d.id for d in initech_hits[\"documents\"]}\n    assert acme_ids.isdisjoint(initech_ids), \\\n        f\"CROSS-TENANT LEAK: overlap={acme_ids & initech_ids}\"\n    assert all(\"acme\"    in doc_id for doc_id in acme_ids)\n    assert all(\"initech\" in doc_id for doc_id in initech_ids)\n```\n\nRun in CI on every PR. A regression to import-time retriever binding fails\nimmediately. See\n[Multi-tenant regression tests](references\u002Fmulti-tenant-regression-tests.md)\nfor fixtures covering tool-allowlist violation, audit-log completeness, and\nrate-limiter scoping.\n\n## Output\n\n- Retriever factory keyed by `RunnableConfig.configurable[\"tenant_id\"]`\n- Vector-store choice made against the 4-row isolation table, not by defaults\n- Agent constructed per-request with a role-scoped tool allowlist (not a\n  deny-all at tool-call time)\n- Rate limiter and cost budget keyed by `tenant_id`, never a process global\n- Structured audit log emitted on both success and failure paths with\n  required fields (`user_id`, `tenant_id`, `chain_name`, `outcome`,\n  `latency_ms`, `trace_id`)\n- Two-tenant pytest fixture in CI that asserts cross-tenant non-overlap\n\n## Error Handling\n\n| Error \u002F symptom | Cause | Fix |\n|---|---|---|\n| Tenant A's docs returned to Tenant B after deploy | Singleton retriever bound at import (P33) | Move to per-request factory keyed by `config[\"configurable\"][\"tenant_id\"]` (Step 1) |\n| `KeyError: 'tenant_id'` in retriever factory | Caller forgot to pass `configurable` | Fail fast with `PermissionError`; never default to a tenant |\n| `permission denied for relation documents` on PGVector | RLS policy enabled but session variable not set | `SET LOCAL app.tenant_id = :tid` inside the transaction |\n| Agent calls a tool the user's role should not have | Every tool bound at agent construction | Build agent per-request with only role-permitted tools (Step 3) |\n| Audit log missing entries for errored invocations | Log emitted inside `try` only, not `finally` | Move emit to `finally` block (Step 5) |\n| Shared rate limit trips all tenants when one misbehaves | Process-global `InMemoryRateLimiter` | Key limiter by `tenant_id`; use Redis-backed for multi-process (Step 4) |\n| Cross-tenant leak regression ships to prod | No two-tenant CI test | Add the Step 6 fixture; run on every PR |\n| Audit log contains raw PII from prompts | Logging `inputs` verbatim | Log field names \u002F token counts \u002F IDs only; never log raw message content |\n\n## Examples\n\n### Full multi-tenant RAG agent, end-to-end\n\nCombines all six steps: retriever-per-request, Pinecone namespace isolation,\nrole-scoped tools, per-tenant rate limit, audit-log context manager, regression\ntest. Assembly is ~80 lines. See\n[Retriever-per-request](references\u002Fretriever-per-request.md).\n\n### Migrating from a shared singleton to per-request\n\nWrap the old singleton, add the factory alongside, route by feature flag, ship\nthe regression test first, flip the flag, delete the singleton. Typical\nmigration window: 1-2 sprints. See\n[Multi-tenant regression tests](references\u002Fmulti-tenant-regression-tests.md).\n\n### Exporting audit log to BigQuery for compliance queries\n\nStream each record to BigQuery per the\n[Audit-log schema](references\u002Faudit-log-schema.md). Recipes: \"tool calls by\nuser X in last 24h\", \"tenants with >1% error rate\", \"highest-spend tenants\".\n\n## Resources\n\n- [LangChain Python: `RunnableConfig`](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Frunnables\u002F#runnableconfig)\n- [LangChain Python: Multiple retrievers](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fmultiple_queries\u002F)\n- [LangGraph: `create_agent`](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fagents\u002Fagents\u002F)\n- [Pinecone: Namespaces](https:\u002F\u002Fdocs.pinecone.io\u002Fguides\u002Findexes\u002Fuse-namespaces)\n- [PGVector: Row-level security](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fddl-rowsecurity.html)\n- [SOC2 CC6.1 — logical access controls](https:\u002F\u002Fwww.aicpa-cima.com\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (primary P33; adjacent P18, P24, P31, P37)\n- Sibling skills: `langchain-rate-limits` (per-tenant limiters), `langchain-cost-tuning` (per-tenant budgets), `langchain-security-basics` (input redaction upstream of audit log)\n",{"name":5,"tags":24,"author":34,"license":15,"version":35,"description":36,"allowed-tools":37,"compatible-with":38},[25,26,27,28,29,30,31,32,33],"saas","langchain","langgraph","python","langchain-1.0","multi-tenant","rbac","enterprise","security","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Enforce tenant isolation and role-based access across LangChain 1.0 chains and\nLangGraph 1.0 agents — per-request retriever construction, tenant-scoped rate\nlimits, role-scoped tool allowlists, and structured audit logs. Use when\nbuilding multi-tenant saas, passing soc2 review, or debugging cross-tenant\nleak. Trigger with \"langchain multi-tenant\", \"langchain tenant isolation\",\n\"langchain rbac\", \"langchain row-level security\", \"langchain audit log\".\n","Read, Write, Edit, Bash(python:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-enterprise-rbac",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-enterprise-rbac",{"tool":54,"command":55},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-enterprise-rbac",{"tool":57,"command":58},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-enterprise-rbac","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-enterprise-rbac\u002FSKILL.md",true,[],[63,70,77,84,91,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]