Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

feat: Add optional backend ingest router (#1720)

Edwin Jose17e8a19d3549
diff --git a/.env.example b/.env.example
index acbc787b5..a44ce3c70 100644
--- a/.env.example
+++ b/.env.example
@@ -53,6 +53,26 @@ LANGFLOW_URL_INGEST_FLOW_ID=72c3d17c-2dac-4a73-b48a-6518473d7830
# LANGFLOW_INGEST_FLOW_ID=1402618b-e6d1-4ff2-9a11-d6ce71186915
NUDGES_FLOW_ID=ebc01d31-1976-46ce-a385-b0240327226c
+# --- Backend ingestion-callback proxy router --------------------------------
+# When enabled, a tiny standalone uvicorn app is started in the same process as
+# the backend (its own port) that proxies ONLY the Langflow ingest callback
+# (POST /internal/ingest/chunks) to the real backend. Langflow is then pointed
+# at this router instead of the backend internal URL, narrowing the surface
+# Langflow can reach. Disabled by default.
+# OPENRAG_BACKEND_ROUTER_ENABLE=false
+# Port the router listens on (inside the backend container/pod).
+# OPENRAG_BACKEND_ROUTER_PORT=8100
+# OPENRAG_BACKEND_ROUTER_HOST=0.0.0.0
+# Base URL Langflow calls back to. Defaults to the backend host on the router
+# port (derived from OPENRAG_BACKEND_INTERNAL_URL); set only if the router is
+# fronted by a separate Service/ingress.
+# OPENRAG_BACKEND_ROUTER_URL=
+# Upstream the router forwards callbacks to. The router is co-located with the
+# backend (same process), so it defaults to loopback on the backend's port
+# (port derived from OPENRAG_BACKEND_INTERNAL_URL, host forced to 127.0.0.1).
+# Set only to override the upstream entirely.
+# OPENRAG_BACKEND_ROUTER_UPSTREAM_URL=http://127.0.0.1:8000
+
# Base64 AES-256-GCM Master Encryption Key
# If not provided, OpenRAG will automatically generate a secure 32-byte key when you run the TUI or CLI wizard.
# If completely unset during normal execution, the master encryption system will remain inactive.
diff --git a/Dockerfile.backend b/Dockerfile.backend
index a08f98e08..513f6c37b 100644
--- a/Dockerfile.backend
+++ b/Dockerfile.backend
@@ -97,6 +97,8 @@ RUN mkdir -p keys data config flows/backup openrag-documents \
# (belt-and-suspenders for Docker where :U is not supported), then execs the
# application as appuser via gosu.
EXPOSE 8000
+# Ingestion-callback proxy router (OPENRAG_BACKEND_ROUTER_ENABLE), when enabled.
+EXPOSE 8100
ENTRYPOINT ["/entrypoint.sh"]
CMD ["python", "src/main.py"]
diff --git a/docker-compose.yml b/docker-compose.yml
index 1c5d06ae0..16f8d48d7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -57,6 +57,7 @@ services:
- OPENSEARCH_HOST=${OPENSEARCH_HOST:-opensearch}
- LANGFLOW_URL=http://langflow:7860
- OPENRAG_BACKEND_INTERNAL_URL=${OPENRAG_BACKEND_INTERNAL_URL:-http://openrag-backend:8000}
+ - OPENRAG_BACKEND_ROUTER_ENABLE=${OPENRAG_BACKEND_ROUTER_ENABLE:-false}
- LANGFLOW_PUBLIC_URL=${LANGFLOW_PUBLIC_URL}
- LANGFLOW_AUTO_LOGIN=${LANGFLOW_AUTO_LOGIN}
- LANGFLOW_SUPERUSER=${LANGFLOW_SUPERUSER}
diff --git a/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml b/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml
index b62845b55..6cbdbfd65 100644
--- a/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml
+++ b/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml
@@ -52,6 +52,10 @@ stringData:
# Langflow url
LANGFLOW_URL={{ include "openrag.langflow.url" . | quote }}
OPENRAG_BACKEND_INTERNAL_URL={{ include "openrag.backend.url" . | quote }}
+ {{- if .Values.backend.ingestRouter.enabled }}
+ OPENRAG_BACKEND_ROUTER_ENABLE=true
+ OPENRAG_BACKEND_ROUTER_PORT={{ .Values.backend.ingestRouter.port }}
+ {{- end }}
# Flow IDs
{{- if .Values.langflow.flows.chatFlowId }}
diff --git a/kubernetes/helm/openrag/templates/backend/deployment.yaml b/kubernetes/helm/openrag/templates/backend/deployment.yaml
index 34864bf98..80c3a295a 100644
--- a/kubernetes/helm/openrag/templates/backend/deployment.yaml
+++ b/kubernetes/helm/openrag/templates/backend/deployment.yaml
@@ -209,6 +209,11 @@ spec:
- name: http
containerPort: 8000
protocol: TCP
+ {{- if .Values.backend.ingestRouter.enabled }}
+ - name: ingest-router
+ containerPort: {{ .Values.backend.ingestRouter.port }}
+ protocol: TCP
+ {{- end }}
volumeMounts:
- name: openrag-dotenv
mountPath: /app/.env
diff --git a/kubernetes/helm/openrag/templates/backend/service.yaml b/kubernetes/helm/openrag/templates/backend/service.yaml
index d105de864..b6fc44bf6 100644
--- a/kubernetes/helm/openrag/templates/backend/service.yaml
+++ b/kubernetes/helm/openrag/templates/backend/service.yaml
@@ -13,6 +13,12 @@ spec:
targetPort: http
protocol: TCP
name: http
+ {{- if .Values.backend.ingestRouter.enabled }}
+ - port: {{ .Values.backend.ingestRouter.port }}
+ targetPort: ingest-router
+ protocol: TCP
+ name: ingest-router
+ {{- end }}
selector:
{{- include "openrag.backend.selectorLabels" . | nindent 4 }}
{{- end }}
diff --git a/kubernetes/helm/openrag/values.yaml b/kubernetes/helm/openrag/values.yaml
index ec17ef5e4..8528442ff 100644
--- a/kubernetes/helm/openrag/values.yaml
+++ b/kubernetes/helm/openrag/values.yaml
@@ -350,6 +350,14 @@ backend:
type: ClusterIP
port: 8000
+ # Ingestion-callback proxy router (OPENRAG_BACKEND_ROUTER_ENABLE). When
+ # enabled, the backend also serves a tiny proxy on `port` that forwards only
+ # the Langflow ingest callback; Langflow is pointed at it instead of the full
+ # backend internal API. Exposes the port on the backend Deployment + Service.
+ ingestRouter:
+ enabled: false
+ port: 8100
+
# ============================================================================
# OpenRAG Frontend Configuration
# ============================================================================
diff --git a/kubernetes/operator/internal/controller/env.go b/kubernetes/operator/internal/controller/env.go
index 56d7eeff5..df9af75c4 100644
--- a/kubernetes/operator/internal/controller/env.go
+++ b/kubernetes/operator/internal/controller/env.go
@@ -94,14 +94,16 @@ func NewEnvVarManager() *EnvVarManager {
},
DefaultOpenRagBEEnvVars: map[string]string{
// Langflow connection
- "LANGFLOW_URL": "http://langflow:7860",
- "OPENRAG_BACKEND_INTERNAL_URL": "http://openrag-be:8000",
- "LANGFLOW_TIMEOUT": "2400",
- "LANGFLOW_CONNECT_TIMEOUT": "30",
- "LANGFLOW_AUTO_LOGIN": "true",
- "LANGFLOW_KEY_RETRIES": "15",
- "LANGFLOW_KEY_RETRY_DELAY": "2",
- "LANGFLOW_KEY": "",
+ "LANGFLOW_URL": "http://langflow:7860",
+ "OPENRAG_BACKEND_INTERNAL_URL": "http://openrag-be:8000",
+ "OPENRAG_BACKEND_ROUTER_ENABLE": "false",
+ "OPENRAG_BACKEND_ROUTER_PORT": "8100",
+ "LANGFLOW_TIMEOUT": "2400",
+ "LANGFLOW_CONNECT_TIMEOUT": "30",
+ "LANGFLOW_AUTO_LOGIN": "true",
+ "LANGFLOW_KEY_RETRIES": "15",
+ "LANGFLOW_KEY_RETRY_DELAY": "2",
+ "LANGFLOW_KEY": "",
// Backend data paths
"OPENRAG_DATA_PATH": "/app/backend-data",
diff --git a/kubernetes/operator/internal/controller/openrag_controller.go b/kubernetes/operator/internal/controller/openrag_controller.go
index f72316199..5bf46ddae 100644
--- a/kubernetes/operator/internal/controller/openrag_controller.go
+++ b/kubernetes/operator/internal/controller/openrag_controller.go
@@ -33,6 +33,10 @@ const (
specHashAnnotation = "openr.ag/spec-hash"
immutableAnnotation = "openr.ag/immutable"
+ // backendIngestRouterPort is the port the optional ingestion-callback proxy
+ // router listens on inside the backend pod (OPENRAG_BACKEND_ROUTER_ENABLE).
+ backendIngestRouterPort int32 = 8100
+
// Condition types
conditionBackendReady = "BackendReady"
@@ -607,6 +611,18 @@ func (r *OpenRAGReconciler) reconcileServices(ctx context.Context, o *openragv1a
continue
}
+ svcPorts := []corev1.ServicePort{
+ {Name: "http", Port: d.port, Protocol: corev1.ProtocolTCP},
+ }
+ // The backend optionally serves the ingestion-callback proxy router on
+ // its own port (OPENRAG_BACKEND_ROUTER_ENABLE); expose it so Langflow
+ // can reach only that endpoint instead of the full backend API.
+ if d.role == "be" {
+ svcPorts = append(svcPorts, corev1.ServicePort{
+ Name: "ingest-router", Port: backendIngestRouterPort, Protocol: corev1.ProtocolTCP,
+ })
+ }
+
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: getServiceName(o, d.role), // Use custom name if specified
@@ -616,9 +632,7 @@ func (r *OpenRAGReconciler) reconcileServices(ctx context.Context, o *openragv1a
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeClusterIP,
Selector: componentLabels(o.Name, d.role),
- Ports: []corev1.ServicePort{
- {Name: "http", Port: d.port, Protocol: corev1.ProtocolTCP},
- },
+ Ports: svcPorts,
},
}
if err := r.setOwnerOrLabel(o, svc, targetNS); err != nil {
@@ -775,7 +789,7 @@ func (r *OpenRAGReconciler) backendDeployment(o *openragv1alpha1.OpenRAG, target
Name: "backend",
Image: spec.Image,
ImagePullPolicy: spec.ImagePullPolicy,
- Ports: []corev1.ContainerPort{{Name: "http", ContainerPort: 8000}},
+ Ports: []corev1.ContainerPort{{Name: "http", ContainerPort: 8000}, {Name: "ingest-router", ContainerPort: backendIngestRouterPort}},
Env: envVars,
Resources: spec.Resources,
SecurityContext: spec.SecurityContext,
diff --git a/src/app/router_app.py b/src/app/router_app.py
new file mode 100644
index 000000000..805dd144b
--- /dev/null
+++ b/src/app/router_app.py
@@ -0,0 +1,158 @@
+"""Standalone ingestion-callback proxy router.
+
+A deliberately tiny FastAPI/uvicorn app that exposes ONLY the Langflow ingest
+callback endpoint (``POST /internal/ingest/chunks``) and forwards it to the real
+backend. It runs in the same process as the main backend (a daemon thread on its
+own port) when ``OPENRAG_BACKEND_ROUTER_ENABLE`` is set, so Langflow's reachable
+surface narrows to this single route instead of the full backend internal API.
+
+It is a thin reverse proxy only — it does NOT validate the ingest JWT; the real
+backend still does. Its sole job is network-surface isolation.
+"""
+
+from __future__ import annotations
+
+import threading
+
+import httpx
+import uvicorn
+from fastapi import FastAPI, Request, Response
+
+from app.middleware import RequestLoggingMiddleware
+from config.settings import (
+ ACCESS_LOG_ENABLED,
+ INGEST_CALLBACK_PATH,
+ OPENRAG_BACKEND_ROUTER_HOST,
+ OPENRAG_BACKEND_ROUTER_PORT,
+ OPENRAG_BACKEND_ROUTER_UPSTREAM_URL,
+)
+from utils.logging_config import get_logger
+
+logger = get_logger(__name__)
+
+# Where the proxy forwards callbacks: loopback to the co-located backend (NOT the
+# advertised service name, which may not resolve from where the router runs).
+_UPSTREAM_URL = f"{OPENRAG_BACKEND_ROUTER_UPSTREAM_URL}{INGEST_CALLBACK_PATH}"
+
+# Only these request headers are forwarded upstream; everything else (Host,
+# hop-by-hop headers, etc.) is dropped so the router cannot be abused as an open
+# proxy. The ingest token travels in either Authorization or the custom header.
+_FORWARDED_HEADERS = ("authorization", "x-openrag-ingest-token", "content-type")
+_UPSTREAM_TIMEOUT = httpx.Timeout(60.0)
+
+
+async def _proxy_ingest_chunks(request: Request) -> Response:
+ """Forward the ingest callback to the real backend and relay its response."""
+ upstream_url = _UPSTREAM_URL
+ body = await request.body()
+ headers = {
+ key: value for key, value in request.headers.items() if key.lower() in _FORWARDED_HEADERS
+ }
+ try:
+ async with httpx.AsyncClient(timeout=_UPSTREAM_TIMEOUT) as client:
+ upstream = await client.post(upstream_url, content=body, headers=headers)
+ except httpx.HTTPError as e:
+ logger.error(
+ "[Router] Ingest callback failed to reach backend",
+ upstream=upstream_url,
+ error=str(e),
+ )
+ return Response(
+ content=b'{"detail":"ingest router upstream unreachable"}',
+ status_code=502,
+ media_type="application/json",
+ )
+ logger.info(
+ "[Router] Forwarded ingest callback",
+ upstream=upstream_url,
+ upstream_status=upstream.status_code,
+ bytes=len(body),
+ )
+ return Response(
+ content=upstream.content,
+ status_code=upstream.status_code,
+ media_type=upstream.headers.get("content-type"),
+ )
+
+
+async def _health() -> dict[str, str]:
+ return {"status": "ok"}
+
+
+def create_router_app() -> FastAPI:
+ """Build the minimal proxy app: only the ingest callback + a health probe.
+
+ No other paths are registered, so every other request returns 404.
+ """
+ app = FastAPI(
+ title="OpenRAG Ingest Router",
+ docs_url=None,
+ redoc_url=None,
+ openapi_url=None,
+ )
+ # Reuse the backend's structured access logging so every forwarded callback
+ # emits an "[API] Request" line (method/path/status/duration) to the same
+ # stdout as the backend. Without this, uvicorn.access is globally silenced.
+ app.add_middleware(RequestLoggingMiddleware)
+ app.add_api_route(INGEST_CALLBACK_PATH, _proxy_ingest_chunks, methods=["POST"])
+ app.add_api_route("/health", _health, methods=["GET"])
+ return app
+
+
+class _RouterServer(uvicorn.Server):
+ """uvicorn Server tailored for the router's daemon thread.
+
+ - Signal handlers are only installable on the main thread, so make them a
+ no-op (the router runs on a daemon thread).
+ - Emit an explicit readiness/failure log once ``startup()`` has bound (or
+ failed to bind) the listening socket, so operators can confirm the router
+ is actually up — uvicorn's own "Uvicorn running on …" line is INFO and is
+ filtered out by the ``uvicorn.error`` WARNING level.
+ """
+
+ def install_signal_handlers(self) -> None: # pragma: no cover - thread glue
+ pass
+
+ async def startup(self, sockets=None) -> None:
+ # uvicorn aborts a failed bind (e.g. port in use) by raising SystemExit
+ # from startup(); surface it with router context so the failure is
+ # attributable, then let the daemon thread unwind.
+ try:
+ await super().startup(sockets=sockets)
+ except (SystemExit, OSError) as e:
+ logger.error(
+ "[Router] Ingest router failed to start",
+ host=OPENRAG_BACKEND_ROUTER_HOST,
+ port=OPENRAG_BACKEND_ROUTER_PORT,
+ error=str(e),
+ )
+ raise
+ if self.should_exit:
+ logger.error(
+ "[Router] Ingest router failed to start",
+ host=OPENRAG_BACKEND_ROUTER_HOST,
+ port=OPENRAG_BACKEND_ROUTER_PORT,
+ )
+ else:
+ logger.info(
+ "[Router] Ingest router ready",
+ host=OPENRAG_BACKEND_ROUTER_HOST,
+ port=OPENRAG_BACKEND_ROUTER_PORT,
+ upstream=_UPSTREAM_URL,
+ )
+
+
+def start_backend_router() -> None:
+ """Launch the proxy app on a daemon thread (it dies with the process)."""
+ config = uvicorn.Config(
+ create_router_app(),
+ host=OPENRAG_BACKEND_ROUTER_HOST,
+ port=OPENRAG_BACKEND_ROUTER_PORT,
+ log_config=None,
+ access_log=ACCESS_LOG_ENABLED,
+ )
+ threading.Thread(
+ target=_RouterServer(config).run,
+ daemon=True,
+ name="backend-router",
+ ).start()
diff --git a/src/config/settings.py b/src/config/settings.py
index cadc63b7d..280667e73 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -3,6 +3,7 @@ import concurrent.futures
import os
import threading
from typing import Any
+from urllib.parse import urlsplit, urlunsplit
import httpx
from agentd.patch import patch_openai_with_mcp
@@ -67,6 +68,72 @@ OPENRAG_BACKEND_INTERNAL_URL = os.getenv(
"OPENRAG_BACKEND_INTERNAL_URL",
"http://openrag-backend:8000",
).rstrip("/")
+
+# --- Backend ingestion-callback proxy router ------------------------------
+# A standalone, minimal uvicorn app (spun up in the same process as the main
+# backend, on its own port) that proxies ONLY the Langflow ingest callback
+# (POST /internal/ingest/chunks) to the real backend. When enabled, Langflow is
+# pointed at the router instead of the backend internal URL, so Langflow's
+# reachable surface narrows to that single endpoint.
+INGEST_CALLBACK_PATH = "/internal/ingest/chunks"
+OPENRAG_BACKEND_ROUTER_ENABLE = os.getenv("OPENRAG_BACKEND_ROUTER_ENABLE", "false").lower() in (
+ "true",
+ "1",
+ "yes",
+)
+OPENRAG_BACKEND_ROUTER_HOST = os.getenv("OPENRAG_BACKEND_ROUTER_HOST", "0.0.0.0")
+OPENRAG_BACKEND_ROUTER_PORT = get_env_int("OPENRAG_BACKEND_ROUTER_PORT", 8100)
+
+
+def _derive_router_url() -> str:
+ """Default router URL: the backend host on the router port.
+
+ The router runs in the SAME pod/container as the backend, so it shares the
+ backend's host and differs only by port. Deriving from
+ OPENRAG_BACKEND_INTERNAL_URL means this resolves correctly in every
+ environment that var already works in (Helm, operator) with no new Service.
+ """
+ parts = urlsplit(OPENRAG_BACKEND_INTERNAL_URL)
+ host = parts.hostname or "openrag-backend"
+ netloc = f"{host}:{OPENRAG_BACKEND_ROUTER_PORT}"
+ return urlunsplit((parts.scheme or "http", netloc, "", "", ""))
+
+
+# Externally reachable base URL Langflow calls back to. Defaults to the backend
+# host on the router port; override only if fronted by a separate Service/ingress.
+OPENRAG_BACKEND_ROUTER_URL = (
+ os.getenv("OPENRAG_BACKEND_ROUTER_URL") or _derive_router_url()
+).rstrip("/")
+
+
+# Upstream the router FORWARDS callbacks to. The router is co-located with the
+# backend (same process), so the HOST is always loopback — but the scheme/port
+# are sourced from OPENRAG_BACKEND_INTERNAL_URL so the upstream tracks the
+# backend's configured port automatically. We force 127.0.0.1 (not the advertised
+# service name) because that name need not resolve where the router runs (e.g. a
+# host-run backend). Loopback is correct in every mode: host dev, single
+# container, and same k8s pod.
+def _derive_router_upstream_url() -> str:
+ parts = urlsplit(OPENRAG_BACKEND_INTERNAL_URL)
+ port = parts.port or 8000
+ return urlunsplit((parts.scheme or "http", f"127.0.0.1:{port}", "", "", ""))
+
+
+OPENRAG_BACKEND_ROUTER_UPSTREAM_URL = (
+ os.getenv("OPENRAG_BACKEND_ROUTER_UPSTREAM_URL") or _derive_router_upstream_url()
+).rstrip("/")
+
+
+def get_ingest_callback_url() -> str:
+ """URL Langflow should call back to: the router when enabled, else the backend."""
+ base = (
+ OPENRAG_BACKEND_ROUTER_URL
+ if OPENRAG_BACKEND_ROUTER_ENABLE
+ else OPENRAG_BACKEND_INTERNAL_URL
+ )
+ return f"{base}{INGEST_CALLBACK_PATH}"
+
+
NUDGES_FLOW_ID = os.getenv("NUDGES_FLOW_ID") or "ebc01d31-1976-46ce-a385-b0240327226c"
diff --git a/src/main.py b/src/main.py
index 6042f460c..96c852998 100644
--- a/src/main.py
+++ b/src/main.py
@@ -87,6 +87,17 @@ if __name__ == "__main__":
app = asyncio.run(create_app())
+ # Optionally spin up the standalone ingestion-callback proxy router in this
+ # same process (own daemon thread + port) so Langflow calls back to it
+ # instead of the full backend internal API surface.
+ from config.settings import OPENRAG_BACKEND_ROUTER_ENABLE, OPENRAG_BACKEND_ROUTER_PORT
+
+ if OPENRAG_BACKEND_ROUTER_ENABLE:
+ from app.router_app import start_backend_router
+
+ start_backend_router()
+ logger.info("Backend ingestion router enabled", port=OPENRAG_BACKEND_ROUTER_PORT)
+
uvicorn.run(
app,
workers=1,
diff --git a/src/services/langflow_file_service.py b/src/services/langflow_file_service.py
index ae50b0edb..ca2942115 100644
--- a/src/services/langflow_file_service.py
+++ b/src/services/langflow_file_service.py
@@ -12,8 +12,8 @@ from config.settings import (
LANGFLOW_INGEST_CALLBACK_BATCH_SIZE,
LANGFLOW_INGEST_FLOW_ID,
LANGFLOW_URL_INGEST_FLOW_ID,
- OPENRAG_BACKEND_INTERNAL_URL,
clients,
+ get_ingest_callback_url,
)
from services.document_index_writer import DocumentIndexContext
from utils.hash_utils import hash_id
@@ -226,7 +226,7 @@ class LangflowFileService:
document_id=document_id,
ingest_run_id=ingest_run_id,
index_name=context.index_name,
- callback_url=f"{OPENRAG_BACKEND_INTERNAL_URL}/internal/ingest/chunks",
+ callback_url=get_ingest_callback_url(),
)
return token, ingest_run_id
@@ -239,9 +239,7 @@ class LangflowFileService:
if not ingest_token or not ingest_run_id:
return {}
return {
- "X-Langflow-Global-Var-OPENRAG_INGEST_URL": (
- f"{OPENRAG_BACKEND_INTERNAL_URL}/internal/ingest/chunks"
- ),
+ "X-Langflow-Global-Var-OPENRAG_INGEST_URL": get_ingest_callback_url(),
"X-Langflow-Global-Var-OPENRAG_INGEST_TOKEN": ingest_token,
"X-Langflow-Global-Var-OPENRAG_INGEST_RUN_ID": ingest_run_id,
"X-Langflow-Global-Var-OPENRAG_INGEST_BATCH_SIZE": str(
diff --git a/tests/unit/test_backend_router.py b/tests/unit/test_backend_router.py
new file mode 100644
index 000000000..567e523f2
--- /dev/null
+++ b/tests/unit/test_backend_router.py
@@ -0,0 +1,106 @@
+"""Tests for the standalone ingestion-callback proxy router and the callback-URL
+selection helper that points Langflow at it."""
+
+from fastapi.testclient import TestClient
+
+from app import router_app
+from config import settings
+
+# --- callback URL selection -------------------------------------------------
+
+
+def test_callback_url_uses_router_when_enabled(monkeypatch):
+ monkeypatch.setattr(settings, "OPENRAG_BACKEND_ROUTER_ENABLE", True)
+ monkeypatch.setattr(settings, "OPENRAG_BACKEND_ROUTER_URL", "http://router:8100")
+ assert settings.get_ingest_callback_url() == "http://router:8100/internal/ingest/chunks"
+
+
+def test_callback_url_uses_backend_when_disabled(monkeypatch):
+ monkeypatch.setattr(settings, "OPENRAG_BACKEND_ROUTER_ENABLE", False)
+ monkeypatch.setattr(settings, "OPENRAG_BACKEND_INTERNAL_URL", "http://be:8000")
+ assert settings.get_ingest_callback_url() == "http://be:8000/internal/ingest/chunks"
+
+
+def test_router_url_derives_backend_host_on_router_port(monkeypatch):
+ monkeypatch.setattr(settings, "OPENRAG_BACKEND_INTERNAL_URL", "http://openrag-be:8000")
+ monkeypatch.setattr(settings, "OPENRAG_BACKEND_ROUTER_PORT", 8100)
+ assert settings._derive_router_url() == "http://openrag-be:8100"
+
+
+# --- proxy behaviour --------------------------------------------------------
+
+
+class _FakeResponse:
+ def __init__(self, status_code, content, headers):
+ self.status_code = status_code
+ self.content = content
+ self.headers = headers
+
+
+class _FakeClient:
+ """Async-context-manager stand-in for httpx.AsyncClient capturing the call."""
+
+ def __init__(self, captured):
+ self._captured = captured
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def post(self, url, content=None, headers=None):
+ self._captured["url"] = url
+ self._captured["content"] = content
+ self._captured["headers"] = headers
+ return _FakeResponse(200, b'{"status":"ok"}', {"content-type": "application/json"})
+
+
+def test_proxy_forwards_only_allowlisted_headers(monkeypatch):
+ captured: dict = {}
+ monkeypatch.setattr(router_app.httpx, "AsyncClient", lambda *a, **k: _FakeClient(captured))
+
+ client = TestClient(router_app.create_router_app())
+ resp = client.post(
+ "/internal/ingest/chunks",
+ content=b'{"ingest_run_id":"run-1","chunks":[]}',
+ headers={
+ "Authorization": "Bearer tok",
+ "X-OpenRAG-Ingest-Token": "tok2",
+ "Content-Type": "application/json",
+ "X-Evil": "should-be-dropped",
+ },
+ )
+
+ assert resp.status_code == 200
+ assert resp.json() == {"status": "ok"}
+ # Forwarded to the co-located backend over LOOPBACK (not the service name),
+ # with the original body.
+ assert captured["url"] == router_app._UPSTREAM_URL
+ assert captured["url"].startswith("http://127.0.0.1:8000")
+ assert captured["url"].endswith(settings.INGEST_CALLBACK_PATH)
+ assert captured["content"] == b'{"ingest_run_id":"run-1","chunks":[]}'
+ fwd = {k.lower() for k in captured["headers"]}
+ assert "authorization" in fwd
+ assert "x-openrag-ingest-token" in fwd
+ assert "x-evil" not in fwd
+
+
+def test_proxy_returns_502_when_upstream_unreachable(monkeypatch):
+ class _BoomClient(_FakeClient):
+ async def post(self, *a, **k):
+ raise router_app.httpx.ConnectError("nope")
+
+ monkeypatch.setattr(router_app.httpx, "AsyncClient", lambda *a, **k: _BoomClient({}))
+ client = TestClient(router_app.create_router_app())
+ resp = client.post("/internal/ingest/chunks", content=b"{}")
+ assert resp.status_code == 502
+
+
+def test_router_exposes_only_the_callback_and_health():
+ client = TestClient(router_app.create_router_app())
+ assert client.get("/health").status_code == 200
+ # No other path is registered.
+ assert client.get("/some/other/path").status_code == 404
+ # Callback is POST-only.
+ assert client.get("/internal/ingest/chunks").status_code == 405