Documentation
¶
Overview ¶
Package politeness enforces per-origin serialization, RFC 9110 `Retry-After` cooldowns, three-state dead-origin circuit breaking, zero-allocation RFC 9309 `/robots.txt` matching, and dial-time DNS-rebinding SSRF protection (`net.Dialer.Control`).
Concurrency & SSRF Design ¶
- Context-aware host locks: HostState pairs a buffered `chan struct{}` (capacity 1) with a metadata `sync.Mutex` so waiting goroutines unblock immediately when a caller's `context.Context` cancels.
- Rate-limit vs dead-origin separation: HTTP `429` honors `Retry-After` on `nextAllowed` without tripping the dead-socket circuit breaker, whereas 5 consecutive transport/5xx failures open the circuit for 30s.
- Linear-time `robots.txt` matching: wildcard `*` and `$` rules evaluate via `strings.Cut` in $O(P \times T)$ time with `0 allocs/op` and zero regular-expression backtracking risk.
- Dial-time SSRF guard: RejectNonPublicPeer inspects the resolved `netip.Addr` inside `net.Dialer.Control` right before the OS `connect()` syscall, eliminating DNS-rebinding TOCTOU races while preserving Happy Eyeballs dual-stack fallback and `httptrace` DNS timing hooks.
Index ¶
- Constants
- Variables
- func CanonicalHost(host string) string
- func CheckPublicPeerAddress(address string) error
- func IsPublicAddr(addr netip.Addr) bool
- func IsPublicIP(ip net.IP) bool
- func NormalizeRobotsURI(s string) string
- func ParseRetryAfter(val string, now time.Time) time.Duration
- func RedactEmbeddedURLs(s string) string
- func RejectNonPublicPeer(_, address string, _ syscall.RawConn) error
- func SanitizeURL(raw string) string
- type HostState
- func (h *HostState) Acquire(ctx context.Context) error
- func (h *HostState) CachedRobots(now time.Time) *RobotsEntry
- func (h *HostState) CheckCircuit(now time.Time, host string) string
- func (h *HostState) CoolingDownRetryAfterMs(now time.Time) int64
- func (h *HostState) CrawlDelay(now time.Time) time.Duration
- func (h *HostState) NoteRateLimit(now time.Time, wait time.Duration)
- func (h *HostState) RecordOutcome(now time.Time, minPause, retryAfter time.Duration, status int, ...)
- func (h *HostState) Release()
- func (h *HostState) SetRobots(now time.Time, entry *RobotsEntry, distressPause time.Duration)
- func (h *HostState) WaitDelay(now time.Time) time.Duration
- type Registry
- type RobotsEntry
- type RobotsRule
Examples ¶
Constants ¶
const ( MaxTrackedHosts = 512 HostIdleTTL = 24 * time.Hour MaxRetryAfter = 5 * time.Minute DefaultThrottlePause = 15 * time.Second CircuitFailureThreshold = 5 CircuitFailureWindow = 60 * time.Second CircuitOpenCooldown = 30 * time.Second RobotsCacheTTL = 24 * time.Hour RobotsDistressTTL = 60 * time.Second RobotsMaxBytes = 1 << 20 // 1 MiB (>= 500 KiB minimum required by RFC 9309 §2.5; closes 520 KiB padding bypass). RobotsTimeout = 5 * time.Second MaxRobotsFetchTimeout = 10 * time.Second MaxCrawlDelay = 30 * time.Second )
Tuning bounds for per-host politeness, circuit breaking, and `/robots.txt` caching.
Variables ¶
var ErrNonPublicPeer = errors.New("non-public peer IP")
ErrNonPublicPeer is returned when dial-time resolution maps a hostname onto a non-public IP address.
Functions ¶
func CanonicalHost ¶
CanonicalHost normalizes a hostname to lowercase ASCII with any trailing FQDN dot stripped.
func CheckPublicPeerAddress ¶
CheckPublicPeerAddress validates the resolved IP:port string right before the OS connect() syscall fires.
func IsPublicAddr ¶
IsPublicAddr evaluates a value-typed netip.Addr with zero heap allocations.
func IsPublicIP ¶
IsPublicIP returns true ONLY for globally routable public unicast IPv4/IPv6 addresses.
Example ¶
package main
import (
"fmt"
"net"
"github.com/bartrumb/edgefetch/v2/internal/politeness"
)
func main() {
fmt.Println("cloudflare-dns:", politeness.IsPublicIP(net.ParseIP("1.1.1.1")))
fmt.Println("loopback:", politeness.IsPublicIP(net.ParseIP("127.0.0.1")))
fmt.Println("cgnat-tailscale:", politeness.IsPublicIP(net.ParseIP("100.100.100.100")))
fmt.Println("ipv4-mapped-loopback:", politeness.IsPublicIP(net.ParseIP("::ffff:127.0.0.1")))
}
Output: cloudflare-dns: true loopback: false cgnat-tailscale: false ipv4-mapped-loopback: false
func NormalizeRobotsURI ¶
NormalizeRobotsURI normalizes percent-encoding in `/robots.txt` patterns and target paths per RFC 9309 §2.2.2:
- Unreserved ASCII octets (`A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, `~`) encoded as `%XX` decode to literal ASCII.
- Valid `%xx` sequences for reserved or non-ASCII octets uppercase to `%XX` (`%c3%a9` -> `%C3%A9`).
- Raw non-ASCII UTF-8 bytes (`>= 0x80`) encode to uppercase `%XX`.
- Pure ASCII strings without `%` return `s` directly with zero allocations (`0 B/op`).
func ParseRetryAfter ¶
ParseRetryAfter parses an RFC 9110 `Retry-After` header (delta-seconds or HTTP-date), clamped to `[0, MaxRetryAfter]`. Clamps `secs` before multiplying by `time.Second` so large headers like `Retry-After: 9227000000` cannot overflow `int64`.
func RedactEmbeddedURLs ¶ added in v2.7.1
RedactEmbeddedURLs scrubs query strings (`?...`), `#fragments`, matrix parameters (`;...`), `user:pass@` credentials (both schemed and schemeless), reset path tokens, and inline bearer/basic/token/api_key secrets from URLs embedded inside error, log, or OpenTelemetry span strings in a single linear O(N) pass.
func RejectNonPublicPeer ¶
RejectNonPublicPeer is a `net.Dialer.Control` hook (`func(network, address string, c syscall.RawConn) error`).
Why inspect the peer IP in `Dialer.Control` instead of calling `net.LookupIP` beforehand?
- Eliminates DNS-rebinding TOCTOU (time-of-check to time-of-use) races: `address` is the exact resolved IP the kernel socket is about to `connect()` to.
- Preserves Go's built-in RFC 8305 Happy Eyeballs dual-stack fallback and `httptrace` DNS timing hooks.
func SanitizeURL ¶ added in v2.7.1
SanitizeURL strips `user:pass@` credentials (including schemeless `user:secret@host/path` and `%40`-encoded userinfo), query parameters (`?...`), `#fragments`, matrix parameters (`;...`), and sensitive action path tokens (`/reset/<token>`) from `raw` for safe structured logging and OpenTelemetry `url.full` attributes.
Types ¶
type HostState ¶
type HostState struct {
// contains filtered or unexported fields
}
HostState coordinates concurrent callers targeting the same hostname across independent crawl invocations. `inFlight` (capacity 1) provides context-cancellable per-host serialization, while `mu` guards non-blocking metadata updates.
func (*HostState) Acquire ¶
Acquire claims exclusive in-flight access to this host, or returns `ctx.Err()` immediately if `ctx` cancels first.
func (*HostState) CachedRobots ¶
func (h *HostState) CachedRobots(now time.Time) *RobotsEntry
CachedRobots returns the cached `RobotsEntry` when fresh (`nil` when absent or expired).
func (*HostState) CheckCircuit ¶
CheckCircuit returns a non-empty reason when the host's dead-origin circuit breaker is currently Open. Once `now` passes `circuitOpenUntil`, it returns `""` so a single Half-Open probe request is allowed through.
func (*HostState) CoolingDownRetryAfterMs ¶ added in v2.6.0
CoolingDownRetryAfterMs returns the remaining HTTP 429 cooldown in milliseconds (`0` when not cooling down from a 429).
func (*HostState) CrawlDelay ¶
CrawlDelay returns the cached `/robots.txt` `Crawl-delay` for this host (`0` when unset or expired).
func (*HostState) NoteRateLimit ¶ added in v2.6.0
NoteRateLimit records an active HTTP 429 backoff window so concurrent callers whose contexts expire while waiting on `Acquire` can report `Status: 429` with `RetryAfterMs` instead of a generic cancellation.
func (*HostState) RecordOutcome ¶
func (h *HostState) RecordOutcome(now time.Time, minPause, retryAfter time.Duration, status int, throttled, transientDead bool)
RecordOutcome updates `nextAllowed` and drives the three-state dead-origin circuit breaker (Closed -> Open -> Half-Open).
Why don't HTTP 403 or 429 responses trip the dead-origin circuit breaker? Because an HTTP 429 proves the TCP/TLS server is healthy and asking us to slow down — so we honor `Retry-After` (or `DefaultThrottlePause`) on `nextAllowed` instead of misclassifying a rate limit as a dead socket.
func (*HostState) Release ¶
func (h *HostState) Release()
Release frees the single in-flight host token. Pair with `defer hs.Release()` right after `Acquire` succeeds.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry tracks HostState entries across domains with bounded memory eviction. Two-tier locking keeps map lookups sub-microsecond while per-host updates run under each HostState's own mutex.
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry creates an empty per-host politeness registry.
type RobotsEntry ¶
type RobotsEntry struct {
Rules []RobotsRule
CrawlDelay time.Duration
DisallowAIInput bool
Distressed bool
DNSNotFound bool
SSRFBlocked bool
Reason string
ExpiresAt time.Time
// contains filtered or unexported fields
}
RobotsEntry caches parsed `/robots.txt` rules, Content Signals, and `Crawl-delay` for one origin. When `Distressed` is true (RFC 9309 §2.3.1.4 unreachable: network error, 429, or 5xx), all paths are treated as disallowed. When `DisallowAIInput` is true (`Content-Signal: ai-input=no`), all paths are disallowed for user-triggered agent retrieval.
func ParseRobotsTxt ¶
func ParseRobotsTxt(body, agentToken string, expiresAt time.Time) *RobotsEntry
ParseRobotsTxt extracts directives matching `agentToken` (lowercase product token, preferred per RFC 9309 specificity) or fallback `*`, plus `Crawl-delay` clamped to `MaxCrawlDelay` and `Content-Signal` (`ai-input`).
Example ¶
package main
import (
"fmt"
"time"
"github.com/bartrumb/edgefetch/v2/internal/politeness"
)
func main() {
robotsTxt := `
User-agent: *
Disallow: /admin/
Allow: /admin/public-status$
Crawl-delay: 2
`
entry := politeness.ParseRobotsTxt(robotsTxt, "EdgeFetch/2.1", time.Now().Add(time.Hour))
fmt.Println("public:", entry.Allowed("/docs/getting-started"))
fmt.Println("admin:", entry.Allowed("/admin/users"))
fmt.Println("longest-match allow:", entry.Allowed("/admin/public-status"))
fmt.Println("crawl-delay:", entry.CrawlDelay)
}
Output: public: true admin: false longest-match allow: true crawl-delay: 2s
func (*RobotsEntry) Allowed ¶
func (e *RobotsEntry) Allowed(pathAndQuery string) bool
Allowed evaluates RFC 9309 longest-match precedence: whichever matching `Allow` or `Disallow` rule has the longest pattern wins; ties break in favor of `Allow`. Also evaluates dot-segment/collapsed-slash/matrix-stripped path canonicalization (`/../`, `/./`, `//`, `;param`) so origin path normalization cannot bypass a `Disallow` rule.
func (*RobotsEntry) ContentSignalBlocked ¶ added in v2.5.5
func (e *RobotsEntry) ContentSignalBlocked() bool
ContentSignalBlocked reports whether `/robots.txt` disallowed agent retrieval via `Content-Signal: ai-input=no`.
type RobotsRule ¶
RobotsRule represents one `Allow` or `Disallow` path directive inside `/robots.txt`.