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
+4 -24
View File
@@ -3,10 +3,10 @@ package webhook
import (
"context"
"fmt"
"log"
"strconv"
"log/slog"
"strings"
"github.com/alexei/docker-watcher/internal/docker"
"github.com/alexei/docker-watcher/internal/store"
)
@@ -37,9 +37,9 @@ func AutoCreateProject(
if inspector != nil {
info, err := inspector.InspectImage(ctx, imageRef)
if err != nil {
log.Printf("[webhook] image inspection failed for %s (using defaults): %v", imageRef, err)
slog.Warn("webhook: image inspection failed, using defaults", "image", imageRef, "error", err)
} else {
port = extractPort(info.ExposedPorts)
port = docker.ExtractPort(info.ExposedPorts)
healthcheck = info.Healthcheck
}
}
@@ -89,23 +89,3 @@ func buildImageRef(parsed ParsedImage) 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
}
// Take the first port entry.
raw := exposedPorts[0]
// Strip protocol suffix (e.g. "/tcp", "/udp").
if idx := strings.Index(raw, "/"); idx != -1 {
raw = raw[:idx]
}
port, err := strconv.Atoi(raw)
if err != nil {
return 0
}
return port
}
+32 -25
View File
@@ -5,7 +5,7 @@ import (
"crypto/subtle"
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
"strings"
@@ -125,6 +125,18 @@ func (h *Handler) Route() chi.Router {
return r
}
// respondWebhookJSON writes a JSON response for webhook handlers.
func respondWebhookJSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data) //nolint:errcheck
}
// respondWebhookError writes a JSON error response for webhook handlers.
func respondWebhookError(w http.ResponseWriter, status int, msg string) {
respondWebhookJSON(w, status, map[string]any{"success": false, "error": msg})
}
// handleWebhook processes an incoming webhook request.
// URL format: POST /api/webhook/{secret-uuid}
// Returns 404 for invalid secrets (no information leak).
@@ -140,7 +152,7 @@ func (h *Handler) handleWebhook(w http.ResponseWriter, r *http.Request) {
// Validate the webhook secret against stored settings.
settings, err := h.store.GetSettings()
if err != nil {
log.Printf("[webhook] failed to read settings: %v", err)
slog.Error("webhook: failed to read settings", "error", err)
http.NotFound(w, r)
return
}
@@ -153,19 +165,18 @@ func (h *Handler) handleWebhook(w http.ResponseWriter, r *http.Request) {
// Parse the request body.
var payload Payload
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, `{"error":"invalid JSON payload"}`, http.StatusBadRequest)
respondWebhookError(w, http.StatusBadRequest, "invalid JSON payload")
return
}
if payload.Image == "" {
http.Error(w, `{"error":"missing image field"}`, http.StatusBadRequest)
respondWebhookError(w, http.StatusBadRequest, "missing image field")
return
}
parsed, err := ParseImageRef(payload.Image)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
respondWebhookError(w, http.StatusBadRequest, "invalid image reference")
return
}
@@ -174,47 +185,43 @@ func (h *Handler) handleWebhook(w http.ResponseWriter, r *http.Request) {
parsed.Tag = "latest"
}
log.Printf("[webhook] received push for image %s:%s", parsed.FullName(), parsed.Tag)
slog.Info("webhook: received push", "image", parsed.FullName(), "tag", parsed.Tag)
// Look up a matching project by image name.
project, stage, found, err := FindProjectAndStage(ctx, h.store, parsed)
if err != nil {
log.Printf("[webhook] lookup error: %v", err)
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
slog.Error("webhook: lookup error", "error", err)
respondWebhookError(w, http.StatusInternalServerError, "internal error")
return
}
if !found {
// Unknown project — auto-create with defaults from image inspection.
log.Printf("[webhook] unknown image %s, auto-creating project", parsed.FullName())
slog.Info("webhook: unknown image, auto-creating project", "image", parsed.FullName())
project, stage, err = AutoCreateProject(ctx, h.store, h.inspector, parsed)
if err != nil {
log.Printf("[webhook] auto-create failed: %v", err)
http.Error(w, `{"error":"failed to auto-create project"}`, http.StatusInternalServerError)
slog.Error("webhook: auto-create failed", "error", err)
respondWebhookError(w, http.StatusInternalServerError, "failed to auto-create project")
return
}
log.Printf("[webhook] auto-created project %s (%s) with stage %s", project.Name, project.ID, stage.Name)
slog.Info("webhook: auto-created project", "project", project.Name, "id", project.ID, "stage", stage.Name)
}
// Only deploy if auto_deploy is enabled for the matched stage.
if !stage.AutoDeploy {
log.Printf("[webhook] auto_deploy disabled for project %s stage %s, skipping deploy", project.Name, stage.Name)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]any{"status": "accepted", "deploy": false, "project": project.Name, "stage": stage.Name})
slog.Info("webhook: auto_deploy disabled, skipping", "project", project.Name, "stage", stage.Name)
respondWebhookJSON(w, http.StatusOK, map[string]any{"success": true, "deploy": false, "project": project.Name, "stage": stage.Name})
return
}
if err := h.deployer.TriggerDeploy(ctx, project.ID, stage.ID, parsed.Tag); err != nil {
log.Printf("[webhook] deploy trigger failed: %v", err)
http.Error(w, `{"error":"deploy trigger failed"}`, http.StatusInternalServerError)
slog.Error("webhook: deploy trigger failed", "error", err)
respondWebhookError(w, http.StatusInternalServerError, "deploy trigger failed")
return
}
log.Printf("[webhook] triggered deploy for project %s stage %s tag %s", project.Name, stage.Name, parsed.Tag)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]any{"status": "accepted", "deploy": true, "project": project.Name, "stage": stage.Name, "tag": parsed.Tag})
slog.Info("webhook: triggered deploy", "project", project.Name, "stage", stage.Name, "tag", parsed.Tag)
respondWebhookJSON(w, http.StatusOK, map[string]any{"success": true, "deploy": true, "project": project.Name, "stage": stage.Name, "tag": parsed.Tag})
}
// EnsureWebhookSecret checks whether a webhook secret exists in settings.
@@ -234,7 +241,7 @@ func EnsureWebhookSecret(st *store.Store) (string, error) {
return "", fmt.Errorf("store webhook secret: %w", err)
}
log.Printf("[webhook] generated new webhook secret")
slog.Info("webhook: generated new secret")
return settings.WebhookSecret, nil
}
@@ -251,6 +258,6 @@ func RegenerateWebhookSecret(st *store.Store) (string, error) {
return "", fmt.Errorf("store webhook secret: %w", err)
}
log.Printf("[webhook] regenerated webhook secret")
slog.Info("webhook: regenerated secret")
return settings.WebhookSecret, nil
}