Agent-serving HTTP API has only a single shared token — no per-principal/per-agent authorization and no invocation rate limiting

Aperta
#5,976 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
22/100
Tipo di issue
Funzionalità
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
fastapi, python

Direzione di ricerca

Start with verify_token and the invoke_agent route in src/praisonai/praisonai/api/agent_invoke.py, then read AuthRateLimiter in src/praisonai-bot/praisonai_bot/gateway/rate_limiter.py to see how it keys its buckets. Done means the shared token still works unchanged by default, a principal can be restricted to listed agents (403 otherwise), and a per-principal rate limit returns 429. The design of the principal model and the core protocol needs maintainer input first.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

claude enhancement origin/outsider

Summary

The HTTP endpoint that exposes agents for invocation — POST /api/v1/agents/{agent_id}/invoke — is protected by a single, process-wide shared bearer token. There is no notion of a caller identity (principal), no per-agent scoping (any valid token can invoke every registered agent), and no rate limiting on the invocation path. For a gateway that serves agents to external callers (n8n workflows, internal services, third parties), this is an all-or-nothing gate: one leaked token grants full access to every hosted agent, and there is no throttle to contain abuse or runaway cost.

This is notable because PraisonAI's messaging gateway already models layered, fail-closed access control (per-user allowlists, admission policy, pairing, group policy) and already ships a per-(endpoint, identity) rate limiter. Those patterns simply have not been extended to the programmatic HTTP serving surface.

Current behaviour

src/praisonai/praisonai/api/agent_invoke.py — the only gate is a shared token:

def _call_server_token() -> Optional[str]:          # l.36 — one env token
    ...

async def verify_token(                              # l.58
    ...
    request: Request,
    authorization: Optional[str] = Header(None),
) -> None:
    expected = _call_server_token()
    ...
    if not token or not hmac.compare_digest(token, expected):   # l.112 — all-or-nothing
        raise HTTPException(status_code=401, ...)

The invoke route is gated by that token alone — no principal, no per-agent authorization:

@router.post("/agents/{agent_id}/invoke")            # l.511
async def invoke_agent(
    agent_id: str,
    request: AgentInvokeRequest,
    _: None = Depends(verify_token),                 # l.515 — shared token only
    registry: AgentRegistry = Depends(_registry_dependency),
) -> Union[AgentInvokeResponse, ErrorResponse]:
    ...

Rate limiting exists in the gateway but is scoped to auth/approval, not invocation — src/praisonai-bot/praisonai_bot/gateway/rate_limiter.py:

"""Thread-safe rate limiters for PraisonAI gateway endpoints ...
Protects authentication and approval endpoints against brute-force attacks ..."""
class AuthRateLimiter:                                # keyed by (endpoint, identity)

And gateway/auth.py confirms the single shared secret model (gateway.auth_token). There is no path by which an operator can say "principal X may invoke agent A but not agent B", nor cap a caller's request rate on /invoke.

By contrast, the messaging side already does fine-grained, fail-closed access control — e.g. src/praisonai-bot/praisonai_bot/bots/_config_schema.py (allowlist, blocklist, allowed_users, admin_users, admission policy deny/pair) and bots/_admission.py. The capability exists in the SDK; it just is not available on the HTTP serving surface.

Desired behaviour

  • A caller is identified by a principal (e.g. an API key mapped to a name/role, or an upstream-delegated identity), not just "holds the one token".
  • An operator can scope authorization per agent (and ideally per action), declaratively: principal → which agent IDs it may invoke.
  • The invocation endpoint can be rate limited per principal (token bucket / sliding window), reusing the limiter the gateway already has.
  • Fully backward compatible: with nothing configured, today's single-token behaviour remains the default.

Layer placement

  • Primary layer: wrapper (src/praisonai/praisonai/api/) — this is how users serve/run agents over HTTP; wiring keys/principals and the limiter belongs here.
  • Why not core: core should only expose a small, heavy-import-free authorizer protocol/hook (a contract), not HTTP auth wiring or a credential store.
  • Why not wrapper (as the only layer): the contract (an Authorizer) wants a protocol seam in core so the same decision point is reusable by other front-ends; the wrapper is the primary implementer but references a core protocol.
  • Why not tools: this is not an agent-callable integration.
  • Why not plugins: endpoint-level principal authorization and throttling live at the HTTP boundary, not as a lifecycle wrap around agent execution (a plugin on_auth/on_permission_ask hook may consume the decision, but the gate itself is a serving concern).
  • Secondary touch (optional): core AuthorizerProtocol; reuse gateway/rate_limiter.py.
  • 3-way surface (CLI + YAML + Python): yes — YAML/env for principal→agent grants and rate limits, a CLI flag to enable, and a Python Authorizer override.

Proposed approach

  • Extension point: a core protocol + a wrapper-level FastAPI dependency.
# core: praisonaiagents (protocol only, no heavy imports)
from typing import Protocol, runtime_checkable

@runtime_checkable
class AuthorizerProtocol(Protocol):
    def authorize(self, *, principal: str, agent_id: str, action: str = "invoke") -> bool: ...

# wrapper: api/agent_invoke.py — resolve principal from the credential, then authorize
async def verify_principal(request, authorization=Header(None)) -> str:
    principal = _principal_for_credential(authorization, request)  # key -> name/role; back-compat: shared token -> "default"
    if principal is None:
        raise HTTPException(status_code=401, detail="Unauthorized")
    return principal

@router.post("/agents/{agent_id}/invoke")
async def invoke_agent(agent_id: str, request: AgentInvokeRequest,
                       principal: str = Depends(verify_principal),
                       registry: AgentRegistry = Depends(_registry_dependency)):
    if not _authorizer().authorize(principal=principal, agent_id=agent_id):
        raise HTTPException(status_code=403, detail="Forbidden for this agent")
    if not _invoke_limiter().allow("invoke", principal):            # reuse existing limiter
        raise HTTPException(status_code=429, detail="Rate limit exceeded")
    ...

Resolution sketch

# Before (today): one secret unlocks everything, no throttle
# env: PRAISONAI_CALL_SERVER_TOKEN=supersecret   # grants invoke on ALL agents, unlimited

# After (proposed): per-principal keys, per-agent grants, per-principal rate limit
serve:
  auth:
    principals:
      n8n-prod:   { key_env: N8N_PROD_KEY,  agents: ["support", "sales"], rate: "60/min" }
      analytics:  { key_env: ANALYTICS_KEY, agents: ["reporting"],        rate: "10/min" }
  # omitting this block => today's single-token behaviour (back-compat)
# Python override for embedders:
app.dependency_overrides[_authorizer] = lambda: MyAuthorizer(policy_table)

Severity

High — security + cost/abuse. A single shared token on an agent-execution endpoint means no blast-radius containment (leak = every agent) and no throttle (a stuck or hostile caller can drive unbounded LLM spend). The building blocks already exist in the messaging gateway and the rate limiter; this extends them to the serving surface.

Validation

  • src/praisonai/praisonai/api/agent_invoke.py: _call_server_token (l.36), verify_token (l.58, constant-time compare of one token l.112), invoke_agent route gated only by Depends(verify_token) (l.511–517). No principal, no per-agent check, no rate limit on the route.
  • src/praisonai-bot/praisonai_bot/gateway/rate_limiter.py: limiter docstring states it protects auth/approval endpoints; not applied to invocation.
  • src/praisonai-bot/praisonai_bot/gateway/auth.py: single gateway.auth_token model.
  • Contrast (capability already exists): src/praisonai-bot/praisonai_bot/bots/_config_schema.py fine-grained allowlist/admission; bots/_admission.py.
  • No existing open issue covers invoke-API authorization/rate-limiting (checked #5743 — multi-tenant singletons, a different axis).
Lingua principale
Python
Stelle
9.3k
Fork
1.5k
Merge medio
1g 5h
PR unite (30g)
520

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di MervinPraison/PraisonAI

Tutte le issue di MervinPraison/PraisonAI

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.