Spaces:
Running

File size: 13,272 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
"""OpenAPI 3.x import: every operation becomes a tenant tool (Phase 16).



``parse_spec`` accepts JSON or YAML text (or an already-parsed dict); ``fetch_spec`` reads a

URL through an injectable fetcher (tests pass fixtures, production uses httpx with the SSRF

guard, a timeout and a size cap). ``import_operations`` resolves local ``$ref``s and turns

each ``paths.<path>.<method>`` into an ``ImportedOperation``:



* ``input_schema``: one property per path/query/header parameter, plus the JSON request

  body (its top-level properties are flattened when they don't collide with a parameter,

  otherwise the body is a single ``body`` argument);

* ``suggested_tier`` from the HTTP method (GET/HEAD -> T0, POST/PUT/PATCH -> T2,

  DELETE -> T3). The tool is *stored* as T3 until an owner confirms a tier;

* ``http``: the ``HttpOperation`` the handler executes; credentials are referenced by the

  tenant's secret ref and injected by the gateway, never part of the spec.



Third-party descriptions are untrusted text that ends up in tool search results, so they

are stripped of control characters and truncated; the owner reviews every tool before it

can run outside T3/test mode (tool-poisoning defense).

"""

from __future__ import annotations

import json
import re
from collections.abc import Awaitable, Callable
from typing import Any

import httpx
import yaml
from pydantic import BaseModel

from core.config import get_settings
from core.tools.http_tool import HttpAuth, HttpOperation, HttpParam, check_url
from core.tools.jsonschema_model import (
    SchemaError,
    field_name,
    model_from_schema,
    property_fields,
)
from core.tools.preview import canonical_json, sha256_hex
from core.tools.spec import RiskTier

METHODS = ("get", "head", "post", "put", "patch", "delete")
SUGGESTED_TIER = {
    "GET": RiskTier.T0_READ,
    "HEAD": RiskTier.T0_READ,
    "POST": RiskTier.T2_EXTERNAL,
    "PUT": RiskTier.T2_EXTERNAL,
    "PATCH": RiskTier.T2_EXTERNAL,
    "DELETE": RiskTier.T3_CRITICAL,
}
MAX_REF_DEPTH = 25
MAX_DESCRIPTION = 500
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
_SLUG = re.compile(r"^[a-z][a-z0-9_]{1,39}$")

Fetcher = Callable[[str], Awaitable[bytes]]


class OpenAPIImportError(ValueError):
    pass


class ImportedOperation(BaseModel):
    name: str  # "<prefix>.<operation>"
    operation_id: str
    description: str
    method: str
    path: str
    input_schema: dict[str, Any]
    suggested_tier: int
    http: HttpOperation

    def definition(self) -> dict[str, Any]:
        """What the owner confirms; its hash is pinned (a re-import that changes it shows up

        as a definition change)."""
        return {
            "name": self.name,
            "description": self.description,
            "input_schema": self.input_schema,
            "http": self.http.model_dump(mode="json"),
        }

    def definition_hash(self) -> str:
        return sha256_hex(canonical_json(self.definition()))


def clean_text(text: Any, limit: int = MAX_DESCRIPTION) -> str:
    return _CONTROL.sub(" ", str(text or "")).strip()[:limit]


def parse_spec(raw: bytes | str | dict[str, Any]) -> dict[str, Any]:
    if isinstance(raw, dict):
        doc: Any = raw
    else:
        data = raw.encode() if isinstance(raw, str) else raw
        if len(data) > get_settings().ext_max_spec_bytes:
            raise OpenAPIImportError("spec is too large")
        text = data.decode("utf-8", "replace")
        try:
            doc = json.loads(text)
        except ValueError:
            try:
                doc = yaml.safe_load(text)
            except yaml.YAMLError as exc:
                raise OpenAPIImportError(f"not JSON or YAML: {exc}") from exc
    if not isinstance(doc, dict):
        raise OpenAPIImportError("spec must be a JSON/YAML object")
    version = str(doc.get("openapi", ""))
    if not version.startswith("3."):
        raise OpenAPIImportError("only OpenAPI 3.x documents are supported")
    if not isinstance(doc.get("paths"), dict):
        raise OpenAPIImportError("spec has no paths")
    return doc


async def default_fetcher(url: str) -> bytes:
    check_url(url)
    s = get_settings()
    async with (
        httpx.AsyncClient(timeout=s.ext_http_timeout_s, follow_redirects=False) as client,
        client.stream("GET", url) as resp,
    ):
        if resp.status_code != 200:
            raise OpenAPIImportError(f"fetching spec failed: HTTP {resp.status_code}")
        out = b""
        async for chunk in resp.aiter_bytes():
            out += chunk
            if len(out) > s.ext_max_spec_bytes:
                raise OpenAPIImportError("spec is too large")
        return out


async def fetch_spec(url: str, fetcher: Fetcher | None = None) -> dict[str, Any]:
    return parse_spec(await (fetcher or default_fetcher)(url))


# ------------------------------------------------------------------ $ref resolution


def _pointer(root: dict[str, Any], ref: str) -> Any:
    if not ref.startswith("#/"):
        raise OpenAPIImportError(f"only local $refs are supported: {ref}")
    node: Any = root
    for part in ref[2:].split("/"):
        part = part.replace("~1", "/").replace("~0", "~")
        if not isinstance(node, dict) or part not in node:
            raise OpenAPIImportError(f"unresolvable $ref {ref}")
        node = node[part]
    return node


def resolve(node: Any, root: dict[str, Any], seen: tuple[str, ...] = ()) -> Any:
    """Inline local ``$ref``s. A cycle (or excessive depth) becomes an open object."""
    if len(seen) > MAX_REF_DEPTH:
        return {"type": "object"}
    if isinstance(node, dict):
        ref = node.get("$ref")
        if isinstance(ref, str):
            if ref in seen:
                return {"type": "object", "description": "recursive structure"}
            return resolve(_pointer(root, ref), root, (*seen, ref))
        return {k: resolve(v, root, seen) for k, v in node.items()}
    if isinstance(node, list):
        return [resolve(v, root, seen) for v in node]
    return node


# ----------------------------------------------------------------------- operations


def _snake(text: str) -> str:
    s = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", text)
    s = re.sub(r"[^a-zA-Z0-9]+", "_", s).strip("_").lower()
    return s or "op"


def server_url(doc: dict[str, Any]) -> str | None:
    servers = doc.get("servers") or []
    if not servers or not isinstance(servers[0], dict):
        return None
    url = str(servers[0].get("url") or "")
    for var, spec in (servers[0].get("variables") or {}).items():
        url = url.replace("{" + var + "}", str((spec or {}).get("default", "")))
    return url or None


def auth_from_spec(doc: dict[str, Any]) -> HttpAuth | None:
    """The first supported security scheme (apiKey in header/query, http bearer/basic)."""
    schemes = ((doc.get("components") or {}).get("securitySchemes")) or {}
    for scheme in schemes.values():
        scheme = resolve(scheme, doc)
        kind = scheme.get("type")
        if kind == "apiKey" and scheme.get("in") in ("header", "query") and scheme.get("name"):
            return HttpAuth(type="api_key", location=scheme["in"], name=str(scheme["name"]))
        if kind == "http" and str(scheme.get("scheme", "")).lower() == "bearer":
            return HttpAuth(type="bearer")
        if kind == "http" and str(scheme.get("scheme", "")).lower() == "basic":
            return HttpAuth(type="basic")
    return None


def _operation(

    doc: dict[str, Any],

    prefix: str,

    path: str,

    method: str,

    op: dict[str, Any],

    path_params: list[Any],

    base_url: str,

    sandbox_base_url: str | None,

    auth: HttpAuth | None,

) -> ImportedOperation:
    op = resolve(op, doc)
    params_by_key: dict[tuple[str, str], dict[str, Any]] = {}
    for p in [*resolve(path_params, doc), *(op.get("parameters") or [])]:
        if isinstance(p, dict) and p.get("name") and p.get("in") in ("path", "query", "header"):
            params_by_key[(p["in"], p["name"])] = p
    props: dict[str, Any] = {}
    required: list[str] = []
    wire: list[HttpParam] = []
    for (loc, name), p in params_by_key.items():
        if loc == "header" and auth is not None and name.lower() == auth.name.lower():
            continue  # the credential is injected by the gateway, never an argument
        if name in props:
            continue
        schema = dict(p.get("schema") or {"type": "string"})
        if p.get("description") and "description" not in schema:
            schema["description"] = clean_text(p["description"], 300)
        props[name] = schema
        if p.get("required") or loc == "path":
            required.append(name)
        wire.append(HttpParam(name=name, field=field_name(name), location=loc))
    body_field: str | None = None
    content = ((op.get("requestBody") or {}).get("content")) or {}
    body_schema = (content.get("application/json") or {}).get("schema")
    if isinstance(body_schema, dict):
        body_required = bool((op.get("requestBody") or {}).get("required"))
        body_props = body_schema.get("properties")
        flat = (
            body_schema.get("type", "object") == "object"
            and isinstance(body_props, dict)
            and body_props
            and not set(body_props) & set(props)
            and not {field_name(k) for k in body_props} & {w.field for w in wire}
        )
        if flat:
            assert isinstance(body_props, dict)
            for name, sub in body_props.items():
                props[name] = sub
                wire.append(HttpParam(name=name, field=field_name(name), location="body"))
            if body_required:
                required.extend(n for n in body_schema.get("required") or [] if n in body_props)
        else:
            props["body"] = body_schema
            body_field = "body"
            if body_required:
                required.append("body")
    input_schema = {"type": "object", "properties": props, "required": sorted(set(required))}
    fields = property_fields(input_schema)
    wire = [w.model_copy(update={"field": fields[w.name]}) for w in wire]
    if body_field is not None:
        body_field = fields["body"]
    op_id = str(op.get("operationId") or f"{method}_{path}")
    name = f"{prefix}.{_snake(op_id)}"[:200]
    text = op.get("summary") or op.get("description") or f"{method.upper()} {path}"
    upper = method.upper()
    return ImportedOperation(
        name=name,
        operation_id=op_id,
        description=clean_text(f"{clean_text(text)} ({upper} {path})"),
        method=upper,
        path=path,
        input_schema=input_schema,
        suggested_tier=int(SUGGESTED_TIER[upper]),
        http=HttpOperation(
            method=upper,
            path=path,
            base_url=base_url,
            sandbox_base_url=sandbox_base_url,
            params=wire,
            body_field=body_field,
            auth=auth,
        ),
    )


def import_operations(

    doc: dict[str, Any],

    *,

    prefix: str,

    base_url: str | None = None,

    sandbox_base_url: str | None = None,

    auth: HttpAuth | None = None,

    use_spec_auth: bool = True,

) -> list[ImportedOperation]:
    if not _SLUG.match(prefix):
        raise OpenAPIImportError("name must be 2-40 chars: lowercase letters, digits, _")
    base = base_url or server_url(doc)
    if not base or not base.startswith(("http://", "https://")):
        raise OpenAPIImportError("spec has no absolute server URL; pass base_url")
    check_url(base)
    if sandbox_base_url:
        check_url(sandbox_base_url)
    if auth is None and use_spec_auth:
        auth = auth_from_spec(doc)
    out: list[ImportedOperation] = []
    names: set[str] = set()
    for path, item in doc["paths"].items():
        item = resolve(item, doc) if isinstance(item, dict) else {}
        for method in METHODS:
            op = item.get(method)
            if not isinstance(op, dict):
                continue
            imported = _operation(
                doc,
                prefix,
                str(path),
                method,
                op,
                item.get("parameters") or [],
                base,
                sandbox_base_url,
                auth,
            )
            n, i = imported.name, 2
            while imported.name in names:
                imported = imported.model_copy(update={"name": f"{n}_{i}"})
                i += 1
            names.add(imported.name)
            try:
                model_from_schema(imported.input_schema, imported.name)
            except SchemaError as exc:
                raise OpenAPIImportError(f"{imported.name}: {exc}") from exc
            out.append(imported)
    limit = get_settings().ext_max_tools_per_import
    if len(out) > limit:
        raise OpenAPIImportError(f"spec has {len(out)} operations (max {limit} per import)")
    if not out:
        raise OpenAPIImportError("spec has no operations")
    return out