Files
spark-mcp/internal/httpclient/redirect.go
T
tao.chenandClaude 2c39091706 Phase 3+4: 共享 HTTP 客户端 + admin API + audit log
Phase 3 (httpclient):
- shared Client (Timeout + MaxResponseBytes 截断)
- SSRF: 16 段私网 CIDR (含 169.254/::ffff:0:0/96 IPv4-mapped)
  + hostname allowlist (精确/后缀/*. 通配)
  + scheme 校验 (仅 http/https)
- auth 适配器: none / simple (YARN user.name) / basic (SetBasicAuth)
- DoWithRedirect: 跨主机跳转保留 Authorization, max 5 默认
- 19 个测试全绿 (httptest 模拟)

Phase 4 (admin + audit):
- internal/audit: Entry + Repo.Insert/List + MarshalDetails, snake_case JSON
- internal/middleware: AdminAuth/AgentAuth (constant-time 比对)
- internal/admin: 6 端点 (GET/POST/PUT/DELETE /admin/clusters, GET /admin/audit)
  + 写操作触发 audit_log (含 before/after diff)
  + AuthPassword 空=保留旧密码
  + 校验: 必填字段 + auth_type 枚举 + rate_limit>=0
- main.go: 挂载 storage.Open + admin.Mount
- L fix: audit.Entry 加 json tag (smoke test 发现大写 key 不规范)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-10 13:54:24 +08:00

63 lines
1.6 KiB
Go

package httpclient
import (
"context"
"errors"
"fmt"
"net/http"
)
const defaultMaxRedirects = 5
// DoWithRedirect 手动跟随 3xx,跨主机跳转保留 Authorization header。
// maxRedirects == 0 禁止 redirect(等同 Do)
// maxRedirects < 0 用 defaultMaxRedirects
func (c *Client) DoWithRedirect(ctx context.Context, req *http.Request, maxRedirects int, allowedHosts ...string) (*http.Response, error) {
if maxRedirects == 0 {
return c.Do(ctx, req, allowedHosts...)
}
if maxRedirects < 0 {
maxRedirects = defaultMaxRedirects
}
current := req
remaining := maxRedirects
for {
resp, err := c.Do(ctx, current, allowedHosts...)
if err != nil {
return nil, err
}
if resp.StatusCode < 300 || resp.StatusCode >= 400 {
return resp, nil
}
// 3xx
if remaining == 0 {
_ = resp.Body.Close()
return nil, errors.New("httpclient: too many redirects")
}
remaining--
loc := resp.Header.Get("Location")
if loc == "" {
_ = resp.Body.Close()
return nil, fmt.Errorf("httpclient: %d %s without Location header", resp.StatusCode, resp.Status)
}
next, err := current.URL.Parse(loc)
if err != nil {
_ = resp.Body.Close()
return nil, fmt.Errorf("httpclient: parse redirect Location %q: %w", loc, err)
}
_ = resp.Body.Close()
newReq, err := http.NewRequestWithContext(ctx, current.Method, next.String(), nil)
if err != nil {
return nil, fmt.Errorf("httpclient: build redirect request: %w", err)
}
// **保留** header (Authorization 等)
newReq.Header = current.Header.Clone()
newReq.Body = nil
current = newReq
}
}