Documentation
¶
Overview ¶
Package api provides HTTP API handlers for apt-proxy management endpoints.
Package api provides HTTP API handlers for apt-proxy management endpoints.
Package api provides HTTP API handlers for apt-proxy management endpoints.
Package api provides HTTP API handlers for apt-proxy management endpoints.
Index ¶
- func CalculateHitRate(hits, misses int64) float64
- func FormatBytes(bytes int64) string
- func RequireAuth(apiKey string, next http.HandlerFunc) http.HandlerFunc
- func WriteAppError(w http.ResponseWriter, err *apperrors.AppError)
- func WriteJSON(w http.ResponseWriter, statusCode int, data interface{}) error
- type AuthConfig
- type AuthMiddleware
- type CacheCleanupResponse
- type CacheHandler
- type CachePurgeResponse
- type CacheStatsResponse
- type ClientIPExtractor
- type MirrorsHandler
- type MirrorsRefreshResponse
- type RateLimitMiddleware
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CalculateHitRate ¶
CalculateHitRate calculates the cache hit rate
func FormatBytes ¶
FormatBytes formats bytes into a human-readable string. Uses 1024-based (binary) units to match filesystem conventions; delegates to system.ByteCountBinary so the formatting is centralised.
func RequireAuth ¶
func RequireAuth(apiKey string, next http.HandlerFunc) http.HandlerFunc
RequireAuth is a middleware function that can be used with standard http.ServeMux. It wraps a handler function with authentication.
func WriteAppError ¶ added in v0.9.0
func WriteAppError(w http.ResponseWriter, err *apperrors.AppError)
WriteAppError writes a structured AppError as HTTP JSON (code + message) for API consistency.
Types ¶
type AuthConfig ¶
type AuthConfig struct {
// APIKey is the required API key for accessing protected endpoints.
// If empty, authentication is disabled.
APIKey string
// HeaderName is the HTTP header name to read the API key from.
// Defaults to "X-API-Key" if not specified.
HeaderName string
// AllowQueryParam allows API key to be passed as a query parameter.
// The parameter name will be "api_key". Default is false for security.
AllowQueryParam bool
// Logger is the structured logger for authentication events.
Logger *logger.Logger
// ClientIP extracts the real client IP for log records. When nil, the
// raw r.RemoteAddr is logged. Pass the same instance you use for the
// rate-limit middleware so audit trails are consistent across layers.
ClientIP *ClientIPExtractor
}
AuthConfig holds authentication configuration for the API middleware.
type AuthMiddleware ¶
type AuthMiddleware struct {
// contains filtered or unexported fields
}
AuthMiddleware provides API key authentication for protected endpoints.
func NewAuthMiddleware ¶
func NewAuthMiddleware(config AuthConfig) *AuthMiddleware
NewAuthMiddleware creates a new AuthMiddleware with the provided configuration. If config.HeaderName is empty, it defaults to "X-API-Key".
func (*AuthMiddleware) IsEnabled ¶
func (m *AuthMiddleware) IsEnabled() bool
IsEnabled returns true if authentication is enabled (API key is configured).
func (*AuthMiddleware) Wrap ¶
func (m *AuthMiddleware) Wrap(next http.Handler) http.Handler
Wrap wraps an http.Handler with API key authentication. If no API key is configured, the handler is returned without modification. Returns 401 Unauthorized if authentication fails.
func (*AuthMiddleware) WrapFunc ¶
func (m *AuthMiddleware) WrapFunc(next http.HandlerFunc) http.HandlerFunc
WrapFunc wraps an http.HandlerFunc with API key authentication.
type CacheCleanupResponse ¶
type CacheCleanupResponse struct {
Success bool `json:"success"`
ItemsRemoved int `json:"items_removed"`
BytesFreed int64 `json:"bytes_freed"`
StaleEntriesRemoved int `json:"stale_entries_removed"`
DurationMs int64 `json:"duration_ms"`
}
CacheCleanupResponse holds the result of a cache cleanup operation
type CacheHandler ¶
type CacheHandler struct {
// contains filtered or unexported fields
}
CacheHandler handles cache-related API endpoints
func NewCacheHandler ¶
func NewCacheHandler(cache httpcache.ExtendedCache, log *logger.Logger) *CacheHandler
NewCacheHandler creates a new CacheHandler
func (*CacheHandler) HandleCacheCleanup ¶
func (h *CacheHandler) HandleCacheCleanup(w http.ResponseWriter, r *http.Request)
HandleCacheCleanup triggers a manual cleanup cycle
func (*CacheHandler) HandleCachePurge ¶
func (h *CacheHandler) HandleCachePurge(w http.ResponseWriter, r *http.Request)
HandleCachePurge clears all cached items
func (*CacheHandler) HandleCacheStats ¶
func (h *CacheHandler) HandleCacheStats(w http.ResponseWriter, r *http.Request)
HandleCacheStats returns cache statistics as JSON
type CachePurgeResponse ¶
type CachePurgeResponse struct {
Success bool `json:"success"`
ItemsRemoved int `json:"items_removed"`
BytesFreed int64 `json:"bytes_freed"`
}
CachePurgeResponse holds the result of a cache purge operation
type CacheStatsResponse ¶
type CacheStatsResponse struct {
TotalSizeBytes int64 `json:"total_size_bytes"`
TotalSizeHuman string `json:"total_size_human"`
ItemCount int `json:"item_count"`
StaleCount int `json:"stale_count"`
HitCount int64 `json:"hit_count"`
MissCount int64 `json:"miss_count"`
HitRate float64 `json:"hit_rate"`
}
CacheStatsResponse holds cache statistics data
type ClientIPExtractor ¶ added in v0.10.0
type ClientIPExtractor struct {
// contains filtered or unexported fields
}
ClientIPExtractor returns the "real" client IP for an incoming request, honouring X-Forwarded-For only when the immediate peer is a trusted proxy.
This is shared between the auth and rate-limit middlewares so they cannot drift: if rate-limiting honours XFF for trusted proxies but auth logging records r.RemoteAddr, operators get inconsistent forensic trails.
Construct one via NewClientIPExtractor and reuse it across handlers; the underlying CIDR list is parsed once at construction time.
func NewClientIPExtractor ¶ added in v0.10.0
func NewClientIPExtractor(trustedProxies []string) *ClientIPExtractor
NewClientIPExtractor parses the given trusted-proxy CIDR list. Empty or malformed entries are skipped silently (callers that want diagnostics should validate beforehand). Pass nil/empty to disable XFF entirely (default secure behaviour).
func (*ClientIPExtractor) AddTrustedProxy ¶ added in v0.10.0
func (e *ClientIPExtractor) AddTrustedProxy(n *net.IPNet)
AddTrustedProxy registers an already-parsed CIDR. Used by call sites that have validated the input themselves and want to report errors directly.
func (*ClientIPExtractor) ClientIP ¶ added in v0.10.0
func (e *ClientIPExtractor) ClientIP(r *http.Request) string
ClientIP returns the request's client IP. When the immediate peer (r.RemoteAddr) is in trustedProxies, the left-most syntactically valid entry of X-Forwarded-For is preferred; otherwise the peer's host part is used. Whitespace inside an XFF entry is rejected so attackers cannot smuggle a fake left-most identifier (e.g. "1.2.3.4 attacker").
type MirrorsHandler ¶
type MirrorsHandler struct {
// contains filtered or unexported fields
}
MirrorsHandler handles mirror-related API endpoints.
reloadFunc is required: it is the per-Server reload closure that owns distribution-registry reload + mirror refresh. The handler intentionally has no package-global fallback so that misconfigured callers fail loudly rather than mutating an unrelated Server's state.
func NewMirrorsHandler ¶
func NewMirrorsHandler(log *logger.Logger, reloadFunc func()) *MirrorsHandler
NewMirrorsHandler creates a new MirrorsHandler. reloadFunc is required; passing nil makes HandleMirrorsRefresh return 500.
func (*MirrorsHandler) HandleMirrorsRefresh ¶
func (h *MirrorsHandler) HandleMirrorsRefresh(w http.ResponseWriter, r *http.Request)
HandleMirrorsRefresh triggers distribution config reload and mirror refresh.
type MirrorsRefreshResponse ¶
type MirrorsRefreshResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
DurationMs int64 `json:"duration_ms"`
}
MirrorsRefreshResponse holds the result of a mirrors refresh operation
type RateLimitMiddleware ¶ added in v0.9.0
type RateLimitMiddleware struct {
// contains filtered or unexported fields
}
RateLimitMiddleware applies per-IP rate limiting to API handlers. When limit is 0, the next handler is called without limiting.
func NewRateLimitMiddleware ¶ added in v0.9.0
func NewRateLimitMiddleware(limitPerMinute int, log *logger.Logger, trustedProxies ...string) *RateLimitMiddleware
NewRateLimitMiddleware creates a middleware that allows limitPerMinute requests per IP per minute. Pass 0 to disable rate limiting (next handler is returned unchanged). trustedProxies is a list of CIDR networks (e.g. "10.0.0.0/8") whose X-Forwarded-For header should be honored. Pass nil/empty to ignore XFF entirely.
func (*RateLimitMiddleware) Wrap ¶ added in v0.9.0
func (m *RateLimitMiddleware) Wrap(next http.Handler) http.Handler
Wrap wraps an http.Handler with per-IP rate limiting. When limit is 0, returns next unchanged. On rate limit exceeded, responds with 429 and ErrRateLimited.
func (*RateLimitMiddleware) WrapFunc ¶ added in v0.9.0
func (m *RateLimitMiddleware) WrapFunc(next http.HandlerFunc) http.HandlerFunc
WrapFunc wraps an http.HandlerFunc with rate limiting.