Files
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

61 lines
1.4 KiB
Go

package httpclient
import (
"context"
"io"
"net/http"
"time"
)
// Config tunes the shared HTTP client.
type Config struct {
Timeout time.Duration // e.g. 30s
MaxResponseBytes int64 // e.g. 1 << 20
}
// Client is a thin, SSRF-aware wrapper around net/http.Client.
type Client struct {
cfg Config
hc *http.Client
}
// New creates a Client with redirect following disabled.
// Redirect handling is intentionally left to DoWithRedirect.
func New(cfg Config) *Client {
return &Client{
cfg: cfg,
hc: &http.Client{
Timeout: cfg.Timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
},
}
}
// Do executes a single HTTP request. The response body is truncated to
// MaxResponseBytes. The request URL is validated by CheckURL before sending;
// hosts listed in allowedHosts bypass SSRF checks.
//
// TODO(prod): implement IP-pinned dialer to fully close TOCTOU between the
// SSRF check here and the actual TCP dial performed by net/http.
func (c *Client) Do(ctx context.Context, req *http.Request, allowedHosts ...string) (*http.Response, error) {
if err := CheckURL(req.URL.String(), allowedHosts...); err != nil {
return nil, err
}
resp, err := c.hc.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
resp.Body = struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(resp.Body, c.cfg.MaxResponseBytes),
Closer: resp.Body,
}
return resp, nil
}