diff --git a/CLAUDE.md b/CLAUDE.md index 4228170..a654741 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1 +1 @@ -每次执行命令前均需阅读项目根目录下的 ./AGENTS.md 文件 \ No newline at end of file +每次执行命令前均需阅读项目根目录下的 @AGENTS.md 文件 \ No newline at end of file diff --git a/README.md b/README.md index f47c10a..31f8376 100644 --- a/README.md +++ b/README.md @@ -60,15 +60,11 @@ Please note, there are exceptions to this synchronization. If a version of NTrac ### Automated Install - Debian / Ubuntu - - Recommended: install from the official `nexttrace-debs` APT repository + - Recommended: install from the official APT repository at `apt.nxtrace.org` - Supports: `amd64`, `i386`, `arm64`, `armel`, `armhf`, `loong64`, `mipsel`, `mips64el`, `ppc64el`, `riscv64`, `s390x` - - Add the repository and install the default package: + - Set up the repository, then refresh APT and install NextTrace. Requires `curl`, Bash, and `sudo` privileges: ```shell - sudo install -d -m 0755 /etc/apt/keyrings - curl -fsSL -o /tmp/nexttrace-archive-keyring.gpg https://github.com/nxtrace/nexttrace-debs/releases/latest/download/nexttrace-archive-keyring.gpg - sudo install -m 0644 /tmp/nexttrace-archive-keyring.gpg /etc/apt/keyrings/nexttrace.gpg - rm -f /tmp/nexttrace-archive-keyring.gpg - printf '%s\n' 'Types: deb' 'URIs: https://github.com/nxtrace/nexttrace-debs/releases/latest/download/' 'Suites: ./' 'Signed-By: /etc/apt/keyrings/nexttrace.gpg' | sudo tee /etc/apt/sources.list.d/nexttrace.sources >/dev/null + curl -fsSL https://apt.nxtrace.org/setup-apt.sh | bash sudo apt update sudo apt install nexttrace ``` @@ -78,6 +74,8 @@ Please note, there are exceptions to this synchronization. If a version of NTrac sudo apt install ntr ``` - Packages can be installed side by side. Commands: `nexttrace`, `nexttrace-tiny`, `ntr` + - To switch from GitHub, run the setup script. It backs up the standard `nexttrace.sources` entry before switching. For custom entries or legacy `.list` files, back up and disable the old entry first. See the [manual APT setup and switching guide](https://github.com/nxtrace/nexttrace-debs/blob/main/README.md). + - The [legacy GitHub APT source](https://github.com/nxtrace/nexttrace-debs/releases/latest/download/) remains available. To switch back, disable the new source, restore the backup, and run `sudo apt update`. To configure the legacy source manually, use the GitHub URL in `URIs`, omit `By-Hash: force`, and install the [GitHub archive key](https://github.com/nxtrace/nexttrace-debs/releases/latest/download/nexttrace-archive-keyring.gpg) if needed. - Linux / macOS / BSD - One-click installation script (Full, default) @@ -1180,6 +1178,8 @@ nexttrace --deploy --mcp --listen 0.0.0.0:1080 --deploy-token "$TOKEN" Loopback listen addresses (`127.0.0.1`, `::1`, `localhost`) are tokenless by default. External listen addresses require a token; if none is set with `--deploy-token` or `NEXTTRACE_DEPLOY_TOKEN`, NextTrace generates one and prints it to stdout. API, WebSocket, and MCP clients may use `Authorization: Bearer ` or `X-NextTrace-Token`; browser WebUI users can sign in at `/auth/login`. +In tokenless mode, the request `Host` must be `localhost` or a loopback IP address. A custom hostname requires deploy token authentication. + ### Register MCP in Agent clients Start NextTrace first. The MCP endpoint is Streamable HTTP, not stdio: diff --git a/README_zh_CN.md b/README_zh_CN.md index ab032c2..67d70d3 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -64,15 +64,11 @@ Document Language: [English](README.md) | 简体中文 ### Automated Install - Debian / Ubuntu - - 推荐:通过官方 `nexttrace-debs` APT 源安装 + - 推荐:通过 `apt.nxtrace.org` 官方 APT 源安装 - 当前支持:`amd64`、`i386`、`arm64`、`armel`、`armhf`、`loong64`、`mipsel`、`mips64el`、`ppc64el`、`riscv64`、`s390x` - - 添加源并安装默认包: + - 需要 `curl`、Bash 和 `sudo` 权限。先配置源,再刷新索引并安装 NextTrace。 ```shell - sudo install -d -m 0755 /etc/apt/keyrings - curl -fsSL -o /tmp/nexttrace-archive-keyring.gpg https://github.com/nxtrace/nexttrace-debs/releases/latest/download/nexttrace-archive-keyring.gpg - sudo install -m 0644 /tmp/nexttrace-archive-keyring.gpg /etc/apt/keyrings/nexttrace.gpg - rm -f /tmp/nexttrace-archive-keyring.gpg - printf '%s\n' 'Types: deb' 'URIs: https://github.com/nxtrace/nexttrace-debs/releases/latest/download/' 'Suites: ./' 'Signed-By: /etc/apt/keyrings/nexttrace.gpg' | sudo tee /etc/apt/sources.list.d/nexttrace.sources >/dev/null + curl -fsSL https://apt.nxtrace.org/setup-apt.sh | bash sudo apt update sudo apt install nexttrace ``` @@ -82,6 +78,8 @@ Document Language: [English](README.md) | 简体中文 sudo apt install ntr ``` - 三个包可以共存安装,对应命令分别是:`nexttrace`、`nexttrace-tiny`、`ntr` + - 从 GitHub 切换时,可直接运行配置脚本,标准 `nexttrace.sources` 会先备份再迁移。自定义条目或旧 `.list` 文件,请先备份并停用。详见 [APT 手动配置和切换说明](https://github.com/nxtrace/nexttrace-debs/blob/main/README.md)。 + - [GitHub 旧源](https://github.com/nxtrace/nexttrace-debs/releases/latest/download/)仍可继续使用。回退时停用新源、恢复备份,再运行 `sudo apt update`。手动配置旧源时,将 `URIs` 改为 GitHub 地址,省略 `By-Hash: force`。尚未安装公钥时,可使用 [GitHub 公钥下载地址](https://github.com/nxtrace/nexttrace-debs/releases/latest/download/nexttrace-archive-keyring.gpg)。 - Linux / macOS / BSD - 一键安装脚本(完整版,默认) @@ -1180,6 +1178,8 @@ nexttrace --deploy --mcp --listen 0.0.0.0:1080 --deploy-token "$TOKEN" 监听 loopback 地址(`127.0.0.1`、`::1`、`localhost`)时默认免 token。监听外网地址时必须启用 token;如果没有通过 `--deploy-token` 或 `NEXTTRACE_DEPLOY_TOKEN` 设置,NextTrace 会启动时随机生成 token 并输出到 stdout。若 stdout 会被日志系统、CI 控制台或平台采集,建议通过 `--deploy-token` 或 `NEXTTRACE_DEPLOY_TOKEN` 显式提供 token,避免泄漏。API、WebSocket 与 MCP 客户端可使用 `Authorization: Bearer ` 或 `X-NextTrace-Token`;浏览器 WebUI 用户可访问 `/auth/login` 登录。 +免 token 模式只接受 `Host` 为 `localhost` 或回环 IP 地址的请求。自定义域名须启用 token 鉴权。 + ### 在 Agent 客户端注册 MCP 先启动 NextTrace。MCP endpoint 是 Streamable HTTP,不是 stdio: diff --git a/go.mod b/go.mod index 39c75df..bff7308 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/akamensky/argparse v1.4.0 github.com/ameshkov/dnscrypt/v2 v2.4.0 github.com/charmbracelet/log v1.0.0 - github.com/charmbracelet/x/ansi v0.11.9 + github.com/charmbracelet/x/ansi v0.11.10 github.com/fatih/color v1.19.0 github.com/gin-gonic/gin v1.12.0 github.com/google/gopacket v1.1.19 @@ -27,14 +27,14 @@ require ( github.com/sthorne/odoh-go v1.0.4 github.com/stretchr/testify v1.12.1 github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 - github.com/tidwall/gjson v1.20.1 + github.com/tidwall/gjson v1.20.5 github.com/tsosunchia/powclient v0.3.0 github.com/xjasonlyu/windivert-go v0.0.0-20201010013527-4239d0afa76f - golang.org/x/mod v0.42.0 - golang.org/x/net v0.62.0 + golang.org/x/mod v0.43.0 + golang.org/x/net v0.63.0 golang.org/x/sync v0.25.0 - golang.org/x/sys v0.49.0 - golang.org/x/term v0.47.0 + golang.org/x/sys v0.50.0 + golang.org/x/term v0.48.0 ) require ( @@ -89,7 +89,7 @@ require ( github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/tidwall/match v1.2.0 // indirect - github.com/tidwall/pretty v1.2.1 // indirect + github.com/tidwall/pretty v1.3.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect @@ -97,11 +97,11 @@ require ( go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.58.0 // indirect + golang.org/x/crypto v0.59.0 // indirect golang.org/x/exp v0.0.0-20260812173653-3d80eb74bc5b // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/perf v0.0.0-20260825160852-19be9d8e6c70 // indirect - golang.org/x/text v0.43.0 // indirect + golang.org/x/text v0.44.0 // indirect golang.org/x/time v0.15.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index ede7a62..ddb869d 100644 --- a/go.sum +++ b/go.sum @@ -25,8 +25,8 @@ github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoF github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= github.com/charmbracelet/log v1.0.0 h1:HVVVMmfOorfj3BA9i8X8UL69Hoz9lI0PYwXfJvOdRc4= github.com/charmbracelet/log v1.0.0/go.mod h1:uYgY3SmLpwJWxmlrPwXvzVYujxis1vAKRV/0VQB7yWA= -github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= -github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/ansi v0.11.10 h1:GjcX3+rAk+8wDX/jY0XwrZstxkjRcLkYU3TvwzZWiRA= +github.com/charmbracelet/x/ansi v0.11.10/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= @@ -176,12 +176,12 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8 github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 h1:kdXcSzyDtseVEc4yCz2qF8ZrQvIDBJLl4S1c3GCXmoI= github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= -github.com/tidwall/gjson v1.20.1 h1:Jmex4ygKZxn92HFHlejG8sHcEODHttXyrj63hsJ7/GE= -github.com/tidwall/gjson v1.20.1/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc= +github.com/tidwall/gjson v1.20.5 h1:OV4dBDripDl7ZK0GJIxWe1pn2zD6VB8vX+6hq6fLmuw= +github.com/tidwall/gjson v1.20.5/go.mod h1:jV1Xkr7LRLVFhesDFU/nInoQ+MjVlnuqkUreTWMveUo= github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM= github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= -github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.3.0 h1:DZmEzADnMIbThFXXslDgq9C0LCC/xzMrONm7iM77RM0= +github.com/tidwall/pretty v1.3.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tsosunchia/powclient v0.3.0 h1:EFVnXyWdw2w8HkyMwjR+4PQTzkKG84l0Bow49hW1iok= github.com/tsosunchia/powclient v0.3.0/go.mod h1:TG05HvU+N/R4sCLuZHImpgUAtpZ+h+gvaCzMNO+/4J4= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= @@ -208,18 +208,18 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/exp v0.0.0-20260812173653-3d80eb74bc5b h1:3XR0v9KL97wjTmRb+6RqMylL4d7ZWM1sQYIITGDxtmg= golang.org/x/exp v0.0.0-20260812173653-3d80eb74bc5b/go.mod h1:EdfpwwqSu+0Li0mzskwHU6FWDV3t9Q+RZDo3QMUtL3Q= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= -golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= +golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= -golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/perf v0.0.0-20260825160852-19be9d8e6c70 h1:M+kM03JKR23KkrutTue5KEQYDSbZTZTJ4FJ1v5zYrHM= @@ -234,19 +234,19 @@ golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201008064518-c1f3e3309c71/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= -golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= -golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= 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-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= -golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/server/browser_access.go b/server/browser_access.go index b069af5..1181c2a 100644 --- a/server/browser_access.go +++ b/server/browser_access.go @@ -1,6 +1,7 @@ package server import ( + "net" "net/http" "net/url" "strings" @@ -33,8 +34,24 @@ func browserOriginAllowed(r *http.Request) bool { return strings.EqualFold(u.Host, r.Host) } -func browserAccessMiddleware() gin.HandlerFunc { +func isLoopbackRequestHost(authority string) bool { + host, _, err := net.SplitHostPort(authority) + if err != nil { + host = authority + if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { + return net.ParseIP(host[1 : len(host)-1]).IsLoopback() + } + } + return strings.EqualFold(host, "localhost") || net.ParseIP(host).IsLoopback() +} + +func browserAccessMiddleware(requireLoopbackHost bool) gin.HandlerFunc { return func(c *gin.Context) { + // Matching Origin and Host alone does not protect tokenless deploy from DNS rebinding. + if requireLoopbackHost && !isLoopbackRequestHost(c.Request.Host) { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "deploy without a token requires a loopback host"}) + return + } if !browserOriginAllowed(c.Request) { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin browser access is disabled"}) return diff --git a/server/browser_access_test.go b/server/browser_access_test.go index 2e1a2fb..65738cd 100644 --- a/server/browser_access_test.go +++ b/server/browser_access_test.go @@ -48,7 +48,7 @@ func TestBrowserAccessMiddleware_DefaultRejectsCrossOriginHTTP(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() - router.Use(browserAccessMiddleware()) + router.Use(browserAccessMiddleware(true)) router.GET("/ok", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) }) @@ -69,7 +69,7 @@ func TestBrowserAccessMiddleware_CanEnableCORSViaEnv(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() - router.Use(browserAccessMiddleware()) + router.Use(browserAccessMiddleware(true)) router.OPTIONS("/*path", func(c *gin.Context) { c.Status(http.StatusNoContent) }) @@ -89,4 +89,53 @@ func TestBrowserAccessMiddleware_CanEnableCORSViaEnv(t *testing.T) { if got := resp.Header().Get("Access-Control-Allow-Methods"); got != "GET, POST, DELETE, OPTIONS" { t.Fatalf("allow-methods = %q, want DELETE included", got) } + + req.Host = "example.test:1080" + resp = httptest.NewRecorder() + router.ServeHTTP(resp, req) + if resp.Code != http.StatusForbidden || resp.Header().Get("Access-Control-Allow-Origin") != "" { + t.Fatalf("non-loopback preflight status = %d, headers = %v", resp.Code, resp.Header()) + } +} + +func TestDeployRouterTokenlessHostPolicy(t *testing.T) { + t.Setenv(util.EnvAllowCrossOriginKey, "0") + gin.SetMode(gin.TestMode) + router := newDeployRouter(deployAuth{}, true) + + for _, path := range []string{"/", "/api/options", "/ws/trace", "/mcp"} { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Host = "example.test:1080" + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + if resp.Code != http.StatusForbidden { + t.Errorf("GET %s with non-loopback Host: status = %d, want 403", path, resp.Code) + } + } + + for _, host := range []string{"LOCALHOST", "127.0.0.2:1080", "[::1]:1080", "[::1]"} { + req := httptest.NewRequest(http.MethodGet, "/api/options", nil) + req.Host = host + req.Header.Set("Origin", "http://"+host) + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + if resp.Code != http.StatusOK { + t.Errorf("loopback Host %q: status = %d, want 200", host, resp.Code) + } + } +} + +func TestDeployRouterAllowsNonLoopbackHostWithToken(t *testing.T) { + t.Setenv(util.EnvAllowCrossOriginKey, "0") + gin.SetMode(gin.TestMode) + router := newDeployRouter(deployAuth{Enabled: true, Token: "test-token"}, false) + req := httptest.NewRequest(http.MethodGet, "/api/options", nil) + req.Host = "nexttrace.example.test" + req.Header.Set("Origin", "https://nexttrace.example.test") + req.Header.Set("Authorization", "Bearer test-token") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + if resp.Code != http.StatusOK { + t.Fatalf("token-authenticated request: status = %d, want 200", resp.Code) + } } diff --git a/server/server.go b/server/server.go index 3ec826f..f8af24b 100644 --- a/server/server.go +++ b/server/server.go @@ -68,34 +68,7 @@ func RunWithOptions(opts Options, onReady func(net.Addr)) error { auth := deployAuth{Enabled: opts.AuthEnabled, Token: deployToken} gin.SetMode(gin.ReleaseMode) - router := gin.New() - router.Use(gin.Logger(), gin.Recovery()) - router.Use(browserAccessMiddleware()) - registerDeployAuthRoutes(router, auth) - router.Use(deployAuthMiddleware(auth)) - - router.OPTIONS("/*path", func(c *gin.Context) { - c.Status(http.StatusNoContent) - }) - - router.GET("/", func(c *gin.Context) { - c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage) - }) - - router.StaticFS("/assets", http.FS(assetsFS)) - - router.GET("/api/options", optionsHandler) - router.POST("/api/trace", traceHandler) - router.POST("/api/cache/clear", cacheClearHandler) - router.GET("/ws/trace", traceWebsocketHandler) - if opts.EnableMCP { - mcpHandler := gin.WrapH(newMCPHTTPHandler()) - router.GET("/mcp", mcpHandler) - router.POST("/mcp", mcpHandler) - router.DELETE("/mcp", mcpHandler) - } - - srv := newHTTPServer(listenAddr, router) + srv := newHTTPServer(listenAddr, newDeployRouter(auth, opts.EnableMCP)) listener, err := listenHTTP(listenAddr) if err != nil { return err @@ -122,6 +95,37 @@ func RunWithOptions(opts Options, onReady func(net.Addr)) error { return nil } +func newDeployRouter(auth deployAuth, enableMCP bool) *gin.Engine { + router := gin.New() + router.Use(gin.Logger(), gin.Recovery()) + router.Use(browserAccessMiddleware(!auth.Enabled)) + registerDeployAuthRoutes(router, auth) + router.Use(deployAuthMiddleware(auth)) + + router.OPTIONS("/*path", func(c *gin.Context) { + c.Status(http.StatusNoContent) + }) + + router.GET("/", func(c *gin.Context) { + c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage) + }) + + router.StaticFS("/assets", http.FS(assetsFS)) + + router.GET("/api/options", optionsHandler) + router.POST("/api/trace", traceHandler) + router.POST("/api/cache/clear", cacheClearHandler) + router.GET("/ws/trace", traceWebsocketHandler) + if enableMCP { + mcpHandler := gin.WrapH(newMCPHTTPHandler()) + router.GET("/mcp", mcpHandler) + router.POST("/mcp", mcpHandler) + router.DELETE("/mcp", mcpHandler) + } + + return router +} + func newHTTPServer(listenAddr string, handler http.Handler) *http.Server { return &http.Server{ Addr: listenAddr, Handler: handler, diff --git a/trace/mtr_scheduler_runtime.go b/trace/mtr_scheduler_runtime.go index d184111..cdcace8 100644 --- a/trace/mtr_scheduler_runtime.go +++ b/trace/mtr_scheduler_runtime.go @@ -50,6 +50,7 @@ type mtrSchedulerRuntime struct { progressDelay time.Duration maxConsecErrs int maxInFlightHop int + nextProbeTTL int states []mtrHopState generation uint64 knownFinalTTL atomic.Int32 @@ -167,6 +168,7 @@ func newMTRSchedulerRuntimeWithSession( progressDelay: progressDelay, maxConsecErrs: maxConsecErrs, maxInFlightHop: maxInFlightHop, + nextProbeTTL: beginHop, states: make([]mtrHopState, maxHops+1), resultCh: make(chan mtrCompletedProbe, parallelism*2), metadataCh: make(chan mtrMetadataResult, parallelism*2), @@ -816,12 +818,22 @@ func (rt *mtrSchedulerRuntime) scheduleReady() { now := time.Now() eMax := rt.effectiveMax() - for ttl := rt.beginHop; ttl <= eMax; ttl++ { + if rt.nextProbeTTL < rt.beginHop || rt.nextProbeTTL > eMax { + rt.nextProbeTTL = rt.beginHop + } + ttl := rt.nextProbeTTL + for scanned := 0; scanned <= eMax-rt.beginHop; scanned++ { if rt.inFlight >= rt.parallelism { return } if rt.canLaunchProbe(ttl, now) { rt.launchProbe(ttl) + // Resume after the last launch so saturated slots are shared across TTLs. + rt.nextProbeTTL = ttl + 1 + } + ttl++ + if ttl > eMax { + ttl = rt.beginHop } } } @@ -880,6 +892,7 @@ func (rt *mtrSchedulerRuntime) handleReset() { for idx := range rt.states { rt.states[idx] = mtrHopState{} } + rt.nextProbeTTL = rt.beginHop clear(rt.metadataGeoInFlight) clear(rt.metadataHostInFlight) clear(rt.metadataCache) diff --git a/trace/mtr_scheduler_test.go b/trace/mtr_scheduler_test.go index 34faac6..4c5eba5 100644 --- a/trace/mtr_scheduler_test.go +++ b/trace/mtr_scheduler_test.go @@ -3128,6 +3128,83 @@ func TestScheduler_FinalHopSntNotInflated_WithLowering(t *testing.T) { // Multi in-flight per hop: high-loss hops should accumulate Snt equally // --------------------------------------------------------------------------- +func TestScheduler_SaturatedCapacitySharesProbesAcrossReadyHops(t *testing.T) { + prober := &mockTTLProber{} + workers := newMTRWorkerSession(t.Context()) + defer workers.shutdown(func() { _ = prober.Close() }) + rt, err := newMTRSchedulerRuntimeWithSession(workers, prober, NewMTRAggregator(), mtrSchedulerConfig{ + BeginHop: 5, + MaxHops: 8, + HopInterval: time.Second, + MaxInFlightPerHop: 3, + ParallelRequests: 2, + }, nil, nil) + if err != nil { + t.Fatalf("newMTRSchedulerRuntimeWithSession returned error: %v", err) + } + + rt.scheduleReady() + for launched := rt.inFlight; launched < 12; launched++ { + select { + case completed := <-rt.resultCh: + rt.processResult(completed) + case <-time.After(time.Second): + t.Fatal("probe did not finish") + } + // All hops become due while the previous probes occupy the global slots. + for ttl := rt.beginHop; ttl <= rt.maxHops; ttl++ { + rt.states[ttl].nextAt = time.Time{} + } + rt.scheduleReady() + if got := rt.inFlight; got != rt.parallelism { + t.Fatalf("in-flight probes = %d, want %d", got, rt.parallelism) + } + } + + for ttl := rt.beginHop; ttl <= rt.maxHops; ttl++ { + state := rt.states[ttl] + if got := state.completed + state.inFlightCount; got != 3 { + t.Errorf("TTL %d: dispatched probes = %d, want 3 under saturated capacity", ttl, got) + } + } +} + +func TestScheduler_SchedulingContinuesAfterDestinationBoundsShrink(t *testing.T) { + prober := &mockTTLProber{} + workers := newMTRWorkerSession(t.Context()) + defer workers.shutdown(func() { _ = prober.Close() }) + rt, err := newMTRSchedulerRuntimeWithSession(workers, prober, NewMTRAggregator(), mtrSchedulerConfig{ + BeginHop: 5, + MaxHops: 8, + HopInterval: time.Second, + ParallelRequests: 2, + }, nil, nil) + if err != nil { + t.Fatalf("newMTRSchedulerRuntimeWithSession returned error: %v", err) + } + + rt.scheduleReady() + for range 2 { + select { + case completed := <-rt.resultCh: + rt.processResult(completed) + case <-time.After(time.Second): + t.Fatal("probe did not finish") + } + } + rt.observeProbeResponse(5, &MTRProbeResponse{Kind: MTRResponseDestination}) + rt.states[5].nextAt = time.Time{} + rt.scheduleReady() + if got := rt.states[5].inFlightCount; got != 1 { + t.Fatalf("destination in-flight probes = %d, want 1 after the active TTL range shrinks", got) + } + for ttl := 6; ttl <= rt.maxHops; ttl++ { + if got := rt.states[ttl].inFlightCount; got != 0 { + t.Errorf("disabled TTL %d: in-flight probes = %d, want 0", ttl, got) + } + } +} + func TestScheduler_MultiInFlightPerHop_HighLossEqualSnt(t *testing.T) { // This test reproduces the original bug: when each TTL allows only 1 // in-flight probe and nextAt is based on completion time, a TTL with