mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-11-23 04:41:41 +01:00
feat(http): add bounded proxy pool failover to HTTP test tool
This commit is contained in:
1 parent
697e875fa4
commit
5d7cb1ff5d
11 files changed
+987
-5
No files matched your search
@@ -0,0 +1,22 @@
|
||||
name: HTTP proxy pool
|
||||
on:
|
||||
push:
|
||||
paths: ['tools/http-framework-test.yaml', 'scripts/test_http_proxy_pool.py', 'requirements.txt', '.github/workflows/http-proxy-pool.yml']
|
||||
pull_request:
|
||||
paths: ['tools/http-framework-test.yaml', 'scripts/test_http_proxy_pool.py', 'requirements.txt', '.github/workflows/http-proxy-pool.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
proxy-pool:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
httpx: ['0.27.0', '0.28.1']
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- run: python -m pip install 'httpx[http2,socks]==${{ matrix.httpx }}' PyYAML
|
||||
- run: python -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
### Added
|
||||
|
||||
- `http-framework-test` 新增可选代理池:支持代理列表与供应商接口、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。
|
||||
|
||||
- 支持通过 `agent.task_timeout_minutes` 配置单代理、多代理、工作流及异步任务执行超时:未配置默认 600 分钟,`0` 表示不限时,负数拒绝加载;续跑保留重新计时行为,单次工具超时仍独立生效。
|
||||
|
||||
- 新增单代理与多代理异步对话 API:接收后返回任务回执,客户端断线不停止执行;支持按用户隔离的幂等提交、持久状态与结果查询、显式取消以及服务重启后的中断状态。同步接口保持兼容。
|
||||
|
||||
@@ -32,6 +32,7 @@ CyberStrikeAI documentation is organized by user journey. Start with deployment,
|
||||
- [资产管理](zh-CN/asset-management.md)
|
||||
- [项目任务续接](zh-CN/project-resume.md)
|
||||
- [Token 用量分析](zh-CN/token-usage-monitoring.md)
|
||||
- [HTTP 测试工具代理池](zh-CN/http-proxy-pool.md)
|
||||
- [知识库](zh-CN/knowledge-base.md)
|
||||
- [RBAC 权限管理](zh-CN/rbac.md)
|
||||
- [机器人接入](zh-CN/robot.md)
|
||||
@@ -76,6 +77,7 @@ CyberStrikeAI documentation is organized by user journey. Start with deployment,
|
||||
- [Asset Management](en-US/asset-management.md)
|
||||
- [Resuming Project Tasks](en-US/project-resume.md)
|
||||
- [Token Usage Analysis](en-US/token-usage-monitoring.md)
|
||||
- [HTTP Test Tool Proxy Pool](en-US/http-proxy-pool.md)
|
||||
- [Knowledge Base](en-US/knowledge-base.md)
|
||||
- [RBAC Administration](en-US/rbac.md)
|
||||
- [Robot / Chatbot](en-US/robot.md)
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
## Feature guides
|
||||
|
||||
- [Resuming Project Tasks](project-resume.md) · [Token Usage Analysis](token-usage-monitoring.md)
|
||||
- [HTTP Test Tool Proxy Pool](http-proxy-pool.md)
|
||||
- [Asset Management](asset-management.md) · [Knowledge Base](knowledge-base.md) · [Robot / Chatbot](robot.md) · [Vision](VISION.md)
|
||||
- [WebShell](webshell.md) · [C2](c2.md) · [MCP Federation](mcp-federation.md)
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# HTTP test tool proxy pool
|
||||
|
||||
[中文](../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.
|
||||
|
||||
## 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.
|
||||
|
||||
Example MCP tool arguments:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"method": "GET",
|
||||
"proxy_pool": "[\"http://127.0.0.1:8081\",\"http://127.0.0.1:8082\"]",
|
||||
"proxy_max_attempts": 3,
|
||||
"proxy_cooldown": "60",
|
||||
"proxy_fail_status": "403,429",
|
||||
"response_max_bytes": 8192
|
||||
}
|
||||
```
|
||||
|
||||
`proxy_pool` also accepts newline-separated endpoints. Supported forms are `http://host:port`, `https://host:port`, `socks5://host:port`, and bare `host:port` (HTTP). An explicit port is required. IPv6 brackets and URL-encoded `user:password@host:port` credentials are supported. SOCKS support is included in the `httpx[http2,socks]` requirement.
|
||||
|
||||
To fetch proxies automatically, add or use `proxy_source` alone:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"proxy_source": "https://your-proxy-provider.example/api/proxies"
|
||||
}
|
||||
```
|
||||
|
||||
The endpoint must return UTF-8 newline-separated endpoints, a JSON array of endpoint strings, or an object containing a `proxies` or `data` array:
|
||||
|
||||
```json
|
||||
{"proxies": ["http://127.0.0.1:8081", "127.0.0.1:8082"]}
|
||||
```
|
||||
|
||||
Other provider formats require an adapter. No public free-proxy sources are built in. The source is fetched at startup and at most once more per request/redirect hop when available candidates run out. New endpoints are deduplicated and merged without clearing cooldowns. Fetches have a 10-second timeout, do not follow redirects, accept at most 1 MiB, and the pool holds at most 256 endpoints. An initial fetch failure stops the call. A refresh failure preserves the last HTTP failure response, or reports an error if no response exists.
|
||||
|
||||
## Behavior
|
||||
|
||||
| Parameter | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `proxy_pool` | Empty | JSON string array or newline-separated list |
|
||||
| `proxy_source` | Empty | User-configured HTTP(S) provider endpoint, optionally combined with a list |
|
||||
| `proxy_max_attempts` | `3` | 1–10 distinct proxy attempts per request/redirect hop |
|
||||
| `proxy_cooldown` | `"60"` | 0–86400 seconds before a failed proxy is eligible again |
|
||||
| `proxy_fail_status` | `"403,429"` | Comma-separated status codes from 400–599; `"none"` disables status-based switching |
|
||||
|
||||
- Successful proxies stay selected. Failed proxies enter cooldown. Each proxy is tried at most once per request/redirect hop.
|
||||
- Only GET, HEAD and OPTIONS are replayed automatically. POST, PUT, DELETE and other methods retain the first result. An explicit `repeat` still requests additional executions.
|
||||
- Transport failures before response headers can trigger switching. Failures while reading a response body are reported without replaying a partial response.
|
||||
- A 429 with a valid future `Retry-After` stops automatic replay and reports that the caller should retry later. Further requests to that origin within the same tool invocation are blocked until the wait expires; waits are recorded for at most 24 hours.
|
||||
- If the final attempt returns an HTTP failure response, it is preserved with a nonzero exit code. A network failure or a pool with all endpoints cooling down reports an error. There is no direct fallback or extra direct DNS/TCP/TLS target probe.
|
||||
- Pool diagnostics show attempt numbers, proxy numbers and failure types. They omit proxy credentials and provider URLs. The platform's existing argument traces, audit records and logs still apply; treat arguments containing credentials as sensitive configuration.
|
||||
|
||||
## Scope and design
|
||||
|
||||
[#357](https://github.com/AIPentest/CyberStrikeAI/issues/357) requests automatic proxy acquisition and switching after a ban, without specifying providers, detection or tool scope. This implementation starts with `http-framework-test`, where both HTTP and decrypted HTTPS responses can be inspected. A standalone forwarding proxy cannot read HTTPS responses inside a CONNECT tunnel. See the [HTTPX proxy](https://www.python-httpx.org/advanced/proxies/) and [transport](https://www.python-httpx.org/advanced/transports/) documentation.
|
||||
|
||||
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.
|
||||
|
||||
## Troubleshooting and source
|
||||
|
||||
| Message | Action |
|
||||
| --- | --- |
|
||||
| `Proxy pool exhausted` | Check endpoint connectivity, wait for cooldown, or replace the list/provider results |
|
||||
| `failure policy still matched` | Inspect the preserved response and distinguish IP restrictions from normal authorization/rate limits; adjust `proxy_fail_status` if needed |
|
||||
| `Retry-After is still active` | Wait for the target's requested delay before another call |
|
||||
| `Could not fetch proxy source` | Check provider connectivity, authentication and TLS; target `allow_insecure` does not affect provider connections |
|
||||
| `SOCKS support requires ...` | Install `httpx[socks]` in the tool's Python environment or update its requirements |
|
||||
|
||||
The implementation and MCP parameter definitions are in [tools/http-framework-test.yaml](../../tools/http-framework-test.yaml); regression scenarios are in [scripts/test_http_proxy_pool.py](../../scripts/test_http_proxy_pool.py).
|
||||
|
||||
## Local verification
|
||||
|
||||
```sh
|
||||
python3 -m pip install 'httpx[http2,socks]>=0.27.0' PyYAML
|
||||
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`.
|
||||
@@ -20,6 +20,7 @@
|
||||
## 功能指南
|
||||
|
||||
- [项目任务续接](project-resume.md) · [Token 用量分析](token-usage-monitoring.md)
|
||||
- [HTTP 测试工具代理池](http-proxy-pool.md)
|
||||
- [资产管理](asset-management.md) · [知识库](knowledge-base.md) · [机器人接入](robot.md) · [视觉分析](VISION.md)
|
||||
- [WebShell](webshell.md) · [C2](c2.md) · [MCP 联邦](mcp-federation.md)
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# HTTP 测试工具代理池
|
||||
|
||||
[English](../en-US/http-proxy-pool.md) | [文档首页](README.md)
|
||||
|
||||
`http-framework-test` 支持用户提供的代理列表及代理供应商接口。连接失败或响应命中指定状态码时,在次数上限内切换代理;成功代理继续复用连接。默认关闭,原有 `proxy` 参数及无代理调用方式继续可用。
|
||||
|
||||
## 使用
|
||||
|
||||
更新工具文件后,在系统设置中应用配置或重启服务以重新加载工具参数。代理池通过每次工具调用的参数启用,不需要修改 `config.yaml`。
|
||||
|
||||
调用 `http-framework-test` 时传入以下参数(MCP 工具参数示例):
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"method": "GET",
|
||||
"proxy_pool": "[\"http://127.0.0.1:8081\",\"http://127.0.0.1:8082\"]",
|
||||
"proxy_max_attempts": 3,
|
||||
"proxy_cooldown": "60",
|
||||
"proxy_fail_status": "403,429",
|
||||
"response_max_bytes": 8192
|
||||
}
|
||||
```
|
||||
|
||||
`proxy_pool` 也接受每行一个代理的字符串。支持 `http://host:port`、`https://host:port`、`socks5://host:port` 和省略协议的 `host:port`(按 HTTP 解析);端口必须显式指定。支持 IPv6 方括号及 `user:password@host:port` 认证,凭证中的特殊字符须做 URL 编码。SOCKS 依赖包含在 `requirements.txt` 的 `httpx[http2,socks]` 中。
|
||||
|
||||
使用供应商接口自动获取代理时,增加或单独使用:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"proxy_source": "https://your-proxy-provider.example/api/proxies"
|
||||
}
|
||||
```
|
||||
|
||||
接口返回 UTF-8 文本,每行一个代理,或以下 JSON 格式之一:
|
||||
|
||||
```json
|
||||
["http://127.0.0.1:8081", "127.0.0.1:8082"]
|
||||
```
|
||||
|
||||
```json
|
||||
{"proxies": ["http://127.0.0.1:8081"]}
|
||||
```
|
||||
|
||||
也支持 `{"data": ["http://127.0.0.1:8081"]}`。需要其他供应商字段格式时,应由供应商或自建适配接口转换为上述格式。项目不内置公共免费代理来源。
|
||||
|
||||
供应商接口在调用开始时拉取一次;每个请求或重定向跳的可用代理耗尽时,最多再拉取一次。新地址与现有地址去重合并,已有冷却记录保留。接口超时固定 10 秒,不跟随重定向,响应上限 1 MiB,代理总数上限 256。首次拉取失败直接结束调用;切换过程中拉取失败则保留最后的 HTTP 失败响应,若还未收到响应则报错。
|
||||
|
||||
## 切换与结果
|
||||
|
||||
| 参数 | 默认值 | 行为 |
|
||||
| --- | --- | --- |
|
||||
| `proxy_pool` | 空 | JSON 字符串数组或换行列表 |
|
||||
| `proxy_source` | 空 | 用户配置的 HTTP(S) 供应商接口,可与列表合用 |
|
||||
| `proxy_max_attempts` | `3` | 每个请求/重定向跳最多尝试 1–10 个不同代理 |
|
||||
| `proxy_cooldown` | `"60"` | 失败代理冷却 0–86400 秒 |
|
||||
| `proxy_fail_status` | `"403,429"` | 逗号分隔的 400–599 状态码,传 `"none"` 禁用状态码切换 |
|
||||
|
||||
具体规则:
|
||||
|
||||
- 池内成功代理保持粘性复用;失败后冷却,在剩余可用代理中切换。每个请求或重定向跳内,同一代理最多尝试一次。
|
||||
- 仅 GET、HEAD、OPTIONS 自动重放。POST、PUT、DELETE 等方法发生错误或命中状态码时保留首次结果;用户显式设置的 `repeat` 仍表示额外执行次数。
|
||||
- 连接、代理、超时等传输错误可触发上述切换;响应体开始读取后的中断直接报错,不重放部分响应。
|
||||
- 429 若包含有效且尚未到期的 `Retry-After`,停止自动重放并提示稍后重试。同一工具调用中,对该目标源的后续请求也会被阻止至等待期结束,等待值最多记为 24 小时。
|
||||
- 最后一次尝试若收到 HTTP 失败响应,保留该响应并返回非零退出码;网络故障或所有代理处于冷却时报告错误。不会回退到直连,也不会运行额外的目标 DNS/TCP/TLS 直连探针。
|
||||
- stderr 记录尝试编号、代理编号及失败类型;stdout 保留最终响应及最终代理编号。代理池自身诊断不输出代理凭证或供应商 URL。工具调用参数仍沿用平台既有的轨迹、审计与日志规则,带凭证的参数应按敏感配置管理。
|
||||
|
||||
## 调研结论与覆盖范围
|
||||
|
||||
[#357](https://github.com/AIPentest/CyberStrikeAI/issues/357) 仅提出自动获取代理与被封后切换,未定义供应商、识别方式或工具范围。当前实现从能读取 HTTP 响应的 `http-framework-test` 接入,使 HTTP 和 HTTPS 的切换行为都可验证。
|
||||
|
||||
HTTP CONNECT 隧道中的 HTTPS 响应需要由发起请求的客户端解密才能读取,因此单独增加全局转发代理不足以识别全部工具的 HTTPS 封禁响应。HTTPX 的代理与自定义传输接口适合在本工具内完成切换,见 [HTTPX 代理文档](https://www.python-httpx.org/advanced/proxies/)与[传输文档](https://www.python-httpx.org/advanced/transports/)。
|
||||
|
||||
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。
|
||||
|
||||
## 排错与源码
|
||||
|
||||
| 提示 | 处理 |
|
||||
| --- | --- |
|
||||
| `Proxy pool exhausted` | 检查代理可达性,等待冷却或更换列表/供应商返回值 |
|
||||
| `failure policy still matched` | 查看保留的响应;确认是 IP 限制还是正常的权限/限流结果,按需调整 `proxy_fail_status` |
|
||||
| `Retry-After is still active` | 等待目标指定的时间后再发起调用 |
|
||||
| `Could not fetch proxy source` | 检查供应商接口网络、认证和 TLS;目标的 `allow_insecure` 不影响供应商连接 |
|
||||
| `SOCKS support requires ...` | 在工具使用的 Python 环境安装 `httpx[socks]` 或更新 `requirements.txt` 依赖 |
|
||||
|
||||
执行代码与 MCP 参数定义位于 [tools/http-framework-test.yaml](../../tools/http-framework-test.yaml),回归场景位于 [scripts/test_http_proxy_pool.py](../../scripts/test_http_proxy_pool.py)。
|
||||
|
||||
## 本地验证
|
||||
|
||||
```sh
|
||||
python3 -m pip install 'httpx[http2,socks]>=0.27.0' PyYAML
|
||||
python3 -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
|
||||
```
|
||||
|
||||
测试从 YAML 读取实际执行代码,使用本地 HTTP 代理、CONNECT 隧道及 TLS 服务验证切换、路径保真、重放限制、等待期、供应商刷新与凭证隔离;不访问外部目标或真实供应商。HTTPS 测试需要 `openssl`。
|
||||
@@ -0,0 +1,42 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Check the public tool's YAML through the same argument mapping used by MCP.
|
||||
// In particular, an empty optional string is dropped by that mapping, so the
|
||||
// status-policy off switch must use a nonempty sentinel.
|
||||
func TestHTTPProxyPoolToolArguments(t *testing.T) {
|
||||
tool, err := config.LoadToolFromFile(filepath.Join("..", "..", "tools", "http-framework-test.yaml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
executor := NewExecutor(&config.SecurityConfig{Tools: []config.ToolConfig{*tool}}, nil, zap.NewNop())
|
||||
pool := "http://user:p%40ss@localhost:8081\nhttp://localhost:8082"
|
||||
args := executor.buildCommandArgs(tool.Name, tool, map[string]interface{}{
|
||||
"url": "https://target.invalid/a/../b", "proxy_pool": pool,
|
||||
"proxy_source": "https://provider.invalid/?key=placeholder",
|
||||
"proxy_max_attempts": float64(2), "proxy_cooldown": "0", "proxy_fail_status": "none",
|
||||
})
|
||||
want := map[string]string{
|
||||
"--proxy-pool": pool, "--proxy-source": "https://provider.invalid/?key=placeholder",
|
||||
"--proxy-max-attempts": "2", "--proxy-cooldown": "0", "--proxy-fail-status": "none",
|
||||
}
|
||||
for flag, value := range want {
|
||||
found := false
|
||||
for i, arg := range args {
|
||||
if arg == flag && i+1 < len(args) && args[i+1] == value {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("tool argument mapping lost or changed %s", flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Python HTTP helpers leveraged by tools like api-fuzzer, dnslog, http-intruder, http-framework-test
|
||||
requests>=2.32.3
|
||||
httpx[http2]>=0.27.0
|
||||
httpx[http2,socks]>=0.27.0
|
||||
charset-normalizer>=3.3.2
|
||||
chardet>=5.2.0,<6
|
||||
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
"""Local-only integration tests for the exact Python shipped in the tool YAML.
|
||||
|
||||
Run: python3 -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
|
||||
Requires: httpx[http2,socks], PyYAML; openssl for the CONNECT/TLS fixture.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import datetime
|
||||
import email.utils
|
||||
import http.server
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import select
|
||||
import shutil
|
||||
import socket
|
||||
import socketserver
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOL = yaml.safe_load((ROOT / "tools/http-framework-test.yaml").read_text())
|
||||
SCRIPT = TOOL["args"][1]
|
||||
NS = {"__name__": "http_framework_tool"}
|
||||
exec(compile(SCRIPT, "http-framework-test.yaml", "exec"), NS)
|
||||
Pool = NS["ProxyPoolTransport"]
|
||||
|
||||
|
||||
def relay(connection, upstream):
|
||||
while True:
|
||||
readable, _, _ = select.select([connection, upstream], [], [], 3)
|
||||
if not readable:
|
||||
return
|
||||
for current in readable:
|
||||
data = current.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
(upstream if current is connection else connection).sendall(data)
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def respond(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
body = self.rfile.read(length) if length else b""
|
||||
self.server.requests.append((self.command, self.path, self.headers, body))
|
||||
status, headers, body = self.server.reply(self)
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
for key, value in headers.items():
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(body)
|
||||
|
||||
do_GET = do_POST = do_HEAD = do_OPTIONS = do_PUT = do_DELETE = respond
|
||||
|
||||
def do_CONNECT(self):
|
||||
self.server.requests.append(("CONNECT", self.path, self.headers, b""))
|
||||
# Connect only to the local TLS fixture, regardless of the requested host.
|
||||
with socket.create_connection(("127.0.0.1", self.server.tunnel_port), timeout=3) as upstream:
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.flush()
|
||||
self.close_connection = True
|
||||
relay(self.connection, upstream)
|
||||
|
||||
|
||||
class SocksHandler(socketserver.StreamRequestHandler):
|
||||
def handle(self):
|
||||
version, count = self.rfile.read(2)
|
||||
self.rfile.read(count)
|
||||
if version != 5:
|
||||
return
|
||||
self.wfile.write(b"\x05\x00")
|
||||
self.wfile.flush()
|
||||
version, command, _, address_type = self.rfile.read(4)
|
||||
if version != 5 or command != 1 or address_type != 3:
|
||||
return
|
||||
length = self.rfile.read(1)[0]
|
||||
host = self.rfile.read(length).decode("ascii")
|
||||
port = int.from_bytes(self.rfile.read(2), "big")
|
||||
self.server.requests.append((host, port))
|
||||
with socket.create_connection(("127.0.0.1", self.server.tunnel_port), timeout=3) as upstream:
|
||||
self.wfile.write(b"\x05\x00\x00\x01\x7f\x00\x00\x01\x00\x00")
|
||||
self.wfile.flush()
|
||||
relay(self.connection, upstream)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def socks_server(tunnel_port):
|
||||
instance = socketserver.ThreadingTCPServer(("127.0.0.1", 0), SocksHandler)
|
||||
instance.daemon_threads = True
|
||||
instance.tunnel_port = tunnel_port
|
||||
instance.requests = []
|
||||
instance.url = f"socks5://127.0.0.1:{instance.server_address[1]}"
|
||||
worker = threading.Thread(target=instance.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
yield instance
|
||||
finally:
|
||||
instance.shutdown()
|
||||
instance.server_close()
|
||||
worker.join(timeout=3)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def server(status=200, body=b"ok", headers=None, reply=None, tls=None, tunnel_port=None):
|
||||
instance = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
instance.daemon_threads = True
|
||||
instance.requests = []
|
||||
instance.reply = reply or (lambda _: (status, headers or {}, body))
|
||||
instance.tunnel_port = tunnel_port
|
||||
if tls:
|
||||
instance.socket = tls.wrap_socket(instance.socket, server_side=True)
|
||||
instance.url = f"http://127.0.0.1:{instance.server_port}"
|
||||
worker = threading.Thread(target=instance.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
yield instance
|
||||
finally:
|
||||
instance.shutdown()
|
||||
instance.server_close()
|
||||
worker.join(timeout=3)
|
||||
|
||||
|
||||
def send(client, method="GET", url="http://target.invalid/a/../b?x=%2F", **kwargs):
|
||||
return NS["send_path_as_is"](client, method=method, url=url, headers=httpx.Headers(), **kwargs)
|
||||
|
||||
|
||||
class ProxyPoolTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.diagnostics = io.StringIO()
|
||||
self.redirect_stderr = contextlib.redirect_stderr(self.diagnostics)
|
||||
self.redirect_stderr.__enter__()
|
||||
|
||||
def tearDown(self):
|
||||
self.redirect_stderr.__exit__(None, None, None)
|
||||
|
||||
def test_parse_formats_validate_and_deduplicate(self):
|
||||
parse = NS["parse_proxy_list"]
|
||||
self.assertEqual(parse("LOCALHOST:8080\nhttp://localhost:8080/"), ["http://localhost:8080"])
|
||||
self.assertEqual(parse('{"data":["socks5://[::1]:1080"]}'), ["socks5://[::1]:1080"])
|
||||
self.assertEqual(parse('{"proxies":["https://user:p%40ss@EXAMPLE.COM:443"]}'),
|
||||
["https://user:p%40ss@example.com:443"])
|
||||
for value in ["http://user:secret@host:bad", "http://host:80/path", "file://host:80",
|
||||
"http://host:0", "http://host:65536", "http://host:80?q=secret", "[invalid",
|
||||
{"data": [{"ip": "127.0.0.1"}]}, ["host:80"] * 257]:
|
||||
with self.subTest(value=type(value)):
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
parse(value)
|
||||
self.assertNotIn("secret", str(caught.exception))
|
||||
|
||||
def test_configuration_bounds(self):
|
||||
for kwargs in [dict(max_attempts=0), dict(max_attempts=11), dict(cooldown=-1),
|
||||
dict(cooldown=float("nan")), dict(cooldown=float("inf")),
|
||||
dict(fail_status="200"), dict(fail_status="oops")]:
|
||||
with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
|
||||
Pool("localhost:8080", **kwargs)
|
||||
|
||||
def test_failover_and_sticky_connection_preserve_raw_path(self):
|
||||
with server(403, b"blocked") as blocked, server() as good:
|
||||
pool = Pool(json.dumps([blocked.url, good.url]), cooldown=60)
|
||||
with httpx.Client(transport=pool, trust_env=False) as client:
|
||||
for _ in range(2):
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"ok")
|
||||
self.assertFalse(response.extensions["proxy_pool"]["failed"])
|
||||
self.assertEqual(len(blocked.requests), 1)
|
||||
self.assertEqual(len(good.requests), 2)
|
||||
self.assertEqual(good.requests[0][1], "http://target.invalid/a/../b?x=%2F")
|
||||
|
||||
def test_network_failure_switches_and_never_retries_same_proxy(self):
|
||||
# Reserve then close a local port: connection refused, no Internet access.
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
dead = f"http://127.0.0.1:{sock.getsockname()[1]}"
|
||||
sock.close()
|
||||
with server() as good:
|
||||
with httpx.Client(transport=Pool(json.dumps([dead, good.url])), trust_env=False, timeout=1) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"ok")
|
||||
with httpx.Client(transport=Pool(dead, cooldown=0, max_attempts=10), trust_env=False, timeout=1) as client:
|
||||
with self.assertRaisesRegex(httpx.ProxyError, "exhausted"):
|
||||
send(client)
|
||||
|
||||
def test_no_replacement_preserves_block_response_and_skips_direct_probe(self):
|
||||
with server(403, b"evidence") as blocked:
|
||||
with httpx.Client(transport=Pool(blocked.url), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"evidence")
|
||||
self.assertTrue(response.extensions["proxy_pool"]["failed"])
|
||||
with self.assertRaisesRegex(httpx.ProxyError, "direct fallback disabled"):
|
||||
send(client)
|
||||
self.assertEqual(len(blocked.requests), 1)
|
||||
|
||||
def test_attempt_budget(self):
|
||||
with server(403) as first, server(403) as second, server() as third:
|
||||
with httpx.Client(transport=Pool(json.dumps([first.url, second.url, third.url]), max_attempts=2), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertTrue(response.extensions["proxy_pool"]["failed"])
|
||||
self.assertEqual(len(third.requests), 0)
|
||||
|
||||
def test_post_put_delete_never_replayed(self):
|
||||
for method in ["POST", "PUT", "DELETE"]:
|
||||
with self.subTest(method=method), server(403) as first, server() as second:
|
||||
with httpx.Client(transport=Pool(json.dumps([first.url, second.url])), trust_env=False) as client:
|
||||
response, *_ = send(client, method, content=b"write once")
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(len(second.requests), 0)
|
||||
self.assertEqual(first.requests[0][3], b"write once")
|
||||
|
||||
def test_post_transport_error_never_replayed(self):
|
||||
pool = Pool("localhost:8001\nlocalhost:8002")
|
||||
first = mock.Mock()
|
||||
first.handle_request.side_effect = httpx.ReadTimeout("private credentials")
|
||||
pool.transports[pool.proxies[0]] = first
|
||||
with httpx.Client(transport=pool, trust_env=False) as client:
|
||||
with self.assertRaisesRegex(httpx.ProxyError, "automatic replay stopped") as caught:
|
||||
send(client, "POST", content=b"once")
|
||||
self.assertNotIn("private", str(caught.exception))
|
||||
self.assertEqual(len(pool.transports), 1)
|
||||
|
||||
def test_retry_after_delta_and_date_stop_replay(self):
|
||||
date = email.utils.format_datetime(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=5))
|
||||
for value in ["120", date]:
|
||||
with self.subTest(value=value), server(429, headers={"Retry-After": value}) as first, server() as second:
|
||||
with httpx.Client(transport=Pool(json.dumps([first.url, second.url])), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertEqual(response.status_code, 429)
|
||||
with self.assertRaisesRegex(httpx.ProxyError, "Retry-After is still active"):
|
||||
send(client)
|
||||
self.assertEqual(len(second.requests), 0)
|
||||
self.assertEqual(NS["retry_after_seconds"]("9" * 5000), 86400)
|
||||
self.assertEqual(NS["retry_after_seconds"]("0" * 5000 + "1"), 1)
|
||||
self.assertEqual(NS["retry_after_seconds"]("²"), 0)
|
||||
self.assertEqual(NS["retry_after_seconds"]("garbage"), 0)
|
||||
|
||||
def test_429_without_retry_after_and_safe_methods_switch(self):
|
||||
for method in ["GET", "HEAD", "OPTIONS"]:
|
||||
with self.subTest(method=method), server(429) as first, server() as second:
|
||||
with httpx.Client(transport=Pool(json.dumps([first.url, second.url])), trust_env=False) as client:
|
||||
response, *_ = send(client, method)
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(len(second.requests), 1)
|
||||
|
||||
def test_body_stream_failure_is_not_replayed(self):
|
||||
class BrokenBody(httpx.SyncByteStream):
|
||||
def __iter__(self):
|
||||
yield b"partial"
|
||||
raise httpx.ReadError("connection lost during body")
|
||||
pool = Pool("localhost:8001\nlocalhost:8002")
|
||||
first = mock.Mock()
|
||||
first.handle_request.return_value = httpx.Response(200, stream=BrokenBody())
|
||||
pool.transports[pool.proxies[0]] = first
|
||||
with httpx.Client(transport=pool, trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response), self.assertRaises(httpx.ReadError):
|
||||
response.read()
|
||||
self.assertEqual(len(pool.transports), 1)
|
||||
|
||||
def test_status_policy_is_configurable(self):
|
||||
with server(403) as first, server() as second:
|
||||
with httpx.Client(transport=Pool(json.dumps([first.url, second.url]), fail_status="none"), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertFalse(response.extensions["proxy_pool"]["failed"])
|
||||
self.assertEqual(len(second.requests), 0)
|
||||
|
||||
def test_cooldown_expiry(self):
|
||||
pool = Pool("localhost:8001\nlocalhost:8002", cooldown=10)
|
||||
pool.cooling[pool.proxies[0]] = 110
|
||||
pool.cooling[pool.proxies[1]] = 110
|
||||
with mock.patch.object(NS["time"], "monotonic", return_value=100):
|
||||
self.assertIsNone(pool.select(set()))
|
||||
with mock.patch.object(NS["time"], "monotonic", return_value=111):
|
||||
self.assertEqual(pool.select(set()), pool.proxies[0])
|
||||
|
||||
def test_source_refresh_has_no_target_credentials_or_environment_proxy(self):
|
||||
with server(403) as blocked, server() as good:
|
||||
def reply(handler):
|
||||
proxies = [blocked.url] if len(handler.server.requests) == 1 else [good.url]
|
||||
return 200, {}, json.dumps({"proxies": proxies}).encode()
|
||||
with server(reply=reply) as provider:
|
||||
with mock.patch.dict(os.environ, {"HTTP_PROXY": "http://127.0.0.1:1", "NO_PROXY": ""}):
|
||||
pool = Pool("", source=provider.url + "/?key=source-secret")
|
||||
with httpx.Client(transport=pool, trust_env=False, cookies={"session": "target-secret"}) as client:
|
||||
response, *_ = NS["send_path_as_is"](
|
||||
client, method="GET", url="http://target.invalid/",
|
||||
headers=httpx.Headers({"Authorization": "Bearer target-secret"}))
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"ok")
|
||||
self.assertEqual(len(provider.requests), 2)
|
||||
for _, _, headers, _ in provider.requests:
|
||||
self.assertNotIn("Cookie", headers)
|
||||
self.assertNotIn("Authorization", headers)
|
||||
self.assertNotIn("Proxy-Authorization", headers)
|
||||
self.assertNotIn("secret", self.diagnostics.getvalue())
|
||||
|
||||
def test_source_validation_limits_and_errors_redact_url(self):
|
||||
for body in [b'[{"ip":"127.0.0.1"}]', b"", b"x" * (1024 * 1024 + 1)]:
|
||||
with self.subTest(size=len(body)), server(body=body) as provider:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
Pool("", source=provider.url + "/?key=secret")
|
||||
self.assertNotIn("secret", str(caught.exception))
|
||||
with server(302, headers={"Location": "http://127.0.0.1:1/?key=secret"}) as provider:
|
||||
with self.assertRaisesRegex(ValueError, "HTTP 302"):
|
||||
Pool("", source=provider.url)
|
||||
with self.assertRaisesRegex(ValueError, "HTTP\\(S\\)"):
|
||||
Pool("", source="file:///secret")
|
||||
|
||||
def test_source_exhaustion_refresh_is_bounded(self):
|
||||
with server(403) as blocked, server(body=blocked.url.encode()) as provider:
|
||||
with httpx.Client(transport=Pool("", source=provider.url, cooldown=0), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(len(provider.requests), 2)
|
||||
self.assertEqual(len(blocked.requests), 1)
|
||||
|
||||
def test_proxy_auth_never_in_diagnostics(self):
|
||||
with server() as good:
|
||||
proxy = good.url.replace("http://", "http://private-user:private-password@")
|
||||
with httpx.Client(transport=Pool(proxy), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
response.read()
|
||||
self.assertIn("Proxy-Authorization", good.requests[0][2])
|
||||
self.assertNotIn("private", self.diagnostics.getvalue())
|
||||
|
||||
def test_redirects_keep_literal_path(self):
|
||||
def reply(handler):
|
||||
if handler.path.endswith("/start"):
|
||||
return 302, {"Location": "/x/../final"}, b""
|
||||
return 200, {}, b"redirected"
|
||||
with server(reply=reply) as proxy:
|
||||
with httpx.Client(transport=Pool(proxy.url), trust_env=False) as client:
|
||||
response, final_url, _, history = send(client, url="http://target.invalid/start", follow_redirects=True)
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"redirected")
|
||||
self.assertEqual(final_url, "http://target.invalid/x/../final")
|
||||
for item in history:
|
||||
item.close()
|
||||
self.assertEqual(proxy.requests[-1][1], "http://target.invalid/x/../final")
|
||||
|
||||
@unittest.skipUnless(shutil.which("openssl"), "openssl required for local TLS fixture")
|
||||
def test_https_connect_switches_on_decrypted_status(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cert = str(Path(directory) / "cert.pem")
|
||||
key = str(Path(directory) / "key.pem")
|
||||
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1",
|
||||
"-subj", "/CN=target.invalid", "-keyout", key, "-out", cert],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
tls.load_cert_chain(cert, key)
|
||||
with server(403, b"tls-blocked", tls=tls) as blocked, server(tls=tls) as good:
|
||||
with server(tunnel_port=blocked.server_port) as first, server(tunnel_port=good.server_port) as second:
|
||||
pool = Pool(json.dumps([first.url, second.url]), transport_kwargs={"verify": False})
|
||||
with httpx.Client(transport=pool, trust_env=False) as client:
|
||||
response, *_ = send(client, url="https://target.invalid/a/../b")
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"ok")
|
||||
self.assertEqual(blocked.requests[0][1], "/a/../b")
|
||||
self.assertEqual(good.requests[0][1], "/a/../b")
|
||||
self.assertEqual(first.requests[0][0], "CONNECT")
|
||||
self.assertEqual(second.requests[0][0], "CONNECT")
|
||||
|
||||
@unittest.skipUnless(importlib.util.find_spec("socksio"), "install httpx[socks] for SOCKS fixture")
|
||||
def test_socks5_switches_and_preserves_path(self):
|
||||
with server(403) as blocked, server() as good:
|
||||
with socks_server(blocked.server_port) as first, socks_server(good.server_port) as second:
|
||||
with httpx.Client(transport=Pool(json.dumps([first.url, second.url])), trust_env=False) as client:
|
||||
response, *_ = send(client)
|
||||
with contextlib.closing(response):
|
||||
self.assertEqual(response.read(), b"ok")
|
||||
self.assertEqual(first.requests, [("target.invalid", 80)])
|
||||
self.assertEqual(second.requests, [("target.invalid", 80)])
|
||||
self.assertEqual(good.requests[0][1], "/a/../b?x=%2F")
|
||||
|
||||
def run_cli(self, *args):
|
||||
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"})
|
||||
|
||||
def test_cli_pool_exhaustion_exit_code_and_no_direct_probe(self):
|
||||
with server(403, b"blocked evidence") as proxy:
|
||||
result = self.run_cli("--url", "http://target.invalid/", "--proxy-pool", proxy.url)
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertIn("blocked evidence", result.stdout)
|
||||
self.assertIn("direct fallback disabled", result.stdout)
|
||||
self.assertNotIn("DNS", result.stdout)
|
||||
|
||||
def test_cli_single_proxy_and_no_pool_remain_compatible(self):
|
||||
with server(body=b"single-proxy") as proxy:
|
||||
result = self.run_cli("--url", "http://target.invalid/", "--proxy", proxy.url)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("single-proxy", result.stdout)
|
||||
with server(body=b"direct") as target:
|
||||
result = self.run_cli("--url", target.url, "--additional-args", "trust_env=false")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("direct", result.stdout)
|
||||
|
||||
def test_cli_conflicting_proxy_options_fail_before_network(self):
|
||||
result = self.run_cli("--url", "http://target.invalid", "--proxy", "localhost:8000",
|
||||
"--proxy-pool", "localhost:8001")
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertIn("mutually exclusive", result.stderr)
|
||||
|
||||
def test_cli_pool_flags(self):
|
||||
# Exercise all public pool flags through the real CLI parser.
|
||||
with server() as proxy:
|
||||
result = self.run_cli("--url", "http://target.invalid/", "--proxy-pool", proxy.url,
|
||||
"--proxy-max-attempts", "1", "--proxy-cooldown", "0",
|
||||
"--proxy-fail-status", "none")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,7 +4,10 @@ args:
|
||||
- "-c"
|
||||
- |
|
||||
import argparse
|
||||
import datetime
|
||||
import email.utils
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
@@ -274,6 +277,227 @@ args:
|
||||
request.url = original_url
|
||||
|
||||
|
||||
def parse_proxy_list(raw):
|
||||
"""Accept newline-separated endpoints or JSON strings/{proxies: [...]}.
|
||||
|
||||
Validate the entire update before using it. Never include credentials in errors.
|
||||
"""
|
||||
if isinstance(raw, str):
|
||||
raw = raw.strip()
|
||||
if not raw:
|
||||
return []
|
||||
if raw.startswith(("[", "{")):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid proxy list JSON") from None
|
||||
else:
|
||||
raw = raw.splitlines()
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get("proxies", raw.get("data"))
|
||||
if not isinstance(raw, list) or len(raw) > 256:
|
||||
raise ValueError("Proxy list must contain at most 256 entries")
|
||||
proxies = []
|
||||
for value in raw:
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("Proxy entries must be URL strings or host:port strings")
|
||||
value = value.strip()
|
||||
if not value:
|
||||
continue
|
||||
if "://" not in value:
|
||||
value = "http://" + value
|
||||
try:
|
||||
parts = urllib.parse.urlsplit(value)
|
||||
valid = (
|
||||
parts.scheme.lower() in {"http", "https", "socks5"}
|
||||
and parts.hostname and parts.port and 0 < parts.port <= 65535
|
||||
and parts.path in {"", "/"} and not parts.query and not parts.fragment
|
||||
and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value)
|
||||
)
|
||||
if not valid:
|
||||
raise ValueError()
|
||||
# Normalize host/scheme for deduplication, preserving encoded credentials.
|
||||
host = parts.hostname.lower()
|
||||
if ":" in host:
|
||||
host = "[" + host + "]"
|
||||
auth = parts.netloc.rsplit("@", 1)[0] + "@" if "@" in parts.netloc else ""
|
||||
value = f"{parts.scheme.lower()}://{auth}{host}:{parts.port}"
|
||||
httpx.URL(value)
|
||||
except (ValueError, httpx.InvalidURL):
|
||||
raise ValueError("Invalid proxy endpoint (expected http(s)://host:port or socks5://host:port)") from None
|
||||
if value not in proxies:
|
||||
proxies.append(value)
|
||||
return proxies
|
||||
|
||||
|
||||
def fetch_proxy_source(source):
|
||||
try:
|
||||
parts = urllib.parse.urlsplit(source)
|
||||
if parts.scheme not in {"http", "https"} or not parts.hostname or parts.fragment:
|
||||
raise ValueError()
|
||||
httpx.URL(source)
|
||||
except (ValueError, httpx.InvalidURL):
|
||||
raise ValueError("Proxy source must be an HTTP(S) URL") from None
|
||||
# Separate control-plane client: no target cookies, headers, proxy or env proxy.
|
||||
try:
|
||||
with httpx.Client(timeout=10.0, trust_env=False, follow_redirects=False) as client:
|
||||
with client.stream("GET", source) as response:
|
||||
if response.status_code != 200:
|
||||
raise ValueError("Proxy source returned HTTP " + str(response.status_code))
|
||||
body = bytearray()
|
||||
for chunk in response.iter_bytes(chunk_size=65536):
|
||||
body.extend(chunk)
|
||||
if len(body) > 1024 * 1024:
|
||||
raise ValueError("Proxy source response exceeds 1 MiB")
|
||||
proxies = parse_proxy_list(body.decode("utf-8-sig"))
|
||||
if not proxies:
|
||||
raise ValueError("Proxy source returned an empty list")
|
||||
return proxies
|
||||
except (httpx.HTTPError, UnicodeError):
|
||||
raise ValueError("Could not fetch proxy source (check connectivity, credentials and TLS)") from None
|
||||
|
||||
|
||||
def retry_after_seconds(value):
|
||||
if not value:
|
||||
return 0.0
|
||||
value = value.strip()
|
||||
if value.isascii() and value.isdigit():
|
||||
value = value.lstrip("0") or "0"
|
||||
return 86400.0 if len(value) > 6 else float(min(int(value), 86400))
|
||||
try:
|
||||
date = email.utils.parsedate_to_datetime(value)
|
||||
if date.tzinfo is None:
|
||||
date = date.replace(tzinfo=datetime.timezone.utc)
|
||||
return min(86400.0, max(0.0, (date - datetime.datetime.now(datetime.timezone.utc)).total_seconds()))
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return 0.0
|
||||
|
||||
|
||||
class ProxyPoolTransport(httpx.BaseTransport):
|
||||
"""Invocation-local sticky proxy pool; retries only GET/HEAD/OPTIONS headers.
|
||||
|
||||
Each hop has a bounded budget and never falls back to a direct connection.
|
||||
Body-stream failures are surfaced rather than replaying a partial response.
|
||||
"""
|
||||
RETRY_METHODS = {"GET", "HEAD", "OPTIONS"}
|
||||
|
||||
def __init__(self, proxies, source="", max_attempts=3, cooldown=60.0,
|
||||
fail_status="403,429", transport_kwargs=None):
|
||||
if not 1 <= max_attempts <= 10:
|
||||
raise ValueError("proxy_max_attempts must be between 1 and 10")
|
||||
if not math.isfinite(cooldown) or not 0 <= cooldown <= 86400:
|
||||
raise ValueError("proxy_cooldown must be between 0 and 86400 seconds")
|
||||
try:
|
||||
statuses = set() if fail_status.strip().lower() == "none" else {
|
||||
int(v.strip()) for v in fail_status.split(",") if v.strip()
|
||||
}
|
||||
if any(v < 400 or v > 599 for v in statuses):
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise ValueError("proxy_fail_status must be comma-separated HTTP error codes (400-599)") from None
|
||||
self.proxies = parse_proxy_list(proxies)
|
||||
self.source = source.strip()
|
||||
self.max_attempts = max_attempts
|
||||
self.cooldown = cooldown
|
||||
self.fail_status = statuses
|
||||
self.transport_kwargs = dict(transport_kwargs or {})
|
||||
self.transport_kwargs.pop("proxy", None)
|
||||
self.transport_kwargs["trust_env"] = False
|
||||
self.transports = {}
|
||||
self.cooling = {}
|
||||
self.target_wait = {}
|
||||
self.current = None
|
||||
if self.source:
|
||||
self.refresh()
|
||||
if not self.proxies:
|
||||
raise ValueError("Proxy pool has no endpoints")
|
||||
|
||||
def refresh(self):
|
||||
proxies = fetch_proxy_source(self.source)
|
||||
merged = list(dict.fromkeys(self.proxies + proxies))
|
||||
if len(merged) > 256:
|
||||
raise ValueError("Proxy pool exceeds 256 endpoints")
|
||||
self.proxies = merged
|
||||
|
||||
def select(self, attempted):
|
||||
now = time.monotonic()
|
||||
candidates = ([self.current] if self.current else []) + self.proxies
|
||||
for proxy in candidates:
|
||||
if proxy not in attempted and self.cooling.get(proxy, 0) <= now:
|
||||
self.current = proxy
|
||||
return proxy
|
||||
return None
|
||||
|
||||
def handle_request(self, request):
|
||||
target = (request.url.scheme, request.url.host, request.url.port)
|
||||
if self.target_wait.get(target, 0) > time.monotonic():
|
||||
raise httpx.ProxyError("Target Retry-After is still active; no request sent", request=request)
|
||||
attempted = set()
|
||||
refreshed = False
|
||||
retryable = request.method.upper() in self.RETRY_METHODS
|
||||
for attempt in range(1, self.max_attempts + 1):
|
||||
proxy = self.select(attempted)
|
||||
if proxy is None and self.source and not refreshed:
|
||||
refreshed = True
|
||||
try:
|
||||
self.refresh()
|
||||
except ValueError as exc:
|
||||
raise httpx.ProxyError(str(exc), request=request) from None
|
||||
proxy = self.select(attempted)
|
||||
if proxy is None:
|
||||
raise httpx.ProxyError("Proxy pool exhausted: no unused healthy endpoint; direct fallback disabled", request=request)
|
||||
attempted.add(proxy)
|
||||
label = self.proxies.index(proxy) + 1
|
||||
print(f"[proxy pool] attempt {attempt}/{self.max_attempts} via proxy #{label}", file=sys.stderr)
|
||||
try:
|
||||
if proxy not in self.transports:
|
||||
self.transports[proxy] = PathAsIsTransport(proxy=proxy, **self.transport_kwargs)
|
||||
response = self.transports[proxy].handle_request(request)
|
||||
except ImportError:
|
||||
raise httpx.ProxyError("SOCKS support requires pip install 'httpx[socks]'", request=request) from None
|
||||
except httpx.TransportError as exc:
|
||||
self.cooling[proxy] = time.monotonic() + self.cooldown
|
||||
print(f"[proxy pool] proxy #{label}: {type(exc).__name__}; cooling down", file=sys.stderr)
|
||||
if not retryable or attempt == self.max_attempts:
|
||||
raise httpx.ProxyError(
|
||||
f"Proxy pool request failed ({type(exc).__name__}); automatic replay stopped",
|
||||
request=request,
|
||||
) from None
|
||||
continue
|
||||
blocked = response.status_code in self.fail_status
|
||||
wait = retry_after_seconds(response.headers.get("Retry-After")) if response.status_code == 429 else 0.0
|
||||
response.extensions["proxy_pool"] = {"proxy": label, "attempts": attempt, "failed": blocked}
|
||||
if wait > 0:
|
||||
self.target_wait[target] = time.monotonic() + wait
|
||||
print("[proxy pool] Retry-After received; automatic replay stopped, retry later", file=sys.stderr)
|
||||
if not blocked:
|
||||
return response
|
||||
self.cooling[proxy] = time.monotonic() + max(self.cooldown, wait)
|
||||
print(f"[proxy pool] proxy #{label}: HTTP {response.status_code} matched failure policy; cooling down", file=sys.stderr)
|
||||
if not retryable:
|
||||
print("[proxy pool] method is not GET/HEAD/OPTIONS; automatic replay stopped", file=sys.stderr)
|
||||
if not retryable or wait > 0 or attempt == self.max_attempts:
|
||||
return response
|
||||
# Keep the last response observable if no replacement is available.
|
||||
available = self.select(attempted)
|
||||
if available is None and self.source and not refreshed:
|
||||
refreshed = True
|
||||
try:
|
||||
self.refresh()
|
||||
except ValueError as exc:
|
||||
print(f"[proxy pool] {exc}; preserving last response", file=sys.stderr)
|
||||
available = self.select(attempted)
|
||||
if available is None:
|
||||
print("[proxy pool] no replacement available; preserving last response", file=sys.stderr)
|
||||
return response
|
||||
response.close()
|
||||
raise httpx.ProxyError("Proxy pool attempt budget exhausted", request=request)
|
||||
|
||||
def close(self):
|
||||
for transport in self.transports.values():
|
||||
transport.close()
|
||||
|
||||
|
||||
def send_path_as_is(
|
||||
client: "httpx.Client",
|
||||
*,
|
||||
@@ -964,6 +1188,11 @@ args:
|
||||
parser.add_argument("--cookies", default="")
|
||||
parser.add_argument("--user-agent", dest="user_agent", default="")
|
||||
parser.add_argument("--proxy", default="")
|
||||
parser.add_argument("--proxy-pool", default="")
|
||||
parser.add_argument("--proxy-source", default="")
|
||||
parser.add_argument("--proxy-max-attempts", type=int, default=3)
|
||||
parser.add_argument("--proxy-cooldown", type=float, default=60.0)
|
||||
parser.add_argument("--proxy-fail-status", default="403,429")
|
||||
parser.add_argument("--timeout", default="")
|
||||
parser.add_argument("--repeat", type=int, default=1)
|
||||
parser.add_argument("--delay", default="0")
|
||||
@@ -1118,6 +1347,9 @@ args:
|
||||
sys.exit(1)
|
||||
cert = additional_options.get("cert")
|
||||
explicit_proxy = (args.proxy or "").strip()
|
||||
pool_enabled = bool(args.proxy_pool.strip() or args.proxy_source.strip())
|
||||
if pool_enabled and explicit_proxy:
|
||||
parser.error("proxy and proxy_pool/proxy_source are mutually exclusive")
|
||||
forward_proxy = resolve_forward_proxy(explicit_proxy, trust_env, encoded_url)
|
||||
|
||||
transport_kwargs = {
|
||||
@@ -1133,6 +1365,19 @@ args:
|
||||
if forward_proxy:
|
||||
transport_kwargs["proxy"] = forward_proxy
|
||||
|
||||
if pool_enabled:
|
||||
try:
|
||||
transport = ProxyPoolTransport(
|
||||
args.proxy_pool, source=args.proxy_source,
|
||||
max_attempts=args.proxy_max_attempts, cooldown=args.proxy_cooldown,
|
||||
fail_status=args.proxy_fail_status, transport_kwargs=transport_kwargs,
|
||||
)
|
||||
except ValueError as exc:
|
||||
parser.error(str(exc))
|
||||
forward_proxy = ""
|
||||
else:
|
||||
transport = PathAsIsTransport(**transport_kwargs)
|
||||
|
||||
# Always path-as-is (security-testing default; matches curl --path-as-is)
|
||||
initial_absolute = needs_http_absolute_form(forward_proxy, encoded_url)
|
||||
initial_wire_target = wire_request_target(encoded_url, absolute_form=initial_absolute)
|
||||
@@ -1143,8 +1388,8 @@ args:
|
||||
"verify": verify_option,
|
||||
"follow_redirects": False, # redirects handled by send_path_as_is
|
||||
"cookies": cookie_jar,
|
||||
"trust_env": trust_env,
|
||||
"transport": PathAsIsTransport(**transport_kwargs),
|
||||
"trust_env": False if pool_enabled else trust_env,
|
||||
"transport": transport,
|
||||
}
|
||||
|
||||
if args.show_command:
|
||||
@@ -1164,7 +1409,7 @@ args:
|
||||
|
||||
exit_code = 0
|
||||
verify_tls = verify_option if isinstance(verify_option, bool) else True
|
||||
skip_probe = bool(forward_proxy)
|
||||
skip_probe = pool_enabled or bool(forward_proxy)
|
||||
|
||||
client = httpx.Client(**client_kwargs)
|
||||
try:
|
||||
@@ -1214,6 +1459,12 @@ args:
|
||||
decoded_body, used_encoding, encoding_source = decode_body_bytes(bytes(body_buffer), response.headers, args.response_encoding)
|
||||
|
||||
print(f"\n===== Response #{run_index + 1} =====")
|
||||
pool_meta = response.extensions.get("proxy_pool")
|
||||
if pool_meta:
|
||||
print(f"[proxy pool] final proxy #{pool_meta['proxy']}, attempts={pool_meta['attempts']}")
|
||||
if pool_meta["failed"]:
|
||||
exit_code = 1
|
||||
print("[proxy pool] failure policy still matched; response preserved, direct fallback disabled")
|
||||
download_target = (args.download or "").strip()
|
||||
if download_target:
|
||||
# 支持多次请求时通过 {i} 占位符区分文件名
|
||||
@@ -1344,7 +1595,7 @@ args:
|
||||
print("\nInterrupted.", file=sys.stderr)
|
||||
sys.exit(130)
|
||||
enabled: true
|
||||
short_description: "纯Python HTTP测试框架(httpx,会话复用+编码守护)"
|
||||
short_description: "纯Python HTTP测试框架(httpx,代理池切换+会话复用+编码守护)"
|
||||
description: |
|
||||
纯 Python 构建的 HTTP 测试框架:基于 httpx 会话,结合 socket 探针补齐 DNS/TCP/TLS 观测,
|
||||
提供全流程的请求体编码守护、重复播放与可观测能力,适配盲注延时、复杂 payload 调优等场景。
|
||||
@@ -1358,6 +1609,7 @@ description: |
|
||||
- 可重复观测:repeat/delay + TTFB/total/speed_download 统计,便于盲注/时序测试
|
||||
- 扩展开关:http2 / httpx_options 解析 http2、cert、verify、trust_env、max_redirects 等 httpx 选项
|
||||
- 响应体瘦身:response_filter 按行/块正则提取,配合 max_lines/max_bytes 限制 stdout,降低 Agent token 消耗
|
||||
- 代理池:proxy_pool 列表 / proxy_source HTTP(S) 接口,故障冷却与有界切换;仅自动重放 GET/HEAD/OPTIONS,429 Retry-After 停止重放;耗尽不直连
|
||||
|
||||
**响应过滤最佳实践:**
|
||||
- 大页面/HTML:用 `response_filter` 抓 error|exception|password|token|uid 等关键字行
|
||||
@@ -1401,6 +1653,34 @@ parameters:
|
||||
description: "代理(http(s)://或socks5://地址,直接传递给httpx Client)"
|
||||
required: false
|
||||
flag: "--proxy"
|
||||
- name: "proxy_pool"
|
||||
type: "string"
|
||||
description: "代理池:JSON 字符串数组或换行列表,支持 http(s)://host:port、socks5://host:port;与 proxy 互斥;状态仅在本次工具调用内保留"
|
||||
required: false
|
||||
flag: "--proxy-pool"
|
||||
- name: "proxy_source"
|
||||
type: "string"
|
||||
description: "用户配置的代理供应商 HTTP(S) 接口;返回换行列表、JSON 数组或 {proxies:[...]} / {data:[...]};开始及耗尽时有界拉取;与 proxy 互斥"
|
||||
required: false
|
||||
flag: "--proxy-source"
|
||||
- name: "proxy_max_attempts"
|
||||
type: "int"
|
||||
description: "每个请求/重定向跳的代理尝试上限(1-10);每个代理最多尝试一次;仅 GET/HEAD/OPTIONS 自动重放"
|
||||
required: false
|
||||
default: 3
|
||||
flag: "--proxy-max-attempts"
|
||||
- name: "proxy_cooldown"
|
||||
type: "string"
|
||||
description: "失败代理冷却秒数(0-86400,默认60);仅在本次工具调用内生效"
|
||||
required: false
|
||||
default: "60"
|
||||
flag: "--proxy-cooldown"
|
||||
- name: "proxy_fail_status"
|
||||
type: "string"
|
||||
description: "触发代理切换的 HTTP 错误状态码,逗号分隔(默认403,429);只是切换策略,不代表确认封禁;传 none 禁用状态码切换;429 带有效 Retry-After 时停止自动重放"
|
||||
required: false
|
||||
default: "403,429"
|
||||
flag: "--proxy-fail-status"
|
||||
- name: "timeout"
|
||||
type: "string"
|
||||
description: "最大超时时间(秒,支持小数)"
|
||||
|
||||
Reference in new issue
Block a user