fix: comprehensive security, performance, and quality hardening

Security: apply AdminOnly middleware to mutating routes, require
ENCRYPTION_KEY and ADMIN_PASSWORD (no insecure defaults), restrict
CORS to same-origin, fix OIDC token delivery via cookie instead of
URL query param, add rate limiting on login, add MaxBytesReader,
validate volume paths against traversal, add security headers,
validate user roles, add Secure flag to OIDC cookie.

Performance: set SQLite MaxOpenConns(1) to prevent SQLITE_BUSY,
add FK indexes on 8 columns, track notifier goroutines with
WaitGroup for graceful shutdown, use GetRegistryByName instead of
GetAllRegistries in deployer, pass basePath param to avoid redundant
settings query, return empty slices from store to remove reflection.

Quality: refactor TriggerDeploy to delegate to runDeploy (~100 lines
removed), consolidate duplicated utilities (extractPort, boolToInt,
now, isTerminalStatus) into shared exports, migrate all log.Printf
to slog structured logging, use consistent webhook response envelope,
remove dead code (parseEnvVars, duplicate auth types).

UX: clean up NPM proxy on instance removal via API, add README with
quickstart guide, add .env.example, require ADMIN_PASSWORD in
docker-compose, document staging-net prerequisite.
This commit is contained in:
2026-03-29 12:49:24 +03:00
parent c5bfc586c1
commit be6ad15efc
32 changed files with 519 additions and 392 deletions
+33 -4
View File
@@ -14,6 +14,21 @@ import (
"github.com/alexei/docker-watcher/internal/store"
)
// rateLimitedLogin wraps the login handler with per-IP rate limiting.
func (s *Server) rateLimitedLogin(rl *rateLimiter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
ip = fwd
}
if !rl.allow(ip) {
respondError(w, http.StatusTooManyRequests, "too many login attempts, try again later")
return
}
s.login(w, r)
}
}
// login handles POST /api/auth/login.
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
var req auth.LoginRequest
@@ -32,7 +47,8 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
respondError(w, http.StatusUnauthorized, "invalid credentials")
return
}
respondError(w, http.StatusInternalServerError, "failed to get user: "+err.Error())
slog.Error("failed to get user", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
@@ -93,6 +109,7 @@ func (s *Server) oidcLogin(w http.ResponseWriter, r *http.Request) {
Path: "/api/auth/oidc",
MaxAge: 300, // 5 minutes
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
})
@@ -177,9 +194,17 @@ func (s *Server) oidcCallback(w http.ResponseWriter, r *http.Request) {
return
}
// Redirect to frontend with token in query parameter.
// The frontend extracts the token and stores it in localStorage.
http.Redirect(w, r, "/?token="+token.Token, http.StatusFound)
// Set the token in a short-lived cookie the frontend can read once.
http.SetCookie(w, &http.Cookie{
Name: "auth_token",
Value: token.Token,
Path: "/",
MaxAge: 60, // 1 minute — frontend reads it immediately
HttpOnly: false,
Secure: true,
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/?oidc=success", http.StatusFound)
}
// getAuthSettings handles GET /api/auth/settings.
@@ -270,6 +295,10 @@ func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
if req.Role == "" {
req.Role = "viewer"
}
if req.Role != "admin" && req.Role != "viewer" {
respondError(w, http.StatusBadRequest, "role must be 'admin' or 'viewer'")
return
}
hash, err := auth.HashPassword(req.Password)
if err != nil {
+2 -14
View File
@@ -6,6 +6,7 @@ import (
"strconv"
"strings"
"github.com/alexei/docker-watcher/internal/docker"
"github.com/alexei/docker-watcher/internal/store"
)
@@ -71,7 +72,7 @@ func (s *Server) inspectImage(w http.ResponseWriter, r *http.Request) {
return
}
port := extractPort(info.ExposedPorts)
port := docker.ExtractPort(info.ExposedPorts)
respondJSON(w, http.StatusOK, inspectResponse{
Image: req.Image,
@@ -165,16 +166,3 @@ func splitImageTag(ref string) (string, string) {
return ref, ""
}
// extractPort parses the first exposed port from Docker EXPOSE entries.
// Entries are in the form "8080/tcp" or "8080". Returns 0 if none found.
func extractPort(exposedPorts []string) int {
if len(exposedPorts) == 0 {
return 0
}
raw := exposedPorts[0]
if idx := strings.Index(raw, "/"); idx != -1 {
raw = raw[:idx]
}
port, _ := strconv.Atoi(raw)
return port
}
+17 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/alexei/docker-watcher/internal/crypto"
"github.com/alexei/docker-watcher/internal/store"
)
@@ -109,9 +110,24 @@ func (s *Server) removeInstance(w http.ResponseWriter, r *http.Request) {
}
}
// Delete NPM proxy host if it has one.
if inst.NpmProxyID > 0 {
settings, err := s.store.GetSettings()
if err == nil {
npmPassword, err := crypto.Decrypt(s.encKey, settings.NpmPassword)
if err == nil {
if authErr := s.npm.Authenticate(r.Context(), settings.NpmEmail, npmPassword); authErr == nil {
if delErr := s.npm.DeleteProxyHost(r.Context(), inst.NpmProxyID); delErr != nil {
slog.Warn("delete proxy host on instance removal", "proxy_id", inst.NpmProxyID, "error", delErr)
}
}
}
}
}
// Delete instance record.
if err := s.store.DeleteInstance(instanceID); err != nil {
respondError(w, http.StatusInternalServerError, "failed to delete instance: "+err.Error())
respondError(w, http.StatusInternalServerError, "failed to delete instance")
return
}
respondJSON(w, http.StatusOK, map[string]string{"deleted": instanceID})
+68 -4
View File
@@ -4,6 +4,7 @@ import (
"log/slog"
"net/http"
"runtime/debug"
"sync"
"time"
)
@@ -38,12 +39,29 @@ func recovery(next http.Handler) http.Handler {
})
}
// cors is an HTTP middleware that sets permissive CORS headers for development.
// securityHeaders sets standard security headers on all responses.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
next.ServeHTTP(w, r)
})
}
// cors is an HTTP middleware that restricts CORS to same-origin requests.
// The frontend is served from the same origin, so no wildcard is needed.
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
origin := r.Header.Get("Origin")
if origin != "" {
// Only allow the same origin (frontend is served from the same host).
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Vary", "Origin")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
@@ -54,6 +72,52 @@ func cors(next http.Handler) http.Handler {
})
}
// maxBodySize limits request body sizes to prevent memory exhaustion.
const maxBodySize = 1 << 20 // 1 MB
func limitBody(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxBodySize)
next.ServeHTTP(w, r)
})
}
// rateLimiter provides per-IP rate limiting for login endpoints.
type rateLimiter struct {
mu sync.Mutex
attempts map[string][]time.Time
}
func newRateLimiter() *rateLimiter {
return &rateLimiter{attempts: make(map[string][]time.Time)}
}
// allow checks if the IP is allowed to make another request.
// Returns false if the IP has exceeded the limit (10 requests per minute).
func (rl *rateLimiter) allow(ip string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
window := now.Add(-1 * time.Minute)
// Clean old entries.
filtered := rl.attempts[ip][:0]
for _, t := range rl.attempts[ip] {
if t.After(window) {
filtered = append(filtered, t)
}
}
rl.attempts[ip] = filtered
if len(filtered) >= 10 {
return false
}
rl.attempts[ip] = append(rl.attempts[ip], now)
return true
}
// jsonContentType is an HTTP middleware that sets the default Content-Type to JSON.
func jsonContentType(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-9
View File
@@ -4,7 +4,6 @@ import (
"encoding/json"
"log/slog"
"net/http"
"reflect"
)
// envelope is the standard API response wrapper.
@@ -15,15 +14,7 @@ type envelope struct {
}
// respondJSON writes a JSON success response with the given status code and data.
// Nil slices are converted to empty arrays to avoid "null" in JSON output.
func respondJSON(w http.ResponseWriter, status int, data any) {
// Convert nil slices to empty arrays so JSON encodes as [] not null.
if data != nil {
v := reflect.ValueOf(data)
if v.Kind() == reflect.Slice && v.IsNil() {
data = reflect.MakeSlice(v.Type(), 0, 0).Interface()
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(envelope{Success: true, Data: data}); err != nil {
+74 -59
View File
@@ -10,6 +10,7 @@ import (
"github.com/alexei/docker-watcher/internal/crypto"
"github.com/alexei/docker-watcher/internal/docker"
"github.com/alexei/docker-watcher/internal/events"
"github.com/alexei/docker-watcher/internal/npm"
"github.com/alexei/docker-watcher/internal/store"
"github.com/alexei/docker-watcher/internal/webhook"
)
@@ -18,6 +19,7 @@ import (
type Server struct {
store *store.Store
docker *docker.Client
npm *npm.Client
deployer DeployTriggerer
webhook *webhook.Handler
eventBus *events.Bus
@@ -30,6 +32,7 @@ type Server struct {
func NewServer(
st *store.Store,
dockerClient *docker.Client,
npmClient *npm.Client,
deployer DeployTriggerer,
webhookHandler *webhook.Handler,
eventBus *events.Bus,
@@ -40,6 +43,7 @@ func NewServer(
s := &Server{
store: st,
docker: dockerClient,
npm: npmClient,
deployer: deployer,
webhook: webhookHandler,
eventBus: eventBus,
@@ -86,15 +90,19 @@ func (s *Server) Router() chi.Router {
// Global middleware.
r.Use(recovery)
r.Use(securityHeaders)
r.Use(logging)
r.Use(cors)
loginLimiter := newRateLimiter()
r.Route("/api", func(r chi.Router) {
// JSON content type only for API routes (not static files).
// JSON content type and body size limit for API routes.
r.Use(jsonContentType)
r.Use(limitBody)
// Public auth endpoints (no auth required).
r.Post("/auth/login", s.login)
r.Post("/auth/login", s.rateLimitedLogin(loginLimiter))
r.Get("/auth/oidc/login", s.oidcLogin)
r.Get("/auth/oidc/callback", s.oidcCallback)
@@ -105,80 +113,87 @@ func (s *Server) Router() chi.Router {
r.Group(func(r chi.Router) {
r.Use(auth.Middleware(s.localAuth))
// Config export (protected — reveals project/infra details).
r.Get("/config/export", s.exportConfig)
// Auth management.
// Read-only endpoints (any authenticated user).
r.Get("/auth/me", s.currentUser)
r.Get("/auth/settings", s.getAuthSettings)
r.Put("/auth/settings", s.updateAuthSettings)
r.Get("/auth/users", s.listUsers)
r.Post("/auth/users", s.createUser)
r.Delete("/auth/users/{uid}", s.deleteUser)
// Project endpoints.
r.Get("/projects", s.listProjects)
r.Post("/projects", s.createProject)
r.Route("/projects/{id}", func(r chi.Router) {
r.Get("/", s.getProject)
r.Put("/", s.updateProject)
r.Delete("/", s.deleteProject)
// Stage endpoints.
r.Post("/stages", s.createStage)
r.Put("/stages/{stage}", s.updateStage)
r.Delete("/stages/{stage}", s.deleteStage)
// Stage env override endpoints.
r.Get("/stages/{stage}/env", s.listStageEnv)
r.Post("/stages/{stage}/env", s.createStageEnv)
r.Put("/stages/{stage}/env/{envId}", s.updateStageEnv)
r.Delete("/stages/{stage}/env/{envId}", s.deleteStageEnv)
// Instance endpoints.
r.Get("/stages/{stage}/instances", s.listInstances)
r.Post("/stages/{stage}/instances", s.deployInstance)
r.Delete("/stages/{stage}/instances/{iid}", s.removeInstance)
// Instance control endpoints.
r.Post("/stages/{stage}/instances/{iid}/stop", s.stopInstance)
r.Post("/stages/{stage}/instances/{iid}/start", s.startInstance)
r.Post("/stages/{stage}/instances/{iid}/restart", s.restartInstance)
// Volume endpoints.
r.Get("/volumes", s.listVolumes)
r.Post("/volumes", s.createVolume)
r.Put("/volumes/{volId}", s.updateVolume)
r.Delete("/volumes/{volId}", s.deleteVolume)
})
// Deploy endpoints.
r.Get("/deploys", s.listDeploys)
r.Get("/deploys/{id}/logs", s.streamDeployLogs)
// SSE endpoint for real-time instance status and deploy events.
r.Get("/events", s.streamEvents)
// Quick deploy endpoints.
r.Post("/deploy/inspect", s.inspectImage)
r.Post("/deploy/quick", s.quickDeploy)
// Registry endpoints.
r.Get("/registries", s.listRegistries)
r.Post("/registries", s.createRegistry)
r.Route("/registries/{id}", func(r chi.Router) {
r.Put("/", s.updateRegistry)
r.Delete("/", s.deleteRegistry)
r.Post("/test", s.testRegistry)
r.Get("/tags/*", s.listRegistryTags)
r.Get("/images", s.listRegistryImages)
})
// Settings endpoints.
r.Get("/settings", s.getSettings)
r.Put("/settings", s.updateSettings)
r.Get("/settings/webhook-url", s.getWebhookURL)
r.Post("/settings/webhook-url/regenerate", s.regenerateWebhookSecret)
// Admin-only routes: require admin role.
r.Group(func(r chi.Router) {
r.Use(auth.AdminOnly)
// Config export (reveals project/infra details).
r.Get("/config/export", s.exportConfig)
// Auth management.
r.Get("/auth/settings", s.getAuthSettings)
r.Put("/auth/settings", s.updateAuthSettings)
r.Get("/auth/users", s.listUsers)
r.Post("/auth/users", s.createUser)
r.Delete("/auth/users/{uid}", s.deleteUser)
// Project mutation endpoints.
r.Post("/projects", s.createProject)
r.Route("/projects/{id}", func(r chi.Router) {
r.Put("/", s.updateProject)
r.Delete("/", s.deleteProject)
// Stage endpoints.
r.Post("/stages", s.createStage)
r.Put("/stages/{stage}", s.updateStage)
r.Delete("/stages/{stage}", s.deleteStage)
// Stage env override endpoints.
r.Post("/stages/{stage}/env", s.createStageEnv)
r.Put("/stages/{stage}/env/{envId}", s.updateStageEnv)
r.Delete("/stages/{stage}/env/{envId}", s.deleteStageEnv)
// Instance endpoints.
r.Post("/stages/{stage}/instances", s.deployInstance)
r.Delete("/stages/{stage}/instances/{iid}", s.removeInstance)
// Instance control endpoints.
r.Post("/stages/{stage}/instances/{iid}/stop", s.stopInstance)
r.Post("/stages/{stage}/instances/{iid}/start", s.startInstance)
r.Post("/stages/{stage}/instances/{iid}/restart", s.restartInstance)
// Volume endpoints.
r.Post("/volumes", s.createVolume)
r.Put("/volumes/{volId}", s.updateVolume)
r.Delete("/volumes/{volId}", s.deleteVolume)
})
// Quick deploy endpoints.
r.Post("/deploy/inspect", s.inspectImage)
r.Post("/deploy/quick", s.quickDeploy)
// Registry mutation endpoints.
r.Post("/registries", s.createRegistry)
r.Route("/registries/{id}", func(r chi.Router) {
r.Put("/", s.updateRegistry)
r.Delete("/", s.deleteRegistry)
r.Post("/test", s.testRegistry)
})
// Settings endpoints.
r.Put("/settings", s.updateSettings)
r.Get("/settings/webhook-url", s.getWebhookURL)
r.Post("/settings/webhook-url/regenerate", s.regenerateWebhookSecret)
})
})
})
+1 -6
View File
@@ -183,10 +183,5 @@ func writeSSE(w http.ResponseWriter, flusher http.Flusher, evt events.Event) {
// isTerminalStatus returns true if the deploy status is final.
func isTerminalStatus(status string) bool {
switch status {
case "success", "failed", "rolled_back":
return true
default:
return false
}
return store.IsTerminalDeployStatus(status)
}
+16
View File
@@ -3,12 +3,20 @@ package api
import (
"errors"
"net/http"
"path/filepath"
"strings"
"github.com/go-chi/chi/v5"
"github.com/alexei/docker-watcher/internal/store"
)
// validateVolumePath checks that the source path does not contain path traversal.
func validateVolumePath(source string) bool {
cleaned := filepath.Clean(source)
return !strings.Contains(cleaned, "..")
}
// volumeRequest is the expected JSON body for creating/updating a volume.
type volumeRequest struct {
Source string `json:"source"`
@@ -66,6 +74,14 @@ func (s *Server) createVolume(w http.ResponseWriter, r *http.Request) {
respondError(w, http.StatusBadRequest, "target is required")
return
}
if !validateVolumePath(req.Source) {
respondError(w, http.StatusBadRequest, "source path must not contain '..'")
return
}
if !validateVolumePath(req.Target) {
respondError(w, http.StatusBadRequest, "target path must not contain '..'")
return
}
if req.Mode == "" {
req.Mode = "shared"
}