From 5f3519d0afa68b1ffbc8b1a1c3c37d2800427458 Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Thu, 19 Nov 2026 22:39:14 +0000 Subject: [PATCH] security: retire the legacy /v1/* key-injection proxy and PORTAL_SECRET --- README.md | 18 +++++------ app/main.py | 93 +---------------------------------------------------- 2 files changed, 9 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index 92d02ce..4ad3914 100644 --- a/README.md +++ b/README.md @@ -145,22 +145,20 @@ with non-expiring purchased credit packs. The per-tier budgets the portal once shipped (free/member/supporter) are retired — there are no per-tier portal settings; the single env knob is `MEMBER_BUDGET`. -## LibreChat wiring +## Chat wiring -Point LibreChat's custom endpoint at this portal (not directly at LiteLLM), -and add the identity header: +LibreChat talks to the **gateway directly** with each member's own key; the +portal is not in the chat request path. (The old `/v1/*` key-injection proxy — +`X-Portal-Secret` + `X-User-Email` — was retired 2026-11-19. It let anyone with +that shared secret spend as any member, and nothing used it.) ```yaml +# librechat-custom/librechat.yaml (excerpt) endpoints: custom: - name: "Inference Cooperative" - apiKey: "${LITELLM_KEY}" - baseURL: "https://portal.inference.coop/v1" - headers: - X-User-Email: "{{LIBRECHAT_USER_EMAIL}}" - models: - default: ["deepseek-v4-flash", "gpt-oss-120b"] - fetch: true + apiKey: "${INFERENCE_COOP_API_KEY}" + baseURL: "https://gateway.inference.coop/v1" ``` ## Status diff --git a/app/main.py b/app/main.py index c889100..9f83d74 100644 --- a/app/main.py +++ b/app/main.py @@ -209,17 +209,6 @@ CLOUDRON_TOKEN = os.environ.get("CLOUDRON_TOKEN", "") LITELLM_BASE = os.environ.get("LITELLM_BASE", "https://gateway.inference.coop") LITELLM_MASTER_KEY = os.environ.get("LITELLM_MASTER_KEY", "") -# Shared secret that the chat frontend uses to authenticate requests to the -# portal. LibreChat sends it as an X-Portal-Secret header; OpenWebUI signs the -# user's email as a JWT (see FORWARD_USER_INFO_HEADER_JWT_SECRET below). -PORTAL_SECRET = os.environ.get("PORTAL_SECRET", "") - -# OpenWebUI can sign the forwarded user identity as a JWT using this shared -# secret. When set, the portal verifies the JWT (HS256) to confirm the email -# genuinely came from OpenWebUI (behind Cloudron SSO) rather than a spoofed -# header. This is stronger than the plain X-Portal-Secret header because the -# email itself is tamper-proof. - # Open WebUI admin API key — used at provisioning time to add the new member to # Open WebUI's `members` group, which gates read access to the shared # "Inference Cooperative Docs" RAG collection. Without this, a new member's @@ -234,8 +223,7 @@ DOCS_KNOWLEDGE_ID = os.environ.get("DOCS_KNOWLEDGE_ID", "946e18ef-c1bc-4c57-b23e # Shared secret that the member dashboard uses to authenticate broker requests. # The dashboard is Cloudron-SSO-gated and passes the authenticated member's -# email; the portal trusts that email only because it carries this secret. Kept -# separate from PORTAL_SECRET so the two can be rotated independently. +# email; the portal trusts that email only because it carries this secret. BROKER_SECRET = os.environ.get("BROKER_SECRET", "") # Secret token required in the Open Collective webhook URL path. Open @@ -956,16 +944,6 @@ async def listmonk_reconcile() -> dict: return {"removed": 0, "emails": [], "error": str(e)} -def _verify_portal_secret(request: Request) -> None: - """Reject requests that didn't come through LibreChat (shared secret).""" - if not PORTAL_SECRET: - # If no secret is configured, refuse to inject keys (fail closed). - raise HTTPException(503, "Portal secret not configured") - provided = request.headers.get("x-portal-secret", "") - if not secrets.compare_digest(provided, PORTAL_SECRET): - raise HTTPException(401, "Invalid portal secret") - - def _verify_admin_token(request: Request) -> None: """Authorize a /admin/* caller (SECURITY 2026-10-27). @@ -4519,75 +4497,6 @@ async def list_models(request: Request): return JSONResponse(content=payload) -@app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"]) -@limiter.limit("120/minute") -async def inject_key(request: Request, path: str): - """Read the member's email from a header, inject their key, forward to LiteLLM.""" - # Verify the request came through the chat frontend, so a direct caller - # can't spoof the user-email header and use another member's key. - # - # ONE auth path: LibreChat sends a plain X-User-Email header plus an - # X-Portal-Secret shared-secret header. OpenWebUI's signed-JWT path was - # retired with the app (2026-11-13) — honouring a shared-secret-signed token - # for an integration nobody runs is auth surface with no user. - _verify_portal_secret(request) - email = ( - request.headers.get("x-user-email", "") - or request.headers.get("x-openwebui-user-email", "") - ) - - if not email: - raise HTTPException(401, "No member identity (user-email header)") - - # Look up the member's key from the persistent store - member_key = get_member_key(email) - - if not member_key: - raise HTTPException(403, "No active membership key") - - # Forward the request to LiteLLM with the member's key, STREAMING the - # response back token-by-token (or byte-by-byte) rather than buffering it. - # Buffering collapsed the model's stream and handed OpenWebUI the full - # answer in one blob, so members saw nothing until generation finished — - # which made chat feel slow even though time-to-first-byte was fine. - body = await request.body() - headers = dict(request.headers) - headers["authorization"] = f"Bearer {member_key}" - headers.pop("host", None) - headers.pop("content-length", None) - headers.pop("accept-encoding", None) # let httpx handle decompression - - timeout = httpx.Timeout(connect=15.0, read=600.0, write=30.0, pool=15.0) - - # Send the request upstream, but don't buffer the body — use a stream. - client = httpx.AsyncClient(timeout=timeout) - upstream_req = client.build_request( - method=request.method, - url=f"{LITELLM_BASE}/v1/{path}", - headers=headers, - content=body, - ) - upstream = await client.send(upstream_req, stream=True) - - async def gen(): - try: - async for chunk in upstream.aiter_raw(): - yield chunk - finally: - await upstream.aclose() - await client.aclose() - - # Pass through the content-type (critical for SSE streaming) and status. - return StreamingResponse( - gen(), - status_code=upstream.status_code, - headers={ - "content-type": upstream.headers.get("content-type", "application/json"), - "cache-control": "no-cache", - }, - ) - - # --- D. Admin / health --- @app.get("/health")