Documentation
¶
Overview ¶
Package api provides Watchtower's HTTP API server, built on Fiber v3.
It handles token-authenticated and session-authenticated requests for triggering container updates, checking update availability, serving Prometheus metrics, listing watched container image identities, and streaming real-time events via SSE.
Endpoints:
GET /livez Liveness probe GET /readyz Readiness probe — checks Docker client connectivity GET /startupz Startup probe POST /v1/update Trigger container update scan (requires auth) POST /v1/check Check for available updates (requires auth) GET /v1/metrics Prometheus metrics (requires auth) GET /v1/status Last scan results (requires auth) GET /v1/containers List watched container statuses (requires auth) GET /v1/containers/details Detailed container info (requires auth) GET /v1/history Historical scan results (requires auth) GET /v1/images Tracked images with digests (requires auth) GET /v1/config Active configuration settings (requires auth) GET /v1/events Real-time events via SSE (requires events token) GET /swagger/* Swagger UI (requires http-api-swagger)
Health probes (/livez, /readyz, /startupz) are enabled via EnableHealthAPI and require no authentication. All /v1/* endpoints except /v1/events require Bearer token authentication. /v1/events requires a separate events token (via http-api-events-token).
Key components:
- New: Creates a Fiber application with the configured middleware stack (fiber.go).
- NewAPIAuthMiddleware: Bearer token authentication (auth.go).
- routes.ValidateAndRegister: Validates options and registers enabled endpoints.
- SetupAndStartAPI: Orchestrates endpoint registration and server lifecycle (lifecycle.go).
- config.ValidateUpdateOptions: Validates required update API dependencies (config/).
- config.TimeoutMiddleware: Per-request timeout enforcement (config/).
File organization:
- config/: Shared configuration types, validation, and sentinel errors.
- lifecycle.go: Server startup, shutdown, and address formatting.
- fiber.go: Fiber app factory, configuration types, and middleware stack.
- auth.go: Token authentication middleware.
- routes/: Per-endpoint registration including health checks.
Security features:
- Token hashing: Tokens are hashed with SHA-256 at initialization.
- Constant-time comparison: Uses crypto/subtle to prevent timing attacks.
- Per-IP rate limiting: Sliding window via Fiber's limiter middleware.
- Panic recovery: Catches handler panics and returns 500.
- Security headers: X-Content-Type-Options, X-Frame-Options, X-XSS-Protection.
- Request ID: Unique ID per request for log correlation.
- Response compression: gzip, deflate, brotli, zstd.
- CORS: Configured for cross-origin requests.
Middleware stack (outermost to innermost):
- recover — panic recovery
- helmet — security headers
- cors — cross-origin headers (only when AllowedOrigins is configured)
- requestid — request ID propagation
- zerolog — structured request logging via gofiber/contrib/v3/zerolog
- compress — response compression
- limiter — per-IP rate limiting (sliding window)
- auth — Bearer token authentication (per-route)
API server timeout behavior:
- ReadTimeout is set to 10s. It bounds reading the full request including body. Required for clean Fiber shutdown.
- IdleTimeout is set to 30s. It bounds the wait for the next request on keep-alive connections. SSE sends stream comments every 5 seconds, so idle timeout does not fire on quiet event streams.
- WriteTimeout is left at zero. A global write deadline conflicts with long-lived routes. SSE idles between events, and the update handler can run up to 10 minutes under its own per-route timeout middleware. Route-specific timeouts bound each handler instead.
Index ¶
- Constants
- func GetAPIAddr(host, port string) string
- func New(log *zerolog.Logger, rateLimitPerMinute int, proxyCfg ProxyConfig, ...) *fiber.App
- func NewAPIAuthMiddleware(log *zerolog.Logger, token string) fiber.Handler
- func SetupAndStartAPI(ctx context.Context, opts config.Options) error
- type CORSConfig
- type ProxyConfig
- type Server
Constants ¶
const ShutdownGracePeriod = 5 * time.Second
ShutdownGracePeriod defines the maximum duration allowed for the server to shut down gracefully.
Variables ¶
This section is empty.
Functions ¶
func GetAPIAddr ¶
GetAPIAddr formats the API address string from host and port, bracketing IPv6 addresses as needed.
Parameters:
- host: Hostname or IP address.
- port: Port number.
Returns:
- string: Formatted address string.
func New ¶
func New( log *zerolog.Logger, rateLimitPerMinute int, proxyCfg ProxyConfig, corsCfg CORSConfig, noStartupMessage bool, ) *fiber.App
New creates a new Fiber-based API application with the configured middleware stack and lifecycle hooks.
Parameters:
- log: Logger for Fiber middleware and server lifecycle messages.
- rateLimitPerMinute: Maximum requests per minute per IP. Values <= 0 fall back to defaultRateLimitPerMinute (60).
- proxyCfg: Reverse proxy configuration.
- corsCfg: CORS middleware configuration.
- noStartupMessage: When true, suppresses the HTTP API startup log entries.
Returns:
- *fiber.App: Configured Fiber application.
func NewAPIAuthMiddleware ¶
NewAPIAuthMiddleware returns a Fiber middleware that validates the HTTP API token using constant-time SHA-256 comparison.
Accepted credentials (first match wins):
- Authorization: Bearer <token>
- Authorization: <token> (raw value. Swagger UI apiKey style)
- Cookie access_token=<token>
Auth failure logs use notify=no so they never fan out through notification hooks.
func SetupAndStartAPI ¶
SetupAndStartAPI configures and launches the HTTP API.
It creates a Fiber application with the middleware stack, registers the configured endpoints, and starts the server. When the update API is enabled and UnblockHTTPAPI is false (API-only mode), this call blocks until ctx is canceled. Otherwise the server runs in the background and this function returns after the listen socket is bound so scheduled updates can run concurrently.
Parameters:
- ctx: Context for server lifecycle management.
- opts: API configuration options. opts.Logger is required when any endpoint is enabled. Nil yields config.ErrMissingLogger.
Returns:
- error: Non-nil if route registration or server startup fails.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// AllowedOrigins is a list of origins allowed to make cross-origin requests.
// Use ["*"] to allow all origins.
AllowedOrigins []string
// AllowedMethods is a list of HTTP methods allowed for cross-origin requests.
AllowedMethods []string
// AllowedHeaders is a list of headers allowed in cross-origin requests.
AllowedHeaders []string
}
CORSConfig holds configuration for CORS middleware.
type ProxyConfig ¶
type ProxyConfig struct {
// TrustedProxies is a list of trusted proxy IPs/CIDRs.
TrustedProxies []string
// ProxyHeader is the header for the real client IP (e.g. X-Forwarded-For).
ProxyHeader string
}
ProxyConfig holds configuration for reverse proxy support.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package config defines the shared configuration types, validation functions, and sentinel errors used across the API packages.
|
Package config defines the shared configuration types, validation functions, and sentinel errors used across the API packages. |
|
handlers
|
|
|
check
Package check provides the /v1/check endpoint for read-only update availability checks.
|
Package check provides the /v1/check endpoint for read-only update availability checks. |
|
config
Package config provides the HTTP handler for the /v1/config endpoint.
|
Package config provides the HTTP handler for the /v1/config endpoint. |
|
containers
Package containers provides the /v1/containers HTTP API endpoint, exposing the current image identity (name, local ID, and registry manifest digest) of each container Watchtower watches.
|
Package containers provides the /v1/containers HTTP API endpoint, exposing the current image identity (name, local ID, and registry manifest digest) of each container Watchtower watches. |
|
containers/details
Package details provides the /v1/containers/details HTTP API endpoint, exposing detailed information about a single watched container including its image identity, digest, and update availability status.
|
Package details provides the /v1/containers/details HTTP API endpoint, exposing detailed information about a single watched container including its image identity, digest, and update availability status. |
|
events
Package events provides the /v1/events HTTP API endpoint for real-time Server-Sent Events (SSE).
|
Package events provides the /v1/events HTTP API endpoint for real-time Server-Sent Events (SSE). |
|
health
Package health provides HTTP health check handlers for Watchtower.
|
Package health provides HTTP health check handlers for Watchtower. |
|
history
Package history provides the /v1/history HTTP API endpoint, exposing historical scan results from the in-memory ring buffer (up to 500 entries).
|
Package history provides the /v1/history HTTP API endpoint, exposing historical scan results from the in-memory ring buffer (up to 500 entries). |
|
images
Package images provides the /v1/images HTTP API endpoint, exposing the current image identity (name, local ID, registry manifest digest) and container count for each image Watchtower tracks.
|
Package images provides the /v1/images HTTP API endpoint, exposing the current image identity (name, local ID, registry manifest digest) and container count for each image Watchtower tracks. |
|
metrics
Package metrics provides the /v1/metrics HTTP API endpoint for serving Prometheus metrics.
|
Package metrics provides the /v1/metrics HTTP API endpoint for serving Prometheus metrics. |
|
update
Package update provides an HTTP API handler for triggering Watchtower container updates.
|
Package update provides an HTTP API handler for triggering Watchtower container updates. |
|
Package routes registers all enabled API endpoints on a Fiber application.
|
Package routes registers all enabled API endpoints on a Fiber application. |
|
Package swagger Code generated by swaggo/swag.
|
Package swagger Code generated by swaggo/swag. |