# Web

`gvn_tools.web` gives a model two tools that make HTTPS requests, only to the hosts you
allow: `http_get` to read, and `http_request` for anything with an effect.

- **You will learn:** how to build the web tools, what they return, how they handle
  redirects, and what you arrange around an allow-list of host names.
- **Read first:** [Tools](index.md) for the safety model.
- **Time:** about 10 minutes; the tables at the end are for lookup.

## Where this family sits

In the picture of [where tools plug in](index.md#where-tools-plug-in), this family gives the
tool fulfiller two tools and the policy fulfiller one policy for them,
`web.rules(web_tools)`. It sits on the
`Http` port, which sends one HTTPS request and returns the answer. The tools add the limits:
which hosts and ports may be reached, which headers a model may set, and which redirects are
followed. The [Jira Cloud](jira-cloud.md) and [GitHub](github.md) families sit on the same
port.

## A first example

You build the tools with an `Http` port and a list of allowed hosts. `LocalHttp()` (from the
`http` extra, see [Installing](index.md#installing)) makes real requests; `FakeHttp`, used here, answers from a script and reaches
nothing. You script the fake with a method, a URL and the response it should give:

```python
import asyncio
import typing

from gvn.harness.tools import Invocation, Tool
from gvn_tools import web
from gvn_tools.fakes import FakeHttp
from gvn_tools.transport import Response

http = FakeHttp().script(
    "GET",
    "https://api.example.com/v1/status",
    Response(status=200, headers={"content-type": "text/plain"}, text="all good"),
)
web_tools = web.tools(http=http, hosts=["api.example.com"])
invocation = Invocation(key="run/2#c1", origin="agent")

status_url = "https://api.example.com/v1/status"
page = asyncio.run(web_tools.http_get.run(arguments={"url": status_url}, invocation=invocation))
print(page)
# {'url': 'https://api.example.com/v1/status', 'status': 200, 'headers': {'content-type':
#  'text/plain'}, 'text': 'all good', 'truncated': False, 'redirects': []}
```

`web.tools(...)` returns a `WebTools`, a named tuple of the two tools: `web_tools.http_get`
is one, with the identity `gvn_tools.web.http_get` (see
[Tools](index.md#step-1-a-tool-is-built-with-its-limits)). The result names the final URL,
the status, a few safe headers, the text and the redirects followed (none here).

## A tour of refusals

The next example scripts an allowed URL whose answer is a redirect to a host that is not
allowed, then tries a raw IP address and a plain `http://` URL:

```python
http.script(
    "GET",
    "https://api.example.com/v1/items",
    Response(status=302, headers={"location": "https://evil.test/"}),
)


async def show(tool: Tool, arguments: dict[str, typing.Any]) -> None:
    try:
        print(await tool.run(arguments=arguments, invocation=invocation))
    except Exception as error:
        print(type(error).__name__, error)


async def tour() -> None:
    await show(web_tools.http_get, {"url": "https://api.example.com/v1/items"})
    await show(web_tools.http_get, {"url": "https://127.0.0.1/admin"})
    await show(web_tools.http_get, {"url": "http://api.example.com/v1/items"})


asyncio.run(tour())
# ToolFailure host 'evil.test' is not in the allowed hosts ['api.example.com']
# ToolFailure host '127.0.0.1' is not in the allowed hosts ['api.example.com']
# ToolFailure only https:// URLs are allowed
```

The first request was allowed, but its redirect pointed at a host that is not, so the tool
refused to follow it. The other two never left the tool.

## What it refuses

Each refusal is a `ToolFailure`, which an agent's tools report as a failed result that is not
retried (`{"error": "tool_rejected", "detail": ...}`).

- **Anything but https.** The URL must be printable ASCII without spaces or backslashes; a
  host is lower-case letters, digits, hyphens and dots (IDNs in their `xn--` form), with no
  trailing dot. User information (`user:pass@`) is refused. The fragment is dropped.
- **Hosts not on the list.** An entry is an exact host (`api.example.com`) or a suffix
  starting with a dot (`.example.com`: every subdomain, but not `example.com` itself, and at
  least two labels). IP literals, including the numeric forms resolvers accept such as
  `2130706433` or `0x7f.1`, `localhost` and its subdomains, and single-label hosts are refused
  unless listed exactly; a suffix never matches them. When the run context carries `"hosts"`,
  the host must match that list too (the run context is trusted data fixed when the run
  starts; see [Run context](../concepts/run-context.md)).
- **Other ports.** Port 443 only, unless listed in `ports`.
- **Headers outside an allow-list.** A model may set only `accept`, `accept-language`,
  `content-type`, `if-match`, `if-none-match`, `if-modified-since`, `if-unmodified-since` and
  `range`. `Authorization`, `Cookie`, `Host`, `Idempotency-Key` and the rest are refused.
- **Redirects anywhere else.** The port never follows redirects; this tool does, at most 5,
  each checked against everything above. A redirect to another host drops the model's
  headers; a 303 (and a 301 or 302 of a non-GET) becomes a GET without a body; a 307 or 308 of
  a request with a body is followed only on the same host and port.

`LocalHttp` makes its own client without proxies, `.netrc` or certificate settings from the
environment (a `.netrc` would add credentials to requests a model chose), and clears cookies
after every exchange.

## What comes back as content, and what fails

An answer from the server is a result, whatever its status: a 404, a 429 with its `retry-after`
header or a 500 is returned as `status` and `text`, and the model reads it and decides. Only a
call that gets no answer at all fails: when the host could not be reached, the tool raises a
retryable `ToolFailure` (`{"error": "tool_unavailable", "detail": ...}`), and the call may be
tried again: by the tool itself, when it was built with a retry. `web.tools(...,
retry=Retry(...))` gives the retry to `http_get` only, which has no effect to repeat. To retry
`http_request` too, build it on its own, `web.HttpRequest(http, hosts, retry=Retry(...))`,
and put it in the tuple in place of the one `web.tools` built
(`web_tools._replace(http_request=...)`, so `web.rules` still takes the tuple); do so only
when every allowed host honours `Idempotency-Key` (next section): every attempt carries the
same key.

## How repeats are harmless

`http_get` has no effect of its own. `http_request` sends `Idempotency-Key: <invocation.key()>` with
every non-GET request, so a server that honours the header (the IETF draft, Stripe-style APIs)
applies a repeat once. A server that ignores it may apply a repeat twice; that is why
`http_request` needs approval by default.

## The tools, for lookup

Each row gives a tool's arguments (`?` marks an optional one), its **default verdict** (what
`web.rules(web_tools)` answers for it; see [verdicts](index.md#step-4-a-rule-you-can-see-deciding))
and whether it is **independent**:

| Tool | Arguments | Default verdict | Independent |
|---|---|---|---|
| `http_get` | `url`, `headers?` | `cleared` | yes |
| `http_request` | `method`, `url`, `headers?`, `body?` | `needs_approval` | no |

**Independent** tools are pure reads: calls to them that sit next to each other in one
model reply run together; every other call runs in the order the model gave, one at a time
(see [The order of a reply's tool calls](../concepts/governor.md#the-order-of-a-replys-tool-calls)).

`method` is one of `POST`, `PUT`, `PATCH`, `DELETE`. Both return
`{"url", "status", "headers", "text", "truncated", "redirects"}`: the final URL, the status, a
few safe response headers (never `set-cookie`), the body cut at `limit` characters, and the
URLs redirected through. The text is data from a web server: untrusted, whatever it says.

So both tools declare their results untrusted (`untrusted()` is `True`). An agent or a
conversation that hands their result to its model records the tool in its exposure, and its
policy and its approver see that record with every later call: a policy can clear an effect
while the model has read no page and ask a person once it has
([Trust](../concepts/trust.md), and `exposed=` in [Rules](rules.md#a-rule-that-reads-the-exposure)).

## Configuration

`web.tools` and `web.rules`, with their defaults:

```python
# not runnable: the signatures.
web.tools(http, hosts, ports=(), limit=100_000, timeout=30, retry=None)
# -> WebTools(http_get, http_request)
web.HttpGet(http, hosts, ports=(), limit=100_000, timeout=30, retry=None)
web.HttpRequest(http, hosts, ports=(), limit=100_000, timeout=30, retry=None)
web.rules(web_tools)
```

Each argument of `web.tools`:

| Argument | Default | Meaning |
|---|---|---|
| `http` | | the `Http` port: `LocalHttp()` (the `http` extra) or `FakeHttp` |
| `hosts` | | the allow-list of exact hosts and `.suffix` entries |
| `ports` | `()` | ports allowed besides 443 |
| `limit` | 100,000 | characters of body text returned |
| `timeout` | 30 | seconds per request |
| `retry` | `None` | a `gvn.harness.ports.Retry` that `http_get` declares (`Tool.retry()`); `http_request` gets none from `web.tools` |

## Running them safely

The tools check every URL, header and redirect by its host **name** and port. What you add:

- **Egress controls for addresses.** The port connects to whatever address an allowed name
  resolves to, so a name whose DNS points at a private, loopback or link-local address (by
  misconfiguration or DNS rebinding) is reached. Deploy behind a firewall, or an egress proxy
  that refuses private ranges, when that matters.
- **Treat the text as untrusted.** An allowed host can serve anything, including text written
  to steer the model that reads it.
- **Clear `http_request` only for hosts that honour `Idempotency-Key`.** Every non-GET
  request carries the call's key; a server that applies it runs a repeat once.

## Recap

- `web.tools(http=..., hosts=[...])` reaches only https URLs on the allowed hosts, follows at
  most 5 redirects and checks each one, and lets a model set only a few harmless headers.
- `http_get` is cleared; `http_request` needs a person, because a server may ignore the
  `Idempotency-Key` it sends.
- The allow-list is on host names; egress controls decide which addresses are reachable.

**Next:** [Jira Cloud](jira-cloud.md) and [GitHub](github.md), which build on the same `Http` port.
