Security
Relevant source files
The following files were used as context for generating this wiki page:
LangChain is a framework for building applications with Large Language Models (LLMs). Due to its extensive ecosystem of integrations with external resources like file systems, APIs, and databases, security is a critical consideration. The framework's security posture is based on a shared responsibility model: LangChain provides tools and guidelines, but developers are ultimately responsible for building secure applications.
This document outlines LangChain's security policy, best practices for developers, and specific security mechanisms implemented within the framework's components. The core philosophy emphasizes limiting permissions, anticipating misuse, and applying a defense-in-depth strategy to mitigate risks such as data corruption, unauthorized access, and resource compromise.
Sources: SECURITY.md, README.md
Vulnerability Reporting
LangChain has a formal process for reporting security vulnerabilities through a partnership with Huntr by Protect AI, which includes a bounty program for its open-source projects.
Sources: SECURITY.md:30-32
Reporting Process
The diagram below illustrates the process for reporting an open-source vulnerability.
This flowchart shows the steps a developer should take to report a security vulnerability in a LangChain open-source project.
Key Points:
- OSS Vulnerabilities: Report to Huntr.
- LangSmith Vulnerabilities: Report via email to
security@langchain.dev. - Other Concerns: Contact
security@langchain.dev.
Sources: SECURITY.md:30-32, SECURITY.md:62-63, SECURITY.md:68-69
Scope of Bug Bounties
The bug bounty program has a defined scope for what is considered eligible.
| Scope | Targets - |
|---|---|
| In-Scope | langchain-core, langchain (with exceptions), langchain-community (with exceptions), langgraph, langserve - |
| Out-of-Scope | langchain-experimental, tools directories in langchain and langchain-community, code documented with security notices, and any LangSmith related repositories or APIs. |
Sources: SECURITY.md:40-60
Developer Security Best Practices
Developers building on LangChain are expected to follow security best practices, as the framework's flexibility can introduce vulnerabilities if not used carefully.
Sources: SECURITY.md:6-8
Core Principles
This diagram shows the three core security principles for developers using LangChain.
- Limit Permissions: Adhere to the principle of least privilege. Grant applications only the permissions they absolutely need. For example, use read-only credentials for databases or limit file system access to specific, safe directories.
- Anticipate Potential Misuse: Assume that an LLM can and will use any permissions it is granted in any possible way. If an agent has credentials that can delete data, assume it might delete data.
- Defense in Depth: Use multiple layers of security. Do not rely on a single technique. For example, combine read-only permissions with sandboxing (e.g., running in a container) to ensure an agent can only access intended data.
Sources: SECURITY.md:9-20
Security Checklist for Contributions
All code contributed to LangChain projects must adhere to a security checklist to prevent common vulnerabilities.
| Check | Description - |
|---|---|
| No Dangerous Patterns | Avoid eval(), exec(), or pickle on user-controlled input. - |
| Proper Exception Handling | Do not use bare except: clauses. Use specific exceptions and a msg variable for error messages. - |
| Clean Code | Remove unreachable or commented-out code before committing. - |
| Resource Management | Ensure proper cleanup of resources like file handles, network connections, and threads to prevent leaks. - |
Sources: CLAUDE.md:68-83
Implemented Security Controls
LangChain includes several components with built-in security considerations.
API Chain Security
The APIChain is designed to make API calls and process responses. It includes a critical security feature to restrict which domains the chain can interact with.
Sources: libs/langchain/langchain/chains/api/base.py
Domain Whitelisting
The APIChain enforces a domain whitelist through the limit_to_domains parameter. If an LLM generates a URL that is not in this list, the chain will raise a ValueError and refuse to make the request. This prevents the chain from making arbitrary requests to potentially malicious or internal-only endpoints.
The logic for this check is implemented in the _check_in_allowed_domain function.
# From: libs/langchain/langchain/chains/api/base.py
def _check_in_allowed_domain(url: str, limit_to_domains: Sequence[str]) -> bool:
"""Check if a URL is in the allowed domains.
Args:
url (str): The input URL.
limit_to_domains (Sequence[str]): The allowed domains.
Returns:
bool: True if the URL is in the allowed domains, False otherwise.
"""
scheme, domain = _extract_scheme_and_domain(url)
for allowed_domain in limit_to_domains:
allowed_scheme, allowed_domain_ = _extract_scheme_and_domain(allowed_domain)
if scheme == allowed_scheme and domain == allowed_domain_:
return True
return False
Sources: libs/langchain/langchain/chains/api/base.py:40-55
The following diagram shows the request flow within APIChain.
This flowchart depicts the control flow in APIChain, highlighting the domain validation step.
The APIChain itself contains a security note in its docstring, warning developers about the risks of exposing it to end-users without proper controls.
Sources: libs/langchain/langchain/chains/api/base.py:68-82, libs/langchain/langchain/chains/api/base.py:246-253
HTML Parsing Security
When splitting HTML documents, LangChain takes measures to prevent XML External Entity (XXE) attacks. The HTMLSectionSplitter is designed with security in mind.
Sources: libs/text-splitters/tests/unit_tests/test_html_security.py
Security tests confirm that:
- External entity loading is blocked.
- The
document()function in XSLT, which could be used to access local files, is disabled. - Network access during parsing is blocked.
- DTD (Document Type Definition) processing is disabled to prevent entity expansion.
An example test case demonstrates how the splitter blocks XXE attacks:
# From: libs/text-splitters/tests/unit_tests/test_html_security.py
def test_xxe_entity_attack_blocked(self) -> None:
"""Test that external entity attacks are blocked."""
# Create HTML content to process
html_content = """<html><body><p>Test content</p></body></html>"""
# Since xslt_path parameter is removed, this attack vector is eliminated
# The splitter should use only the default XSLT
splitter = HTMLSectionSplitter(headers_to_split_on=[("h1", "Header 1")])
# Process the HTML - should not contain any external entity content
result = splitter.split_text(html_content)
# Verify that no external entity content is present
all_content = " ".join([doc.page_content for doc in result])
assert "root:" not in all_content # /etc/passwd content
assert "XXE Attack Result" not in all_content
Sources: libs/text-splitters/tests/unit_tests/test_html_security.py:11-28
Constitutional AI for Harmful Content Prevention
LangChain incorporates the concept of "Constitutional AI," which uses a set of principles to guide and constrain the output of LLMs. This serves as a security and safety layer to prevent the generation of harmful, unethical, or illegal content.
The system uses ConstitutionalPrinciple objects, each containing a critique_request and a revision_request, to self-correct potentially problematic responses.
Sources: libs/langchain/langchain/chains/constitutional_ai/principles.py
Below are some examples of principles aimed at preventing harmful content:
| Name | Critique Request | Revision Request |
|---|---|---|
harmful1 | Identify specific ways in which the assistant's last response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal. | Please rewrite the assistant response to remove any and all harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. |
illegal | Discuss whether the assistant provided any advice that may encourage illegal or dangerous activity from either the human or others. | Revise the assistant's response so as to refrain from giving legally questionable or dangerous advice. |
criminal | Read the assistant's last response carefully and identify anything it said that provides advice or assistance in potentially criminal activities... | Rewrite the assistant response to avoid assisting the human with criminal plans or activities... |
uo-security-2 | Discuss whether the AI model's response appropriately handles unethical, misleading, manipulative or otherwise problematic requests or information. | Please rewrite the AI model's response so that it appropriately handles unethical, misleading, manipulative or otherwise problematic requests or information. |
uo-ethics-3 | Discuss whether the AI model's response contains any protected information that should not be shared, such as confidential material or sensitive personal data. | Please rewrite the AI model's response so that it does not contain any protected information that should not be shared... |
Sources: libs/langchain/langchain/chains/constitutional_ai/principles.py:8-11, libs/langchain/langchain/chains/constitutional_ai/principles.py:82-85, libs/langchain/langchain/chains/constitutional_ai/principles.py:100-103, libs/langchain/langchain/chains/constitutional_ai/principles.py:202-205, libs/langchain/langchain/chains/constitutional_ai/principles.py:220-223
Summary
Security in LangChain is a collaborative effort between the framework and the application developer. LangChain provides a secure foundation by offering mechanisms like domain whitelisting in API chains, hardened HTML parsers, and safety-oriented features like Constitutional AI. However, developers must remain vigilant, follow established security best practices like the principle of least privilege and defense-in-depth, and understand the implications of granting LLMs access to external tools and data. The official security policy and vulnerability reporting program further underscore the project's commitment to maintaining a secure ecosystem.
Sources: SECURITY.md, CLAUDE.md