feat(proxy): add stable HTTP egress settings isolated from tools and models

This commit is contained in:
Sycun 2026-11-01 00:03:51 +08:00
parent cb15de1760
commit cc37959e14
26 changed files with 606 additions and 15 deletions

View File

@ -4,7 +4,7 @@
### Added ### Added
- `http-framework-test` 新增可选代理池:支持静态/结构化代理列表与供应商接口、粘性/轮询策略、供应商故障静态回退、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。 - 系统设置新增代理二级菜单,提供固定出口、代理池、最短切换间隔及凭证脱敏;配置仅注入后续 HTTP 工具进程,不影响 Kali 其他工具和模型 API。`http-framework-test` 新增可选代理池:支持静态/结构化代理列表与供应商接口、粘性/轮询策略、供应商故障静态回退、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。
- 支持通过 `agent.task_timeout_minutes` 配置单代理、多代理、工作流及异步任务执行超时:未配置默认 600 分钟,`0` 表示不限时,负数拒绝加载;续跑保留重新计时行为,单次工具超时仍独立生效。 - 支持通过 `agent.task_timeout_minutes` 配置单代理、多代理、工作流及异步任务执行超时:未配置默认 600 分钟,`0` 表示不限时,负数拒绝加载;续跑保留重新计时行为,单次工具超时仍独立生效。

View File

@ -608,3 +608,15 @@ project:
# 把目录变成跟踪该仓库的 git 工作树,此后按正常安装一键更新。 # 把目录变成跟踪该仓库的 git 工作树,此后按正常安装一键更新。
# update: # update:
# repo: https://github.com/AIPentest/CyberStrikeAI.git # 一个仓库地址;留空/不写 = 官方仓库 # repo: https://github.com/AIPentest/CyberStrikeAI.git # 一个仓库地址;留空/不写 = 官方仓库
# HTTP 测试工具的受管出口;不影响 Kali 其他工具、外部 MCP 或大模型 API。
# 固定 URL 是否固定公网 IP 取决于供应商。运行中的工具使用启动时快照。
proxy:
mode: manual # manual=沿用工具参数,fixed=固定代理,pool=显式启用代理池
proxy_url: "" # fixed 模式必填,支持 http(s)/socks5://host:port
proxy_pool: "" # pool 模式:每行一个代理 URL;与供应商至少配置一项
proxy_source: "" # 可选供应商 HTTP(S) 地址
strategy: sticky # sticky 或 round_robin
max_attempts: 3
cooldown: 60
min_switch_interval: 60 # 间隔内即使失败也不提前切换;0 表示不限制

View File

@ -2,11 +2,11 @@
[中文](../zh-CN/http-proxy-pool.md) | [Documentation home](README.md) [中文](../zh-CN/http-proxy-pool.md) | [Documentation home](README.md)
`http-framework-test` accepts a user-supplied proxy list and/or provider endpoint. It switches proxies within a bounded attempt budget on transport failures or configured HTTP status codes, and reuses a successful proxy. The feature is opt-in; the existing single `proxy` option and calls without a pool remain available. `http-framework-test` accepts a user-supplied proxy list and/or provider endpoint. It switches proxies within a bounded attempt budget on transport failures or configured HTTP status codes, and reuses a successful proxy. Settings → Proxy settings can manage egress for this HTTP tool; the default remains per-call arguments.
## Usage ## Usage
After updating the tool file, apply configuration in settings or restart the service to reload its parameters. Pool options are per-call arguments; no `config.yaml` change is required. After updating the tool file, apply configuration in settings or restart the service to reload its parameters. The proxy submenu also supports persistent settings that apply to subsequent invocations without restarting active processes.
Example MCP tool arguments: Example MCP tool arguments:
@ -65,7 +65,7 @@ Entries may also be objects such as `{"host":"127.0.0.1","port":8081,"scheme":"h
A 403 can be an application authorization failure; a 429 can apply to an account or other scope. Status matching is a configurable policy, not proof of an IP ban. CAPTCHA or HTTP 200 block pages remain unchanged. Replay and waiting rules are informed by [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) and [RFC 6585 §4](https://www.rfc-editor.org/rfc/rfc6585.html#section-4). A 403 can be an application authorization failure; a 429 can apply to an account or other scope. Status matching is a configurable policy, not proof of an IP ban. CAPTCHA or HTTP 200 block pages remain unchanged. Replay and waiting rules are informed by [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) and [RFC 6585 §4](https://www.rfc-editor.org/rfc/rfc6585.html#section-4).
Pool state lasts for one tool invocation. Other scanners, `exec`, Eino `execute`, external MCP servers and LLM API connections are outside this pool; no global settings page is added. Provider fetching uses a separate client with TLS verification and no target cookies, target Authorization, environment proxies or inherited `allow_insecure`. Use HTTPS for production provider endpoints. Pool state lasts for one tool invocation. Other scanners, `exec`, Eino `execute`, external MCP servers and LLM API connections are outside this pool; the settings submenu manages only this HTTP tool. Provider fetching uses a separate client with TLS verification and no target cookies, target Authorization, environment proxies or inherited `allow_insecure`. Use HTTPS for production provider endpoints.
## Troubleshooting and source ## Troubleshooting and source
@ -87,3 +87,13 @@ python3 -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
``` ```
Tests execute the code read from the tool YAML against local HTTP proxies, CONNECT tunnels and TLS servers. No external targets or real providers are contacted. The HTTPS fixture requires `openssl`. Tests execute the code read from the tool YAML against local HTTP proxies, CONNECT tunnels and TLS servers. No external targets or real providers are contacted. The HTTPS fixture requires `openssl`.
## Managed settings and stable egress
Settings → Proxy settings offers manual arguments, a fixed proxy, or a pool. Fixed mode keeps the configured endpoint across calls and does not fail over. Pool mode offers sticky or round-robin selection with a minimum switch interval (60 seconds in the settings form). The interval also prevents early failover: return the failure response/error instead. Timing is invocation-local; use fixed mode and a provider with fixed egress for stability across calls. A fixed URL alone cannot guarantee the provider's public IP.
`PUT /api/config` persists the `proxy` object and applies it to future HTTP tool invocations. GET masks `proxy_url`, `proxy_pool`, and `proxy_source`; preserve `********` to keep a saved value or send an empty string to clear it. The settings list accepts one URL per line; provider responses may still use structured entries. See `config.example.yaml`. Managed values override model-supplied proxy arguments through a process-local environment snapshot, never global HTTP_PROXY or command arguments. This is not a network sandbox for arbitrary shell commands.
Design references: [Zyte sessions](https://docs.zyte.com/zyte-api/usage/features.html#sessions) motivate stable IP/cookie conditions; [HTTPX clients](https://www.python-httpx.org/advanced/clients/) motivate connection reuse; [Nuclei](https://docs.projectdiscovery.io/opensource/nuclei/running) exposes distinct proxy/rate controls; [Nmap](https://nmap.org/book/man-bypass-firewalls-ids.html) documents limits on which scan phases support proxies. Other Kali tools retain native routing, proxy and rate settings. No output-based ban guessing or process restarts are introduced.
LLM API transports, streams and retry/backoff remain separate from the scan pool. Account/token rate limits are handled by existing provider retry policies. Stable public-IP requirements depend on the provider; this feature never rotates model API egress.

View File

@ -2,11 +2,11 @@
[English](../en-US/http-proxy-pool.md) | [文档首页](README.md) [English](../en-US/http-proxy-pool.md) | [文档首页](README.md)
`http-framework-test` 支持用户提供的代理列表及代理供应商接口。连接失败或响应命中指定状态码时,在次数上限内切换代理;成功代理继续复用连接。默认关闭,原有 `proxy` 参数及无代理调用方式继续可用。 `http-framework-test` 支持用户提供的代理列表及代理供应商接口。连接失败或响应命中指定状态码时,在次数上限内切换代理;成功代理继续复用连接。默认沿用工具参数。也可在「系统设置 → 代理设置」统一管理此 HTTP 工具的出口。
## 使用 ## 使用
更新工具文件后,在系统设置中应用配置或重启服务以重新加载工具参数。代理池通过每次工具调用的参数启用,不需要修改 `config.yaml`。 更新工具文件后,在系统设置中应用配置或重启服务以重新加载工具参数。也可以在代理二级菜单保存配置,后续调用立即生效;运行中进程保留启动时快照。
调用 `http-framework-test` 时传入以下参数(MCP 工具参数示例): 调用 `http-framework-test` 时传入以下参数(MCP 工具参数示例):
@ -75,7 +75,7 @@ HTTP CONNECT 隧道中的 HTTPS 响应需要由发起请求的客户端解密才
403 也可能是业务权限错误,429 也可能按账号或其他维度限流;默认状态码只是可配置的失败策略,不宣称已确认 IP 被封。不匹配状态码的验证码页、HTTP 200 拦截页目前保持原样。重放和等待规则参考 [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) 和 [RFC 6585 §4](https://www.rfc-editor.org/rfc/rfc6585.html#section-4)。 403 也可能是业务权限错误,429 也可能按账号或其他维度限流;默认状态码只是可配置的失败策略,不宣称已确认 IP 被封。不匹配状态码的验证码页、HTTP 200 拦截页目前保持原样。重放和等待规则参考 [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) 和 [RFC 6585 §4](https://www.rfc-editor.org/rfc/rfc6585.html#section-4)。
池状态只在单次工具调用内保留,不跨会话共享。其他扫描工具、`exec`、Eino `execute`、外部 MCP、LLM API 连接暂不接入本池;未新增全局代理设置页。供应商拉取使用独立客户端,开启 TLS 校验,不继承目标请求的 Cookie、Authorization、环境代理或 `allow_insecure`;生产供应商接口建议使用 HTTPS。 池状态只在单次工具调用内保留,不跨会话共享。其他扫描工具、`exec`、Eino `execute`、外部 MCP、LLM API 连接暂不接入本池;系统设置中的代理页面只管理上述 HTTP 工具。供应商拉取使用独立客户端,开启 TLS 校验,不继承目标请求的 Cookie、Authorization、环境代理或 `allow_insecure`;生产供应商接口建议使用 HTTPS。
## 排错与源码 ## 排错与源码
@ -97,3 +97,20 @@ python3 -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
``` ```
测试从 YAML 读取实际执行代码,使用本地 HTTP 代理、CONNECT 隧道及 TLS 服务验证切换、路径保真、重放限制、等待期、供应商刷新与凭证隔离;不访问外部目标或真实供应商。HTTPS 测试需要 `openssl`。 测试从 YAML 读取实际执行代码,使用本地 HTTP 代理、CONNECT 隧道及 TLS 服务验证切换、路径保真、重放限制、等待期、供应商刷新与凭证隔离;不访问外部目标或真实供应商。HTTPS 测试需要 `openssl`。
## 系统设置与稳定出口
系统设置 → 代理设置提供三种模式:沿用工具参数、固定代理、代理池。固定模式在不同调用之间持续使用配置的同一代理地址,不做失败切换;需要稳定 IP 的登录态优先选它。池模式可选择复用或轮询,界面默认最短切换间隔 60 秒。间隔同时限制故障切换,尚未到期时保留响应或报错,不提前更换出口。计时只在单次调用内有效;跨调用仍需稳定出口时使用固定模式及供应商的固定 IP 服务。
保存通过既有 `PUT /api/config` 的 `proxy` 段持久化并热应用,只影响以后启动的 `http-framework-test`。`proxy_url`、`proxy_pool`、`proxy_source` 在 GET 响应中整体脱敏;`********` 原样提交会保留已有值,空字符串表示清除。设置页列表每行一个 URL;结构化供应商格式仍可由供应商接口提供。配置示例见 `config.example.yaml` 的 `proxy` 段。受管设置通过该工具专用的进程环境快照传递,不加入命令参数或自动注入模型上下文;它不限制任意 Shell 命令的网络行为。
### 参考项目与采用的做法
| 参考 | 做法与本项目选择 |
| --- | --- |
| [Zyte Sessions](https://docs.zyte.com/zyte-api/usage/features.html#sessions) | IP、Cookie 和连接环境共同影响会话。提供固定出口模式,登录态不默认轮询。 |
| [HTTPX Clients](https://www.python-httpx.org/advanced/clients/) | 复用连接和 Cookie。运行中的调用保持快照,设置变更不拆除已有连接。 |
| [Nuclei](https://docs.projectdiscovery.io/opensource/nuclei/running) | 原生代理选项和请求速率分别配置。其他 Kali 工具使用自身代理与限速能力,不从文本输出猜测封禁并重新启动进程。 |
| [Nmap 代理限制](https://nmap.org/book/man-bypass-firewalls-ids.html) | 代理支持有协议和扫描阶段限制,不能承诺统一 HTTP 环境变量覆盖所有原始报文扫描。未适配工具保持原路由。 |
大模型 API 的流式响应、连接池和提供商重试继续使用既有客户端,不接入扫描代理池;模型侧的账号/Token 限流应走现有退避策略。不同供应商是否要求固定公网 IP 需按其接口约定判断,本功能不会自动改动模型出口或轮询 API 连接。

View File

@ -162,6 +162,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath string) (*App, error
// 创建安全工具执行器 // 创建安全工具执行器
executor := security.NewExecutor(&cfg.Security, mcpServer, log.Logger) executor := security.NewExecutor(&cfg.Security, mcpServer, log.Logger)
executor.SetProxyConfig(cfg.Proxy)
executor.SetShellNoOutputTimeoutSeconds(cfg.Agent.ShellNoOutputTimeoutSeconds) executor.SetShellNoOutputTimeoutSeconds(cfg.Agent.ShellNoOutputTimeoutSeconds)
executor.SetToolOutputMaxBytes(cfg.MultiAgent.EinoMiddleware.ReductionMaxLengthForTruncEffective()) executor.SetToolOutputMaxBytes(cfg.MultiAgent.EinoMiddleware.ReductionMaxLengthForTruncEffective())
executor.SetToolOutputSpillRoot(cfg.MultiAgent.EinoMiddleware.ReductionRootDir) executor.SetToolOutputSpillRoot(cfg.MultiAgent.EinoMiddleware.ReductionRootDir)

View File

@ -21,6 +21,7 @@ import (
) )
type Config struct { type Config struct {
Proxy ProxyConfig `yaml:"proxy,omitempty" json:"proxy"`
Version string `yaml:"version,omitempty" json:"version,omitempty"` // 前端显示的版本号,如 v1.3.3 Version string `yaml:"version,omitempty" json:"version,omitempty"` // 前端显示的版本号,如 v1.3.3
Server ServerConfig `yaml:"server"` Server ServerConfig `yaml:"server"`
Log LogConfig `yaml:"log"` Log LogConfig `yaml:"log"`
@ -1653,6 +1654,9 @@ func Load(path string) (*Config, error) {
if err := yaml.Unmarshal(data, &cfg); err != nil { if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("解析配置文件失败: %w", err) return nil, fmt.Errorf("解析配置文件失败: %w", err)
} }
if err := cfg.Proxy.Validate(); err != nil {
return nil, err
}
if err := cfg.Agent.validateTaskTimeout(); err != nil { if err := cfg.Agent.validateTaskTimeout(); err != nil {
return nil, err return nil, err
} }

73
internal/config/proxy.go Normal file
View File

@ -0,0 +1,73 @@
package config
import (
"fmt"
"net/url"
"strconv"
"strings"
)
// ProxyConfig governs only the built-in HTTP test tool, never process-wide routing.
type ProxyConfig struct {
Mode string `yaml:"mode" json:"mode"`
URL string `yaml:"proxy_url" json:"proxy_url"`
Pool string `yaml:"proxy_pool" json:"proxy_pool"`
Source string `yaml:"proxy_source" json:"proxy_source"`
Strategy string `yaml:"strategy" json:"strategy"`
MaxAttempts int `yaml:"max_attempts" json:"max_attempts"`
Cooldown int `yaml:"cooldown" json:"cooldown"`
MinSwitchInterval int `yaml:"min_switch_interval" json:"min_switch_interval"`
}
func (p ProxyConfig) Validate() error {
if p.Mode != "" && p.Mode != "manual" && p.Mode != "fixed" && p.Mode != "pool" {
return fmt.Errorf("proxy.mode must be manual, fixed or pool")
}
if p.Strategy != "" && p.Strategy != "sticky" && p.Strategy != "round_robin" {
return fmt.Errorf("proxy.strategy must be sticky or round_robin")
}
if p.MaxAttempts < 0 || p.MaxAttempts > 10 || p.Cooldown < 0 || p.Cooldown > 86400 || p.MinSwitchInterval < 0 || p.MinSwitchInterval > 86400 {
return fmt.Errorf("invalid proxy attempt or timing limits")
}
if p.Mode == "fixed" {
return validateProxyEndpoint(p.URL)
}
if p.Mode != "pool" {
return nil
}
count := 0
for _, line := range strings.Split(p.Pool, "\n") {
if strings.TrimSpace(line) != "" {
count++
if err := validateProxyEndpoint(line); err != nil {
return err
}
}
}
if count > 256 {
return fmt.Errorf("proxy pool exceeds 256 endpoints")
}
if p.Source != "" {
u, err := url.Parse(p.Source)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.Fragment != "" {
return fmt.Errorf("proxy source must be an HTTP(S) URL")
}
}
if count == 0 && p.Source == "" {
return fmt.Errorf("proxy pool requires endpoints or a provider URL")
}
return nil
}
func validateProxyEndpoint(value string) error {
value = strings.TrimSpace(value)
if !strings.Contains(value, "://") {
value = "http://" + value
}
u, err := url.Parse(value)
if err == nil && u.Hostname() != "" && (u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "socks5") && (u.Path == "" || u.Path == "/") && u.RawQuery == "" && u.Fragment == "" && !strings.ContainsAny(value, "\r\n\t ") {
if port, err := strconv.Atoi(u.Port()); err == nil && port > 0 && port <= 65535 {
return nil
}
}
return fmt.Errorf("proxy endpoint must be http(s)://host:port or socks5://host:port")
}

View File

@ -0,0 +1,16 @@
package config
import "testing"
func TestProxyValidation(t *testing.T) {
for _, p := range []ProxyConfig{{}, {Mode: "manual"}, {Mode: "fixed", URL: "http://u:p@localhost:8080"}, {Mode: "pool", Pool: "[::1]:8080\nlocalhost:8081", MinSwitchInterval: 60}} {
if err := p.Validate(); err != nil {
t.Fatal(err)
}
}
for _, p := range []ProxyConfig{{Mode: "bad"}, {Mode: "fixed"}, {Mode: "fixed", URL: "file:///secret"}, {Mode: "pool"}, {Mode: "pool", Pool: "http://host:80/path"}, {Mode: "pool", Source: "file:///secret"}, {MinSwitchInterval: -1}, {MaxAttempts: 11}} {
if p.Validate() == nil {
t.Fatalf("accepted invalid config: mode=%s", p.Mode)
}
}
}

View File

@ -264,6 +264,7 @@ func (h *ConfigHandler) ApplyWechatRobotBinding(wc config.RobotWechatConfig) err
// GetConfigResponse 获取配置响应 // GetConfigResponse 获取配置响应
type GetConfigResponse struct { type GetConfigResponse struct {
Proxy config.ProxyConfig `json:"proxy"`
AI config.AIConfig `json:"ai"` AI config.AIConfig `json:"ai"`
OpenAI config.OpenAIConfig `json:"openai"` OpenAI config.OpenAIConfig `json:"openai"`
Vision config.VisionConfig `json:"vision"` Vision config.VisionConfig `json:"vision"`
@ -374,6 +375,7 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
} }
response, err := maskedConfigResponse(GetConfigResponse{ response, err := maskedConfigResponse(GetConfigResponse{
Proxy: h.config.Proxy,
AI: h.config.AI, AI: h.config.AI,
OpenAI: h.config.OpenAI, OpenAI: h.config.OpenAI,
Vision: h.config.Vision, Vision: h.config.Vision,
@ -723,6 +725,7 @@ func (h *ConfigHandler) GetTools(c *gin.Context) {
// UpdateConfigRequest 更新配置请求 // UpdateConfigRequest 更新配置请求
type UpdateConfigRequest struct { type UpdateConfigRequest struct {
Proxy *config.ProxyConfig `json:"proxy,omitempty"`
AI *config.AIConfig `json:"ai,omitempty"` AI *config.AIConfig `json:"ai,omitempty"`
OpenAI *config.OpenAIConfig `json:"openai,omitempty"` OpenAI *config.OpenAIConfig `json:"openai,omitempty"`
Vision *config.VisionConfig `json:"vision,omitempty"` Vision *config.VisionConfig `json:"vision,omitempty"`
@ -807,6 +810,21 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
return return
} }
previousProxy := h.config.Proxy
proxySaved := false
defer func() {
if !proxySaved {
h.config.Proxy = previousProxy
}
}()
if req.Proxy != nil {
if err := req.Proxy.Validate(); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
h.config.Proxy = *req.Proxy
}
// 更新OpenAI配置 // 更新OpenAI配置
if req.AI != nil { if req.AI != nil {
h.config.AI = *req.AI h.config.AI = *req.AI
@ -1254,6 +1272,10 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
return return
} }
proxySaved = true
if req.Proxy != nil && h.executor != nil {
h.executor.SetProxyConfig(h.config.Proxy)
}
if h.audit != nil { if h.audit != nil {
h.audit.RecordOK(c, "config", "update", "更新内存配置", "config", "", nil) h.audit.RecordOK(c, "config", "update", "更新内存配置", "config", "", nil)
} }
@ -1763,6 +1785,7 @@ func (h *ConfigHandler) ApplyConfig(c *gin.Context) {
h.mcpServer.ClearTools() h.mcpServer.ClearTools()
// 重新注册安全工具 // 重新注册安全工具
h.executor.SetProxyConfig(h.config.Proxy)
h.executor.SetToolOutputMaxBytes(h.config.MultiAgent.EinoMiddleware.ReductionMaxLengthForTruncEffective()) h.executor.SetToolOutputMaxBytes(h.config.MultiAgent.EinoMiddleware.ReductionMaxLengthForTruncEffective())
h.executor.SetToolOutputSpillRoot(h.config.MultiAgent.EinoMiddleware.ReductionRootDir) h.executor.SetToolOutputSpillRoot(h.config.MultiAgent.EinoMiddleware.ReductionRootDir)
h.executor.RegisterTools(h.mcpServer) h.executor.RegisterTools(h.mcpServer)
@ -1955,6 +1978,7 @@ func (h *ConfigHandler) saveConfig() error {
return fmt.Errorf("解析配置文件失败: %w", err) return fmt.Errorf("解析配置文件失败: %w", err)
} }
updateProxyConfig(root, h.config.Proxy)
updateAgentConfig(root, h.config.Agent) updateAgentConfig(root, h.config.Agent)
updateMCPConfig(root, h.config.MCP) updateMCPConfig(root, h.config.MCP)
updateAIConfig(root, h.config.AI) updateAIConfig(root, h.config.AI)
@ -2940,3 +2964,15 @@ func convertParamType(t string) string {
return "string" return "string"
} }
} }
func updateProxyConfig(doc *yaml.Node, cfg config.ProxyConfig) {
node := ensureMap(doc.Content[0], "proxy")
setStringInMap(node, "mode", cfg.Mode)
setStringInMap(node, "proxy_url", cfg.URL)
setStringInMap(node, "proxy_pool", cfg.Pool)
setStringInMap(node, "proxy_source", cfg.Source)
setStringInMap(node, "strategy", cfg.Strategy)
setIntInMap(node, "max_attempts", cfg.MaxAttempts)
setIntInMap(node, "cooldown", cfg.Cooldown)
setIntInMap(node, "min_switch_interval", cfg.MinSwitchInterval)
}

View File

@ -13,14 +13,14 @@ const maskedSecret = "********"
func secretConfigKey(key string) bool { func secretConfigKey(key string) bool {
switch strings.ToLower(key) { switch strings.ToLower(key) {
case "api_key", "apikey", "password", "secret", "client_secret", "app_secret", "token", "bot_token", "app_token", "verify_token", "encoding_aes_key", "authorization", "x-api-key": case "proxy_url", "proxy_pool", "proxy_source", "api_key", "apikey", "password", "secret", "client_secret", "app_secret", "token", "bot_token", "app_token", "verify_token", "encoding_aes_key", "authorization", "x-api-key":
return true return true
} }
return false return false
} }
func configSecretSnapshot(cfg *config.Config) GetConfigResponse { func configSecretSnapshot(cfg *config.Config) GetConfigResponse {
return GetConfigResponse{AI: cfg.AI, OpenAI: cfg.OpenAI, Vision: cfg.Vision, FOFA: cfg.FOFA, return GetConfigResponse{Proxy: cfg.Proxy, AI: cfg.AI, OpenAI: cfg.OpenAI, Vision: cfg.Vision, FOFA: cfg.FOFA,
ZoomEye: cfg.ZoomEye, Quake: cfg.Quake, Shodan: cfg.Shodan, MCP: cfg.MCP, ZoomEye: cfg.ZoomEye, Quake: cfg.Quake, Shodan: cfg.Shodan, MCP: cfg.MCP,
Hitl: cfg.Hitl, Knowledge: cfg.Knowledge, Robots: cfg.Robots} Hitl: cfg.Hitl, Knowledge: cfg.Knowledge, Robots: cfg.Robots}
} }

View File

@ -846,6 +846,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
"type": "object", "type": "object",
"description": "配置信息(含 openai、vision、multi_agent 等)", "description": "配置信息(含 openai、vision、multi_agent 等)",
"properties": map[string]interface{}{ "properties": map[string]interface{}{
"proxy": map[string]interface{}{"type": "object", "description": "HTTP-tool-only egress policy: mode manual/fixed/pool, masked proxy_url/proxy_pool/proxy_source, strategy sticky/round_robin, max_attempts 1-10 (0=3), cooldown and min_switch_interval 0-86400 seconds. PUT persists and applies to subsequent HTTP invocations; model/other tool egress is unchanged."},
"agent": map[string]interface{}{ "agent": map[string]interface{}{
"$ref": "#/components/schemas/AgentConfig", "$ref": "#/components/schemas/AgentConfig",
}, },
@ -858,6 +859,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
"type": "object", "type": "object",
"description": "更新配置请求", "description": "更新配置请求",
"properties": map[string]interface{}{ "properties": map[string]interface{}{
"proxy": map[string]interface{}{"type": "object", "description": "HTTP-tool-only egress policy: mode manual/fixed/pool, masked proxy_url/proxy_pool/proxy_source, strategy sticky/round_robin, max_attempts 1-10 (0=3), cooldown and min_switch_interval 0-86400 seconds. PUT persists and applies to subsequent HTTP invocations; model/other tool egress is unchanged."},
"agent": map[string]interface{}{ "agent": map[string]interface{}{
"$ref": "#/components/schemas/AgentConfig", "$ref": "#/components/schemas/AgentConfig",
}, },

View File

@ -0,0 +1,92 @@
package handler
import (
"bytes"
"context"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/security"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestProxySettingsPersistMaskAndRollback(t *testing.T) {
path := filepath.Join(t.TempDir(), "settings.yaml")
if err := os.WriteFile(path, []byte("version: test\n"), 0600); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
executor := security.NewExecutor(&config.SecurityConfig{Tools: []config.ToolConfig{{Name: "http-framework-test", Enabled: true, Command: executable, Args: []string{"-test.run=^TestProxySettingsChild$"}}}}, nil, zap.NewNop())
h := &ConfigHandler{config: cfg, configPath: path, logger: zap.NewNop(), executor: executor}
r := gin.New()
r.PUT("/config", h.UpdateConfig)
r.GET("/config", h.GetConfig)
put := func(p config.ProxyConfig) *httptest.ResponseRecorder {
data, _ := json.Marshal(map[string]interface{}{"proxy": p})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/config", bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w
}
policy := config.ProxyConfig{Mode: "fixed", URL: "http://user:test-secret@localhost:8080", MinSwitchInterval: 60}
if w := put(policy); w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
result, err := executor.ExecuteTool(context.Background(), "http-framework-test", map[string]interface{}{})
if err != nil || result.IsError || !strings.Contains(result.Content[0].Text, "test-secret") {
t.Fatal("saved proxy not applied to executor", err)
}
raw, _ := os.ReadFile(path)
var disk config.Config
if err := yaml.Unmarshal(raw, &disk); err != nil || disk.Proxy.URL != policy.URL {
t.Fatal("proxy not persisted", err)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/config", nil))
if strings.Contains(w.Body.String(), "test-secret") {
t.Fatal("secret exposed")
}
var response struct {
Proxy config.ProxyConfig `json:"proxy"`
}
json.Unmarshal(w.Body.Bytes(), &response)
if response.Proxy.URL != maskedSecret {
t.Fatal("not masked")
}
if w := put(response.Proxy); w.Code != 200 || cfg.Proxy.URL != policy.URL {
t.Fatal("masked save lost secret")
}
invalid := policy
invalid.Mode = "pool"
invalid.Pool = "bad"
invalid.URL = ""
if w := put(invalid); w.Code != 400 || cfg.Proxy != policy {
t.Fatal("invalid save mutated state")
}
h.configPath = filepath.Join(t.TempDir(), "missing", "settings.yaml")
changed := policy
changed.URL = "http://localhost:9090"
if w := put(changed); w.Code != 500 || cfg.Proxy != policy {
t.Fatal("failed save changed proxy config")
}
}
func TestProxySettingsChild(t *testing.T) {
if raw := os.Getenv("CSAI_HTTP_PROXY_CONFIG"); raw != "" {
fmt.Print(raw)
os.Exit(0)
}
}

View File

@ -32,6 +32,8 @@ var ToolOutputCallbackCtxKey = toolOutputCallbackCtxKey{}
// Executor 安全工具执行器 // Executor 安全工具执行器
type Executor struct { type Executor struct {
proxyMu sync.RWMutex
proxyConfig config.ProxyConfig
config *config.SecurityConfig config *config.SecurityConfig
toolIndex map[string]*config.ToolConfig // 工具索引,用于 O(1) 查找 toolIndex map[string]*config.ToolConfig // 工具索引,用于 O(1) 查找
mcpServer *mcp.Server mcpServer *mcp.Server
@ -183,9 +185,11 @@ func (e *Executor) ExecuteTool(ctx context.Context, toolName string, args map[st
}, nil }, nil
} }
proxySnapshot := e.proxySnapshot(toolName)
// 执行命令 // 执行命令
cmd := exec.CommandContext(ctx, toolConfig.Command, cmdArgs...) cmd := exec.CommandContext(ctx, toolConfig.Command, cmdArgs...)
applyDefaultTerminalEnv(cmd) applyDefaultTerminalEnv(cmd)
applyHTTPProxySnapshot(cmd, proxySnapshot)
attachNonInteractiveStdin(cmd) attachNonInteractiveStdin(cmd)
_ = prepareShellCmdSession(cmd) _ = prepareShellCmdSession(cmd)
@ -207,6 +211,7 @@ func (e *Executor) ExecuteTool(ctx context.Context, toolName string, args map[st
) )
cmd2 := exec.CommandContext(ctx, toolConfig.Command, cmdArgs...) cmd2 := exec.CommandContext(ctx, toolConfig.Command, cmdArgs...)
applyDefaultTerminalEnv(cmd2) applyDefaultTerminalEnv(cmd2)
applyHTTPProxySnapshot(cmd2, proxySnapshot)
_ = prepareShellCmdSession(cmd2) _ = prepareShellCmdSession(cmd2)
output, err = runCommandWithPTY(ctx, cmd2, cb, e.toolOutputMaxBytes, spill) output, err = runCommandWithPTY(ctx, cmd2, cb, e.toolOutputMaxBytes, spill)
} }
@ -219,6 +224,7 @@ func (e *Executor) ExecuteTool(ctx context.Context, toolName string, args map[st
) )
cmd2 := exec.CommandContext(ctx, toolConfig.Command, cmdArgs...) cmd2 := exec.CommandContext(ctx, toolConfig.Command, cmdArgs...)
applyDefaultTerminalEnv(cmd2) applyDefaultTerminalEnv(cmd2)
applyHTTPProxySnapshot(cmd2, proxySnapshot)
_ = prepareShellCmdSession(cmd2) _ = prepareShellCmdSession(cmd2)
output, err = runCommandWithPTY(ctx, cmd2, nil, e.toolOutputMaxBytes, spill) output, err = runCommandWithPTY(ctx, cmd2, nil, e.toolOutputMaxBytes, spill)
} }

View File

@ -0,0 +1,47 @@
package security
import (
"encoding/json"
"os/exec"
"strings"
"cyberstrike-ai/internal/config"
)
func (e *Executor) SetProxyConfig(cfg config.ProxyConfig) {
e.proxyMu.Lock()
defer e.proxyMu.Unlock()
e.proxyConfig = cfg
}
func (e *Executor) proxySnapshot(tool string) string {
if tool != "http-framework-test" {
return ""
}
e.proxyMu.RLock()
defer e.proxyMu.RUnlock()
if e.proxyConfig.Mode == "" || e.proxyConfig.Mode == "manual" {
return ""
}
policy := e.proxyConfig
if policy.Mode == "fixed" {
policy.Pool, policy.Source = "", ""
} else {
policy.URL = ""
}
raw, _ := json.Marshal(policy)
return string(raw)
}
func applyHTTPProxySnapshot(cmd *exec.Cmd, snapshot string) {
// Never mutate os.Environ or HTTP_PROXY: models and other tools are isolated.
env := cmd.Environ()
filtered := make([]string, 0, len(env)+1)
for _, entry := range env {
if !strings.HasPrefix(entry, "CSAI_HTTP_PROXY_CONFIG=") {
filtered = append(filtered, entry)
}
}
if snapshot != "" {
filtered = append(filtered, "CSAI_HTTP_PROXY_CONFIG="+snapshot)
}
cmd.Env = filtered
}

View File

@ -0,0 +1,34 @@
package security
import (
"cyberstrike-ai/internal/config"
"go.uber.org/zap"
"os"
"os/exec"
"strings"
"testing"
)
func TestProxySnapshotIsolation(t *testing.T) {
t.Setenv("HTTP_PROXY", "http://existing:8080")
e := NewExecutor(&config.SecurityConfig{}, nil, zap.NewNop())
e.SetProxyConfig(config.ProxyConfig{Mode: "fixed", URL: "http://private:secret@localhost:8081"})
snapshot := e.proxySnapshot("http-framework-test")
if snapshot == "" || e.proxySnapshot("nmap") != "" || e.proxySnapshot("exec") != "" {
t.Fatal("wrong routing scope")
}
e.SetProxyConfig(config.ProxyConfig{Mode: "fixed", URL: "http://new:8082"})
cmd := exec.Command("unused")
applyHTTPProxySnapshot(cmd, snapshot)
if !strings.Contains(strings.Join(cmd.Env, "\n"), "private:secret") || strings.Contains(strings.Join(cmd.Args, " "), "secret") {
t.Fatal("snapshot lost or leaked to argv")
}
if os.Getenv("HTTP_PROXY") != "http://existing:8080" {
t.Fatal("global proxy changed")
}
other := exec.Command("unused")
applyHTTPProxySnapshot(other, e.proxySnapshot("nmap"))
if strings.Contains(strings.Join(other.Env, "\n"), "CSAI_HTTP_PROXY_CONFIG=") {
t.Fatal("policy leaked to other tool")
}
}

View File

@ -107,13 +107,17 @@ func TestNonInteractiveStdinReadBlocksWithoutRedirect(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
defer r.Close() defer r.Close()
defer w.Close()
// 保持 w 打开且不写数据,模拟「等待用户输入」 // 保持 w 打开且不写数据,模拟「等待用户输入」
cmd := exec.Command("sh", "-c", `read x; echo done`) cmd := exec.Command("sh", "-c", `read x; echo done`)
cmd.Stdin = r cmd.Stdin = r
done := make(chan error, 1) done := make(chan error, 1)
go func() { done <- cmd.Run() }() if err := cmd.Start(); err != nil {
t.Fatal(err)
}
go func() { done <- cmd.Wait() }()
select { select {
case err := <-done: case err := <-done:

View File

@ -474,6 +474,32 @@ class ProxyPoolTests(unittest.TestCase):
self.assertEqual(second.requests, [("target.invalid", 80)]) self.assertEqual(second.requests, [("target.invalid", 80)])
self.assertEqual(good.requests[0][1], "/a/../b?x=%2F") self.assertEqual(good.requests[0][1], "/a/../b?x=%2F")
def test_min_switch_interval_prevents_early_failover(self):
with server(403) as first, server() as second:
pool = Pool(json.dumps([first.url, second.url]), min_switch_interval=60, cooldown=0)
with httpx.Client(transport=pool, trust_env=False) as client:
with mock.patch.object(NS["time"], "monotonic", return_value=100):
response, *_ = send(client)
with contextlib.closing(response):
response.read()
self.assertEqual(response.status_code, 403)
self.assertEqual(len(second.requests), 0)
with mock.patch.object(NS["time"], "monotonic", return_value=161):
response, *_ = send(client)
with contextlib.closing(response):
self.assertEqual(response.read(), b"ok")
def test_managed_fixed_policy_overrides_model_pool(self):
with server(body=b"managed") as fixed, server(body=b"model-choice") as other:
policy = {"mode": "fixed", "proxy_url": fixed.url}
result = subprocess.run([sys.executable, "-c", SCRIPT, "--url", "http://target.invalid/",
"--proxy-pool", other.url, "--proxy-strategy", "round_robin"],
text=True, capture_output=True, timeout=15,
env={**os.environ, "CSAI_HTTP_PROXY_CONFIG": json.dumps(policy)})
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("managed", result.stdout)
self.assertEqual(len(other.requests), 0)
def run_cli(self, *args): def run_cli(self, *args):
return subprocess.run([sys.executable, "-c", SCRIPT, *args], text=True, capture_output=True, return subprocess.run([sys.executable, "-c", SCRIPT, *args], text=True, capture_output=True,
timeout=15, env={**os.environ, "HTTP_PROXY": "http://127.0.0.1:1"}) timeout=15, env={**os.environ, "HTTP_PROXY": "http://127.0.0.1:1"})

View File

@ -404,7 +404,11 @@ args:
RETRY_METHODS = {"GET", "HEAD", "OPTIONS"} RETRY_METHODS = {"GET", "HEAD", "OPTIONS"}
def __init__(self, proxies, source="", max_attempts=3, cooldown=60.0, def __init__(self, proxies, source="", max_attempts=3, cooldown=60.0,
fail_status="403,429", transport_kwargs=None, strategy="sticky"): fail_status="403,429", transport_kwargs=None, strategy="sticky", min_switch_interval=0):
if not math.isfinite(min_switch_interval) or not 0 <= min_switch_interval <= 86400:
raise ValueError("proxy_min_switch_interval must be between 0 and 86400")
self.min_switch_interval = min_switch_interval
self.last_switch = None
if strategy not in {"sticky", "round_robin"}: if strategy not in {"sticky", "round_robin"}:
raise ValueError("proxy_strategy must be sticky or round_robin") raise ValueError("proxy_strategy must be sticky or round_robin")
self.strategy = strategy self.strategy = strategy
@ -452,13 +456,17 @@ args:
def select(self, attempted, advance=True): def select(self, attempted, advance=True):
now = time.monotonic() now = time.monotonic()
if self.strategy == "round_robin": if self.current and self.last_switch is not None and now - self.last_switch < self.min_switch_interval:
candidates = [self.current]
elif self.strategy == "round_robin":
candidates = self.proxies[self.cursor:] + self.proxies[:self.cursor] candidates = self.proxies[self.cursor:] + self.proxies[:self.cursor]
else: else:
candidates = ([self.current] if self.current else []) + self.proxies candidates = ([self.current] if self.current else []) + self.proxies
for proxy in candidates: for proxy in candidates:
if proxy not in attempted and self.cooling.get(proxy, 0) <= now: if proxy not in attempted and self.cooling.get(proxy, 0) <= now:
if advance: if advance:
if self.current != proxy:
self.last_switch = now
self.current = proxy self.current = proxy
self.cursor = (self.proxies.index(proxy) + 1) % len(self.proxies) self.cursor = (self.proxies.index(proxy) + 1) % len(self.proxies)
return proxy return proxy
@ -1227,6 +1235,7 @@ args:
parser.add_argument("--proxy-pool", default="") parser.add_argument("--proxy-pool", default="")
parser.add_argument("--proxy-source", default="") parser.add_argument("--proxy-source", default="")
parser.add_argument("--proxy-strategy", choices=["sticky", "round_robin"], default="sticky") parser.add_argument("--proxy-strategy", choices=["sticky", "round_robin"], default="sticky")
parser.add_argument("--proxy-min-switch-interval", type=float, default=0)
parser.add_argument("--proxy-max-attempts", type=int, default=3) parser.add_argument("--proxy-max-attempts", type=int, default=3)
parser.add_argument("--proxy-cooldown", type=float, default=60.0) parser.add_argument("--proxy-cooldown", type=float, default=60.0)
parser.add_argument("--proxy-fail-status", default="403,429") parser.add_argument("--proxy-fail-status", default="403,429")
@ -1274,6 +1283,27 @@ args:
) )
# parse_known_args: tolerate legacy executor that appended bare "http2=true" tokens # parse_known_args: tolerate legacy executor that appended bare "http2=true" tokens
args, unknown_args = parser.parse_known_args() args, unknown_args = parser.parse_known_args()
managed = os.environ.get("CSAI_HTTP_PROXY_CONFIG", "")
if managed:
try:
policy = json.loads(managed)
args.proxy = ""
args.proxy_pool = ""
args.proxy_source = ""
if policy["mode"] == "fixed":
args.proxy = parse_proxy_list(policy["proxy_url"])[0]
elif policy["mode"] == "pool":
args.proxy_pool = policy["proxy_pool"]
args.proxy_source = policy["proxy_source"]
args.proxy_strategy = policy.get("strategy") or "sticky"
args.proxy_max_attempts = policy.get("max_attempts") or 3
args.proxy_cooldown = policy.get("cooldown", 60)
args.proxy_min_switch_interval = policy.get("min_switch_interval", 60)
args.proxy_fail_status = "403,429"
else:
raise ValueError()
except (ValueError, KeyError, TypeError, IndexError, RecursionError):
parser.error("Invalid managed HTTP proxy configuration")
leaked_options = parse_additional_options(" ".join(unknown_args)) if unknown_args else {} leaked_options = parse_additional_options(" ".join(unknown_args)) if unknown_args else {}
response_filter = (args.response_filter or "").strip() response_filter = (args.response_filter or "").strip()
@ -1409,6 +1439,7 @@ args:
max_attempts=args.proxy_max_attempts, cooldown=args.proxy_cooldown, max_attempts=args.proxy_max_attempts, cooldown=args.proxy_cooldown,
fail_status=args.proxy_fail_status, transport_kwargs=transport_kwargs, fail_status=args.proxy_fail_status, transport_kwargs=transport_kwargs,
strategy=args.proxy_strategy, strategy=args.proxy_strategy,
min_switch_interval=args.proxy_min_switch_interval,
) )
except ValueError as exc: except ValueError as exc:
parser.error(str(exc)) parser.error(str(exc))
@ -1707,6 +1738,12 @@ parameters:
required: false required: false
default: "sticky" default: "sticky"
flag: "--proxy-strategy" flag: "--proxy-strategy"
- name: "proxy_min_switch_interval"
type: "string"
description: "代理最短切换间隔秒数(0-86400,工具参数默认0);间隔内失败也不提前切换;受管设置可覆盖此值"
required: false
default: "0"
flag: "--proxy-min-switch-interval"
- name: "proxy_max_attempts" - name: "proxy_max_attempts"
type: "int" type: "int"
description: "每个请求/重定向跳的代理尝试上限(1-10);每个代理最多尝试一次;仅 GET/HEAD/OPTIONS 自动重放" description: "每个请求/重定向跳的代理尝试上限(1-10);每个代理最多尝试一次;仅 GET/HEAD/OPTIONS 自动重放"

View File

@ -47451,3 +47451,14 @@ html[data-theme="dark"] .token-usage-panel { --token-cache-color: #2dd4bf; }
.token-usage-subtitle { max-width: 220px; line-height: 1.6; } .token-usage-subtitle { max-width: 220px; line-height: 1.6; }
.token-usage-trend-svg { min-width: 480px; } .token-usage-trend-svg { min-width: 480px; }
} }
/* HTTP-tool proxy policy settings */
#settings-section-proxy { max-width: 960px; }
#settings-section-proxy .form-group { margin-bottom: 18px; }
#settings-section-proxy .form-hint { line-height: 1.65; margin: 12px 0 18px; }
#settings-section-proxy textarea { min-height: 120px; max-height: 240px; }
#settings-section-proxy [data-proxy-mode][hidden] { display: none !important; }
#settings-section-proxy .proxy-limit-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
@media (max-width: 700px) {
#settings-section-proxy .proxy-limit-grid { grid-template-columns: 1fr; gap: 0; }
}

View File

@ -5133,5 +5133,31 @@
"promptRequired": "Enter a retest prompt.", "promptRequired": "Enter a retest prompt.",
"navigationChanged": "You switched conversations. Return to the retest branch to send the prompt.", "navigationChanged": "You switched conversations. Return to the retest branch to send the prompt.",
"branchCreated": "The retest branch was created. Continue verification in that branch." "branchCreated": "The retest branch was created. Continue verification in that branch."
},
"proxySettings": {
"title": "Proxy settings",
"scope": "Configure egress for the HTTP test tool. Use a fixed proxy for logins and stable sessions; use a pool for independent requests that allow egress changes.",
"mode": "Egress policy",
"manual": "Use tool arguments (default)",
"fixed": "Fixed proxy (recommended for sessions)",
"pool": "Proxy pool (opt in)",
"proxy_url": "Fixed proxy URL",
"proxy_pool": "Static proxies (one URL per line)",
"proxy_source": "Provider URL (optional)",
"strategy": "Pool selection strategy",
"sticky": "Reuse successful proxy",
"round_robin": "Rotate at intervals",
"max_attempts": "Maximum proxy attempts per request",
"cooldown": "Failure cooldown (seconds)",
"min_switch_interval": "Minimum switch interval (seconds)",
"secrets": "Saved addresses and credentials appear as ********. Keep the marker to retain a value, or clear it to delete. Pool mode requires a static list or provider.",
"isolation": "Kali tools and model APIs: this setting applies only to http-framework-test. Other scanners, terminals, external MCP and model APIs keep their own egress. System HTTP_PROXY is not modified; running tools are not restarted or rerouted. Use native fixed-proxy options for other tools that need a proxy.",
"stability": "A fixed proxy URL does not guarantee a fixed public IP from its provider. Use a provider with fixed egress or sticky sessions. Changes affect subsequent HTTP tool invocations only. Managed mode overrides model-supplied proxy options; it is not a network sandbox for arbitrary shell commands.",
"intervalHint": "Within each HTTP tool invocation, keep the proxy until the interval ends, even on failure. Use fixed mode for stable IPs or logins across invocations.",
"save": "Save and apply proxy settings",
"saved": "Proxy settings applied to subsequent HTTP tool invocations.",
"loadError": "Could not load proxy settings",
"saveError": "Could not apply proxy settings",
"invalidNumber": "Enter valid attempt and timing values"
} }
} }

View File

@ -5146,5 +5146,31 @@
"promptRequired": "Введите инструкцию для проверки.", "promptRequired": "Введите инструкцию для проверки.",
"navigationChanged": "Вы переключились на другой диалог. Вернитесь в ветку проверки для отправки инструкции.", "navigationChanged": "Вы переключились на другой диалог. Вернитесь в ветку проверки для отправки инструкции.",
"branchCreated": "Ветка проверки создана. Продолжите проверку в этой ветке." "branchCreated": "Ветка проверки создана. Продолжите проверку в этой ветке."
},
"proxySettings": {
"title": "Настройки прокси",
"scope": "Исходящее соединение HTTP-инструмента. Фиксированный прокси подходит для авторизации и стабильных сеансов; пул — для независимых запросов.",
"mode": "Режим подключения",
"manual": "Параметры инструмента (по умолчанию)",
"fixed": "Фиксированный прокси (для сеансов)",
"pool": "Пул прокси (включить явно)",
"proxy_url": "URL фиксированного прокси",
"proxy_pool": "Статические прокси (по одному URL в строке)",
"proxy_source": "URL поставщика (необязательно)",
"strategy": "Выбор прокси из пула",
"sticky": "Сохранять рабочий прокси",
"round_robin": "Чередовать с интервалом",
"max_attempts": "Максимум попыток на запрос",
"cooldown": "Пауза после сбоя (секунды)",
"min_switch_interval": "Минимальный интервал смены (секунды)",
"secrets": "Сохранённые адреса и учётные данные показаны как ********. Сохраните маркер, чтобы оставить значение, или очистите поле для удаления. Для пула нужен список или поставщик.",
"isolation": "Инструменты Kali и API моделей: настройка действует только на http-framework-test. Другие сканеры, терминалы, внешние MCP и модели сохраняют свои подключения. Системный HTTP_PROXY не меняется. Для других инструментов используйте их собственные параметры фиксированного прокси.",
"stability": "Постоянный URL прокси не гарантирует постоянный публичный IP. Выберите поставщика с фиксированным выходом или привязкой сеанса. Изменения действуют только для новых запусков HTTP-инструмента. Управляемый режим заменяет параметры прокси от модели и не изолирует произвольные команды Shell.",
"intervalHint": "В рамках одного запуска HTTP-инструмента прокси сохраняется до конца интервала даже при сбое. Для стабильного IP между запусками и авторизации используйте фиксированный режим.",
"save": "Сохранить и применить",
"saved": "Настройки применены для следующих запусков HTTP-инструмента.",
"loadError": "Не удалось загрузить настройки прокси",
"saveError": "Не удалось применить настройки прокси",
"invalidNumber": "Укажите допустимые значения попыток и интервалов"
} }
} }

View File

@ -5121,5 +5121,31 @@
"promptRequired": "请输入复测提示词。", "promptRequired": "请输入复测提示词。",
"navigationChanged": "已切换到其他对话,请返回复测分支继续发送。", "navigationChanged": "已切换到其他对话,请返回复测分支继续发送。",
"branchCreated": "复测分支已创建,请在该分支继续验证。" "branchCreated": "复测分支已创建,请在该分支继续验证。"
},
"proxySettings": {
"title": "代理设置",
"scope": "配置 HTTP 测试工具的出口。固定代理适合登录态和需要稳定 IP 的任务;代理池用于允许切换出口的独立请求。",
"mode": "出口策略",
"manual": "沿用工具参数(默认)",
"fixed": "固定代理(推荐稳定会话)",
"pool": "代理池(显式启用)",
"proxy_url": "固定代理 URL",
"proxy_pool": "静态代理列表(每行一个 URL)",
"proxy_source": "供应商接口 URL(可选)",
"strategy": "代理池选择策略",
"sticky": "复用成功代理",
"round_robin": "按间隔轮询",
"max_attempts": "每个请求最多尝试的代理数",
"cooldown": "失败冷却(秒)",
"min_switch_interval": "最短切换间隔(秒)",
"secrets": "已保存的地址与凭证显示为 ********,原样保存会保留,清空可删除。代理池模式中,静态列表和供应商至少填写一项。",
"isolation": "Kali 工具与大模型 API:此设置仅作用于 http-framework-test。其他扫描工具、终端、外部 MCP 和模型 API 保持自身出口;不会修改系统 HTTP_PROXY,也不会在运行中重启或切换其他工具的连接。需要代理的其他工具请使用其原生固定代理参数。",
"stability": "固定代理地址不保证供应商固定公网 IP。稳定会话请使用供应商的固定出口或粘性会话服务。设置修改仅影响后续启动的 HTTP 工具调用。受管模式会覆盖模型传入的代理选项;这不是对任意 Shell 命令的网络隔离。",
"intervalHint": "每次 HTTP 工具调用内保持当前代理至间隔结束;失败时也不提前切换。跨调用需要稳定 IP 或登录态时,请使用固定代理。",
"save": "保存并应用代理设置",
"saved": "代理设置已应用,后续 HTTP 工具调用生效。",
"loadError": "加载代理设置失败",
"saveError": "应用代理设置失败",
"invalidNumber": "请填写有效的代理次数和时间参数"
} }
} }

View File

@ -0,0 +1,42 @@
// Managed HTTP-tool policy. Model transports and unrelated tool processes are separate.
let proxySettingsLoaded = false;
async function loadProxySettings() {
proxySettingsLoaded = false;
document.getElementById("proxy-settings-save").disabled = true;
try {
const response = await apiFetch('/api/config');
if (!response.ok) throw new Error(window.t('proxySettings.loadError'));
const saved = (await response.json()).proxy || {};
const cfg = saved.mode ? saved : {};
const defaults = {mode: 'manual', proxy_url: '', proxy_pool: '', proxy_source: '', strategy: 'sticky', max_attempts: 3, cooldown: 60, min_switch_interval: 60};
for (const [key, fallback] of Object.entries(defaults)) {
document.getElementById(`proxy-setting-${key}`).value = cfg[key] === undefined || cfg[key] === '' || (key === 'max_attempts' && cfg[key] === 0) ? fallback : cfg[key];
}
syncProxySettingsMode();
proxySettingsLoaded = true;
document.getElementById("proxy-settings-save").disabled = false;
} catch (error) { alert(error.message); }
}
function syncProxySettingsMode() {
const mode = document.getElementById('proxy-setting-mode').value;
document.querySelectorAll('[data-proxy-mode]').forEach(el => { el.hidden = el.dataset.proxyMode !== mode; });
}
async function saveProxySettings() {
if (!proxySettingsLoaded) return;
const button = document.getElementById('proxy-settings-save');
button.disabled = true;
try {
const proxy = {};
for (const key of ['mode', 'proxy_url', 'proxy_pool', 'proxy_source', 'strategy']) proxy[key] = document.getElementById(`proxy-setting-${key}`).value.trim();
for (const key of ['max_attempts', 'cooldown', 'min_switch_interval']) {
const input = document.getElementById(`proxy-setting-${key}`);
if (!input.checkValidity() || input.value === '') throw new Error(window.t('proxySettings.invalidNumber'));
proxy[key] = Number(input.value);
}
const response = await apiFetch('/api/config', {method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({proxy})});
if (!response.ok) throw new Error((await response.json()).error || window.t('proxySettings.saveError'));
await loadProxySettings();
alert(window.t('proxySettings.saved'));
} catch (error) { alert(error.message); }
finally { button.disabled = !proxySettingsLoaded; }
}

View File

@ -0,0 +1,25 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const vm = require('node:vm');
const fs = require('node:fs');
function fixture(saved = {}) {
const elements = {};
for (const key of ['mode','proxy_url','proxy_pool','proxy_source','strategy','max_attempts','cooldown','min_switch_interval']) elements[`proxy-setting-${key}`] = {value:'',checkValidity:()=>true};
elements['proxy-settings-save'] = {disabled:false};
const calls = [], alerts = [], panels = ['fixed','pool'].map(mode=>({dataset:{proxyMode:mode},hidden:true}));
const ctx = {window:{t:x=>x}, alert:x=>alerts.push(x),document:{getElementById:id=>elements[id],querySelectorAll:()=>panels},apiFetch:async(url,options)=>{calls.push({url,options});return {ok:true,json:async()=>({proxy:saved})};}};
vm.createContext(ctx);vm.runInContext(fs.readFileSync(__dirname+'/proxy-settings.js','utf8'),ctx);
return {ctx,elements,calls,alerts,panels};
}
test('initial defaults and mode panels are usable', async()=>{
const f=fixture({mode:'',max_attempts:0});await f.ctx.loadProxySettings();
assert.equal(f.elements['proxy-setting-max_attempts'].value,3);
assert.equal(f.elements['proxy-setting-min_switch_interval'].value,60);
f.elements['proxy-setting-mode'].value='fixed';f.ctx.syncProxySettingsMode();assert.equal(f.panels[0].hidden,false);assert.equal(f.panels[1].hidden,true);
});
test('masked credentials survive save without restarting other services',async()=>{
const f=fixture({mode:'fixed',proxy_url:'********',max_attempts:3,cooldown:60,min_switch_interval:60});await f.ctx.loadProxySettings();await f.ctx.saveProxySettings();
const write=f.calls.find(x=>x.options?.method==='PUT');assert.equal(JSON.parse(write.options.body).proxy.proxy_url,'********');
assert.equal(f.calls.some(x=>x.url==='/api/config/apply'),false);
assert.equal(f.elements['proxy-settings-save'].disabled,false);
});

View File

@ -686,6 +686,7 @@ function syncC2NavFromConfig(cfg) {
// 切换设置分类 // 切换设置分类
function switchSettingsSection(section) { function switchSettingsSection(section) {
if (section === "proxy") loadProxySettings();
if (section === 'rbac') { if (section === 'rbac') {
if (typeof switchPage === 'function') { if (typeof switchPage === 'function') {
switchPage('platform-rbac'); switchPage('platform-rbac');

View File

@ -39,7 +39,7 @@
} }
})(); })();
</script> </script>
<link rel="stylesheet" href="/static/css/style.css?v=20261027-pagination-custom-select"> <link rel="stylesheet" href="/static/css/style.css?v=20261031-proxy-settings">
<link rel="stylesheet" href="/static/css/tool-guard.css?v=20260907-7"> <link rel="stylesheet" href="/static/css/tool-guard.css?v=20260907-7">
<link rel="stylesheet" href="/static/css/chat-plan-progress.css?v=20260813-4"> <link rel="stylesheet" href="/static/css/chat-plan-progress.css?v=20260813-4">
<link rel="stylesheet" href="/static/css/c2.css"> <link rel="stylesheet" href="/static/css/c2.css">
@ -3605,6 +3605,7 @@
<div class="settings-nav-item" data-section="token-usage" role="button" tabindex="0" onclick="switchSettingsSection('token-usage')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchSettingsSection('token-usage'); }"> <div class="settings-nav-item" data-section="token-usage" role="button" tabindex="0" onclick="switchSettingsSection('token-usage')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchSettingsSection('token-usage'); }">
<span data-i18n="settings.nav.tokenUsage">Token 用量</span> <span data-i18n="settings.nav.tokenUsage">Token 用量</span>
</div> </div>
<div class="settings-nav-item" data-section="proxy" role="button" tabindex="0" onclick="switchSettingsSection('proxy')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchSettingsSection('proxy'); }"><span data-i18n="proxySettings.title">代理设置</span></div>
<div class="settings-nav-item" data-section="hitl" onclick="switchSettingsSection('hitl')"> <div class="settings-nav-item" data-section="hitl" onclick="switchSettingsSection('hitl')">
<span data-i18n="settings.nav.hitl">人机协同</span> <span data-i18n="settings.nav.hitl">人机协同</span>
</div> </div>
@ -4017,6 +4018,21 @@
</div> </div>
</div> </div>
<div id="settings-section-proxy" class="settings-section-content"><div class="settings-section-header"><h3 data-i18n="proxySettings.title">代理设置</h3></div><p class="form-hint" data-i18n="proxySettings.scope"></p>
<div class="form-group"><label for="proxy-setting-mode" data-i18n="proxySettings.mode"></label><select id="proxy-setting-mode" onchange="syncProxySettingsMode()"><option value="manual" data-i18n="proxySettings.manual">沿用工具参数(默认)</option><option value="fixed" data-i18n="proxySettings.fixed">固定代理(推荐稳定会话)</option><option value="pool" data-i18n="proxySettings.pool">代理池(显式启用)</option></select></div>
<div data-proxy-mode="fixed" hidden><div class="form-group"><label for="proxy-setting-proxy_url" data-i18n="proxySettings.proxy_url"></label><input id="proxy-setting-proxy_url" type="password" autocomplete="new-password"></div></div>
<div data-proxy-mode="pool" hidden>
<div class="form-group"><label for="proxy-setting-proxy_pool" data-i18n="proxySettings.proxy_pool"></label><textarea id="proxy-setting-proxy_pool" rows="5" spellcheck="false"></textarea></div>
<div class="form-group"><label for="proxy-setting-proxy_source" data-i18n="proxySettings.proxy_source"></label><input id="proxy-setting-proxy_source" type="password" autocomplete="new-password"></div>
<div class="form-group"><label for="proxy-setting-strategy" data-i18n="proxySettings.strategy"></label><select id="proxy-setting-strategy"><option value="sticky" data-i18n="proxySettings.sticky">复用成功代理</option><option value="round_robin" data-i18n="proxySettings.round_robin">按间隔轮询</option></select></div>
<div class="proxy-limit-grid"><div class="form-group"><label for="proxy-setting-max_attempts" data-i18n="proxySettings.max_attempts"></label><input id="proxy-setting-max_attempts" type="number" value="3" min="1" max="10" step="1" required></div>
<div class="form-group"><label for="proxy-setting-cooldown" data-i18n="proxySettings.cooldown"></label><input id="proxy-setting-cooldown" type="number" value="60" min="0" max="86400" step="1" required></div>
<div class="form-group"><label for="proxy-setting-min_switch_interval" data-i18n="proxySettings.min_switch_interval"></label><input id="proxy-setting-min_switch_interval" type="number" value="60" min="0" max="86400" step="1" required></div>
</div><p class="form-hint" data-i18n="proxySettings.intervalHint"></p></div>
<p class="form-hint" data-i18n="proxySettings.secrets">已保存的地址与凭证显示为 ********,原样保存会保留,清空可删除。代理池模式中,静态列表和供应商至少填写一项。</p>
<p class="form-hint" data-i18n="proxySettings.isolation">Kali 工具与大模型 API:此设置仅作用于 http-framework-test。其他扫描工具、终端、外部 MCP 和模型 API 保持自身出口;不会修改系统 HTTP_PROXY,也不会在运行中重启或切换其他工具的连接。需要代理的其他工具请使用其原生固定代理参数。</p>
<p class="form-hint" data-i18n="proxySettings.stability">固定代理地址不保证供应商固定公网 IP。稳定会话请使用供应商的固定出口或粘性会话服务。设置修改仅影响后续启动的 HTTP 工具调用。受管模式会覆盖模型传入的代理选项;这不是对任意 Shell 命令的网络隔离。</p>
<div class="settings-actions"><button id="proxy-settings-save" disabled class="btn-primary" onclick="saveProxySettings()" data-require-permission="config:write" data-i18n="proxySettings.save">保存并应用代理设置</button></div></div>
<!-- 人机协同 --> <!-- 人机协同 -->
<div id="settings-section-hitl" class="settings-section-content"> <div id="settings-section-hitl" class="settings-section-content">
<div class="settings-section-header"> <div class="settings-section-header">
@ -7031,7 +7047,8 @@
<script src="/static/js/hitl.js?v=20260819-1-pagination-20261027"></script> <script src="/static/js/hitl.js?v=20260819-1-pagination-20261027"></script>
<script src="/static/js/tool-guard.js?v=20261010-conflict"></script> <script src="/static/js/tool-guard.js?v=20261010-conflict"></script>
<script src="/static/js/token-usage.js?v=20261012-token-analytics"></script> <script src="/static/js/token-usage.js?v=20261012-token-analytics"></script>
<script src="/static/js/settings.js?v=20261011-token-settings-pagination-20261027"></script> <script src="/static/js/proxy-settings.js?v=20261031"></script>
<script src="/static/js/settings.js?v=20261031-proxy-settings"></script>
<script src="/static/js/audit-datetime-picker.js"></script> <script src="/static/js/audit-datetime-picker.js"></script>
<script src="/static/js/audit.js?v=20261027-pagination-custom-select"></script> <script src="/static/js/audit.js?v=20261027-pagination-custom-select"></script>
<script src="/static/js/storage.js"></script> <script src="/static/js/storage.js"></script>