Spaces:
Running
Running
File size: 9,507 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | """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
|