restrict

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBandwidthLimitExceeded = errors.New("bandwidth limit exceeded")

ErrBandwidthLimitExceeded is returned when a bandwidth tier limit is exceeded.

View Source
var ErrByteLimitExceeded = errors.New("per-connection byte limit exceeded")

ErrByteLimitExceeded is returned when the per-connection byte limit is exceeded.

View Source
var ErrDeadlineExceeded = errors.New("connection duration limit exceeded")

ErrDeadlineExceeded is returned when the connection duration limit is exceeded.

Functions

This section is empty.

Types

type BandwidthResult

type BandwidthResult struct {
	// Exceeded is true if any tier's limit was exceeded.
	Exceeded bool
	// ExceededTier is the index of the first exceeded tier, or -1 if none.
	ExceededTier int
}

BandwidthResult holds the result of a multi-tier bandwidth check.

type CloseReason added in v0.6.2

type CloseReason string

CloseReason categorizes why a relay ended.

const (
	CloseNormal  CloseReason = "normal"  // clean EOF from one side
	CloseLimit   CloseReason = "limit"   // byte, bandwidth, or duration limit exceeded
	CloseNetwork CloseReason = "network" // I/O error (not EOF)
)

type ConnLimits

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

ConnLimits tracks per-connection limits and batches byte updates to Redis.

func (*ConnLimits) BytesRead

func (cl *ConnLimits) BytesRead() int64

BytesRead returns the total bytes read from the client side.

func (*ConnLimits) BytesWritten

func (cl *ConnLimits) BytesWritten() int64

BytesWritten returns the total bytes written to the client side.

func (*ConnLimits) ReportBytes

func (cl *ConnLimits) ReportBytes(n int64) error

ReportBytes records bytes transferred and checks per-connection limits. Returns an error if a limit is exceeded.

func (*ConnLimits) ReportRead

func (cl *ConnLimits) ReportRead(n int64) error

ReportRead records bytes read from the client side.

func (*ConnLimits) ReportWrite

func (cl *ConnLimits) ReportWrite(n int64) error

ReportWrite records bytes written to the client side.

func (*ConnLimits) SetFlushIntervalForTest

func (cl *ConnLimits) SetFlushIntervalForTest(d time.Duration)

SetFlushIntervalForTest overrides the flush interval. Must be called before Start.

func (*ConnLimits) Start

func (cl *ConnLimits) Start()

Start begins the background flush goroutine. Call Stop when done.

func (*ConnLimits) Stop

func (cl *ConnLimits) Stop()

Stop flushes remaining bytes and stops the background goroutine.

type Direction added in v0.6.2

type Direction string

Direction indicates which side of the relay initiated the close.

const (
	DirClient  Direction = "client"
	DirBackend Direction = "backend"
)

type RedisStore

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

RedisStore manages per-user counters in Redis.

func NewRedisStore

func NewRedisStore(client redis.UniversalClient, keyPrefix string, m *metrics.Metrics) *RedisStore

NewRedisStore creates a new Redis-backed counter store.

func (*RedisStore) AcquireLock added in v0.2.0

func (s *RedisStore) AcquireLock(ctx context.Context, name string, ttl time.Duration) (string, error)

AcquireLock attempts to acquire a distributed lock using Redis SET NX EX. Returns a token that must be passed to ReleaseLock, or empty string if not acquired.

func (*RedisStore) AddBandwidthBytesMulti

func (s *RedisStore) AddBandwidthBytesMulti(ctx context.Context, user, scope string, n int64, tiers []auth.BandwidthTier) (BandwidthResult, error)

AddBandwidthBytesMulti adds bytes to all bandwidth tiers using the hierarchical sliding window. Writes cascade from scope (leaf) to user (root) at each tier. Returns which tier was exceeded at the leaf level, if any.

func (*RedisStore) AddBytes

func (s *RedisStore) AddBytes(ctx context.Context, user, scope string, n int64) (int64, error)

AddBytes adds to the total byte count, cascading up from scope to user total.

func (*RedisStore) DecrConns

func (s *RedisStore) DecrConns(ctx context.Context, user, scope string) error

DecrConns decrements the connection count for a user/scope, cascading the decrement up to the user-level total.

func (*RedisStore) GetBandwidthBytes

func (s *RedisStore) GetBandwidthBytes(ctx context.Context, user, scope string, period time.Duration) (int64, error)

GetBandwidthBytes returns the current bandwidth usage for a single period at a specific scope level using the sliding window (read-only). Pass scope="" for user-level total, or a listener name for per-endpoint.

func (*RedisStore) GetConns

func (s *RedisStore) GetConns(ctx context.Context, user, scope string) (int64, error)

GetConns returns the current connection count at a specific scope level. Pass scope="" to read the user-level total, or a listener name for per-endpoint.

func (*RedisStore) GetCredential added in v0.7.0

func (s *RedisStore) GetCredential(ctx context.Context, pgUser string) (string, error)

GetCredential returns the currently-in-effect password for a provisioned user, or "" when none is cached. Callers must hold the role lock: the value is only meaningful while nothing else can rotate the role's password.

This is shared across instances on purpose. A per-process cache would let two replicas each believe a different password is current and flip the role back and forth, breaking each other's in-flight logins.

func (*RedisStore) GetLastUsed

func (s *RedisStore) GetLastUsed(ctx context.Context, pgUser string) (time.Time, error)

GetLastUsed returns the last-used time for a provisioned user.

func (*RedisStore) IncrConns

func (s *RedisStore) IncrConns(ctx context.Context, user, scope string) (int64, error)

IncrConns atomically increments the connection count for a user/scope, cascading the increment up to the user-level total. Returns the new leaf (scoped) count.

func (*RedisStore) IsGroupReady added in v0.6.7

func (s *RedisStore) IsGroupReady(ctx context.Context, name string) (bool, error)

IsGroupReady reports whether a group role has been bootstrapped recently. Returns false (without error) when the key is absent so the caller falls through to an idempotent re-bootstrap.

func (*RedisStore) MarkGroupReady added in v0.6.7

func (s *RedisStore) MarkGroupReady(ctx context.Context, name string, ttl time.Duration) error

MarkGroupReady records that a group role has been bootstrapped. The TTL bounds how long the cache is trusted; on miss the bootstrap re-runs idempotently.

func (*RedisStore) ReleaseLock added in v0.2.0

func (s *RedisStore) ReleaseLock(ctx context.Context, name string, token string) error

ReleaseLock releases a distributed lock acquired by AcquireLock. The token must match the one returned by AcquireLock.

func (*RedisStore) SetCredential added in v0.7.0

func (s *RedisStore) SetCredential(ctx context.Context, pgUser, password string, ttl time.Duration) error

SetCredential records the password now in effect for a provisioned user so that connections arriving within ttl reuse it instead of rotating it.

func (*RedisStore) TouchLastUsed

func (s *RedisStore) TouchLastUsed(ctx context.Context, pgUser string) error

TouchLastUsed updates the last-used timestamp for a provisioned user.

type RelayResult added in v0.6.2

type RelayResult struct {
	Reason      CloseReason
	InitiatedBy Direction
	Err         error // underlying error; nil for clean EOF
}

RelayResult describes how a bidirectional relay ended.

func Relay

func Relay(client, backend net.Conn, cl *ConnLimits) RelayResult

Relay copies data bidirectionally between client and backend, enforcing limits via the ConnLimits tracker.

type Tracker

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

Tracker orchestrates per-connection (local) and per-user (Redis) limits.

func NewTracker

func NewTracker(store *RedisStore, m *metrics.Metrics, logger *slog.Logger) *Tracker

NewTracker creates a new limit tracker.

func (*Tracker) Acquire

func (t *Tracker) Acquire(ctx context.Context, user string, limits auth.MergedLimits, listenerName string) (func(), error)

Acquire checks and increments the connection count for a user, enforcing both per-user (global) and per-endpoint limits. Returns a release function that must be called when the connection closes.

func (*Tracker) WrapConn

func (t *Tracker) WrapConn(ctx context.Context, user string, limits auth.MergedLimits, listenerName string) *ConnLimits

WrapConn wraps a net.Conn with byte counting and limit enforcement.

Jump to

Keyboard shortcuts

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