Spaces:
Running

WorkPilot-AI / core /tools /http_tool.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
9.51 kB
"""HTTP operation handler shared by OpenAPI imports and the generic HTTP action connector.
A tenant HTTP tool is an ``HttpOperation`` (method, path template, parameter locations,
base URL, auth *scheme*) stored as JSON. The handler:
* builds the request from validated arguments (path parameters are percent-encoded and
may not be ``.``/``..``, so an argument cannot walk the path);
* on a dry run returns the request it *would* send as the preview (auth redacted);
* otherwise injects the credential the **gateway** resolved from the tool's secret ref
(``ctx.credentials["secret"]``): never in the tool spec, the arguments or the result;
* checks the target URL (https, no private/loopback hosts: SSRF guard), sends with a
timeout and no redirects, and caps the response size.
Responses come from a third party: results carry ``"untrusted": True`` so graph code feeds
them to the quarantine extractor rather than to a planner prompt.
"""
from __future__ import annotations
import base64
import ipaddress
import json
from typing import Any, Literal
from urllib.parse import quote, urlsplit
import httpx
from pydantic import BaseModel, Field
from core.config import get_settings
from core.tools.preview import preview_hash
from core.tools.spec import ToolContext, ToolHandler, ToolResult
REDACTED = "***"
_HOP_HEADERS = {"host", "content-length", "authorization", "cookie", "transfer-encoding"}
class UnsafeURL(ValueError):
pass
class HttpAuth(BaseModel):
"""How to present the secret. The secret itself is resolved by the gateway."""
type: Literal["api_key", "bearer", "basic"]
location: Literal["header", "query"] = "header"
name: str = Field(default="Authorization", max_length=100) # header / query param name
class HttpParam(BaseModel):
name: str # name on the wire
field: str # Python field name in the input model
location: Literal["path", "query", "header", "body"]
class HttpOperation(BaseModel):
method: Literal["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
path: str # "/items/{sku}", appended to the base URL
base_url: str
sandbox_base_url: str | None = None
params: list[HttpParam] = Field(default_factory=list)
body_field: str | None = None # whole JSON body from this field ("field" mode)
static_headers: dict[str, str] = Field(default_factory=dict) # non-secret
auth: HttpAuth | None = None
def check_url(url: str) -> None:
"""SSRF guard for tenant-supplied URLs (literal hosts; DNS rebinding needs an egress
proxy in production, see docs/security)."""
s = get_settings()
parts = urlsplit(url)
if parts.scheme not in ("https", "http") or (parts.scheme == "http" and not s.ext_allow_http):
raise UnsafeURL(f"scheme {parts.scheme or '?'} not allowed (https only)")
host = (parts.hostname or "").lower()
if not host:
raise UnsafeURL("URL has no host")
if parts.username or parts.password:
raise UnsafeURL("credentials in URLs are not allowed; use a secret ref")
if s.ext_allow_private_hosts:
return
if host == "localhost" or host.endswith((".localhost", ".local", ".internal")):
raise UnsafeURL(f"host {host} is not allowed")
try:
ip = ipaddress.ip_address(host)
except ValueError:
return
if not ip.is_global:
raise UnsafeURL(f"address {host} is not a public address")
def _path_value(value: Any) -> str:
text = str(value).lower() if isinstance(value, bool) else str(value)
if text in ("", ".", ".."):
raise ValueError(f"invalid path parameter value {text!r}")
return quote(text, safe="")
def build_request(op: HttpOperation, args: dict[str, Any], base_url: str) -> dict[str, Any]:
"""The request as plain data (also the dry-run preview). ``args`` use Python field
names; ``None`` values are omitted."""
path = op.path
query: dict[str, Any] = {}
headers: dict[str, str] = dict(op.static_headers)
body: dict[str, Any] = {}
for p in op.params:
value = args.get(p.field)
if value is None:
if p.location == "path":
raise ValueError(f"missing path parameter {p.name}")
continue
if p.location == "path":
path = path.replace("{" + p.name + "}", _path_value(value))
elif p.location == "query":
query[p.name] = value
elif p.location == "header":
if p.name.lower() in _HOP_HEADERS:
continue
headers[p.name] = str(value)
else:
body[p.name] = value
json_body: Any = None
if op.body_field is not None and args.get(op.body_field) is not None:
json_body = args[op.body_field]
elif body:
json_body = body
return {
"method": op.method,
"url": base_url.rstrip("/") + "/" + path.lstrip("/"),
"query": query,
"headers": headers,
"json": json_body,
}
def _apply_auth(
auth: HttpAuth, secret: str, headers: dict[str, str], query: dict[str, Any]
) -> None:
if auth.type == "bearer":
value = f"Bearer {secret}"
elif auth.type == "basic":
value = "Basic " + base64.b64encode(secret.encode()).decode()
else:
value = secret
if auth.location == "query":
query[auth.name] = value
else:
headers[auth.name if auth.type == "api_key" else "Authorization"] = value
def _redacted(req: dict[str, Any], auth: HttpAuth | None) -> dict[str, Any]:
out = {**req, "headers": dict(req["headers"]), "query": dict(req["query"])}
if auth is not None:
where = out["query"] if auth.location == "query" else out["headers"]
where[auth.name if auth.type == "api_key" else "Authorization"] = REDACTED
return out
async def _read_capped(resp: httpx.Response, limit: int) -> tuple[bytes, bool]:
chunks: list[bytes] = []
size = 0
async for chunk in resp.aiter_bytes():
chunks.append(chunk)
size += len(chunk)
if size > limit:
return b"".join(chunks)[:limit], True
return b"".join(chunks), False
async def send(
req: dict[str, Any],
*,
transport: httpx.AsyncBaseTransport | None = None,
timeout_s: float | None = None,
max_bytes: int | None = None,
) -> ToolResult:
s = get_settings()
check_url(req["url"])
limit = max_bytes or s.ext_max_response_bytes
try:
async with httpx.AsyncClient(
transport=transport, timeout=timeout_s or s.ext_http_timeout_s, follow_redirects=False
) as client:
async with client.stream(
req["method"],
req["url"],
params=req["query"] or None,
headers=req["headers"],
json=req["json"],
) as resp:
raw, truncated = await _read_capped(resp, limit)
status = resp.status_code
ctype = resp.headers.get("content-type", "")
except httpx.TimeoutException:
return ToolResult(ok=False, error="upstream timeout")
except httpx.TransportError as exc:
return ToolResult(ok=False, error=f"upstream unreachable: {type(exc).__name__}")
body: Any
if "json" in ctype and not truncated:
try:
body = json.loads(raw or b"null")
except ValueError:
body = raw.decode("utf-8", "replace")
else:
body = raw.decode("utf-8", "replace")
data = {"status": status, "body": body, "truncated": truncated, "untrusted": True}
if 200 <= status < 300:
return ToolResult(ok=True, data=data)
return ToolResult(ok=False, data=data, error=f"upstream HTTP {status}")
def make_http_handler(
op: HttpOperation,
*,
transport: httpx.AsyncBaseTransport | None = None,
test_mode: bool = False,
) -> ToolHandler:
"""In test mode the request goes to ``sandbox_base_url`` (with the sandbox secret, never
the live one); without a sandbox only dry runs are possible."""
async def handler(params: BaseModel, ctx: ToolContext) -> ToolResult:
args = params.model_dump(mode="json")
base = op.base_url
if test_mode:
if not op.sandbox_base_url and not ctx.dry_run:
return ToolResult(
ok=False,
error="tool is in test mode without a sandbox URL: only dry runs are allowed",
)
base = op.sandbox_base_url or op.base_url
try:
req = build_request(op, args, base)
check_url(req["url"])
except ValueError as exc: # also UnsafeURL
return ToolResult(ok=False, dry_run=ctx.dry_run, error=str(exc))
if ctx.dry_run:
preview = {"request": _redacted(req, op.auth), "mode": "test" if test_mode else "live"}
return ToolResult(ok=True, dry_run=True, data=preview, preview_hash=preview_hash(req))
if op.auth is not None:
secret = ctx.credentials.get("secret")
if not secret:
return ToolResult(ok=False, error="credential for this tool is not configured")
_apply_auth(op.auth, secret, req["headers"], req["query"])
return await send(req, transport=transport)
return handler