Documentation
¶
Overview ¶
Package client is the HTTP client library consumers use to send outbound requests through pr0xteus. It provides:
- ModeVPNOnly (default): every request routed through SOCKS5, direct dials refused at the transport level. No leak path.
- ModePublicFirst: try the host's direct IPv4 first; on 429/403/503/transport-error fall back to SOCKS5 with full retry policy.
- PreflightSanityCheck: at boot, query two IP-echo services directly AND through the proxy, refuse to start if both report the same address (= proxy not actually rerouting).
- Retry loop: 5-attempt staircase (same proxy → fresh TCP → different proxy → fallback pool) with exponential backoff
- jitter.
Construct one Client per (country, pool) tuple at boot; reuse it for the service's lifetime. Cheap to construct, expensive to throw away (the cookie jar is per-Client).
Package client — usage example.
import (
"context"
"log"
"os"
"time"
"github.com/psyb0t/pr0xteus/pkg/client"
)
func main() {
// Load this from your secret store, never source control.
token := os.Getenv("PR0XTEUS_API_TOKEN")
if token == "" {
log.Fatal("PR0XTEUS_API_TOKEN is required")
}
// PoolService backed by the private pr0xteus control API.
pool := client.NewTunnelPoolClient(
"http://pr0xteus:8000", 30*time.Second,
client.WithPool("western_eu"),
client.WithBearerToken(token),
)
// Build the proxy-routed HTTP client. ModeVPNOnly is the default:
// every request goes through SOCKS5; direct dials are refused.
c, err := client.New("de", pool,
client.WithUserAgent("my-service/1.0"),
)
if err != nil {
log.Fatalf("egress.New: %v", err)
}
// Refuse to proceed if the proxy does not rewrite the outbound IP.
ctx := context.Background()
if err := c.PreflightSanityCheckWithRetry(ctx); err != nil {
log.Fatalf("preflight: %v", err)
}
// Use it like any *http.Client.
resp, err := c.Get(ctx, "https://example.com")
if err != nil {
log.Fatalf("Get: %v", err)
}
defer resp.Body.Close()
}
For sources where the host's public IP buys preferential treatment (e.g. registered API feeder), opt in to public-first:
c, _ := client.New("de", pool, client.WithMode(client.ModePublicFirst))
In ModePublicFirst, the first attempt goes direct; on 429 / 403 / 503 / transport-error the same request retries through the SOCKS5 proxy with the full retry policy.
Index ¶
- Variables
- func IsPreflightFailed(err error) bool
- func IsPreflightLeak(err error) bool
- func IsProxyMiss(err error) bool
- type Client
- func (c *Client) Country() string
- func (c *Client) Do(req *http.Request) (*http.Response, error)
- func (c *Client) Get(ctx context.Context, urlStr string) (*http.Response, error)
- func (c *Client) Mode() Mode
- func (c *Client) PreflightSanityCheck(ctx context.Context) error
- func (c *Client) PreflightSanityCheckWithRetry(ctx context.Context) error
- type DirectTransportFactory
- type Mode
- type Option
- type PoolService
- type ProxyRequest
- type ProxyResponse
- type RetryPolicy
- type StubPool
- type TransportFactory
- type TunnelPoolClient
- type TunnelPoolOption
Constants ¶
This section is empty.
Variables ¶
var ( // URL OR the assigned proxy is unreachable. The single most // important sentinel: it means "we couldn't route this request // through a VPN tunnel and we did NOT dial the target directly". ErrEgressUnavailable = errors.New("egress unavailable") // ErrEgressExhausted — every retry attempt in the policy // failed. Returned after MaxAttempts is reached without a // successful response. The caller decides whether to retry // the whole operation later. ErrEgressExhausted = errors.New("egress retries exhausted") // ErrPoolExhausted — pr0xteus tried every tunnel in the // requested pool AND its fallback (if enabled) and has // nothing left to offer. Distinct from ErrEgressUnavailable // because there's no point retrying further in the same tick. ErrPoolExhausted = errors.New("pool exhausted") // ErrInvalidCountry — country code didn't map to any pool and // no default pool is configured upstream. Config/code bug, // not a runtime condition. ErrInvalidCountry = errors.New("invalid country / no pool configured") // ErrDirectDialForbidden — the proxy-routed transport's // DialContext was invoked, which means something tried to // escape the SOCKS5 path. Defense in depth. ErrDirectDialForbidden = errors.New("direct dial forbidden in vpn-only mode") // ErrNoAttemptError — sentinel for the degenerate retry-loop // exit where every attempt's recorded error was nil. Should // not occur in practice. ErrNoAttemptError = errors.New("retry loop ended with no error recorded") // ErrPreflightLeaked — preflight found the direct public IP // and the proxied public IP are IDENTICAL. The proxy is not // actually rewriting outbound traffic. The caller MUST refuse // to start in this state. ErrPreflightLeaked = errors.New( "preflight: direct IP equals proxied IP — proxy not routing", ) // ErrPreflightFailed — preflight could not determine one or // both public IPs (network error, IP-echo service down, no // quorum across endpoints). Not necessarily a leak, but the // proxy can't be proven to work either. Fail closed. ErrPreflightFailed = errors.New( "preflight: could not establish IP state", ) )
Sentinel errors. Route caller behavior with errors.Is.
var DefaultIPEchoEndpoints = []string{
"https://api.ipify.org",
"https://ifconfig.me/ip",
}
DefaultIPEchoEndpoints is the production list of public-IP echo services PreflightSanityCheck consults. Two distinct providers so a single one being down / lying doesn't block deploy. Both return plain-text IP on the listed endpoints.
Functions ¶
func IsPreflightFailed ¶
IsPreflightFailed reports whether err contains ErrPreflightFailed.
func IsPreflightLeak ¶
IsPreflightLeak reports whether err contains ErrPreflightLeaked.
func IsProxyMiss ¶
IsProxyMiss reports whether the error chain represents the "direct succeeded with non-fallback failure" case where the public-first dispatch deliberately did NOT engage the proxy.
Placeholder hook for callers that want to log public-first hit-rate; returns false today.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the proxy-routed HTTP client.
func New ¶
func New( country string, pool PoolService, opts ...Option, ) (*Client, error)
New constructs a Client bound to country (ISO 3166-1 alpha-2). pool resolves country → proxy URL; nil pool or empty country is rejected.
func (*Client) Do ¶
Do executes req through the egress pool with the retry policy applied.
If req has a body, it MUST have GetBody set (http.NewRequest with bytes.NewReader / strings.NewReader / bytes.Buffer does this automatically). The retry loop calls GetBody to rewind between attempts; absent GetBody, the second attempt errors.
func (*Client) PreflightSanityCheck ¶
PreflightSanityCheck verifies that the configured proxy actually changes the host's apparent public IP. Sequence:
- Fetch the host's public IP via DIRECT (proxy-bypass) dial against two IP-echo services in parallel; cross-check the answers; pick the agreed value.
- Ask pr0xteus for a SOCKS5 URL + dial the same IP-echo services through the proxy; cross-check; pick the agreed value.
- Refuse to start if either step couldn't establish a value, OR if both values are identical (= proxy not actually rerouting → leak).
Returns nil on success. ErrPreflightFailed / ErrPreflightLeaked otherwise.
Callers MUST invoke this from service startup BEFORE production traffic. Use PreflightSanityCheckWithRetry to tolerate transient pool 503s (e.g. pr0xteus spawning a cold cell).
func (*Client) PreflightSanityCheckWithRetry ¶
PreflightSanityCheckWithRetry wraps PreflightSanityCheck with exponential backoff. Retries on ErrEgressUnavailable (pool 503 — cell spawn in flight) + ErrPreflightFailed (transient IP-echo hiccup). Bails immediately on ErrPreflightLeaked because that's a security failure that won't fix itself.
type DirectTransportFactory ¶
DirectTransportFactory builds the IPv4-only direct *http.Transport used by ModePublicFirst's first attempt and by PreflightSanityCheck's direct-IP probe.
type Mode ¶
type Mode int
Mode controls how Client.Do dispatches a request.
const ( // ModeVPNOnly forces every request through pr0xteus's SOCKS5 // proxy. The transport it builds simply has no direct-dial // code path — there is nothing for a request to escape // through. Default for any consumer where the host's public IP // must NEVER touch the target. ModeVPNOnly Mode = iota // ModePublicFirst tries the host's direct internet first; // on rate-limit (429), forbidden (403), service-unavailable // (503), or transport error, the same request is retried // through the SOCKS5 proxy. // // Use when the host's public IP buys preferential treatment // for the target (e.g. registered API feeder, allowlisted // internal endpoint). ModePublicFirst )
type Option ¶
type Option func(*Client)
Option configures a new Client.
func WithDirectTransport ¶
func WithDirectTransport(f DirectTransportFactory) Option
WithDirectTransport overrides the default IPv4-only direct transport factory. Test-only seam.
func WithIPEchoEndpoints ¶
WithIPEchoEndpoints replaces the production IP-echo endpoint list used by PreflightSanityCheck. Test-only seam.
func WithMode ¶
WithMode sets the dispatch mode. Defaults to ModeVPNOnly when unset — callers must explicitly opt in to public-first.
func WithRetryPolicy ¶
func WithRetryPolicy(p RetryPolicy) Option
WithRetryPolicy overrides the default 5-attempt staircase.
func WithTransport ¶
func WithTransport(f TransportFactory) Option
WithTransport overrides the default SOCKS5 transport with a custom factory. Test-only seam — production code must not use it.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header for outbound requests. Defaults to "" (no header set unless the caller's *http.Request already has one).
type PoolService ¶
type PoolService interface {
// ProxyForCountry returns a proxy URL for the given country's
// pool, optionally excluding a previously-failed proxy and
// optionally allowing fallback to a neighbor pool. May return
// ErrPoolExhausted when every option has been tried.
ProxyForCountry(
ctx context.Context, req ProxyRequest,
) (*ProxyResponse, error)
}
PoolService is the seam Client uses to resolve which SOCKS5 proxy a request should go through. The production implementation is TunnelPoolClient (hits pr0xteus over HTTP). Tests use StubPool.
type ProxyRequest ¶
type ProxyRequest struct {
// Country is the ISO 3166-1 alpha-2 code the Client was
// constructed against. The pool maps this to a pool name via
// its own routing config (config/egress-routing.yaml in
// pr0xteus).
Country string
// ExcludeProxy, if non-nil, signals "don't return this proxy
// again; it just failed for me". The pool's recently-failed
// cache absorbs the exclusion and picks a different tunnel.
ExcludeProxy *url.URL
// FallbackOK lets the pool escalate to its configured fallback
// pool when the primary is exhausted. Set to true on the last
// retry attempt; false otherwise.
FallbackOK bool
}
ProxyRequest is the per-call shape Client sends to the pool. ExcludeProxy is set on retry attempts so the pool can pick a DIFFERENT tunnel than the one that just failed. FallbackOK is set on the last attempt so the pool can escalate to a neighbor pool when the primary is exhausted.
type ProxyResponse ¶
type ProxyResponse struct {
ProxyURL *url.URL
Pool string // pool name (e.g. "western_eu")
ExitCountry string // ISO 3166-1 alpha-2 of the exit server
ExitIP string // reserved optional metadata; normally empty
}
ProxyResponse is the pool's answer. ProxyURL is the SOCKS5 member of the controller's dual-proxy lease response that Client dials through. Pool, ExitCountry, and ExitIP are telemetry for logs and metrics.
type RetryPolicy ¶
type RetryPolicy struct {
// MaxAttempts is the total number of attempts including the
// first. Default 5.
MaxAttempts int
// InitialBackoff is the wait between attempt 1 and 2.
InitialBackoff time.Duration
// MaxBackoff caps the exponential growth so attempt 5's wait
// doesn't run away. 30s default.
MaxBackoff time.Duration
// BackoffMultiplier is the per-attempt growth factor (2.0 →
// 1s, 2s, 4s, 8s, 16s...). The cap lives on MaxBackoff.
BackoffMultiplier float64
// Jitter is the ±fraction applied to each backoff. 0.25 means
// "±25%". Required to avoid thundering-herd on simultaneous
// retries.
Jitter float64
// UseFallbackPool toggles whether the LAST attempt is allowed
// to escalate to the pool's configured fallback. Default true.
UseFallbackPool bool
}
RetryPolicy controls Client retry behavior.
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy returns the canonical 5-attempt staircase.
type StubPool ¶
type StubPool struct {
ProxyURL *url.URL
Pool string
Exit string
Fail error
// Calls records how many times ProxyForCountry was invoked,
// useful for asserting retry behavior.
Calls int
// LastRequest records the last ProxyRequest received so tests
// can assert that retries pass ExcludeProxy / FallbackOK
// correctly.
LastRequest ProxyRequest
}
StubPool is a deterministic PoolService for unit tests. Returns a fixed proxy URL by default; Fail forces ProxyForCountry to return that error instead.
func (*StubPool) ProxyForCountry ¶
func (s *StubPool) ProxyForCountry( _ context.Context, req ProxyRequest, ) (*ProxyResponse, error)
ProxyForCountry satisfies PoolService.
type TransportFactory ¶
TransportFactory builds the per-attempt *http.Transport for one outbound request through the SOCKS5 proxy. The production factory wires the SOCKS5 dial path; tests inject a fake that bypasses the proxy for deterministic retry-loop assertions.
type TunnelPoolClient ¶
type TunnelPoolClient struct {
// contains filtered or unexported fields
}
TunnelPoolClient is a PoolService implementation for pr0xteus's private, versioned HTTP API. Consumers create one at boot and reuse it for the lifetime of the service. It selects the SOCKS5 member of each returned lease; callers that need the standard HTTP proxy use the control API shape directly.
func NewTunnelPoolClient ¶
func NewTunnelPoolClient( baseURL string, timeout time.Duration, opts ...TunnelPoolOption, ) *TunnelPoolClient
NewTunnelPoolClient builds the shared client.
baseURL is pr0xteus's control-API URL (e.g. "http://pr0xteus:8000"). timeout caps each ProxyForCountry HTTP roundtrip.
func (*TunnelPoolClient) PoolName ¶
func (c *TunnelPoolClient) PoolName() string
PoolName returns the configured pool ID (read-only; for logs).
func (*TunnelPoolClient) ProxyForCountry ¶
func (c *TunnelPoolClient) ProxyForCountry( ctx context.Context, req ProxyRequest, ) (*ProxyResponse, error)
ProxyForCountry satisfies PoolService and converts the versioned response into the strongly typed ProxyResponse used by callers.
type TunnelPoolOption ¶
type TunnelPoolOption func(*TunnelPoolClient)
TunnelPoolOption tunes a TunnelPoolClient at construction.
func WithBearerToken ¶
func WithBearerToken(token string) TunnelPoolOption
WithBearerToken sets the private control-plane token. The client never logs the token or includes it in a URL.
func WithHTTPClient ¶
func WithHTTPClient(c *http.Client) TunnelPoolOption
WithHTTPClient injects a custom HTTP client.
func WithPool ¶
func WithPool(pool string) TunnelPoolOption
WithPool overrides the default pool name passed to pr0xteus. Each consumer usually has a preferred pool. Empty pool lets pr0xteus fall back to its own default routing.