Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/langchain-enterprise-rbac

@0d57af8
Run it yourself

Enforce tenant isolation and role-based access across LangChain 1.0 chains and LangGraph 1.0 agents — per-request retriever construction, tenant-scoped rate limits, role-scoped tool allowlists, and structured audit logs. Use when building multi-tenant saas, passing soc2 review, or debugging cross-tenant leak. Trigger with "langchain multi-tenant", "langchain tenant isolation", "langchain rbac", "langchain row-level security", "langchain audit log".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/langchain-enterprise-rbac

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesretriever-per-request.md

≈1.5k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Retriever-per-request Factory Pattern

The canonical fix for P33 (per-tenant vector stores leak if retriever bound at process start). Every tenant-scoped retrieval path in LangChain 1.0 / LangGraph 1.0 should follow this pattern.

Why not at import time

A module-scope RETRIEVER = vectorstore.as_retriever(...) captures whatever filter / namespace / collection is in scope when the module first loads. That value is cached for the process lifetime. The retriever has no awareness of RunnableConfig.configurable["tenant_id"] and no reason to re-read it — it is a plain object with pre-baked state.

Result: every tenant gets the same retrieval. The first tenant onboarded wins; everyone else leaks into their namespace. P33 is triggered by the pattern, not by any specific vector store, so it applies equally to Pinecone, Chroma, PGVector, and FAISS.

The factory

from typing import Callable
from langchain_core.retrievers import BaseRetriever
from langchain_core.runnables import RunnableConfig, RunnableLambda

def make_retriever_factory(
    build: Callable[[str], BaseRetriever],
) -> Callable[[RunnableConfig], BaseRetriever]:
    """Returns a function that builds a retriever per-request from config.

    The `build` argument is the store-specific constructor. Keep this
    factory generic so the caller chooses their store.
    """
    def factory(config: RunnableConfig) -> BaseRetriever:
        try:
            tenant_id = config["configurable"]["tenant_id"]
        except KeyError as exc:
            raise PermissionError("tenant_id missing from RunnableConfig") from exc
        if not tenant_id or not isinstance(tenant_id, str):
            raise PermissionError(f"invalid tenant_id: {tenant_id!r}")
        return build(tenant_id)
    return factory

PermissionError on missing tenant — never KeyError, never a silent default. A caller that forgets to pass configurable must fail loudly.

Store-specific build functions

Pinecone (namespace-per-tenant)

from langchain_pinecone import PineconeVectorStore

def build_pinecone(tenant_id: str) -> BaseRetriever:
    store = PineconeVectorStore(
        index_name="rag",
        namespace=tenant_id,
        embedding=emb,
    )
    # Defense in depth — also filter on metadata in case namespace config
    # drifts or a write path forgot to set namespace.
    return store.as_retriever(
        search_kwargs={"k": 4, "filter": {"tenant_id": tenant_id}},
    )

PGVector (row-level security)

from sqlalchemy import text
from langchain_postgres import PGVector

def build_pgvector(tenant_id: str) -> BaseRetriever:
    store = PGVector(
        embeddings=emb,
        collection_name="rag",
        connection=engine,
    )
    # Set the tenant session variable per-transaction. The RLS policy on
    # the documents table reads it. If it's missing, RLS denies all rows.
    with engine.begin() as conn:
        conn.execute(text("SET LOCAL app.tenant_id = :tid"), {"tid": tenant_id})
    return store.as_retriever(search_kwargs={"k": 4})

See Vector-store isolation for the RLS policy DDL.

Chroma (collection-per-tenant)

import chromadb
from langchain_chroma import Chroma

def build_chroma(tenant_id: str) -> BaseRetriever:
    client = chromadb.PersistentClient(path="/var/chroma")
    # get_or_create is idempotent; safe to call per-request.
    collection = client.get_or_create_collection(name=f"rag-{tenant_id}")
    store = Chroma(client=client, collection_name=collection.name, embedding_function=emb)
    return store.as_retriever(search_kwargs={"k": 4})

FAISS (single-tenant only)

# FAISS is in-process only. If you must use it multi-tenant, load a separate
# index file per tenant — but you pay the file-load cost on cold cache, and
# you cannot share memory across processes. Not recommended beyond ~50 tenants.
def build_faiss(tenant_id: str) -> BaseRetriever:
    path = f"/var/faiss/{tenant_id}.index"
    store = FAISS.load_local(path, emb, allow_dangerous_deserialization=False)
    return store.as_retriever(search_kwargs={"k": 4})

Wiring the factory into a chain

factory = make_retriever_factory(build_pinecone)

def retrieve(inputs: dict, config: RunnableConfig):
    return factory(config).invoke(inputs["query"])

chain = RunnableLambda(retrieve) | prompt | model

chain.invoke(
    {"query": "when was the contract signed?"},
    config={"configurable": {"tenant_id": "initech", "user_id": "u_42"}},
)

The retriever is rebuilt on every invoke. For high-QPS endpoints where the cost of rebuilding matters, cache the client (the Pinecone / Chroma / Postgres connection) but rebuild the per-tenant view each request — never cache the retriever itself.

Lifecycle checklist

  1. Retriever is constructed inside the request handler, not at module scope
  2. Factory reads tenant_id from RunnableConfig.configurable, not from env / globals
  3. Missing tenant_id raises PermissionError, not a KeyError or silent default
  4. Vector-store client (connection pool, Pinecone client, Chroma client) is cached; the retriever view is not
  5. Two-tenant regression test runs in CI and asserts non-overlap (see Multi-tenant regression tests)
  6. On deploy, the first request for each tenant triggers a fresh build — no state carries over from a previous deploy

Common anti-patterns

  • @lru_cache on the factory — defeats the whole point, caches first tenant
  • Default tenant_id="public" — silent escape hatch for forgotten configs
  • Building the retriever in a FastAPI lifespan handler — runs once at startup, same as import
  • Reading tenant from an env var instead of RunnableConfig — breaks when the process serves multiple tenants

Related

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 warning2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides security patterns and best practices for building multi-tenant LangChain and LangGraph applications. It includes robust implementations for tenant isolation, role-based tool access, and comprehensive audit logging. No malicious patterns or security vulnerabilities were detected; the skill is designed to improve the security posture of AI agents.

  • Socket2mo

    1 alert: gptAnomaly

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 2 months ago
What it can do
Reads files Edits files Runs commands
version
2.7.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
compatibility
Designed for Claude Code
All 4 allowed tools
ReadWriteEditBash(python:*)
Other metadata
tags
[
  "saas",
  "langchain",
  "langgraph",
  "python",
  "langchain-1.0",
  "multi-tenant",
  "rbac",
  "enterprise",
  "security"
]

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/langchain-enterprise-rbac