Files
honeyDueAPI/internal/handlers/media_handler.go
Trey t 7690f07a2b Harden API security: input validation, safe auth extraction, new tests, and deploy config
Comprehensive security hardening from audit findings:
- Add validation tags to all DTO request structs (max lengths, ranges, enums)
- Replace unsafe type assertions with MustGetAuthUser helper across all handlers
- Remove query-param token auth from admin middleware (prevents URL token leakage)
- Add request validation calls in handlers that were missing c.Validate()
- Remove goroutines in handlers (timezone update now synchronous)
- Add sanitize middleware and path traversal protection (path_utils)
- Stop resetting admin passwords on migration restart
- Warn on well-known default SECRET_KEY
- Add ~30 new test files covering security regressions, auth safety, repos, and services
- Add deploy/ config, audit digests, and AUDIT_FINDINGS documentation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 09:48:01 -06:00

187 lines
5.1 KiB
Go

package handlers
import (
"strconv"
"strings"
"github.com/labstack/echo/v4"
"github.com/treytartt/casera-api/internal/apperrors"
"github.com/treytartt/casera-api/internal/middleware"
"github.com/treytartt/casera-api/internal/repositories"
"github.com/treytartt/casera-api/internal/services"
)
// MediaHandler handles authenticated media serving
type MediaHandler struct {
documentRepo *repositories.DocumentRepository
taskRepo *repositories.TaskRepository
residenceRepo *repositories.ResidenceRepository
storageSvc *services.StorageService
}
// NewMediaHandler creates a new media handler
func NewMediaHandler(
documentRepo *repositories.DocumentRepository,
taskRepo *repositories.TaskRepository,
residenceRepo *repositories.ResidenceRepository,
storageSvc *services.StorageService,
) *MediaHandler {
return &MediaHandler{
documentRepo: documentRepo,
taskRepo: taskRepo,
residenceRepo: residenceRepo,
storageSvc: storageSvc,
}
}
// ServeDocument serves a document file with access control
// GET /api/media/document/:id
func (h *MediaHandler) ServeDocument(c echo.Context) error {
user, err := middleware.MustGetAuthUser(c)
if err != nil {
return err
}
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
if err != nil {
return apperrors.BadRequest("error.invalid_id")
}
// Get document
doc, err := h.documentRepo.FindByID(uint(id))
if err != nil {
return apperrors.NotFound("error.document_not_found")
}
// Check access to residence
hasAccess, err := h.residenceRepo.HasAccess(doc.ResidenceID, user.ID)
if err != nil || !hasAccess {
return apperrors.Forbidden("error.access_denied")
}
// Serve the file
filePath := h.resolveFilePath(doc.FileURL)
if filePath == "" {
return apperrors.NotFound("error.file_not_found")
}
// Set caching headers (private, 1 hour)
c.Response().Header().Set("Cache-Control", "private, max-age=3600")
return c.File(filePath)
}
// ServeDocumentImage serves a document image with access control
// GET /api/media/document-image/:id
func (h *MediaHandler) ServeDocumentImage(c echo.Context) error {
user, err := middleware.MustGetAuthUser(c)
if err != nil {
return err
}
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
if err != nil {
return apperrors.BadRequest("error.invalid_id")
}
// Get document image
img, err := h.documentRepo.FindImageByID(uint(id))
if err != nil {
return apperrors.NotFound("error.image_not_found")
}
// Get parent document to check residence access
doc, err := h.documentRepo.FindByID(img.DocumentID)
if err != nil {
return apperrors.NotFound("error.document_not_found")
}
// Check access to residence
hasAccess, err := h.residenceRepo.HasAccess(doc.ResidenceID, user.ID)
if err != nil || !hasAccess {
return apperrors.Forbidden("error.access_denied")
}
// Serve the file
filePath := h.resolveFilePath(img.ImageURL)
if filePath == "" {
return apperrors.NotFound("error.file_not_found")
}
c.Response().Header().Set("Cache-Control", "private, max-age=3600")
return c.File(filePath)
}
// ServeCompletionImage serves a task completion image with access control
// GET /api/media/completion-image/:id
func (h *MediaHandler) ServeCompletionImage(c echo.Context) error {
user, err := middleware.MustGetAuthUser(c)
if err != nil {
return err
}
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
if err != nil {
return apperrors.BadRequest("error.invalid_id")
}
// Get completion image
img, err := h.taskRepo.FindCompletionImageByID(uint(id))
if err != nil {
return apperrors.NotFound("error.image_not_found")
}
// Get the completion to get the task
completion, err := h.taskRepo.FindCompletionByID(img.CompletionID)
if err != nil {
return apperrors.NotFound("error.completion_not_found")
}
// Get task to check residence access
task, err := h.taskRepo.FindByID(completion.TaskID)
if err != nil {
return apperrors.NotFound("error.task_not_found")
}
// Check access to residence
hasAccess, err := h.residenceRepo.HasAccess(task.ResidenceID, user.ID)
if err != nil || !hasAccess {
return apperrors.Forbidden("error.access_denied")
}
// Serve the file
filePath := h.resolveFilePath(img.ImageURL)
if filePath == "" {
return apperrors.NotFound("error.file_not_found")
}
c.Response().Header().Set("Cache-Control", "private, max-age=3600")
return c.File(filePath)
}
// resolveFilePath converts a stored URL to an actual file path.
// Returns empty string if the URL is empty or the resolved path would escape
// the upload directory (path traversal attempt).
func (h *MediaHandler) resolveFilePath(storedURL string) string {
if storedURL == "" {
return ""
}
uploadDir := h.storageSvc.GetUploadDir()
// Strip legacy /uploads/ prefix to get relative path
relativePath := storedURL
if strings.HasPrefix(storedURL, "/uploads/") {
relativePath = strings.TrimPrefix(storedURL, "/uploads/")
}
// Use SafeResolvePath to validate containment within upload directory
resolved, err := services.SafeResolvePath(uploadDir, relativePath)
if err != nil {
// Path traversal or invalid path — return empty to signal file not found
return ""
}
return resolved
}