File size: 21,010 Bytes
ea775bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | package proxy
import (
"io"
"net/http"
"net/http/httptrace"
"net/http/httputil"
"net/url"
"strings"
"sync"
"github.com/Resinat/Resin/internal/config"
"github.com/Resinat/Resin/internal/netutil"
"github.com/Resinat/Resin/internal/outbound"
"github.com/Resinat/Resin/internal/platform"
"github.com/Resinat/Resin/internal/routing"
)
// PlatformLookup provides read-only access to platforms.
type PlatformLookup interface {
GetPlatform(id string) (*platform.Platform, bool)
GetPlatformByName(name string) (*platform.Platform, bool)
}
// ReverseProxyConfig holds dependencies for the reverse proxy.
type ReverseProxyConfig struct {
ProxyToken string
AuthVersion string
Router *routing.Router
Pool outbound.PoolAccessor
PlatformLookup PlatformLookup
Health HealthRecorder
Matcher AccountRuleMatcher
Events EventEmitter
MetricsSink MetricsEventSink
OutboundTransport OutboundTransportConfig
TransportPool *OutboundTransportPool
ProxyBypassRules []string
}
// ReverseProxy implements an HTTP reverse proxy.
// Identity segment format depends on auth version:
// V1: /PROXY_TOKEN/Platform.Account/protocol/host/path?query
// LEGACY_V0: /PROXY_TOKEN/Platform:Account/protocol/host/path?query
type ReverseProxy struct {
token string
authVersion config.AuthVersion
router *routing.Router
pool outbound.PoolAccessor
platLook PlatformLookup
health HealthRecorder
matcher AccountRuleMatcher
events EventEmitter
metricsSink MetricsEventSink
transportConfig OutboundTransportConfig
transportPool *OutboundTransportPool
transportPoolOnce sync.Once
directTransport *http.Transport
directOnce sync.Once
bypass *TargetBypassMatcher
}
// NewReverseProxy creates a new reverse proxy handler.
func NewReverseProxy(cfg ReverseProxyConfig) *ReverseProxy {
ev := cfg.Events
if ev == nil {
ev = NoOpEventEmitter{}
}
transportCfg := normalizeOutboundTransportConfig(cfg.OutboundTransport)
transportPool := cfg.TransportPool
if transportPool == nil {
transportPool = NewOutboundTransportPool(transportCfg)
}
authVersion := config.NormalizeAuthVersion(cfg.AuthVersion)
if authVersion == "" {
authVersion = config.AuthVersionLegacyV0
}
return &ReverseProxy{
token: cfg.ProxyToken,
authVersion: authVersion,
router: cfg.Router,
pool: cfg.Pool,
platLook: cfg.PlatformLookup,
health: cfg.Health,
matcher: cfg.Matcher,
events: ev,
metricsSink: cfg.MetricsSink,
transportConfig: transportCfg,
transportPool: transportPool,
bypass: NewTargetBypassMatcher(cfg.ProxyBypassRules),
}
}
func (p *ReverseProxy) effectiveAuthVersion() config.AuthVersion {
if p == nil {
return config.AuthVersionLegacyV0
}
if p.authVersion == config.AuthVersionV1 {
return config.AuthVersionV1
}
return config.AuthVersionLegacyV0
}
func (p *ReverseProxy) outboundHTTPTransport(routed routedOutbound) *http.Transport {
p.transportPoolOnce.Do(func() {
if p.transportPool == nil {
p.transportPool = NewOutboundTransportPool(p.transportConfig)
}
})
return p.transportPool.Get(routed.Route.NodeHash, routed.Outbound, p.metricsSink)
}
func (p *ReverseProxy) directHTTPTransport() *http.Transport {
p.directOnce.Do(func() {
p.directTransport = newDirectHTTPTransport(p.transportConfig, p.metricsSink)
})
return p.directTransport
}
// parsedPath holds the result of parsing a reverse proxy request path.
type parsedPath struct {
PlatformName string
Account string
Protocol string
Host string
// Path preserves the original escaped remaining path after host (may be
// empty), e.g. "v1/users/team%2Fa/profile".
Path string
}
// forwardingIdentityHeaders are commonly used to disclose proxy chain identity.
// These are stripped from outbound reverse-proxy requests.
var forwardingIdentityHeaders = []string{
// Internal account override header must not leak to upstream services.
"X-Resin-Account",
"Forwarded",
"X-Forwarded-For",
"X-Forwarded-Host",
"X-Forwarded-Proto",
"X-Forwarded-Port",
"X-Forwarded-Server",
"Via",
"X-Real-IP",
"X-Client-IP",
"True-Client-IP",
"CF-Connecting-IP",
"X-ProxyUser-Ip",
}
func stripForwardingIdentityHeaders(header http.Header) {
if header == nil {
return
}
for _, h := range forwardingIdentityHeaders {
header.Del(h)
}
// net/http/httputil.ReverseProxy with Director auto-populates X-Forwarded-For
// unless the header key exists with a nil value.
header["X-Forwarded-For"] = nil
}
// decodePathSegmentV1 decodes one escaped URL path segment for V1 parsing.
//
// This function intentionally duplicates legacy decoding logic to keep V1 and
// LEGACY_V0 parsing paths structurally independent.
func decodePathSegmentV1(segment string) (string, *ProxyError) {
decoded, err := url.PathUnescape(segment)
if err != nil {
return "", ErrURLParseError
}
return decoded, nil
}
// decodePathSegmentLegacy decodes one escaped URL path segment for LEGACY_V0
// parsing.
//
// This function intentionally duplicates V1 decoding logic so legacy code can
// be removed without touching V1 parser implementations.
func decodePathSegmentLegacy(segment string) (string, *ProxyError) {
decoded, err := url.PathUnescape(segment)
if err != nil {
return "", ErrURLParseError
}
return decoded, nil
}
// parsePath dispatches to a version-specific parser.
//
// New and legacy parsers intentionally remain isolated (including duplicated
// parsing steps) so LEGACY_V0 can be removed cleanly without touching V1 code.
func (p *ReverseProxy) parsePath(rawPath string) (*parsedPath, *ProxyError) {
if p.effectiveAuthVersion() == config.AuthVersionV1 {
return p.parsePathV1(rawPath)
}
return p.parsePathLegacy(rawPath)
}
// parsePathV1 parses reverse proxy path using V1 identity rules.
//
// rawPath must be r.URL.EscapedPath (not r.URL.Path) to preserve escaped
// delimiters in trailing path segments.
func (p *ReverseProxy) parsePathV1(rawPath string) (*parsedPath, *ProxyError) {
path := strings.TrimPrefix(rawPath, "/")
if path == "" {
return nil, ErrAuthFailed
}
segments := strings.SplitN(path, "/", 5) // token, identity, protocol, host, rest
token, perr := decodePathSegmentV1(segments[0])
if perr != nil {
return nil, perr
}
if p.token != "" && token != p.token {
return nil, ErrAuthFailed
}
if len(segments) < 4 {
return nil, ErrURLParseError
}
identity, perr := decodePathSegmentV1(segments[1])
if perr != nil {
return nil, perr
}
platName, account := parseV1PlatformAccountIdentity(identity)
protocolSeg, perr := decodePathSegmentV1(segments[2])
if perr != nil {
return nil, perr
}
protocol := strings.ToLower(protocolSeg)
if protocol != "http" && protocol != "https" {
return nil, ErrInvalidProtocol
}
host, perr := decodePathSegmentV1(segments[3])
if perr != nil {
return nil, perr
}
if host == "" {
return nil, ErrInvalidHost
}
if !isValidHost(host) {
return nil, ErrInvalidHost
}
remainingPath := ""
if len(segments) == 5 {
remainingPath = segments[4]
}
return &parsedPath{
PlatformName: platName,
Account: account,
Protocol: protocol,
Host: host,
Path: remainingPath,
}, nil
}
// parsePathLegacy parses reverse proxy path using LEGACY_V0 identity rules.
//
// This parser is intentionally independent from V1 parser code, including
// repeated parsing steps, to keep legacy removal low-risk.
func (p *ReverseProxy) parsePathLegacy(rawPath string) (*parsedPath, *ProxyError) {
path := strings.TrimPrefix(rawPath, "/")
if path == "" {
return nil, ErrAuthFailed
}
segments := strings.SplitN(path, "/", 5) // token, identity, protocol, host, rest
token, perr := decodePathSegmentLegacy(segments[0])
if perr != nil {
return nil, perr
}
if p.token != "" && token != p.token {
return nil, ErrAuthFailed
}
if len(segments) < 4 {
return nil, ErrURLParseError
}
identity, perr := decodePathSegmentLegacy(segments[1])
if perr != nil {
return nil, perr
}
if !strings.Contains(identity, ":") {
return nil, ErrURLParseError
}
platName, account := parseLegacyPlatformAccountIdentity(identity)
protocolSeg, perr := decodePathSegmentLegacy(segments[2])
if perr != nil {
return nil, perr
}
protocol := strings.ToLower(protocolSeg)
if protocol != "http" && protocol != "https" {
return nil, ErrInvalidProtocol
}
host, perr := decodePathSegmentLegacy(segments[3])
if perr != nil {
return nil, perr
}
if host == "" {
return nil, ErrInvalidHost
}
if !isValidHost(host) {
return nil, ErrInvalidHost
}
remainingPath := ""
if len(segments) == 5 {
remainingPath = segments[4]
}
return &parsedPath{
PlatformName: platName,
Account: account,
Protocol: protocol,
Host: host,
Path: remainingPath,
}, nil
}
func buildReverseTargetURL(parsed *parsedPath, rawQuery string) (*url.URL, *ProxyError) {
targetURL := parsed.Protocol + "://" + parsed.Host
if parsed.Path != "" {
targetURL += "/" + parsed.Path
}
if rawQuery != "" {
targetURL += "?" + rawQuery
}
target, err := url.Parse(targetURL)
if err != nil {
return nil, ErrInvalidHost
}
return target, nil
}
func (p *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
detailCfg := reverseDetailCaptureConfig{
Enabled: false,
ReqHeadersMaxBytes: -1,
ReqBodyMaxBytes: -1,
RespHeadersMaxBytes: -1,
RespBodyMaxBytes: -1,
}
if provider, ok := p.events.(interface {
reverseDetailCaptureConfig() reverseDetailCaptureConfig
}); ok {
detailCfg = provider.reverseDetailCaptureConfig()
}
parsed, perr := p.parsePath(r.URL.EscapedPath())
if perr != nil {
writeProxyError(w, perr)
return
}
lifecycle := newRequestLifecycle(p.events, r, ProxyTypeReverse, false)
lifecycle.setTarget(parsed.Host, "")
upstreamTrace := newUpstreamRequestTrace()
var pendingEgressHeaderBytes int64
var egressBodyCounter *countingReadCloser
var ingressBodyCounter *countingReadCloser
var upgradedStreamCounter *countingReadWriteCloser
if detailCfg.Enabled {
reqHeaders, reqHeadersLen, reqHeadersTruncated := captureHeadersWithLimit(r.Header, detailCfg.ReqHeadersMaxBytes)
lifecycle.setReqHeadersCaptured(reqHeaders, reqHeadersLen, reqHeadersTruncated)
}
if r.Body != nil && r.Body != http.NoBody {
body := r.Body
if detailCfg.Enabled {
reqBodyCapture := newPayloadCaptureReadCloser(body, detailCfg.ReqBodyMaxBytes)
body = reqBodyCapture
lifecycle.setReqBodyCapture(reqBodyCapture)
}
egressBodyCounter = newCountingReadCloser(body)
r.Body = egressBodyCounter
}
defer lifecycle.finish()
// Resolve account in three phases:
// 1) Use path account directly when present.
// 2) If extraction fails, apply miss-action (REJECT or treat-as-empty).
// 3) Continue routing with the resulting account (possibly empty).
behaviorPlatform := p.resolvePlatformForAccountBehavior(parsed.PlatformName)
account, _, extractionFailed := p.resolveReverseProxyAccount(parsed, r, behaviorPlatform)
lifecycle.setAccount(account)
if shouldRejectReverseProxyAccountExtractionFailure(extractionFailed, behaviorPlatform) {
lifecycle.setProxyError(ErrAccountRejected)
lifecycle.setHTTPStatus(ErrAccountRejected.HTTPCode)
writeProxyError(w, ErrAccountRejected)
return
}
target, targetErr := buildReverseTargetURL(parsed, r.URL.RawQuery)
if targetErr != nil {
lifecycle.setProxyError(targetErr)
lifecycle.setHTTPStatus(targetErr.HTTPCode)
writeProxyError(w, targetErr)
return
}
lifecycle.setTarget(parsed.Host, target.String())
var route routing.RouteResult
var hasRoute bool
var transport *http.Transport
var nodeHashRaw = route.NodeHash
domain := netutil.ExtractDomain(parsed.Host)
if p.bypass != nil && p.bypass.ShouldBypass(parsed.Host) {
transport = p.directHTTPTransport()
} else {
routed, routeErr := resolveRoutedOutbound(p.router, p.pool, parsed.PlatformName, account, parsed.Host)
if routeErr != nil {
lifecycle.setProxyError(routeErr)
lifecycle.setHTTPStatus(routeErr.HTTPCode)
writeProxyError(w, routeErr)
return
}
route = routed.Route
hasRoute = true
nodeHashRaw = route.NodeHash
lifecycle.setRouteResult(route)
if p.health != nil {
go p.health.RecordLatency(nodeHashRaw, domain, nil)
}
transport = p.outboundHTTPTransport(routed)
}
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL = target
req.Host = parsed.Host
stripForwardingIdentityHeaders(req.Header)
pendingEgressHeaderBytes = headerWireLen(req.Header)
// Compose request-progress trace first so egress commit logic can
// observe whether the upstream request was actually written.
reqCtx := httptrace.WithClientTrace(req.Context(), upstreamTrace.clientTrace())
// Add httptrace for TLS latency measurement on HTTPS.
if parsed.Protocol == "https" && hasRoute && p.health != nil {
reporter := newReverseLatencyReporter(p.health, nodeHashRaw, domain)
reqCtx = httptrace.WithClientTrace(reqCtx, reporter.clientTrace())
}
*req = *req.WithContext(reqCtx)
},
Transport: transport,
ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
proxyErr := classifyUpstreamError(err)
if proxyErr == nil {
// context.Canceled — no health recording, silently close.
// Treat as net-ok for request-log semantics when canceled
// before upstream response.
lifecycle.setNetOK(true)
return
}
lifecycle.setProxyError(proxyErr)
lifecycle.setUpstreamError("reverse_roundtrip", err)
lifecycle.setNetOK(false)
lifecycle.setHTTPStatus(proxyErr.HTTPCode)
if hasRoute {
recordPassiveResultAsync(p.health, route, false)
}
writeProxyError(rw, proxyErr)
},
ModifyResponse: func(resp *http.Response) error {
lifecycle.setHTTPStatus(resp.StatusCode)
lifecycle.addIngressBytes(headerWireLen(resp.Header))
if resp.StatusCode == http.StatusSwitchingProtocols {
// 101 upgrade responses require a writable backend body
// (io.ReadWriteCloser). Do not wrap resp.Body here; wrapping with a
// read-only wrapper breaks websocket/h2c upgrade tunneling in
// net/http/httputil.ReverseProxy.
//
// We can still account upgrade-session traffic by wrapping with a
// read-write counter that preserves io.ReadWriteCloser semantics.
if rwc, ok := resp.Body.(io.ReadWriteCloser); ok {
upgradedStreamCounter = newCountingReadWriteCloser(rwc)
resp.Body = upgradedStreamCounter
}
if detailCfg.Enabled {
respHeaders, respHeadersLen, respHeadersTruncated := captureHeadersWithLimit(resp.Header, detailCfg.RespHeadersMaxBytes)
lifecycle.setRespHeadersCaptured(respHeaders, respHeadersLen, respHeadersTruncated)
}
lifecycle.setNetOK(true)
if hasRoute {
recordPassiveResultAsync(p.health, route, true)
}
return nil
}
if resp.Body != nil && resp.Body != http.NoBody {
body := resp.Body
if detailCfg.Enabled {
respHeaders, respHeadersLen, respHeadersTruncated := captureHeadersWithLimit(resp.Header, detailCfg.RespHeadersMaxBytes)
lifecycle.setRespHeadersCaptured(respHeaders, respHeadersLen, respHeadersTruncated)
respBodyCapture := newPayloadCaptureReadCloser(body, detailCfg.RespBodyMaxBytes)
body = respBodyCapture
lifecycle.setRespBodyCapture(respBodyCapture)
}
ingressBodyCounter = newCountingReadCloser(body)
resp.Body = ingressBodyCounter
} else if detailCfg.Enabled {
respHeaders, respHeadersLen, respHeadersTruncated := captureHeadersWithLimit(resp.Header, detailCfg.RespHeadersMaxBytes)
lifecycle.setRespHeadersCaptured(respHeaders, respHeadersLen, respHeadersTruncated)
}
// Intentional coarse-grained policy:
// mark node success once upstream response headers arrive.
// Further attribution for mid-body stream failures is expensive and noisy
// (client abort vs upstream reset vs network blip), and the added
// complexity is not worth it for the current phase.
lifecycle.setNetOK(true)
if hasRoute {
recordPassiveResultAsync(p.health, route, true)
}
return nil
},
}
proxy.ServeHTTP(w, r)
if upstreamTrace.shouldCommitEgress() {
lifecycle.addEgressBytes(pendingEgressHeaderBytes)
if egressBodyCounter != nil {
lifecycle.addEgressBytes(egressBodyCounter.Total())
}
}
if ingressBodyCounter != nil {
lifecycle.addIngressBytes(ingressBodyCounter.Total())
}
if upgradedStreamCounter != nil {
lifecycle.addIngressBytes(upgradedStreamCounter.TotalRead())
lifecycle.addEgressBytes(upgradedStreamCounter.TotalWrite())
}
}
// resolveDefaultPlatform looks up the default platform for reverse-proxy
// miss-action checks when PlatformName is empty.
func (p *ReverseProxy) resolveDefaultPlatform() *platform.Platform {
if plat, ok := p.platLook.GetPlatform(platform.DefaultPlatformID); ok {
return plat
}
return nil
}
func (p *ReverseProxy) resolvePlatformForAccountBehavior(platformName string) *platform.Platform {
if p == nil || p.platLook == nil {
return nil
}
if platformName != "" {
if plat, ok := p.platLook.GetPlatformByName(platformName); ok {
return plat
}
return nil
}
return p.resolveDefaultPlatform()
}
func effectiveEmptyAccountBehavior(plat *platform.Platform) platform.ReverseProxyEmptyAccountBehavior {
if plat == nil {
return platform.ReverseProxyEmptyAccountBehaviorRandom
}
behavior := platform.ReverseProxyEmptyAccountBehavior(plat.ReverseProxyEmptyAccountBehavior)
if behavior.IsValid() {
return behavior
}
return platform.ReverseProxyEmptyAccountBehaviorRandom
}
func (p *ReverseProxy) resolveReverseProxyAccount(
parsed *parsedPath,
r *http.Request,
plat *platform.Platform,
) (string, platform.ReverseProxyEmptyAccountBehavior, bool) {
behavior := effectiveEmptyAccountBehavior(plat)
if r != nil {
if headerAccount := r.Header.Get("X-Resin-Account"); headerAccount != "" {
return headerAccount, behavior, false
}
}
account := ""
if parsed != nil {
account = parsed.Account
}
if account != "" {
return account, behavior, false
}
if r == nil {
return account, behavior, behaviorRequiresAccountExtraction(behavior)
}
switch behavior {
case platform.ReverseProxyEmptyAccountBehaviorRandom:
return account, behavior, false
case platform.ReverseProxyEmptyAccountBehaviorFixedHeader:
headers := fixedAccountHeadersForPlatform(plat)
if len(headers) == 0 {
return account, behavior, true
}
account = extractAccountFromHeaders(r, headers)
return account, behavior, account == ""
case platform.ReverseProxyEmptyAccountBehaviorAccountHeaderRule:
if p == nil || p.matcher == nil || parsed == nil {
return account, behavior, true
}
headers := p.matcher.Match(parsed.Host, parsed.Path)
if len(headers) == 0 {
return account, behavior, true
}
account = extractAccountFromHeaders(r, headers)
return account, behavior, account == ""
}
return account, behavior, false
}
func behaviorRequiresAccountExtraction(behavior platform.ReverseProxyEmptyAccountBehavior) bool {
switch behavior {
case platform.ReverseProxyEmptyAccountBehaviorFixedHeader, platform.ReverseProxyEmptyAccountBehaviorAccountHeaderRule:
return true
default:
return false
}
}
func shouldRejectReverseProxyAccountExtractionFailure(
extractionFailed bool,
plat *platform.Platform,
) bool {
if !extractionFailed || plat == nil {
return false
}
return platform.NormalizeReverseProxyMissAction(plat.ReverseProxyMissAction) == platform.ReverseProxyMissActionReject
}
func fixedAccountHeadersForPlatform(plat *platform.Platform) []string {
if plat == nil {
return nil
}
if len(plat.ReverseProxyFixedAccountHeaders) > 0 {
return append([]string(nil), plat.ReverseProxyFixedAccountHeaders...)
}
if plat.ReverseProxyFixedAccountHeader == "" {
return nil
}
_, headers, err := platform.NormalizeFixedAccountHeaders(plat.ReverseProxyFixedAccountHeader)
if err != nil {
return nil
}
return headers
}
// isValidHost validates that the host segment is a reasonable hostname or host:port.
// Rejects empty hosts and hosts containing URL-unsafe characters.
func isValidHost(host string) bool {
if host == "" {
return false
}
// Reject hosts with obviously invalid characters and userinfo marker.
if strings.ContainsAny(host, "/ \t\n\r@") {
return false
}
// Unbracketed multi-colon literals are ambiguous in URL host syntax.
// Require bracket form for IPv6 when used in host[:port].
if strings.Count(host, ":") > 1 && !strings.HasPrefix(host, "[") {
return false
}
u, err := url.Parse("http://" + host)
if err != nil {
return false
}
// Host segment must be a plain host[:port] without userinfo/path/query.
if u.User != nil || u.Host == "" || u.Host != host {
return false
}
if u.Hostname() == "" {
return false
}
return true
}
|