web

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package web serves the browser interface and the REST API used to inspect jobs, trigger runs, and manage jobs created at runtime.

Index

Constants

View Source
const (
	// BearerPrefix is the prefix for Bearer tokens in Authorization header
	BearerPrefix = "Bearer"
)

Variables

View Source
var ErrInvalidTrustedProxy = errors.New("invalid trusted proxy")

ErrInvalidTrustedProxy indicates a trusted proxy value could not be parsed.

Functions

func HashPassword added in v0.10.1

func HashPassword(password string) (string, error)

HashPassword generates a bcrypt hash of the password

func ParseTrustedProxies added in v0.21.2

func ParseTrustedProxies(cidrs []string) ([]*net.IPNet, error)

ParseTrustedProxies parses a slice of CIDR strings (e.g. "172.17.0.0/16", "10.0.0.1/32") into []*net.IPNet. Plain IPs without a mask are treated as /32 (IPv4) or /128 (IPv6).

Types

type HealthCheck added in v0.10.1

type HealthCheck struct {
	Name        string        `json:"name"`
	Status      HealthStatus  `json:"status"`
	Message     string        `json:"message,omitempty"`
	LastChecked time.Time     `json:"lastChecked"`
	Duration    time.Duration `json:"durationMs"`
}

HealthCheck represents a single health check

type HealthChecker added in v0.10.1

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

HealthChecker performs health checks

func NewHealthChecker added in v0.10.1

func NewHealthChecker(dockerProvider core.DockerProvider, scheduler *core.Scheduler, version string) *HealthChecker

NewHealthChecker creates a new health checker.

The scheduler may be nil, in which case the scheduler check reports what it can see rather than claiming health it has not established.

func (*HealthChecker) GetHealth added in v0.10.1

func (hc *HealthChecker) GetHealth() HealthResponse

GetHealth returns the current health status

func (*HealthChecker) HealthHandler added in v0.10.1

func (hc *HealthChecker) HealthHandler() http.HandlerFunc

HealthHandler returns detailed health information

func (*HealthChecker) LivenessHandler added in v0.10.1

func (hc *HealthChecker) LivenessHandler() http.HandlerFunc

LivenessHandler returns a simple liveness check

func (*HealthChecker) ReadinessHandler added in v0.10.1

func (hc *HealthChecker) ReadinessHandler() http.HandlerFunc

ReadinessHandler returns readiness status

func (*HealthChecker) Stop added in v0.29.0

func (hc *HealthChecker) Stop()

Stop ends the periodic check loop.

Without it the loop ran until the process exited, so every checker ever constructed kept a goroutine alive — harmless for the daemon's single long-lived instance, but tests that build one per case leaked one each. Safe to call more than once and from several goroutines.

type HealthResponse added in v0.10.1

type HealthResponse struct {
	Status    HealthStatus           `json:"status"`
	Timestamp time.Time              `json:"timestamp"`
	Uptime    float64                `json:"uptimeSeconds"`
	Version   string                 `json:"version"`
	Checks    map[string]HealthCheck `json:"checks"`
	System    SystemInfo             `json:"system"`
}

HealthResponse represents the health check response

type HealthStatus added in v0.10.1

type HealthStatus string

HealthStatus represents the overall health status

const (
	HealthStatusHealthy   HealthStatus = "healthy"
	HealthStatusDegraded  HealthStatus = "degraded"
	HealthStatusUnhealthy HealthStatus = "unhealthy"
)

The statuses a single check, and the aggregate health report, can carry. GetHealth folds the individual checks into the worst status present, so one unhealthy check makes the whole report unhealthy. Only the readiness endpoint acts on the value, and only for Unhealthy: /ready answers 503 for it and 200 for the other two, so a degraded ofelia stays in rotation. /health and /healthz always answer 200 and put the status in the body.

type RateLimiter added in v0.10.1

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

RateLimiter manages login attempt rate limiting

func NewRateLimiter added in v0.10.1

func NewRateLimiter(ratePerMinute, burst int) *RateLimiter

NewRateLimiter returns a limiter that refills each key's bucket at ratePerMinute tokens per minute and lets burst of them be spent at once. Keys are opaque to the limiter; the login path uses the client IP.

ratePerMinute must be greater than zero — GetLimiter divides by it, so a zero rate panics on the first request rather than at construction. Buckets are created on demand and never expire by themselves, so a caller that can vary its key grows the map unboundedly unless CleanupOldLimiters is called periodically.

func (*RateLimiter) Allow added in v0.10.1

func (rl *RateLimiter) Allow(key string) bool

Allow consumes one token from key's bucket and reports whether the attempt may proceed. It never blocks: a false result means "reject now" (the login handler answers 429), not "wait and retry".

func (*RateLimiter) CleanupOldLimiters added in v0.10.1

func (rl *RateLimiter) CleanupOldLimiters(maxAge time.Duration)

CleanupOldLimiters removes limiters that haven't been accessed for the given maxAge.

func (*RateLimiter) GetLimiter added in v0.10.1

func (rl *RateLimiter) GetLimiter(key string) *rate.Limiter

GetLimiter returns the bucket for key, creating it on first use, and stamps the access time that CleanupOldLimiters later uses to evict idle keys. Safe for concurrent use; it takes the write lock on every call because of that bookkeeping, so it is not a cheap read path.

type SecureAuthConfig added in v0.10.1

type SecureAuthConfig struct {
	Enabled        bool     `json:"enabled"`
	Username       string   `json:"username"`
	PasswordHash   string   `json:"passwordHash"` // bcrypt hash of password
	SecretKey      string   `json:"secretKey"`
	TokenExpiry    int      `json:"tokenExpiry"`    // in hours
	MaxAttempts    int      `json:"maxAttempts"`    // max login attempts per minute
	TrustedProxies []string `json:"trustedProxies"` // CIDRs or IPs whose X-Forwarded-For is trusted
}

SecureAuthConfig holds secure authentication configuration

type SecureLoginHandler added in v0.10.1

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

SecureLoginHandler handles authentication with security best practices

func NewSecureLoginHandler added in v0.10.1

func NewSecureLoginHandler(
	config *SecureAuthConfig, tm *SecureTokenManager, rl *RateLimiter, trustedProxies ...*net.IPNet,
) *SecureLoginHandler

NewSecureLoginHandler returns the handler backing POST /api/login. Per request it rate limits on the client IP through rl, requires a valid one-time CSRF token in X-CSRF-Token, compares the submitted username against config.Username in constant time and the password against config.PasswordHash with bcrypt, and on success issues an auth token both in the JSON body and as an HttpOnly, SameSite=Strict cookie.

trustedProxies are the peers whose X-Forwarded-For and X-Real-IP headers are believed when deriving that client IP; headers from any other peer are ignored. Loopback is always trusted, so passing none still trusts a proxy on the same host.

It does not consult config.Enabled and does no authorization beyond the credential check — deciding whether to mount it, and what an authenticated user may then do, is the caller's job.

func (*SecureLoginHandler) ServeHTTP added in v0.10.1

func (h *SecureLoginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type SecureTokenManager added in v0.10.1

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

SecureTokenManager handles token management with enhanced security

func NewSecureTokenManager added in v0.10.1

func NewSecureTokenManager(secretKey string, expiryHours int) (*SecureTokenManager, error)

NewSecureTokenManager returns a manager that issues and tracks auth tokens (valid for expiryHours) and one-time CSRF tokens (valid for one hour). Both kinds are random values kept in memory and validated by lookup: they do not survive a restart and are not shared between instances. secretKey is stored on the manager but is not currently used to sign or derive anything, so supplying one does not make tokens portable; an empty secretKey is replaced by 32 random bytes, and the only error returned is a failure to read that randomness.

It starts a goroutine that sweeps expired tokens hourly, so every manager must eventually be closed with Close.

func (*SecureTokenManager) Close added in v0.21.0

func (tm *SecureTokenManager) Close()

Close stops the cleanup goroutine. It is safe to call multiple times.

func (*SecureTokenManager) GenerateCSRFToken added in v0.10.1

func (tm *SecureTokenManager) GenerateCSRFToken() (string, error)

GenerateCSRFToken creates a new CSRF token

func (*SecureTokenManager) GenerateToken added in v0.10.1

func (tm *SecureTokenManager) GenerateToken(username string) (string, error)

GenerateToken creates a new authentication token

func (*SecureTokenManager) RevokeToken added in v0.10.1

func (tm *SecureTokenManager) RevokeToken(token string)

RevokeToken invalidates a token

func (*SecureTokenManager) ValidateCSRFToken added in v0.10.1

func (tm *SecureTokenManager) ValidateCSRFToken(token string) bool

ValidateCSRFToken checks if a CSRF token is valid

func (*SecureTokenManager) ValidateToken added in v0.10.1

func (tm *SecureTokenManager) ValidateToken(token string) (*TokenData, bool)

ValidateToken checks if a token is valid

type Server

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

Server is the HTTP front end of a running scheduler: the JSON API under /api, the embedded single-page UI, and — once RegisterHealthEndpoints has been called — the health and readiness probes. It owns the middleware chain (rate limiting, security headers, optional token auth) and the bookkeeping that decides which jobs the API is allowed to mutate.

Build one with NewServer or NewServerWithAuth; the zero value is not usable.

func NewServer

func NewServer(addr string, s *core.Scheduler, cfg any, provider core.DockerProvider) *Server

NewServer builds an unauthenticated Server on addr for scheduler s. cfg is the parsed configuration served by /api/config and reflected over to tell config-owned jobs from API-created ones; provider is the Docker client the handlers use.

This is NewServerWithAuth with no auth config: every route, including the job create/update/delete endpoints, is reachable without credentials, so only bind it where that is acceptable. Returns nil if construction failed.

func NewServerWithAuth added in v0.17.0

func NewServerWithAuth(addr string, s *core.Scheduler, cfg any, provider core.DockerProvider, authCfg *SecureAuthConfig) *Server

NewServerWithAuth builds a Server on addr and assembles its handler chain: the API routes and embedded UI, wrapped in a 100-request-per-minute per-IP rate limiter and the security headers, and — only when authCfg is non-nil and Enabled — token authentication plus the /api/login, /api/logout, /api/auth/status and /api/csrf-token endpoints. Authentication covers the /api/ routes only: the static UI, the login/CSRF/auth-status endpoints and the health probes stay reachable without a token. A nil or disabled authCfg leaves everything open; there is no partial mode.

Returns nil, after logging the reason, when the token manager cannot be created or the embedded UI assets cannot be opened — callers must check for nil rather than assume a usable server. Nothing is listening until Start.

func (*Server) GetHTTPServer added in v0.10.1

func (s *Server) GetHTTPServer() *http.Server

GetHTTPServer returns the underlying http.Server for graceful shutdown support

func (*Server) HTTPServer added in v0.9.0

func (s *Server) HTTPServer() *http.Server

HTTPServer returns the underlying http.Server used by the web interface. It is exposed for tests and may change if the Server struct evolves.

func (*Server) MarkOriginAPI added in v0.26.0

func (s *Server) MarkOriginAPI(name string)

MarkOriginAPI records that the named job came from the API/UI so the delete handler's origin gate (#593) recognizes it after a daemon restart. The persist loader in cli/daemon.go calls this for every job materialized from the state file — otherwise jobOrigin() would fall through to config reflection and either find the stale INI entry (refusing delete) or return "" (passing the gate only by the `origin != ""` clause, which any future tightening would silently break). Safe to call only before Start.

func (*Server) RegisterHealthEndpoints added in v0.10.1

func (s *Server) RegisterHealthEndpoints(hc *HealthChecker)

RegisterHealthEndpoints rebuilds the whole route table so that hc's /health, /healthz, /ready and /live endpoints sit next to the API and UI routes, and installs the result on the running http.Server. The probes stay exempt from authentication but still pass through the security headers and the rate limiter, which is replaced by a fresh one here, discarding the request counters accumulated so far.

Call it before Start: it assigns http.Server.Handler, which is racy once the server is serving. It does nothing if the Server was not constructed successfully.

func (*Server) SetPersistStore added in v0.26.0

func (s *Server) SetPersistStore(store *persist.Store)

SetPersistStore wires the daemon-owned persistence store into the server so create/update/delete/disable/enable handlers can record their mutations across restarts. Pass nil to disable persistence (the default). Safe to call only before Start.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown stops the background goroutines of the rate limiter and the token manager, then gracefully shuts the HTTP server down, letting in-flight requests finish until ctx expires. A Server that has been shut down cannot be started again.

func (*Server) Start

func (s *Server) Start() error

Start serves in a background goroutine and returns immediately, always with a nil error. ListenAndServe's error is discarded, so a failure to bind addr shows up as refused connections rather than as a return value here — check reachability if you need to know the listener came up. Stop with Shutdown.

type SystemInfo added in v0.10.1

type SystemInfo struct {
	GoVersion    string `json:"goVersion"`
	NumGoroutine int    `json:"goroutines"`
	NumCPU       int    `json:"cpus"`
	MemoryAlloc  uint64 `json:"memoryAllocBytes"`
	MemoryTotal  uint64 `json:"memoryTotalBytes"`
	GCRuns       uint32 `json:"gcRuns"`
}

SystemInfo contains system-level information

type TokenData added in v0.10.1

type TokenData struct {
	Username  string    `json:"username"`
	ExpiresAt time.Time `json:"expiresAt"`
}

TokenData is the server-side record behind an issued auth token: the user it was minted for and the instant it stops being accepted. Tokens themselves are opaque random strings carrying no claims, so this record — held only in a SecureTokenManager's in-memory map — is the sole authority on who a token belongs to. It is therefore lost on restart, and revoking a token takes effect immediately rather than at expiry.

Jump to

Keyboard shortcuts

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