politeness

package
v2.8.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
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

View Source
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

func CanonicalHost(host string) string

CanonicalHost normalizes a hostname to lowercase ASCII with any trailing FQDN dot stripped.

func CheckPublicPeerAddress

func CheckPublicPeerAddress(address string) error

CheckPublicPeerAddress validates the resolved IP:port string right before the OS connect() syscall fires.

func IsPublicAddr

func IsPublicAddr(addr netip.Addr) bool

IsPublicAddr evaluates a value-typed netip.Addr with zero heap allocations.

func IsPublicIP

func IsPublicIP(ip net.IP) bool

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

func NormalizeRobotsURI(s string) string

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

func ParseRetryAfter(val string, now time.Time) time.Duration

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

func RedactEmbeddedURLs(s string) string

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

func RejectNonPublicPeer(_, address string, _ syscall.RawConn) error

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?

  1. 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.
  2. Preserves Go's built-in RFC 8305 Happy Eyeballs dual-stack fallback and `httptrace` DNS timing hooks.

func SanitizeURL added in v2.7.1

func SanitizeURL(raw string) string

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

func (h *HostState) Acquire(ctx context.Context) error

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

func (h *HostState) CheckCircuit(now time.Time, host string) string

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

func (h *HostState) CoolingDownRetryAfterMs(now time.Time) int64

CoolingDownRetryAfterMs returns the remaining HTTP 429 cooldown in milliseconds (`0` when not cooling down from a 429).

func (*HostState) CrawlDelay

func (h *HostState) CrawlDelay(now time.Time) time.Duration

CrawlDelay returns the cached `/robots.txt` `Crawl-delay` for this host (`0` when unset or expired).

func (*HostState) NoteRateLimit added in v2.6.0

func (h *HostState) NoteRateLimit(now time.Time, wait time.Duration)

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.

func (*HostState) SetRobots

func (h *HostState) SetRobots(now time.Time, entry *RobotsEntry, distressPause time.Duration)

SetRobots stores a parsed (or distressed) `RobotsEntry` and applies an optional polite pause on `5xx` distress.

func (*HostState) WaitDelay

func (h *HostState) WaitDelay(now time.Time) time.Duration

WaitDelay returns any remaining cooldown before the next request to this host may start.

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.

func (*Registry) Get

func (r *Registry) Get(host string, now time.Time) *HostState

Get returns the persistent `HostState` for `host`, updating `lastSeen` and evicting idle / LRU unlocked entries whenever capacity reaches `MaxTrackedHosts`.

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

type RobotsRule struct {
	Pattern string
	Allow   bool
}

RobotsRule represents one `Allow` or `Disallow` path directive inside `/robots.txt`.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL