Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eee6df9fc6 | ||
|
|
9d338dd370 | ||
|
|
4f5c07e538 | ||
|
|
60e6077408 | ||
|
|
49616eec19 | ||
|
|
e0d9ff88a0 | ||
|
|
1098ee0362 | ||
|
|
d199a33b1a | ||
|
|
5a1983af2f | ||
|
|
e7f2641af5 | ||
|
|
e10c8d2119 | ||
|
|
40fb986b3f | ||
|
|
611198dc64 | ||
|
|
26f81ac21f |
No files matched your search
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
|
||||
token budgeting needed to run a multi-provider agent in production. BYO
|
||||
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
||||
|
||||
> **Status: v0.4.2.** Latest tagged release. The `runtime` API
|
||||
> **Status: v0.6.3.** Latest tagged release. The `runtime` API
|
||||
> surface may still shift in the v0.x line — pin your version.
|
||||
|
||||
## Why Harness
|
||||
@@ -26,6 +26,62 @@ opinions about how your agents should be deployed. There is no
|
||||
`harness` binary. You import packages, compose a `Runtime`, and call
|
||||
`rt.Run(ctx, msg, nil)`.
|
||||
|
||||
## What's in v0.6.3
|
||||
|
||||
[v0.6.3](https://github.com/sausheong/harness/releases/tag/v0.6.3) is a
|
||||
security fix for the browser tools, plus dependency updates:
|
||||
|
||||
- **Browser SSRF containment.** `tools/browser` and Stagehand's local-Chrome
|
||||
mode used Chrome's `--host-resolver-rules` to keep pages away from private
|
||||
addresses, but Chrome only glob-matches those rules, so the CIDR entries
|
||||
never matched. A page could fetch `169.254.169.254`, RFC 1918 addresses, or
|
||||
names that resolve to them. Chrome now runs behind `web.EgressProxy`, an
|
||||
in-process proxy that resolves each destination, refuses private
|
||||
addresses, and connects to the address it checked. This covers redirects,
|
||||
sub-resources, in-page `fetch`/XHR and WebSockets, and WebRTC is limited to
|
||||
proxied traffic. You can also use `web.StartEgressProxy` with your own
|
||||
browser.
|
||||
- **Stricter private-address checks.** The shared SSRF guard now also blocks
|
||||
multicast, reserved and benchmark ranges, Teredo, and IPv6 addresses that
|
||||
embed a private IPv4 address (NAT64, 6to4). `SafeHTTPClient` races IPv4
|
||||
and IPv6 addresses so hosts with broken IPv6 no longer stall.
|
||||
- **Dependencies.** chromedp v0.16.0, go-openai v1.43.0, html-to-markdown
|
||||
v2.5.2, otel v1.47.0, testify v1.12.1, x/sys v0.48.0.
|
||||
|
||||
## What's in v0.6.2
|
||||
|
||||
[v0.6.2](https://github.com/sausheong/harness/releases/tag/v0.6.2) and
|
||||
[v0.6.1](https://github.com/sausheong/harness/releases/tag/v0.6.1) are
|
||||
patch releases with no API changes:
|
||||
|
||||
- **Updated provider and MCP SDKs.** `anthropic-sdk-go` moves to v1.78.0,
|
||||
`google.golang.org/genai` to v1.72.0 and the MCP Go SDK to v1.8.0.
|
||||
Applications that also import these modules will be raised to at least
|
||||
these versions by Go's minimum version selection.
|
||||
- **MCP structured results.** When an MCP tool returns its result only as
|
||||
`structuredContent`, with no text block, the adapter passes the JSON to
|
||||
the agent instead of an empty result. Text still wins when present.
|
||||
|
||||
## What's in v0.6.0
|
||||
|
||||
[v0.6.0](https://github.com/sausheong/harness/releases/tag/v0.6.0) and
|
||||
[v0.5.0](https://github.com/sausheong/harness/releases/tag/v0.5.0) add two
|
||||
tools and raise the minimum Go version:
|
||||
|
||||
- **Go 1.26 required.** The module declares `go 1.26.0`, needed by the
|
||||
Stagehand SDK. With the default `GOTOOLCHAIN=auto`, older toolchains
|
||||
download 1.26 automatically; pinned CI images must be updated.
|
||||
- **Natural-language browser.** `tools/stagehand` drives a browser with
|
||||
instructions such as "click the Sign in button" instead of CSS selectors
|
||||
(`act`, `observe`, `extract`, plus `navigate`, `get_text`, `screenshot`).
|
||||
It runs on local Chrome or Browserbase, and Stagehand's inference goes
|
||||
through your own `LLMProvider`.
|
||||
- **Exa search.** `web.ExaSearchTool` (`exa_search`) returns ranked results
|
||||
with query-relevant highlights, with category, domain and date filters.
|
||||
- **Smaller changes.** PDF attachments are sent to Anthropic as document
|
||||
blocks, Opus 5.5 uses adaptive low-effort thinking when reasoning is off,
|
||||
and `WebFetchTool`'s output cap is raised to about 1M tokens.
|
||||
|
||||
## What's in v0.4.2
|
||||
|
||||
[v0.4.2](https://github.com/sausheong/harness/releases/tag/v0.4.2)
|
||||
@@ -181,7 +237,7 @@ github.com/sausheong/harness/
|
||||
└── tools/ # Batteries-included concrete tools (each importable separately)
|
||||
├── file/ # read_file (with vision), write_file, edit_file
|
||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
||||
├── web/ # web_fetch, web_search, ssrf guard
|
||||
├── web/ # web_fetch, web_search, exa_search, ssrf guard, egress proxy
|
||||
├── browser/ # chromedp wrapper with per-session reuse
|
||||
├── stagehand/ # natural-language browser (Stagehand: act/observe/extract),
|
||||
│ # local Chrome or Browserbase; inference via your LLMProvider
|
||||
@@ -452,12 +508,12 @@ tests. See [`scripts/QUALIFICATION.md`](./scripts/QUALIFICATION.md).
|
||||
|
||||
## Status
|
||||
|
||||
`v0.4.2` is the latest tagged release. The v0.x line follows Go
|
||||
`v0.6.3` is the latest tagged release. The v0.x line follows Go
|
||||
module semver: minor bumps may break API, patch bumps are bug-fix
|
||||
only. Pin your dependency:
|
||||
|
||||
```bash
|
||||
go get github.com/sausheong/harness@v0.4.2
|
||||
go get github.com/sausheong/harness@v0.6.3
|
||||
```
|
||||
|
||||
Likely sources of v0.x churn before a v1.0.0:
|
||||
|
||||
@@ -3,46 +3,45 @@ module github.com/sausheong/harness
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0
|
||||
github.com/anthropics/anthropic-sdk-go v1.35.0
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2
|
||||
github.com/anthropics/anthropic-sdk-go v1.78.0
|
||||
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
|
||||
github.com/chromedp/chromedp v0.14.2
|
||||
github.com/modelcontextprotocol/go-sdk v1.5.0
|
||||
github.com/sashabaranov/go-openai v1.41.2
|
||||
github.com/stretchr/testify v1.11.1
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
golang.org/x/sys v0.42.0
|
||||
google.golang.org/genai v1.49.0
|
||||
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f
|
||||
github.com/chromedp/chromedp v0.16.0
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/sashabaranov/go-openai v1.43.0
|
||||
github.com/stretchr/testify v1.12.1
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
golang.org/x/sys v0.48.0
|
||||
google.golang.org/genai v1.72.0
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go v0.116.0 // indirect
|
||||
cloud.google.com/go/auth v0.9.3 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.9.0 // indirect
|
||||
github.com/JohannesKaufmann/dom v0.2.0 // indirect
|
||||
github.com/JohannesKaufmann/dom v0.3.1 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/buger/jsonparser v1.1.2 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/chromedp/sysutil v1.1.0 // indirect
|
||||
github.com/coder/websocket v1.8.13 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.4.2 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/google/s2a-go v0.1.8 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/invopop/jsonschema v0.14.0 // indirect
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
@@ -50,15 +49,16 @@ require (
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
|
||||
golang.org/x/crypto v0.49.0 // indirect
|
||||
golang.org/x/crypto v0.51.0 // indirect
|
||||
golang.org/x/mod v0.38.0 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
|
||||
google.golang.org/grpc v1.80.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -6,12 +6,12 @@ cloud.google.com/go/auth v0.9.3/go.mod h1:7z6VY+7h3KUdRov5F1i8NDP5ZzWKYmEPO842Bg
|
||||
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/JohannesKaufmann/dom v0.2.0 h1:1bragmEb19K8lHAqgFgqCpiPCFEZMTXzOIEjuxkUfLQ=
|
||||
github.com/JohannesKaufmann/dom v0.2.0/go.mod h1:57iSUl5RKric4bUkgos4zu6Xt5LMHUnw3TF1l5CbGZo=
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0 h1:mklaPbT4f/EiDr1Q+zPrEt9lgKAkVrIBtWf33d9GpVA=
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0/go.mod h1:D56Cl9r8M5i3UwAchE+LlLc5hPN3kJtdZNVJn06lSHU=
|
||||
github.com/anthropics/anthropic-sdk-go v1.35.0 h1:W6K8mIkD1zIU0VUPMuokWONUvdlt2C//b11Zr6v5Oz4=
|
||||
github.com/anthropics/anthropic-sdk-go v1.35.0/go.mod h1:dSIO7kSrOI7MA4fE6RRVaw8tyWP7HNQU5/H/KS4cax8=
|
||||
github.com/JohannesKaufmann/dom v0.3.1 h1:J16l9JAHWgkFPR3VIPbQ1gvS0cWab6laK1q7PFL3qh0=
|
||||
github.com/JohannesKaufmann/dom v0.3.1/go.mod h1:BZPkf8ZeYrBgABjwJn9iiKt8aiCtkxpHkevms+Yp2DE=
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 h1:XFJZFWESIWlUEHHjzBuv8RvrtCWnSGlimEX17ysSDb8=
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2/go.mod h1:BHWO8lJzttJLqwuV8Rb1B3OG2OSzLbssZDI1FRg2eAA=
|
||||
github.com/anthropics/anthropic-sdk-go v1.78.0 h1:8uluL7g84HtSSm347tMGtrUuCEBLmme7vOcFCMn7bnk=
|
||||
github.com/anthropics/anthropic-sdk-go v1.78.0/go.mod h1:x+lPk/cCl48uRegeP0hlYYBN1b7bEBTveInIMgLicnY=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0 h1:XELhAEkPJlyjirc1aWPhd0n+ZdFP0U+wRWamGRD05K0=
|
||||
@@ -21,10 +21,10 @@ github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx2
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E=
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
|
||||
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
|
||||
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
|
||||
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f h1:0Z1zcSLEmnj2c2CmJYBqewtS6pxhB39bNWUSEUAWjgk=
|
||||
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f/go.mod h1:RwFsSODCtFExll+GhHM6R92SARHR3Z3oipaxLHj46C0=
|
||||
github.com/chromedp/chromedp v0.16.0 h1:rOO4deOm4CbZgBCa8mD9g2rDyIoNs0BkgvNrlbp5ouk=
|
||||
github.com/chromedp/chromedp v0.16.0/go.mod h1:rbuGKFT1vMcFcFqKfPIO1GpX/N+2s8onm2qMxZLbU5U=
|
||||
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
|
||||
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
@@ -32,7 +32,6 @@ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGX
|
||||
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
|
||||
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
@@ -40,10 +39,10 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 h1:KZaTBSyshWX3MP5jukJcNSuXDQTO+rNpt0J564dX/eg=
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
@@ -78,8 +77,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
|
||||
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM=
|
||||
github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
@@ -93,8 +92,8 @@ github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8i
|
||||
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||
github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=
|
||||
github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
|
||||
@@ -102,8 +101,8 @@ github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
|
||||
github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
|
||||
github.com/sashabaranov/go-openai v1.43.0 h1:HNRpO8TAQ01ssO7aPXO/68QRlcCCYQQ5GfHbFceRZcY=
|
||||
github.com/sashabaranov/go-openai v1.43.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
|
||||
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
|
||||
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
@@ -112,14 +111,16 @@ github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfv
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI=
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
@@ -132,28 +133,32 @@ github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=
|
||||
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
|
||||
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
||||
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
@@ -166,8 +171,8 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
|
||||
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
@@ -181,12 +186,14 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
@@ -199,8 +206,8 @@ gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/genai v1.49.0 h1:Se+QJaH2GYK1aaR1o5S38mlU2GD5FnVvP76nfkV7LH0=
|
||||
google.golang.org/genai v1.49.0/go.mod h1:A3kkl0nyBjyFlNjgxIwKq70julKbIxpSxqKO5gw/gmk=
|
||||
google.golang.org/genai v1.72.0 h1:sn3V1cHkHQhMcjtUrO2y1r54jprbFjmeokBU1IKfpZk=
|
||||
google.golang.org/genai v1.72.0/go.mod h1:2j40fGpqPPIZNjaDKmjGGjYwCJi6Nm2ofmyP65GnqtY=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
@@ -224,12 +231,10 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD
|
||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
@@ -29,6 +29,16 @@ func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
|
||||
return &AnthropicProvider{client: client}
|
||||
}
|
||||
|
||||
// NewAnthropicProviderWithOptions creates a provider from Anthropic SDK request
|
||||
// options, for endpoints NewAnthropicProvider can't express: gateways that want
|
||||
// a bearer token (option.WithAuthToken) instead of X-Api-Key, or that reject the
|
||||
// SDK's version header (option.WithHeaderDel("anthropic-version")). The SDK's
|
||||
// environment defaults (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN,
|
||||
// ANTHROPIC_BASE_URL) still apply first; opts override them.
|
||||
func NewAnthropicProviderWithOptions(opts ...option.RequestOption) *AnthropicProvider {
|
||||
return &AnthropicProvider{client: anthropic.NewClient(opts...)}
|
||||
}
|
||||
|
||||
// SupportsPromptCaching implements llm.PromptCachingProvider: the
|
||||
// Anthropic Messages API honours cache_control breakpoints regardless
|
||||
// of what the provider block is named in user config.
|
||||
@@ -160,6 +170,13 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
||||
slog.Info("anthropic adaptive thinking",
|
||||
"model", model,
|
||||
"effort", string(anthropicEffort(req.Reasoning)))
|
||||
} else if anthropicThinksBetweenTools(model) {
|
||||
// Sonnet 5.5 rejects {type:"disabled"}: its "off" is
|
||||
// {type:"between_tools"} (no thinking before responding; the
|
||||
// short updates between tool calls come back as thinking blocks).
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfBetweenTools: &anthropic.ThinkingConfigBetweenToolsParam{},
|
||||
}
|
||||
} else if anthropicRejectsDisabledThinking(model) {
|
||||
// Opus 5.5 can't turn thinking off: {type:"disabled"} is a 400
|
||||
// ("use thinking.type.adaptive and output_config.effort").
|
||||
@@ -567,6 +584,12 @@ func anthropicThinksByDefault(model string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// anthropicThinksBetweenTools reports models whose reasoning-off setting is
|
||||
// {type:"between_tools"} rather than {type:"disabled"}.
|
||||
func anthropicThinksBetweenTools(model string) bool {
|
||||
return strings.Contains(model, "claude-sonnet-5-5")
|
||||
}
|
||||
|
||||
// anthropicRejectsDisabledThinking reports whether the model returns a 400
|
||||
// for thinking {type:"disabled"}. Checked before anthropicThinksByDefault,
|
||||
// whose "claude-opus-5" marker also matches Opus 5.5 IDs.
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -522,6 +523,34 @@ data: {"type":"message_stop"}
|
||||
require.Equal(t, 69, done.Usage.InputTokens) // 10 uncached + 42 cache creation + 17 cache read
|
||||
}
|
||||
|
||||
// TestNewAnthropicProviderWithOptionsGatewayAuth checks the gateway shape:
|
||||
// a bearer token instead of X-Api-Key, and no anthropic-version header.
|
||||
func TestNewAnthropicProviderWithOptionsGatewayAuth(t *testing.T) {
|
||||
t.Setenv("ANTHROPIC_API_KEY", "")
|
||||
t.Setenv("ANTHROPIC_AUTH_TOKEN", "")
|
||||
var got http.Header
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got = r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProviderWithOptions(
|
||||
option.WithAuthToken("gw-token"),
|
||||
option.WithBaseURL(srv.URL),
|
||||
option.WithHeaderDel("anthropic-version"),
|
||||
)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-test"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.NotNil(t, got, "expected a request")
|
||||
require.Equal(t, "Bearer gw-token", got.Get("Authorization"))
|
||||
require.Empty(t, got.Get("X-Api-Key"))
|
||||
require.Empty(t, got.Get("Anthropic-Version"))
|
||||
}
|
||||
|
||||
// TestBuildMessageParamsIsPure protects the cache-prefix invariant
|
||||
// behind the stream-fallback feature: when a stream dies mid-flight
|
||||
// the runtime retries via ChatNonStreaming with the SAME llm.ChatRequest,
|
||||
@@ -875,6 +904,26 @@ func TestOpus5_5_ReasoningOffSendsAdaptiveLow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSonnet5_5_ReasoningOffSendsBetweenTools guards against a 400 from
|
||||
// Sonnet 5.5, which rejects {type:"disabled"} ("To turn thinking off on this
|
||||
// model, send thinking: {type: between_tools}"). Gateway aliases match too.
|
||||
func TestSonnet5_5_ReasoningOffSendsBetweenTools(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
for _, model := range []string{"claude-sonnet-5-5", "claude-sonnet-5-5-global"} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.NotContains(t, got, `"disabled"`)
|
||||
assert.Contains(t, got, `"thinking":{"type":"between_tools"}`)
|
||||
})
|
||||
}
|
||||
// Sonnet 5 keeps its explicit disabled config.
|
||||
got := wireJSON(t, p, llm.ChatRequest{Model: "claude-sonnet-5", Messages: []llm.Message{{Role: "user", Content: "hi"}}})
|
||||
assert.Contains(t, got, `"thinking":{"type":"disabled"}`)
|
||||
}
|
||||
|
||||
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
|
||||
@@ -315,6 +315,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
InputTokens: resp.Usage.PromptTokens,
|
||||
OutputTokens: resp.Usage.CompletionTokens,
|
||||
}
|
||||
// OpenAI-compatible servers (vLLM, llama.cpp, ...) report
|
||||
// server-side prefix-cache hits via
|
||||
// prompt_tokens_details.cached_tokens. Surface them as cache
|
||||
// reads so downstream pricing/analytics see them.
|
||||
if resp.Usage.PromptTokensDetails != nil && resp.Usage.PromptTokensDetails.CachedTokens > 0 {
|
||||
lastUsage.CacheReadInputTokens = resp.Usage.PromptTokensDetails.CachedTokens
|
||||
}
|
||||
}
|
||||
|
||||
for _, choice := range resp.Choices {
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# Rejects commit messages carrying AI attribution: Claude/Anthropic
|
||||
# co-author trailers or "Generated with Claude Code" lines.
|
||||
# Install once per clone: git config core.hooksPath scripts/hooks
|
||||
|
||||
if grep -v '^#' "$1" | grep -Eiq '^[[:space:]]*co-authored-by:.*(claude|anthropic)|generated (with|by) (\[)?claude'; then
|
||||
echo "commit-msg: remove the AI attribution line from the commit message:" >&2
|
||||
grep -v '^#' "$1" | grep -Ein '^[[:space:]]*co-authored-by:.*(claude|anthropic)|generated (with|by) (\[)?claude' >&2
|
||||
exit 1
|
||||
fi
|
||||
+30
-19
@@ -36,24 +36,6 @@ const (
|
||||
janitorInterval = 1 * time.Minute
|
||||
)
|
||||
|
||||
// hostResolverRules forces Chrome to fail DNS resolution for private/internal
|
||||
// IP ranges and localhost, so in-page fetch() and evaluate()'d JS cannot reach
|
||||
// cloud-metadata endpoints or localhost services — the Go-side
|
||||
// ValidateURLNotInternal check only sees the top-level URL, so this covers
|
||||
// sub-resource and script-initiated requests. (S3)
|
||||
//
|
||||
// Residual gap: name-based rules do not stop a page that dials a *literal*
|
||||
// private IP URL in some Chrome builds; the complete fix is an allowlisting
|
||||
// proxy (deferred). See the security-deeper spec's limitations section.
|
||||
const hostResolverRules = "MAP localhost ~NOTFOUND," +
|
||||
"MAP *.localhost ~NOTFOUND," +
|
||||
"MAP 127.0.0.0/8 ~NOTFOUND," +
|
||||
"MAP 10.0.0.0/8 ~NOTFOUND," +
|
||||
"MAP 172.16.0.0/12 ~NOTFOUND," +
|
||||
"MAP 169.254.0.0/16 ~NOTFOUND," +
|
||||
"MAP 192.168.0.0/16 ~NOTFOUND," +
|
||||
"MAP [::1] ~NOTFOUND"
|
||||
|
||||
// stealthScript runs before any page script on every new document. It hides the
|
||||
// most common headless/automation tells that JS-heavy sites use to refuse to
|
||||
// render content (Cloudflare, Akamai, anti-bot scripts, "please enable JS"
|
||||
@@ -482,6 +464,17 @@ func (t *BrowserTool) reapIdleSessions() {
|
||||
// reaper watchdog. If the parent dies hard before cleanup runs, the
|
||||
// watchdog SIGKILLs any process whose argv contains that path and rm -rfs
|
||||
// the dir.
|
||||
//
|
||||
// SSRF containment: Chrome is pointed at an in-process web.EgressProxy
|
||||
// (--proxy-server, with <-loopback> so localhost is not exempt). The proxy
|
||||
// resolves each destination, refuses it if any address is private/internal
|
||||
// (loopback, RFC 1918, link-local/metadata, CGNAT, ULA), and dials the
|
||||
// validated IP directly, so nip.io-style names and DNS rebinding are caught
|
||||
// too. This covers redirects, sub-resources, in-page fetch/XHR and
|
||||
// WebSockets. WebRTC is restricted to proxied UDP. Chrome's
|
||||
// --host-resolver-rules is deliberately not used: it only glob-matches host
|
||||
// strings, so CIDR entries never match. The proxy lives and dies with the
|
||||
// returned cleanup func.
|
||||
func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, error) {
|
||||
udd, err := os.MkdirTemp("", "harness-browser-")
|
||||
if err != nil {
|
||||
@@ -489,6 +482,16 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
|
||||
}
|
||||
trackDirForReaping(udd)
|
||||
|
||||
// All Chrome traffic (top-level, sub-resource, in-page fetch, WebSocket)
|
||||
// is forced through an in-process proxy that refuses private/internal
|
||||
// destinations at dial time. See web.EgressProxy.
|
||||
proxy, err := web.StartEgressProxy()
|
||||
if err != nil {
|
||||
untrackDirForReaping(udd)
|
||||
_ = os.RemoveAll(udd)
|
||||
return nil, nil, fmt.Errorf("start egress proxy: %w", err)
|
||||
}
|
||||
|
||||
allocCtx, allocCancel := chromedp.NewExecAllocator(parent,
|
||||
append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.NoSandbox,
|
||||
@@ -496,7 +499,13 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
|
||||
chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
|
||||
chromedp.Flag("disable-blink-features", "AutomationControlled"),
|
||||
chromedp.Flag("lang", "en-US"),
|
||||
chromedp.Flag("host-resolver-rules", hostResolverRules),
|
||||
chromedp.ProxyServer(proxy.URL()),
|
||||
// Drop Chrome's implicit loopback bypass so localhost and
|
||||
// 127.0.0.0/8 also go through (and are refused by) the proxy.
|
||||
chromedp.Flag("proxy-bypass-list", "<-loopback>"),
|
||||
// Keep WebRTC from sending UDP around the proxy.
|
||||
chromedp.Flag("force-webrtc-ip-handling-policy", "disable_non_proxied_udp"),
|
||||
chromedp.Flag("webrtc-ip-handling-policy", "disable_non_proxied_udp"),
|
||||
chromedp.UserDataDir(udd),
|
||||
)...,
|
||||
)
|
||||
@@ -511,6 +520,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
|
||||
); err != nil {
|
||||
taskCancel()
|
||||
allocCancel()
|
||||
_ = proxy.Close()
|
||||
untrackDirForReaping(udd)
|
||||
_ = os.RemoveAll(udd)
|
||||
return nil, nil, err
|
||||
@@ -518,6 +528,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
|
||||
cleanup := func() {
|
||||
taskCancel()
|
||||
allocCancel()
|
||||
_ = proxy.Close()
|
||||
untrackDirForReaping(udd)
|
||||
_ = os.RemoveAll(udd)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,11 @@ package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -12,33 +17,71 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestInPageFetchPrivateIPBlocked_Live verifies host-resolver-rules stops an
|
||||
// in-page fetch to a metadata IP. Requires a real Chrome. Run:
|
||||
// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live
|
||||
// TestInPageFetchPrivateIPBlocked_Live verifies the egress proxy stops
|
||||
// in-page fetches and navigations to loopback, private-resolving names and the
|
||||
// metadata IP, without any request reaching a local server. Requires a real
|
||||
// Chrome and network access. Run:
|
||||
//
|
||||
// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live
|
||||
func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) {
|
||||
tool := NewBrowserTool()
|
||||
defer tool.Shutdown()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
var hits atomic.Int64
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
fmt.Fprint(w, "secret")
|
||||
}))
|
||||
defer srv.Close()
|
||||
port := srv.Listener.Addr().(interface{ String() string }).String()
|
||||
port = port[strings.LastIndex(port, ":")+1:]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
taskCtx, ccancel, err := launchBrowser(ctx)
|
||||
require.NoError(t, err)
|
||||
defer ccancel()
|
||||
|
||||
require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com")))
|
||||
// Positive control: public sites work through the proxy.
|
||||
var title string
|
||||
require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com"), chromedp.Title(&title)))
|
||||
require.Contains(t, title, "Example")
|
||||
|
||||
var result string
|
||||
script := `(async () => {
|
||||
try {
|
||||
await fetch('http://169.254.169.254/latest/meta-data/', {mode:'no-cors'});
|
||||
return 'REACHED';
|
||||
} catch (e) {
|
||||
return 'BLOCKED';
|
||||
}
|
||||
})()`
|
||||
err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams {
|
||||
return p.WithAwaitPromise(true)
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "BLOCKED", result, "in-page fetch to metadata IP must be blocked by host-resolver-rules")
|
||||
targets := []string{
|
||||
"http://127.0.0.1:" + port,
|
||||
"http://localhost:" + port,
|
||||
"http://127.0.0.1.nip.io:" + port,
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
}
|
||||
for _, target := range targets {
|
||||
var result string
|
||||
script := fmt.Sprintf(`(async () => {
|
||||
const ac = new AbortController();
|
||||
const timer = setTimeout(() => ac.abort(), 10000);
|
||||
try {
|
||||
await fetch(%q, {signal: ac.signal});
|
||||
return 'REACHED';
|
||||
} catch (e) {
|
||||
return 'BLOCKED';
|
||||
} finally { clearTimeout(timer); }
|
||||
})()`, target)
|
||||
start := time.Now()
|
||||
err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams {
|
||||
return p.WithAwaitPromise(true)
|
||||
}))
|
||||
require.NoError(t, err, target)
|
||||
require.Equal(t, "BLOCKED", result, "in-page fetch to %s must be blocked", target)
|
||||
require.Less(t, time.Since(start), 8*time.Second, "%s should be refused quickly, not time out", target)
|
||||
}
|
||||
|
||||
navCtx, navCancel := context.WithTimeout(taskCtx, 20*time.Second)
|
||||
defer navCancel()
|
||||
// The proxy answers 403, which Chrome renders as an ordinary page, so
|
||||
// accept either a navigation error or the proxy's refusal text.
|
||||
var body string
|
||||
err = chromedp.Run(navCtx, chromedp.Navigate("http://127.0.0.1.nip.io:"+port), chromedp.Text("body", &body, chromedp.ByQuery))
|
||||
if err == nil {
|
||||
require.Contains(t, body, "blocked by egress policy", "direct navigation to a private-resolving name must be refused")
|
||||
}
|
||||
|
||||
require.EqualValues(t, 0, hits.Load(), "local server must never be reached")
|
||||
}
|
||||
@@ -4,23 +4,12 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestHostResolverRules_BlocksPrivateRanges(t *testing.T) {
|
||||
require.Contains(t, hostResolverRules, "127.0.0.0/8")
|
||||
require.Contains(t, hostResolverRules, "169.254.0.0/16")
|
||||
require.Contains(t, hostResolverRules, "10.0.0.0/8")
|
||||
require.Contains(t, hostResolverRules, "192.168.0.0/16")
|
||||
require.Contains(t, hostResolverRules, "172.16.0.0/12")
|
||||
require.Contains(t, hostResolverRules, "localhost")
|
||||
require.True(t, strings.Contains(hostResolverRules, "~NOTFOUND"))
|
||||
}
|
||||
|
||||
func TestBrowserToolName(t *testing.T) {
|
||||
tool := &BrowserTool{}
|
||||
assert.Equal(t, "browser", tool.Name())
|
||||
|
||||
@@ -79,6 +79,12 @@ func (a *mcpToolAdapter) Execute(ctx context.Context, input json.RawMessage) (to
|
||||
// ToolResult: TextContent concatenated into Output (or Error if
|
||||
// IsError), ImageContent collected into Images. Other content types
|
||||
// (audio, embedded resources) are described in Output as a placeholder.
|
||||
//
|
||||
// StructuredContent is used only when there is no text: the MCP spec says
|
||||
// a tool returning structured content SHOULD also send it serialized as a
|
||||
// TextContent block, so when both are present the text already carries it.
|
||||
// Servers that send structured content alone would otherwise reach the
|
||||
// agent as an empty result.
|
||||
func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
||||
var text strings.Builder
|
||||
var images []llm.ImageContent
|
||||
@@ -103,6 +109,13 @@ func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
||||
fmt.Fprintf(&text, "[unsupported MCP content: %T]", c)
|
||||
}
|
||||
}
|
||||
if text.Len() == 0 && res.StructuredContent != nil {
|
||||
if b, err := json.Marshal(res.StructuredContent); err == nil {
|
||||
text.Write(b)
|
||||
} else {
|
||||
fmt.Fprintf(&text, "[unserializable MCP structured content: %v]", err)
|
||||
}
|
||||
}
|
||||
out := tool.ToolResult{Images: images}
|
||||
if res.IsError {
|
||||
out.Error = text.String()
|
||||
|
||||
@@ -135,6 +135,37 @@ func TestMCPAdapter_ImageContentMapping(t *testing.T) {
|
||||
var _ llm.ImageContent = res.Images[0]
|
||||
}
|
||||
|
||||
func TestMCPAdapter_StructuredContentFallback(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("structured_only", "hits as structured content only", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{
|
||||
Content: []sdk.Content{},
|
||||
StructuredContent: map[string]any{"hits": []any{map[string]any{"text": "leave policy", "score": 0.9}}},
|
||||
}, nil
|
||||
}),
|
||||
stringArgTool("both", "text and structured content", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{
|
||||
Content: []sdk.Content{&sdk.TextContent{Text: "summary text"}},
|
||||
StructuredContent: map[string]any{"hits": []any{}},
|
||||
}, nil
|
||||
}),
|
||||
})
|
||||
byName := map[string]int{}
|
||||
for i, tl := range cli.Tools() {
|
||||
byName[tl.Name()] = i
|
||||
}
|
||||
require.Len(t, byName, 2)
|
||||
|
||||
res, err := cli.Tools()[byName["mcp__srv__structured_only"]].Execute(context.Background(), json.RawMessage(`{}`))
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, res.Error)
|
||||
assert.JSONEq(t, `{"hits":[{"text":"leave policy","score":0.9}]}`, res.Output)
|
||||
|
||||
res, err = cli.Tools()[byName["mcp__srv__both"]].Execute(context.Background(), json.RawMessage(`{}`))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "summary text", res.Output, "text wins when present; structured content is not duplicated")
|
||||
}
|
||||
|
||||
func TestMCPClient_ConnectDiscovers(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("a", "first", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -42,20 +43,6 @@ const (
|
||||
janitorInterval = 1 * time.Minute
|
||||
)
|
||||
|
||||
// hostResolverRules mirrors tools/browser: it makes a *local* Chrome fail DNS
|
||||
// for localhost and private ranges so in-page fetch()/XHR can't reach
|
||||
// cloud-metadata endpoints or local services. The Go-side
|
||||
// ValidateURLNotInternal check only covers the top-level URL. Browserbase
|
||||
// browsers run remotely and can't reach this machine's network anyway.
|
||||
const hostResolverRules = "MAP localhost ~NOTFOUND," +
|
||||
"MAP *.localhost ~NOTFOUND," +
|
||||
"MAP 127.0.0.0/8 ~NOTFOUND," +
|
||||
"MAP 10.0.0.0/8 ~NOTFOUND," +
|
||||
"MAP 172.16.0.0/12 ~NOTFOUND," +
|
||||
"MAP 169.254.0.0/16 ~NOTFOUND," +
|
||||
"MAP 192.168.0.0/16 ~NOTFOUND," +
|
||||
"MAP [::1] ~NOTFOUND"
|
||||
|
||||
// Config configures a StagehandTool.
|
||||
type Config struct {
|
||||
// Provider and Model serve Stagehand's internal inference. Required.
|
||||
@@ -82,6 +69,9 @@ type session struct {
|
||||
browser *sh.Browser
|
||||
client *sh.Stagehand
|
||||
lastUsed time.Time
|
||||
// proxy is the egress proxy a local Chrome is forced through; nil for
|
||||
// Browserbase and in tests.
|
||||
proxy *web.EgressProxy
|
||||
}
|
||||
|
||||
// StagehandTool is an AI-driven browser tool.
|
||||
@@ -393,6 +383,18 @@ func (t *StagehandTool) acquire(ctx context.Context, name string) (*session, fun
|
||||
|
||||
// launchSession starts a browser on the configured backend and attaches a
|
||||
// Stagehand client whose inference runs through the harness provider.
|
||||
//
|
||||
// A local Chrome is forced through an in-process web.EgressProxy that refuses
|
||||
// private/internal destinations at dial time (loopback, RFC 1918, link-local/
|
||||
// metadata, names resolving to them, DNS rebinding), covering sub-resource and
|
||||
// script-initiated requests that the Go-side ValidateURLNotInternal check
|
||||
// never sees. Chrome's --host-resolver-rules is not used: it only glob-matches
|
||||
// host strings, so CIDR entries never match. Browserbase browsers run remotely
|
||||
// and can't reach this machine's network anyway.
|
||||
//
|
||||
// The implicit loopback bypass is removed (<-loopback), so localhost and
|
||||
// 127.0.0.1 are refused too; the one exception is Chrome's own debugging port,
|
||||
// which Stagehand's extension needs (a page could still reach that port).
|
||||
func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) {
|
||||
// The browser outlives this call for persistent sessions, so detach it
|
||||
// from the caller's cancellation and bound only the launch itself.
|
||||
@@ -400,18 +402,45 @@ func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) {
|
||||
defer cancel()
|
||||
|
||||
var browser *sh.Browser
|
||||
var proxy *web.EgressProxy
|
||||
var err error
|
||||
if t.cfg.BrowserbaseAPIKey != "" {
|
||||
browser, err = sh.LaunchBrowserbase(launchCtx, sh.BrowserbaseLaunchOptions{APIKey: t.cfg.BrowserbaseAPIKey})
|
||||
} else {
|
||||
proxy, err = web.StartEgressProxy()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start egress proxy: %w", err)
|
||||
}
|
||||
// Stagehand's in-browser extension connects to Chrome's own debugging
|
||||
// port over loopback, so pick that port up front and let exactly it
|
||||
// through the proxy.
|
||||
var debugPort int
|
||||
debugPort, err = freeLoopbackPort()
|
||||
if err != nil {
|
||||
_ = proxy.Close()
|
||||
return nil, fmt.Errorf("pick debugging port: %w", err)
|
||||
}
|
||||
proxy.AllowLoopbackPort(debugPort)
|
||||
browser, err = sh.LaunchLocalBrowser(launchCtx, &sh.LocalBrowserLaunchOptions{
|
||||
Headless: !t.cfg.Headful,
|
||||
ExecutablePath: t.cfg.ChromePath,
|
||||
Args: []string{"--host-resolver-rules=" + hostResolverRules},
|
||||
Viewport: &sh.LocalViewport{Width: defaultViewportW, Height: defaultViewportH},
|
||||
Port: debugPort,
|
||||
Args: []string{
|
||||
"--proxy-server=" + proxy.URL(),
|
||||
// Drop Chrome's implicit loopback/link-local bypass so those
|
||||
// destinations hit the proxy (and are refused).
|
||||
"--proxy-bypass-list=<-loopback>",
|
||||
// Keep WebRTC from sending UDP around the proxy.
|
||||
"--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
|
||||
"--webrtc-ip-handling-policy=disable_non_proxied_udp",
|
||||
},
|
||||
Viewport: &sh.LocalViewport{Width: defaultViewportW, Height: defaultViewportH},
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
if proxy != nil {
|
||||
_ = proxy.Close()
|
||||
}
|
||||
return nil, fmt.Errorf("launch browser: %w", err)
|
||||
}
|
||||
|
||||
@@ -423,9 +452,13 @@ func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) {
|
||||
if err != nil {
|
||||
closeCtx, cancelClose := context.WithTimeout(context.Background(), closeTimeout)
|
||||
defer cancelClose()
|
||||
return nil, errors.Join(fmt.Errorf("start stagehand: %w", err), browser.Close(closeCtx))
|
||||
cerr := browser.Close(closeCtx)
|
||||
if proxy != nil {
|
||||
_ = proxy.Close()
|
||||
}
|
||||
return nil, errors.Join(fmt.Errorf("start stagehand: %w", err), cerr)
|
||||
}
|
||||
return &session{browser: browser, client: client, lastUsed: time.Now()}, nil
|
||||
return &session{browser: browser, client: client, lastUsed: time.Now(), proxy: proxy}, nil
|
||||
}
|
||||
|
||||
// close tears down the client then the browser. Safe on a partially
|
||||
@@ -439,6 +472,9 @@ func (s *session) close() {
|
||||
if s.browser != nil {
|
||||
_ = s.browser.Close(ctx)
|
||||
}
|
||||
if s.proxy != nil {
|
||||
_ = s.proxy.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *StagehandTool) closeSession(name string) bool {
|
||||
@@ -533,3 +569,13 @@ func truncate(s string) string {
|
||||
}
|
||||
return s[:maxTextOutput] + fmt.Sprintf("\n\n[truncated: %d of %d bytes shown]", maxTextOutput, len(s))
|
||||
}
|
||||
|
||||
// freeLoopbackPort returns a currently unused 127.0.0.1 TCP port.
|
||||
func freeLoopbackPort() (int, error) {
|
||||
ln, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer ln.Close()
|
||||
return ln.Addr().(*net.TCPAddr).Port, nil
|
||||
}
|
||||
+138
-31
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -17,37 +18,7 @@ func SafeHTTPClient(timeout time.Duration) *http.Client {
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host)
|
||||
}
|
||||
// Fail closed: if ANY resolved IP is private, refuse — this defeats
|
||||
// DNS-rebinding where one A record is public and another is private.
|
||||
for _, ip := range ips {
|
||||
if isPrivateIP(ip) {
|
||||
return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
|
||||
}
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
return nil, fmt.Errorf("no usable address for %q", host)
|
||||
}
|
||||
// Try each validated public IP in order, falling back on dial
|
||||
// failure so dual-stack hosts still connect on IPv4-only or
|
||||
// IPv6-broken networks (stock happy-eyeballs is bypassed because we
|
||||
// dial literal IPs to pin the validated address).
|
||||
var lastErr error
|
||||
for _, ip := range ips {
|
||||
conn, derr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
|
||||
if derr == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = derr
|
||||
}
|
||||
return nil, lastErr
|
||||
return safeDialContext(ctx, dialer, isPrivateIP, network, addr)
|
||||
},
|
||||
}
|
||||
return &http.Client{
|
||||
@@ -64,3 +35,139 @@ func SafeHTTPClient(timeout time.Duration) *http.Client {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// blockedError marks a destination refused by the SSRF policy (as opposed to
|
||||
// an ordinary resolve/dial failure), so callers can tell policy from outage.
|
||||
type blockedError struct{ msg string }
|
||||
|
||||
func (e *blockedError) Error() string { return e.msg }
|
||||
|
||||
// safeDialContext is the single SSRF-safe dial path shared by SafeHTTPClient
|
||||
// and the browser egress proxy. It resolves addr's host, fails closed if
|
||||
// blockIP reports ANY resolved IP (or the host is a known metadata name), then
|
||||
// dials the exact validated IPs so nothing is re-resolved after validation.
|
||||
func safeDialContext(ctx context.Context, dialer *net.Dialer, blockIP func(net.IP) bool, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSuffix(host, "."))
|
||||
if lower == "metadata.google.internal" || lower == "metadata" {
|
||||
return nil, &blockedError{"access to internal metadata endpoint is blocked"}
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host)
|
||||
}
|
||||
// Fail closed: if ANY resolved IP is private, refuse — this defeats
|
||||
// DNS-rebinding where one A record is public and another is private.
|
||||
for _, ip := range ips {
|
||||
if blockIP(ip) {
|
||||
return nil, &blockedError{fmt.Sprintf("access to internal address %s (%s) is blocked", host, ip)}
|
||||
}
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
return nil, fmt.Errorf("no usable address for %q", host)
|
||||
}
|
||||
return dialValidated(ctx, dialer, network, interleaveFamilies(ips), port)
|
||||
}
|
||||
|
||||
// happyEyeballsDelay is how long dialValidated waits on one address before
|
||||
// also starting the next (RFC 8305 uses 250ms).
|
||||
const happyEyeballsDelay = 300 * time.Millisecond
|
||||
|
||||
// interleaveFamilies reorders ips to alternate address families, starting with
|
||||
// the resolver's first, so a dead family can't stall the other.
|
||||
func interleaveFamilies(ips []net.IP) []net.IP {
|
||||
var v4, v6 []net.IP
|
||||
for _, ip := range ips {
|
||||
if ip.To4() != nil {
|
||||
v4 = append(v4, ip)
|
||||
} else {
|
||||
v6 = append(v6, ip)
|
||||
}
|
||||
}
|
||||
first, second := v4, v6
|
||||
if len(ips) > 0 && ips[0].To4() == nil {
|
||||
first, second = v6, v4
|
||||
}
|
||||
out := make([]net.IP, 0, len(ips))
|
||||
for i := 0; i < len(first) || i < len(second); i++ {
|
||||
if i < len(first) {
|
||||
out = append(out, first[i])
|
||||
}
|
||||
if i < len(second) {
|
||||
out = append(out, second[i])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// dialValidated dials the already-validated literal IPs RFC 8305 style:
|
||||
// attempts start staggered (or immediately after a failure) and the first to
|
||||
// connect wins, so dual-stack hosts work on IPv4-only or IPv6-broken networks
|
||||
// without waiting out a full dial timeout. Stock happy-eyeballs is bypassed
|
||||
// because we dial literal IPs to pin the validated address.
|
||||
func dialValidated(ctx context.Context, dialer *net.Dialer, network string, ips []net.IP, port string) (net.Conn, error) {
|
||||
if len(ips) == 1 {
|
||||
return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].String(), port))
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
type result struct {
|
||||
conn net.Conn
|
||||
err error
|
||||
}
|
||||
ch := make(chan result, len(ips)) // buffered: attempts never block on send
|
||||
launched, pending := 0, 0
|
||||
launch := func() {
|
||||
addr := net.JoinHostPort(ips[launched].String(), port)
|
||||
launched++
|
||||
pending++
|
||||
go func() {
|
||||
c, err := dialer.DialContext(ctx, network, addr)
|
||||
ch <- result{c, err}
|
||||
}()
|
||||
}
|
||||
// Close any connections that complete after we've returned.
|
||||
drain := func() {
|
||||
n := pending
|
||||
go func() {
|
||||
for ; n > 0; n-- {
|
||||
if r := <-ch; r.conn != nil {
|
||||
_ = r.conn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
timer := time.NewTimer(0)
|
||||
defer timer.Stop()
|
||||
var lastErr error
|
||||
for {
|
||||
select {
|
||||
case <-timer.C:
|
||||
if launched < len(ips) {
|
||||
launch()
|
||||
if launched < len(ips) {
|
||||
timer.Reset(happyEyeballsDelay)
|
||||
}
|
||||
}
|
||||
case r := <-ch:
|
||||
pending--
|
||||
if r.err == nil {
|
||||
drain()
|
||||
return r.conn, nil
|
||||
}
|
||||
lastErr = r.err
|
||||
if launched == len(ips) && pending == 0 {
|
||||
return nil, lastErr
|
||||
}
|
||||
if launched < len(ips) {
|
||||
timer.Reset(0) // failed fast: start the next address now
|
||||
}
|
||||
case <-ctx.Done():
|
||||
drain()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -52,3 +53,22 @@ func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) {
|
||||
|
||||
var _ = isPrivateIP(net.IPv4(127, 0, 0, 1))
|
||||
var _ = strings.TrimSpace
|
||||
|
||||
func TestDialValidated_FallsBackPastDeadAddress(t *testing.T) {
|
||||
ln, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
defer ln.Close()
|
||||
go func() {
|
||||
if c, err := ln.Accept(); err == nil {
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
_, port, _ := net.SplitHostPort(ln.Addr().String())
|
||||
// First address is a black hole (TEST-NET-1); the second is live.
|
||||
ips := []net.IP{net.ParseIP("192.0.2.1"), net.ParseIP("127.0.0.1")}
|
||||
start := time.Now()
|
||||
c, err := dialValidated(context.Background(), &net.Dialer{Timeout: 30 * time.Second}, "tcp", ips, port)
|
||||
require.NoError(t, err)
|
||||
_ = c.Close()
|
||||
require.Less(t, time.Since(start), 5*time.Second)
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
egressDialTimeout = 30 * time.Second
|
||||
halfCloseGrace = 60 * time.Second
|
||||
)
|
||||
|
||||
// EgressProxy is a loopback HTTP proxy that only forwards to public
|
||||
// destinations. Point a browser at it (--proxy-server) so every request it
|
||||
// makes — top-level, sub-resource, in-page fetch, WebSocket — is validated at
|
||||
// dial time against the same private-range policy as SafeHTTPClient. Names
|
||||
// that resolve to private IPs (nip.io, DNS rebinding) are caught because the
|
||||
// check runs on the resolved address, which is then dialed directly.
|
||||
//
|
||||
// It speaks CONNECT (https/wss) and absolute-URI HTTP (http/ws). It does not
|
||||
// follow redirects or honor HTTP_PROXY: a 3xx goes back to the browser, whose
|
||||
// next request re-enters the proxy and is validated again.
|
||||
type EgressProxy struct {
|
||||
ln net.Listener
|
||||
srv *http.Server
|
||||
tr *http.Transport
|
||||
dialer *net.Dialer
|
||||
// blockIP reports whether a resolved IP must be refused. Defaults to
|
||||
// isPrivateIP; tests override it to reach loopback httptest servers.
|
||||
blockIP func(net.IP) bool
|
||||
|
||||
mu sync.Mutex
|
||||
allow map[string]struct{} // loopback ports reachable despite blockIP
|
||||
conns map[net.Conn]struct{}
|
||||
closed bool
|
||||
wg sync.WaitGroup
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// StartEgressProxy starts a proxy on 127.0.0.1 with an ephemeral port.
|
||||
func StartEgressProxy() (*EgressProxy, error) {
|
||||
return startEgressProxy(isPrivateIP)
|
||||
}
|
||||
|
||||
func startEgressProxy(blockIP func(net.IP) bool) (*EgressProxy, error) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("egress proxy listen: %w", err)
|
||||
}
|
||||
p := &EgressProxy{
|
||||
ln: ln,
|
||||
dialer: &net.Dialer{Timeout: egressDialTimeout},
|
||||
blockIP: blockIP,
|
||||
conns: make(map[net.Conn]struct{}),
|
||||
}
|
||||
p.tr = &http.Transport{
|
||||
Proxy: nil, // never chain through HTTP_PROXY
|
||||
DialContext: p.dial,
|
||||
DisableCompression: true, // pass bytes through untouched
|
||||
MaxIdleConns: 32,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
rp := &httputil.ReverseProxy{
|
||||
Rewrite: func(r *httputil.ProxyRequest) { r.Out.Header.Del("Proxy-Connection") },
|
||||
Transport: p.tr,
|
||||
ErrorHandler: p.proxyError,
|
||||
}
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodConnect:
|
||||
p.handleConnect(w, r)
|
||||
case r.URL.IsAbs() && r.URL.Host != "" && r.URL.Scheme == "http":
|
||||
rp.ServeHTTP(w, r)
|
||||
default:
|
||||
http.Error(w, "egress proxy: absolute http URL or CONNECT required", http.StatusBadRequest)
|
||||
}
|
||||
})
|
||||
p.srv = &http.Server{Handler: handler, ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second}
|
||||
p.wg.Add(1)
|
||||
go func() {
|
||||
defer p.wg.Done()
|
||||
_ = p.srv.Serve(ln)
|
||||
}()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// AllowLoopbackPort lets the browser reach 127.0.0.1:port (and localhost:port)
|
||||
// through the proxy despite the private-range policy, for a port the caller
|
||||
// itself owns (e.g. the browser's own debugging port). Nothing else on
|
||||
// loopback is opened.
|
||||
func (p *EgressProxy) AllowLoopbackPort(port int) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.allow == nil {
|
||||
p.allow = make(map[string]struct{})
|
||||
}
|
||||
p.allow[strconv.Itoa(port)] = struct{}{}
|
||||
}
|
||||
|
||||
// allowedLoopback reports whether addr is an exact allowlisted loopback port.
|
||||
func (p *EgressProxy) allowedLoopback(addr string) bool {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if host != "127.0.0.1" && !strings.EqualFold(strings.TrimSuffix(host, "."), "localhost") {
|
||||
return false
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
_, ok := p.allow[port]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Addr returns the listen address as host:port.
|
||||
func (p *EgressProxy) Addr() string { return p.ln.Addr().String() }
|
||||
|
||||
// URL returns the proxy URL suitable for --proxy-server.
|
||||
func (p *EgressProxy) URL() string { return "http://" + p.Addr() }
|
||||
|
||||
// Close stops the listener and tears down every in-flight tunnel and upstream
|
||||
// connection. Idempotent.
|
||||
func (p *EgressProxy) Close() error {
|
||||
var err error
|
||||
p.once.Do(func() {
|
||||
p.mu.Lock()
|
||||
p.closed = true
|
||||
for c := range p.conns {
|
||||
_ = c.Close()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
err = p.srv.Close()
|
||||
p.tr.CloseIdleConnections()
|
||||
p.wg.Wait()
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// track registers c so Close can sever it. Returns false (and closes c) if
|
||||
// the proxy is already closed.
|
||||
func (p *EgressProxy) track(c net.Conn) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.closed {
|
||||
_ = c.Close()
|
||||
return false
|
||||
}
|
||||
p.conns[c] = struct{}{}
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *EgressProxy) untrack(c net.Conn) {
|
||||
p.mu.Lock()
|
||||
delete(p.conns, c)
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
type proxyConn struct {
|
||||
net.Conn
|
||||
p *EgressProxy
|
||||
}
|
||||
|
||||
func (c *proxyConn) Close() error {
|
||||
c.p.untrack(c.Conn)
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// dial is the only way the proxy reaches upstream: validated, pinned, tracked.
|
||||
func (p *EgressProxy) dial(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
var conn net.Conn
|
||||
var err error
|
||||
if p.allowedLoopback(addr) {
|
||||
_, port, _ := net.SplitHostPort(addr)
|
||||
conn, err = p.dialer.DialContext(ctx, network, net.JoinHostPort("127.0.0.1", port))
|
||||
} else {
|
||||
conn, err = safeDialContext(ctx, p.dialer, p.blockIP, network, addr)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !p.track(conn) {
|
||||
return nil, errors.New("egress proxy closed")
|
||||
}
|
||||
return &proxyConn{Conn: conn, p: p}, nil
|
||||
}
|
||||
|
||||
func (p *EgressProxy) proxyError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
writeDialError(w, err)
|
||||
}
|
||||
|
||||
func writeDialError(w http.ResponseWriter, err error) {
|
||||
var be *blockedError
|
||||
if errors.As(err, &be) {
|
||||
http.Error(w, "blocked by egress policy: "+be.msg, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
http.Error(w, "upstream unavailable", http.StatusBadGateway)
|
||||
}
|
||||
|
||||
func (p *EgressProxy) handleConnect(w http.ResponseWriter, r *http.Request) {
|
||||
target := r.Host
|
||||
if h, port, err := net.SplitHostPort(target); err != nil || h == "" || port == "" {
|
||||
http.Error(w, "egress proxy: CONNECT target must be host:port", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Validate and dial before hijacking so a refusal is a clean 403.
|
||||
up, err := p.dial(r.Context(), "tcp", target)
|
||||
if err != nil {
|
||||
writeDialError(w, err)
|
||||
return
|
||||
}
|
||||
hj, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
_ = up.Close()
|
||||
http.Error(w, "hijack unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
client, buf, err := hj.Hijack()
|
||||
if err != nil {
|
||||
_ = up.Close()
|
||||
return
|
||||
}
|
||||
if !p.track(client) {
|
||||
_ = up.Close()
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
p.untrack(client)
|
||||
_ = client.Close()
|
||||
_ = up.Close()
|
||||
}()
|
||||
if _, err := client.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); err != nil {
|
||||
return
|
||||
}
|
||||
done := make(chan struct{}, 2)
|
||||
// Bytes the server already buffered from the client belong upstream.
|
||||
go func() {
|
||||
_, _ = io.Copy(up, buf)
|
||||
_, _ = io.Copy(up, client)
|
||||
closeWrite(up) // propagate the client's FIN, keep reading the reply
|
||||
done <- struct{}{}
|
||||
}()
|
||||
go func() {
|
||||
_, _ = io.Copy(client, up)
|
||||
closeWrite(client)
|
||||
done <- struct{}{}
|
||||
}()
|
||||
// Wait for both directions (half-close is legal), but once one side has
|
||||
// finished give the other a bounded grace so a peer that vanished without
|
||||
// closing can't pin the tunnel. Close() also severs the conns.
|
||||
<-done
|
||||
grace := time.AfterFunc(halfCloseGrace, func() {
|
||||
_ = client.Close()
|
||||
_ = up.Close()
|
||||
})
|
||||
<-done
|
||||
grace.Stop()
|
||||
}
|
||||
|
||||
// closeWrite half-closes c's write side when it supports it, else fully closes.
|
||||
func closeWrite(c net.Conn) {
|
||||
if pc, ok := c.(*proxyConn); ok {
|
||||
c = pc.Conn
|
||||
}
|
||||
if cw, ok := c.(interface{ CloseWrite() error }); ok {
|
||||
_ = cw.CloseWrite()
|
||||
return
|
||||
}
|
||||
_ = c.Close()
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// allowLoopback lets tests reach httptest servers while still blocking every
|
||||
// other private range, so the block path stays exercised.
|
||||
func allowLoopback(ip net.IP) bool {
|
||||
if ip.IsLoopback() {
|
||||
return false
|
||||
}
|
||||
return isPrivateIP(ip)
|
||||
}
|
||||
|
||||
func newTestProxy(t *testing.T, block func(net.IP) bool) *EgressProxy {
|
||||
t.Helper()
|
||||
p, err := startEgressProxy(block)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p
|
||||
}
|
||||
|
||||
// connect sends a CONNECT and returns the status code plus the live conn.
|
||||
func connect(t *testing.T, p *EgressProxy, target string) (int, net.Conn, *bufio.Reader) {
|
||||
t.Helper()
|
||||
c, err := net.Dial("tcp", p.Addr())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = c.Close() })
|
||||
fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target)
|
||||
br := bufio.NewReader(c)
|
||||
resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodConnect})
|
||||
require.NoError(t, err)
|
||||
return resp.StatusCode, c, br
|
||||
}
|
||||
|
||||
func countingServer(t *testing.T) (*httptest.Server, *atomic.Int64) {
|
||||
var hits atomic.Int64
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
fmt.Fprint(w, "secret")
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, &hits
|
||||
}
|
||||
|
||||
func proxyClient(p *EgressProxy) *http.Client {
|
||||
u, _ := url.Parse(p.URL())
|
||||
return &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
Transport: &http.Transport{Proxy: http.ProxyURL(u)},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressProxy_ConnectBlocksPrivateTargets(t *testing.T) {
|
||||
srv, hits := countingServer(t)
|
||||
p := newTestProxy(t, isPrivateIP)
|
||||
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
|
||||
for _, target := range []string{
|
||||
"127.0.0.1:" + port,
|
||||
"localhost:" + port,
|
||||
"[::1]:" + port,
|
||||
"[::ffff:127.0.0.1]:" + port,
|
||||
"169.254.169.254:80",
|
||||
"10.0.0.1:443",
|
||||
"metadata.google.internal:80",
|
||||
"metadata:80",
|
||||
} {
|
||||
code, _, _ := connect(t, p, target)
|
||||
require.Equal(t, http.StatusForbidden, code, target)
|
||||
}
|
||||
require.EqualValues(t, 0, hits.Load())
|
||||
}
|
||||
|
||||
func TestEgressProxy_PlainHTTPBlocksPrivate(t *testing.T) {
|
||||
srv, hits := countingServer(t)
|
||||
p := newTestProxy(t, isPrivateIP)
|
||||
resp, err := proxyClient(p).Get(srv.URL)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
require.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
require.EqualValues(t, 0, hits.Load())
|
||||
}
|
||||
|
||||
func TestEgressProxy_PlainHTTPForwards(t *testing.T) {
|
||||
srv, hits := countingServer(t)
|
||||
p := newTestProxy(t, allowLoopback)
|
||||
resp, err := proxyClient(p).Get(srv.URL)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
require.Equal(t, "secret", string(body))
|
||||
require.EqualValues(t, 1, hits.Load())
|
||||
}
|
||||
|
||||
func TestEgressProxy_RedirectNotFollowed(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://169.254.169.254/", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := newTestProxy(t, allowLoopback)
|
||||
resp, err := proxyClient(p).Get(srv.URL)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
require.Equal(t, http.StatusFound, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestEgressProxy_ConnectTunnelForwards(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
defer ln.Close()
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
_, _ = io.Copy(c, c) // echo
|
||||
}()
|
||||
p := newTestProxy(t, allowLoopback)
|
||||
code, c, br := connect(t, p, ln.Addr().String())
|
||||
require.Equal(t, http.StatusOK, code)
|
||||
_, err = c.Write([]byte("ping\n"))
|
||||
require.NoError(t, err)
|
||||
line, err := br.ReadString('\n')
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "ping\n", line)
|
||||
}
|
||||
|
||||
func TestEgressProxy_OriginFormRejected(t *testing.T) {
|
||||
p := newTestProxy(t, isPrivateIP)
|
||||
c, err := net.Dial("tcp", p.Addr())
|
||||
require.NoError(t, err)
|
||||
defer c.Close()
|
||||
fmt.Fprint(c, "GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n")
|
||||
resp, err := http.ReadResponse(bufio.NewReader(c), nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestEgressProxy_CloseTearsDownTunnel(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
defer ln.Close()
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
_, _ = io.Copy(io.Discard, c)
|
||||
}()
|
||||
p := newTestProxy(t, allowLoopback)
|
||||
code, c, _ := connect(t, p, ln.Addr().String())
|
||||
require.Equal(t, http.StatusOK, code)
|
||||
require.NoError(t, p.Close())
|
||||
require.NoError(t, p.Close(), "Close must be idempotent")
|
||||
_ = c.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
_, err = c.Read(make([]byte, 1))
|
||||
require.Equal(t, io.EOF, err, "tunnel must be closed, not timed out")
|
||||
}
|
||||
|
||||
func TestEgressProxy_HalfClose(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
defer ln.Close()
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
_, _ = io.Copy(io.Discard, c) // read to client EOF
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_, _ = c.Write([]byte("REPLY"))
|
||||
}()
|
||||
p := newTestProxy(t, allowLoopback)
|
||||
status, c, br := connect(t, p, ln.Addr().String())
|
||||
require.Equal(t, 200, status)
|
||||
_, _ = c.Write([]byte("hi"))
|
||||
require.NoError(t, c.(*net.TCPConn).CloseWrite())
|
||||
_ = c.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
got, _ := io.ReadAll(br)
|
||||
require.Equal(t, "REPLY", string(got))
|
||||
}
|
||||
|
||||
func TestEgressProxy_AllowLoopbackPortIsExact(t *testing.T) {
|
||||
srv, hits := countingServer(t)
|
||||
other, otherHits := countingServer(t)
|
||||
p := newTestProxy(t, isPrivateIP) // default policy: loopback blocked
|
||||
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
|
||||
var n int
|
||||
_, _ = fmt.Sscan(port, &n)
|
||||
p.AllowLoopbackPort(n)
|
||||
|
||||
resp, err := proxyClient(p).Get(srv.URL)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
require.Equal(t, int64(1), hits.Load())
|
||||
|
||||
resp, err = proxyClient(p).Get(other.URL)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
require.Equal(t, 403, resp.StatusCode)
|
||||
require.Zero(t, otherHits.Load())
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// exaBaseURL is the Exa API origin. Docs: https://exa.ai/docs/search/quickstart
|
||||
const exaBaseURL = "https://api.exa.ai"
|
||||
|
||||
// exaMaxResultChars bounds the highlight text kept per result so a search
|
||||
// result list stays small in the model's context.
|
||||
const exaMaxResultChars = 1500
|
||||
|
||||
// exaTypes are the search types exa_search accepts. The deep and
|
||||
// deep-reasoning modes (4-40s) are left out: agents that need that depth
|
||||
// can iterate with fetches instead of blocking on one call.
|
||||
var exaTypes = map[string]bool{"auto": true, "fast": true, "instant": true, "deep-lite": true}
|
||||
|
||||
// exaCategories are Exa's known data categories.
|
||||
var exaCategories = map[string]bool{
|
||||
"company": true, "publication": true, "news": true,
|
||||
"personal site": true, "financial report": true, "people": true,
|
||||
}
|
||||
|
||||
// ExaSearchTool searches the web with the Exa Search API, which returns
|
||||
// ranked results with query-relevant highlights extracted from each page.
|
||||
// It requires an Exa API key (https://dashboard.exa.ai/api-keys).
|
||||
type ExaSearchTool struct {
|
||||
// APIKey authenticates requests (sent as the x-api-key header).
|
||||
APIKey string
|
||||
// BaseURL overrides the API origin; empty means https://api.exa.ai.
|
||||
BaseURL string
|
||||
|
||||
// client overrides the HTTP client (tests); nil means the shared
|
||||
// SSRF-safe searchClient.
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type exaSearchInput struct {
|
||||
Query string `json:"query"`
|
||||
NumResults int `json:"num_results,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
IncludeDomains []string `json:"include_domains,omitempty"`
|
||||
ExcludeDomains []string `json:"exclude_domains,omitempty"`
|
||||
StartPublishedDate string `json:"start_published_date,omitempty"`
|
||||
}
|
||||
|
||||
func (t *ExaSearchTool) Name() string { return "exa_search" }
|
||||
|
||||
func (t *ExaSearchTool) Description() string {
|
||||
return "Search the web with Exa, a search engine built for agents. Write the query in natural language, describing what you want to find. Returns ranked results with titles, URLs, publication dates, and the passages of each page most relevant to the query. Optionally filter by category, domains, or publication date."
|
||||
}
|
||||
|
||||
func (t *ExaSearchTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "A natural-language description of what to find, e.g. \"recent news on Singapore's HDB resale prices\""
|
||||
},
|
||||
"num_results": {
|
||||
"type": "integer",
|
||||
"description": "Maximum number of results to return (default: 5, max: 10)"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["auto", "fast", "instant", "deep-lite"],
|
||||
"description": "Search mode: auto (default, ~1s), fast (~0.5s), instant (~0.25s), or deep-lite (~4s, light multi-step research)"
|
||||
},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": ["company", "publication", "news", "personal site", "financial report", "people"],
|
||||
"description": "Focus on one kind of source. company and people do not support exclude_domains or start_published_date."
|
||||
},
|
||||
"include_domains": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Only return results from these domains or path prefixes, e.g. [\"straitstimes.com\", \"*.gov.sg\"]"
|
||||
},
|
||||
"exclude_domains": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Never return results from these domains or path prefixes"
|
||||
},
|
||||
"start_published_date": {
|
||||
"type": "string",
|
||||
"description": "Only return pages published on or after this date (ISO 8601, e.g. 2026-01-01)"
|
||||
}
|
||||
},
|
||||
"required": ["query"]
|
||||
}`)
|
||||
}
|
||||
|
||||
// IsConcurrencySafe returns true — exa_search is a pure read.
|
||||
func (t *ExaSearchTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
|
||||
|
||||
func (t *ExaSearchTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in exaSearchInput
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||
}
|
||||
in.Query = strings.TrimSpace(in.Query)
|
||||
if in.Query == "" {
|
||||
return tool.ToolResult{Error: "query is required"}, nil
|
||||
}
|
||||
if t.APIKey == "" {
|
||||
return tool.ToolResult{Error: "exa_search: no Exa API key configured"}, nil
|
||||
}
|
||||
if in.Type == "" {
|
||||
in.Type = "auto"
|
||||
}
|
||||
if !exaTypes[in.Type] {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid type %q (want auto, fast, instant or deep-lite)", in.Type)}, nil
|
||||
}
|
||||
if in.Category != "" && !exaCategories[in.Category] {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid category %q", in.Category)}, nil
|
||||
}
|
||||
n := in.NumResults
|
||||
if n <= 0 {
|
||||
n = 5
|
||||
}
|
||||
if n > 10 {
|
||||
n = 10
|
||||
}
|
||||
|
||||
body := map[string]any{
|
||||
"query": in.Query,
|
||||
"type": in.Type,
|
||||
"numResults": n,
|
||||
"contents": map[string]any{"highlights": true},
|
||||
}
|
||||
if in.Category != "" {
|
||||
body["category"] = in.Category
|
||||
}
|
||||
if len(in.IncludeDomains) > 0 {
|
||||
body["includeDomains"] = in.IncludeDomains
|
||||
}
|
||||
if len(in.ExcludeDomains) > 0 {
|
||||
body["excludeDomains"] = in.ExcludeDomains
|
||||
}
|
||||
if in.StartPublishedDate != "" {
|
||||
body["startPublishedDate"] = in.StartPublishedDate
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, searchTimeout)
|
||||
defer cancel()
|
||||
|
||||
results, err := t.search(ctx, body)
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("exa search failed: %v", err)}, nil
|
||||
}
|
||||
if len(results) == 0 {
|
||||
return tool.ToolResult{Output: "No results found for: " + in.Query}, nil
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
for i, r := range results {
|
||||
fmt.Fprintf(&sb, "%d. **%s**\n %s\n", i+1, r.Title, r.URL)
|
||||
if r.PublishedDate != "" {
|
||||
date, _, _ := strings.Cut(r.PublishedDate, "T")
|
||||
fmt.Fprintf(&sb, " Published: %s\n", date)
|
||||
}
|
||||
if text := exaHighlightText(r.Highlights); text != "" {
|
||||
fmt.Fprintf(&sb, " %s\n", text)
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
return tool.ToolResult{
|
||||
Output: sb.String(),
|
||||
Metadata: map[string]any{
|
||||
"query": in.Query,
|
||||
"num_results": len(results),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type exaResult struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
PublishedDate string `json:"publishedDate"`
|
||||
Highlights []string `json:"highlights"`
|
||||
}
|
||||
|
||||
func (t *ExaSearchTool) search(ctx context.Context, body map[string]any) ([]exaResult, error) {
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := t.BaseURL
|
||||
if base == "" {
|
||||
base = exaBaseURL
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(base, "/")+"/search", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", t.APIKey)
|
||||
client := t.client
|
||||
if client == nil {
|
||||
client = searchClient
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return nil, fmt.Errorf("exa returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
|
||||
}
|
||||
var parsed struct {
|
||||
Results []exaResult `json:"results"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&parsed); err != nil {
|
||||
return nil, fmt.Errorf("exa decode: %w", err)
|
||||
}
|
||||
return parsed.Results, nil
|
||||
}
|
||||
|
||||
// exaHighlightText joins a result's highlights into one line, collapsing
|
||||
// whitespace and truncating to exaMaxResultChars.
|
||||
func exaHighlightText(highlights []string) string {
|
||||
text := strings.Join(strings.Fields(strings.Join(highlights, " … ")), " ")
|
||||
if r := []rune(text); len(r) > exaMaxResultChars {
|
||||
text = string(r[:exaMaxResultChars]) + "…"
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newExaTestTool(t *testing.T, handler http.HandlerFunc) *ExaSearchTool {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &ExaSearchTool{APIKey: "test-key", BaseURL: srv.URL, client: srv.Client()}
|
||||
}
|
||||
|
||||
func TestExaSearch_RequestAndOutput(t *testing.T) {
|
||||
var gotKey string
|
||||
var gotBody map[string]any
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, "/search", r.URL.Path)
|
||||
gotKey = r.Header.Get("x-api-key")
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&gotBody))
|
||||
w.Write([]byte(`{"results":[
|
||||
{"title":"HDB prices","url":"https://example.com/a","publishedDate":"2026-09-01T00:00:00.000Z","highlights":["Resale prices rose\n 2%.","Second point."]},
|
||||
{"title":"No date","url":"https://example.com/b"}
|
||||
]}`))
|
||||
})
|
||||
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{
|
||||
"query":"HDB resale prices","num_results":50,"category":"news",
|
||||
"include_domains":["straitstimes.com"],"start_published_date":"2026-01-01"}`))
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
|
||||
require.Equal(t, "test-key", gotKey)
|
||||
require.Equal(t, "HDB resale prices", gotBody["query"])
|
||||
require.Equal(t, "auto", gotBody["type"])
|
||||
require.EqualValues(t, 10, gotBody["numResults"], "num_results is capped at 10")
|
||||
require.Equal(t, "news", gotBody["category"])
|
||||
require.Equal(t, []any{"straitstimes.com"}, gotBody["includeDomains"])
|
||||
require.Equal(t, "2026-01-01", gotBody["startPublishedDate"])
|
||||
require.NotContains(t, gotBody, "excludeDomains")
|
||||
require.Equal(t, map[string]any{"highlights": true}, gotBody["contents"])
|
||||
|
||||
require.Contains(t, res.Output, "1. **HDB prices**\n https://example.com/a\n Published: 2026-09-01\n Resale prices rose 2%. … Second point.")
|
||||
require.Contains(t, res.Output, "2. **No date**\n https://example.com/b\n\n")
|
||||
require.Equal(t, 2, res.Metadata["num_results"])
|
||||
}
|
||||
|
||||
func TestExaSearch_HTTPError(t *testing.T) {
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, `{"error":"invalid key"}`, http.StatusUnauthorized)
|
||||
})
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{"query":"x"}`))
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, res.Error, "HTTP 401")
|
||||
require.Contains(t, res.Error, "invalid key")
|
||||
}
|
||||
|
||||
func TestExaSearch_NoResults(t *testing.T) {
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"results":[]}`))
|
||||
})
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{"query":"nothing"}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "No results found for: nothing", res.Output)
|
||||
}
|
||||
|
||||
func TestExaSearch_InvalidInput(t *testing.T) {
|
||||
called := false
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) { called = true })
|
||||
for _, in := range []string{
|
||||
`{"query":" "}`,
|
||||
`{"query":"x","type":"deep-reasoning"}`,
|
||||
`{"query":"x","category":"recipes"}`,
|
||||
`not json`,
|
||||
} {
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(in))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res.Error, in)
|
||||
}
|
||||
require.False(t, called, "invalid input must not reach the API")
|
||||
|
||||
noKey := &ExaSearchTool{}
|
||||
res, _ := noKey.Execute(context.Background(), json.RawMessage(`{"query":"x"}`))
|
||||
require.Contains(t, res.Error, "no Exa API key")
|
||||
}
|
||||
|
||||
func TestExaSearch_DefaultClientIsSafe(t *testing.T) {
|
||||
// The zero-value tool must use the SSRF-safe client, which refuses
|
||||
// loopback addresses.
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"results":[]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
tl := &ExaSearchTool{APIKey: "k", BaseURL: srv.URL}
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{"query":"x"}`))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res.Error)
|
||||
}
|
||||
|
||||
func TestExaHighlightText_Truncates(t *testing.T) {
|
||||
text := exaHighlightText([]string{strings.Repeat("a", exaMaxResultChars+100)})
|
||||
require.Equal(t, exaMaxResultChars+1, len([]rune(text)))
|
||||
require.True(t, strings.HasSuffix(text, "…"))
|
||||
}
|
||||
@@ -21,6 +21,32 @@ var privateNetworks = []string{
|
||||
"fc00::/7", // IPv6 unique local
|
||||
"fe80::/10", // IPv6 link-local
|
||||
"::/128", // IPv6 unspecified
|
||||
"198.18.0.0/15", // benchmarking (RFC 2544)
|
||||
"224.0.0.0/4", // IPv4 multicast
|
||||
"240.0.0.0/4", // reserved, incl. 255.255.255.255 broadcast
|
||||
"ff00::/8", // IPv6 multicast
|
||||
"2001::/32", // Teredo (embeds an obfuscated IPv4)
|
||||
"64:ff9b:1::/48", // local-use NAT64 (RFC 8215)
|
||||
}
|
||||
|
||||
// embeddedV4Nets are IPv6 prefixes that carry an IPv4 address translators may
|
||||
// route to: the embedded address is re-checked so e.g. 64:ff9b::7f00:1 (NAT64
|
||||
// for 127.0.0.1) is blocked while a public embedded address stays allowed.
|
||||
var embeddedV4Nets = []struct {
|
||||
net *net.IPNet
|
||||
offset int // byte offset of the embedded IPv4 address
|
||||
}{
|
||||
{mustCIDR("64:ff9b::/96"), 12}, // NAT64 well-known prefix
|
||||
{mustCIDR("2002::/16"), 2}, // 6to4
|
||||
{mustCIDR("::/96"), 12}, // IPv4-compatible (deprecated)
|
||||
}
|
||||
|
||||
func mustCIDR(s string) *net.IPNet {
|
||||
_, n, err := net.ParseCIDR(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
var parsedPrivateNets []*net.IPNet
|
||||
@@ -41,6 +67,15 @@ func isPrivateIP(ip net.IP) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if ip.To4() == nil {
|
||||
if ip16 := ip.To16(); ip16 != nil {
|
||||
for _, e := range embeddedV4Nets {
|
||||
if e.net.Contains(ip16) {
|
||||
return isPrivateIP(net.IP(ip16[e.offset : e.offset+4]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
+22
-1
@@ -17,7 +17,7 @@ func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) {
|
||||
"http://10.0.0.1/",
|
||||
"http://172.16.0.1/",
|
||||
"http://192.168.1.1/",
|
||||
"http://169.254.169.254/", // AWS/GCP/Azure metadata IP
|
||||
"http://169.254.169.254/", // AWS/GCP/Azure metadata IP
|
||||
"http://metadata.google.internal/", // GCP metadata host
|
||||
}
|
||||
for _, u := range cases {
|
||||
@@ -72,3 +72,24 @@ func TestIsPrivateIP_AllowsPublic(t *testing.T) {
|
||||
require.False(t, isPrivateIP(ip), "%s must be allowed (public)", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPrivateIP_EmbeddedAndReserved(t *testing.T) {
|
||||
blocked := []string{
|
||||
"64:ff9b::7f00:1", // NAT64 -> 127.0.0.1
|
||||
"64:ff9b::a9fe:a9fe", // NAT64 -> 169.254.169.254
|
||||
"2002:7f00:1::", // 6to4 -> 127.0.0.1
|
||||
"::127.0.0.1", // IPv4-compatible
|
||||
"224.0.0.1", "ff02::1", // multicast
|
||||
"198.18.0.1", // benchmarking
|
||||
"240.0.0.1", "255.255.255.255",
|
||||
"2001:0:4136:e378:8000:63bf:3fff:fdd2", // Teredo
|
||||
}
|
||||
for _, s := range blocked {
|
||||
ip := net.ParseIP(s)
|
||||
require.NotNil(t, ip, "parse %s", s)
|
||||
require.True(t, isPrivateIP(ip), "%s must be blocked", s)
|
||||
}
|
||||
for _, s := range []string{"64:ff9b::808:808", "2002:808:808::"} { // embed 8.8.8.8
|
||||
require.False(t, isPrivateIP(net.ParseIP(s)), "%s embeds a public address", s)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user