proxy

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 41 Imported by: ? 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

Index

Constants

View Source
const (

	// DefaultChallengeRequests is the default number of challenges one
	// client network may be issued per DefaultChallengePer. It is sized
	// against a seller whose invoice backend caps the number of unpaid
	// invoices it holds, such as a Wavelength wallet with 32 pending
	// receive intents. One challenge can mint up to three invoices (L402,
	// MPP charge, MPP session), so ten challenges hold at most thirty.
	DefaultChallengeRequests = 10

	// DefaultChallengePer is the default window for challenge issuance. It
	// matches the lifetime of an unpaid invoice, so a client network
	// cannot hold more than its burst of unpaid invoices at a steady state.
	DefaultChallengePer = time.Hour
)
View Source
const (
	// DefaultMaxCacheSize is the default maximum number of rate limiter
	// entries to keep in the LRU cache.
	DefaultMaxCacheSize = 10_000
)
View Source
const Subsystem = "PRXY"

Variables

This section is empty.

Functions

func ExtractRateLimitKey added in v0.4.1

func ExtractRateLimitKey(r *http.Request, remoteIP net.IP,
	authenticated bool) string

ExtractRateLimitKey extracts the rate-limiting key from a request. For authenticated requests, it uses the L402 token ID. For unauthenticated requests, it falls back to the client IP address.

IMPORTANT: The authenticated parameter should only be true if the L402 token has been validated by the authenticator. Using unvalidated L402 tokens as keys is a DoS vector since attackers can flood the cache with garbage tokens.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

func ValidateServiceName added in v0.6.0

func ValidateServiceName(name string) error

ValidateServiceName checks that a service name cannot collide with the per-resource token namespace of another service. ResourceName appends the request path to the name of a dynamic-price service, so a name containing a slash could overlap the names another service issues tokens under.

A caveat splits its condition from its value at the first '=', and a capabilities caveat carries the service name in its condition, so a name containing one could not be read back by the backend that checks it. The timeout caveat names the token instead, whose own name may end in the request path, so the mint checks that one when it is configured.

Types

type ChallengeRateLimitConfig added in v0.6.1

type ChallengeRateLimitConfig struct {
	// Requests is the number of challenges allowed per Per. Zero disables
	// the limit.
	Requests int `long:"requests" description:"Number of 402 challenges allowed per client network per time window. 0 disables the limit."`

	// Per is the time window for Requests.
	Per time.Duration `long:"per" description:"Time window for the challenge limit (e.g., 1m, 1h)."`

	// Burst is the number of challenges a client network may be issued at
	// once. It defaults to Requests.
	Burst int `long:"burst" description:"Maximum burst of challenges per client network (defaults to requests)."`
}

ChallengeRateLimitConfig bounds how many payment challenges the proxy issues to one client network. Every challenge mints invoices at the seller's backend before anyone has paid, so without a bound an unauthenticated client decides how many unpaid invoices the seller holds.

func DefaultChallengeRateLimitConfig added in v0.6.1

func DefaultChallengeRateLimitConfig() *ChallengeRateLimitConfig

DefaultChallengeRateLimitConfig returns the default challenge limit.

type LocalService

type LocalService interface {
	http.Handler

	// IsHandling returns true if the local service is handling the given
	// request. If one of the local services returns true on this method
	// then a request is not forwarded/proxied to any of the remote
	// backends.
	IsHandling(r *http.Request) bool
}

LocalService is an interface that describes a service that is handled internally by aperture and is not proxied to another backend.

func NewLocalService

func NewLocalService(h http.Handler, f func(r *http.Request) bool) LocalService

NewLocalService creates a new local service.

type PrefixLog

type PrefixLog struct {
	// contains filtered or unexported fields
}

PrefixLog logs with a given static string prefix.

func NewIPPrefixLog added in v0.6.1

func NewIPPrefixLog(logger btclog.Logger, ip net.IP) *PrefixLog

NewIPPrefixLog returns a new prefix logger that logs the given client IP address.

func NewRemoteIPPrefixLog

func NewRemoteIPPrefixLog(logger btclog.Logger, remoteAddr string) (net.IP,
	*PrefixLog)

NewRemoteIPPrefixLog returns a new prefix logger that logs the remote IP address.

func (*PrefixLog) Debugf

func (s *PrefixLog) Debugf(format string, params ...interface{})

Debugf formats message according to format specifier and writes to log with LevelDebug.

func (*PrefixLog) Errorf

func (s *PrefixLog) Errorf(format string, params ...interface{})

Errorf formats message according to format specifier and writes to to log with LevelError.

func (*PrefixLog) Infof

func (s *PrefixLog) Infof(format string, params ...interface{})

Infof formats message according to format specifier and writes to log with LevelInfo.

func (*PrefixLog) Warnf

func (s *PrefixLog) Warnf(format string, params ...interface{})

Warnf formats message according to format specifier and writes to to log with LevelError.

type Proxy

type Proxy struct {
	// contains filtered or unexported fields
}

Proxy is a HTTP, HTTP/2 and gRPC handler that takes an incoming request, uses its authenticator to validate the request's headers, and either returns a challenge to the client or forwards the request to another server and proxies the response back to the client.

func New

func New(auth auth.Authenticator, services []*Service,
	blocklist []string, priorityLocalServices []LocalService,
	localServices ...LocalService) (*Proxy, error)

New returns a new Proxy instance that proxies between the services specified, using the auth to validate each request's headers and get new challenge headers if necessary.

func (*Proxy) Close

func (p *Proxy) Close() error

Close cleans up the Proxy by closing any remaining open connections.

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP checks a client's headers for appropriate authorization and either returns a challenge or forwards their request to the target backend service.

func (*Proxy) SetChallengeRateLimit added in v0.6.1

func (p *Proxy) SetChallengeRateLimit(cfg *ChallengeRateLimitConfig) error

SetChallengeRateLimit installs a per client network limit on challenge issuance. Clients are grouped like the service rate limits, by the same masked source address, and the limit applies before any invoice is minted. A nil config, or one with zero Requests, removes the limit. It must be called before the proxy serves requests.

func (*Proxy) SetTrustedProxies added in v0.6.1

func (p *Proxy) SetTrustedProxies(nets []*net.IPNet)

SetTrustedProxies installs the networks of the reverse proxies in front of this proxy. A request from one of them is attributed to the client address the proxy reports in X-Forwarded-For, see netutil.ClientIP, and every per-client control (blocklist, rate limits, freebies, logs) then sees that address rather than the proxy's. It must be called before the proxy serves requests.

func (*Proxy) SetWriteDeadlineWindow added in v0.6.0

func (p *Proxy) SetWriteDeadlineWindow(window time.Duration)

SetWriteDeadlineWindow installs the rolling write deadline window applied to proxied responses. Pass the server's configured write timeout; zero disables the rolling extension and leaves whatever absolute deadline the server armed.

func (*Proxy) UpdateServices

func (p *Proxy) UpdateServices(services []*Service) error

UpdateServices re-configures the proxy to use a new set of backend services.

type RateLimitConfig added in v0.4.1

type RateLimitConfig struct {
	// PathRegexp is a regular expression that matches request paths
	// to which this rate limit applies. If empty, matches all paths.
	PathRegexp string `long:"pathregexp" description:"Regular expression to match the path of the URL against for rate limiting"`

	// Requests is the number of requests allowed per time window (Per).
	Requests int `long:"requests" description:"Number of requests allowed per time window"`

	// Per is the time window duration (e.g., 1s, 1m, 1h). Defaults to 1s.
	Per time.Duration `long:"per" description:"Time window for rate limiting (e.g., 1s, 1m, 1h)"`

	// Burst is the maximum number of requests that can be made in a burst,
	// exceeding the steady-state rate. Defaults to Requests if not set.
	Burst int `long:"burst" description:"Maximum burst size (defaults to Requests if not set)"`
	// contains filtered or unexported fields
}

RateLimitConfig defines a rate limiting rule for a specific path pattern.

func (*RateLimitConfig) EffectiveBurst added in v0.4.1

func (r *RateLimitConfig) EffectiveBurst() int

EffectiveBurst returns the burst value, defaulting to Requests if Burst is 0.

func (*RateLimitConfig) Matches added in v0.4.1

func (r *RateLimitConfig) Matches(path string) bool

Matches returns true if the given path matches this rate limit's path pattern.

func (*RateLimitConfig) Rate added in v0.4.1

func (r *RateLimitConfig) Rate() float64

Rate returns the rate.Limit value (requests per second) for this configuration.

type RateLimiter added in v0.4.1

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter manages per-key rate limiters with LRU eviction.

func NewRateLimiter added in v0.4.1

func NewRateLimiter(serviceName string, configs []*RateLimitConfig,
	opts ...RateLimiterOption) *RateLimiter

NewRateLimiter creates a new RateLimiter with the given configurations.

func (*RateLimiter) Allow added in v0.4.1

func (rl *RateLimiter) Allow(r *http.Request, key string) (bool,
	time.Duration)

Allow checks if a request should be allowed based on all matching rate limits. Returns (allowed, retryAfter) where retryAfter is the suggested duration to wait if denied.

func (*RateLimiter) Size added in v0.4.1

func (rl *RateLimiter) Size() int

Size returns the current number of entries in the cache.

type RateLimiterOption added in v0.4.1

type RateLimiterOption func(*RateLimiter)

RateLimiterOption is a functional option for configuring a RateLimiter.

func WithMaxCacheSize added in v0.4.1

func WithMaxCacheSize(size int) RateLimiterOption

WithMaxCacheSize sets the maximum cache size.

type RewriteConfig added in v0.5.0

type RewriteConfig struct {
	// Prefix is an absolute path that is prepended to the request path
	// before forwarding to the backend service.
	Prefix string `long:"prefix" description:"Absolute path prefix to prepend to the request path"`
}

RewriteConfig defines what should be rewritten in a proxied client request.

type Service

type Service struct {
	// Name is the name of the L402-enabled service. It must not contain a
	// slash; see ValidateServiceName.
	Name string `long:"name" description:"Name of the L402-enabled service"`

	// TLSCertPath is the optional path to the service's TLS certificate.
	TLSCertPath string `long:"tlscertpath" description:"Path to the service's TLS certificate"`

	// Address is the service's IP address and port.
	Address string `long:"address" description:"service instance rpc address"`

	// Protocol is the protocol that should be used to connect to the
	// service. Currently supported is http and https.
	Protocol string `long:"protocol" description:"service instance protocol"`

	// Auth is the authentication level required for this service to be
	// accessed. Valid values are "on" for full authentication, "freebie X"
	// for X free requests per IP address before authentication is required
	// or "off" for no authentication.
	Auth auth.Level `long:"auth" description:"required authentication"`

	// AuthScheme specifies which payment authentication scheme(s) to use
	// for this service. Valid values are "l402" (default), "mpp", or
	// "l402+mpp". An empty value defaults to "l402" for backwards
	// compatibility with existing deployments.
	AuthScheme string `long:"authscheme" description:"Payment auth scheme: l402, mpp, or l402+mpp"`

	// HostRegexp is a regular expression that is tested against the 'Host'
	// HTTP header field to find out if this service should be used.
	HostRegexp string `long:"hostregexp" description:"Regular expression to match the host against"`

	// PathRegexp is a regular expression that is tested against the path
	// of the URL of a request to find out if this service should be used.
	PathRegexp string `long:"pathregexp" description:"Regular expression to match the path of the URL against"`

	// Headers is a map of strings that defines header name and values that
	// should always be passed to the backend service, overwriting any
	// headers with the same name that might have been set by the client
	// request.
	// If the value of a header field starts with the prefix "!file+hex:",
	// the rest of the value is treated as a path to a file and the content
	// of that file is sent to the backend with each call (hex encoded).
	// If the value starts with the prefix "!file+base64:", the content of
	// the file is sent encoded as base64.
	// References of the form ${NAME} are replaced with the value of the
	// environment variable NAME at startup, so secrets like upstream API
	// keys can stay out of the config file (e.g. "Bearer ${UPSTREAM_KEY}").
	// A reference to an unset or empty variable fails startup.
	Headers map[string]string `long:"headers" description:"Header fields to always pass to the service"`

	// Timeout is an optional value that indicates in how many seconds the
	// service's caveat should time out relative to the time of creation. So
	// if a value of 100 is set, then the timeout will be 100 seconds
	// after creation of the L402.
	Timeout int64 `long:"timeout" description:"An integer value that indicates the number of seconds until the service access expires"`

	// Capabilities is the list of capabilities authorized for the service
	// at the base tier.
	Capabilities string `long:"capabilities" description:"A comma-separated list of the service capabilities authorized for the base tier"`

	// Constraints is the set of constraints that will take form of caveats.
	// They'll be enforced for a service at the base tier. The key should
	// correspond to the caveat's condition.
	Constraints map[string]string `long:"constraints" description:"The service constraints to enforce at the base tier"`

	// Price is the custom L402 value in satoshis to be used for the
	// service's endpoint.
	Price int64 `long:"price" description:"Static L402 value in satoshis to be used for this service"`

	// DynamicPrice holds the config options needed for initialising
	// the pricer if a gPRC server is to be used for price data.
	DynamicPrice pricer.Config `long:"dynamicprice" description:"Configuration for connecting to the gRPC server to use for the pricer backend"`

	// AuthWhitelistPaths is an optional list of regular expressions that
	// are matched against the path of the URL of a request. If the request
	// URL matches, L402 authentication is checked but not required. Failed
	// authentication removes Authorization and both macaroon headers before
	// forwarding. Grpc-Metadata-Authorization is always removed when auth is
	// enabled. Explicit service-level Auth "off" bypasses these checks.
	// E.g. the path for a gRPC call looks like this:
	// /package_name.ServiceName/MethodName
	AuthWhitelistPaths []string `long:"authwhitelistpaths" description:"List of regular expressions for paths that don't require authentication'"`

	// AuthSkipInvoiceCreationPaths is an optional list of regular
	// expressions that are matched against the path of the URL of a
	// request. If the request URL matches any of those regular
	// expressions, the call will not try to create an invoice for the
	// request, but still try to do the l402 authentication.
	AuthSkipInvoiceCreationPaths []string `long:"authskipinvoicecreationpaths" description:"List of regular expressions for paths that will skip invoice creation'"`

	// RateLimits is an optional list of rate-limiting rules for this
	// service. Each rule specifies a path pattern and rate limit
	// parameters. All matching rules are evaluated; if any rule denies
	// the request, it is rejected.
	RateLimits []*RateLimitConfig `long:"ratelimits" description:"List of rate limiting rules for this service"`

	// Rewrite defines what should be rewritten in the client request.
	Rewrite RewriteConfig `long:"rewrite" description:"Values to rewrite in the client request"`
	// contains filtered or unexported fields
}

Service generically specifies configuration data for backend services to the Aperture proxy.

func (*Service) AuthRequired

func (s *Service) AuthRequired(r *http.Request) auth.Level

AuthRequired determines the auth level required for a given request.

func (*Service) ResourceName

func (s *Service) ResourceName(resourcePath string) string

ResourceName returns the string to be used to identify which resource a macaroon has access to. If DynamicPrice Enabled option is set to true then the service has further restrictions per resource and so the name will include both the service name and the specific resource name. Otherwise authorisation is only restricted by service name.

func (*Service) SkipInvoiceCreation

func (s *Service) SkipInvoiceCreation(r *http.Request) bool

SkipInvoiceCreation determines if an invoice should be created for a given request.

Jump to

Keyboard shortcuts

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