diff --git a/backend/internal/web/handlers_files.go b/backend/internal/web/handlers_files.go new file mode 100644 index 0000000..8bce45e --- /dev/null +++ b/backend/internal/web/handlers_files.go @@ -0,0 +1,266 @@ +package web + +import ( + "errors" + "log/slog" + "net/http" + + "backend/internal/auth" + "backend/internal/db/sqlc" + "backend/internal/files" + "backend/templates" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + "github.com/gorilla/csrf" + "github.com/jackc/pgx/v5" +) + +// FileStorer is the interface satisfied by files.Store and used for test injection. +// Aliased here so web package can reference it without importing internal/files in tests. +type FileStorer = files.FileStorer + +// FilesDeps holds dependencies for all file handlers. +type FilesDeps struct { + Queries *sqlc.Queries + Files FileStorer // interface — allows stub injection in tests + MaxUploadMB int // parsed from MAX_UPLOAD_SIZE_MB env var (default 25) +} + +// loadOwnedTabloForFile is the shared preamble for all /tablos/{id}/files/{file_id}* +// handlers. It calls loadOwnedTablo for tablo ownership verification, then parses +// the {file_id} URL param and fetches the file (verifying it belongs to the tablo). +// Returns (tablo, file, user, true) on success. On failure it writes the appropriate +// HTTP response and returns false; callers must return immediately. +func loadOwnedTabloForFile(w http.ResponseWriter, r *http.Request, deps FilesDeps) (sqlc.Tablo, sqlc.TabloFile, *auth.User, bool) { + tablo, user, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries}) + if !ok { + return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false + } + + fileID, err := uuid.Parse(chi.URLParam(r, "file_id")) + if err != nil { + http.NotFound(w, r) + return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false + } + + file, err := deps.Queries.GetTabloFileByID(r.Context(), sqlc.GetTabloFileByIDParams{ + ID: fileID, + TabloID: tablo.ID, + }) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + http.NotFound(w, r) + return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false + } + slog.Default().Error("files: GetTabloFileByID failed", "id", fileID, "err", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false + } + + return tablo, file, user, true +} + +// TabloFilesTabHandler handles GET /tablos/{id}/files. +// Returns the FilesTabFragment for HTMX requests or the full TabloDetailPage otherwise. +// +// Security: deps.Files nil guard is the FIRST statement (T-05-02-06). +// Ownership enforced by loadOwnedTablo (T-05-02-04). +func TabloFilesTabHandler(deps FilesDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if deps.Files == nil { + http.Error(w, "storage not configured", http.StatusServiceUnavailable) + return + } + tablo, user, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries}) + if !ok { + return + } + fileList, err := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID) + if err != nil { + slog.Default().Error("files tab: ListFilesByTablo failed", "tablo_id", tablo.ID, "err", err) + fileList = []sqlc.TabloFile{} + } + if fileList == nil { + fileList = []sqlc.TabloFile{} + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if r.Header.Get("HX-Request") == "true" { + _ = templates.FilesTabFragment(tablo, fileList, csrf.Token(r)).Render(r.Context(), w) + return + } + _ = templates.TabloDetailPage(user, csrf.Token(r), tablo, nil, fileList, "files").Render(r.Context(), w) + } +} + +// TabloTasksTabHandler handles GET /tablos/{id}/tasks (Tasks tab entry point). +// Returns the TasksTabFragment for HTMX requests or the full TabloDetailPage otherwise. +// Lives here (not handlers_tasks.go) because it is part of the tab wiring introduced +// in Phase 5 alongside FilesTabHandler. +func TabloTasksTabHandler(deps FilesDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + tablo, user, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries}) + if !ok { + return + } + tasks, err := deps.Queries.ListTasksByTablo(r.Context(), tablo.ID) + if err != nil { + slog.Default().Error("tasks tab: ListTasksByTablo failed", "tablo_id", tablo.ID, "err", err) + tasks = []sqlc.Task{} + } + if tasks == nil { + tasks = []sqlc.Task{} + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if r.Header.Get("HX-Request") == "true" { + _ = templates.TasksTabFragment(tablo, tasks, csrf.Token(r)).Render(r.Context(), w) + return + } + _ = templates.TabloDetailPage(user, csrf.Token(r), tablo, tasks, nil, "tasks").Render(r.Context(), w) + } +} + +// FileUploadHandler handles POST /tablos/{id}/files. +// Accepts a multipart file, streams it to S3 via deps.Files.Upload, inserts a +// tablo_files row, and returns the updated file list fragment (HTMX) or redirects (non-HTMX). +// +// Security invariants: +// - deps.Files nil guard is the FIRST statement before reading any request body (T-05-02-06) +// - r.Body wrapped with http.MaxBytesReader BEFORE ParseMultipartForm (T-05-02-02, Pitfall 2) +// - filename stored as display string only; S3 key is "files/{uuid}" — never reaches FS (T-05-02-01, D-04) +// - content-type sniffed server-side by files.Store.Upload (T-05-02-03, D-05) +// - tablo ownership verified by loadOwnedTablo (T-05-02-04, FILE-06) +func FileUploadHandler(deps FilesDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if deps.Files == nil { + http.Error(w, "storage not configured", http.StatusServiceUnavailable) + return + } + tablo, _, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries}) + if !ok { + return + } + + maxBytes := int64(deps.MaxUploadMB) * 1024 * 1024 + r.Body = http.MaxBytesReader(w, r.Body, maxBytes) // MUST be before ParseMultipartForm (Pitfall 2) + + if err := r.ParseMultipartForm(2 << 20); err != nil { + var mbErr *http.MaxBytesError + if errors.As(err, &mbErr) { + // Re-list files so the error fragment shows the current list. + fileList, _ := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID) + if fileList == nil { + fileList = []sqlc.TabloFile{} + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusUnprocessableEntity) + errMsg := "File too large (max %d MB)." + _ = templates.UploadErrorFragment(tablo, fileList, csrf.Token(r), formatMBError(deps.MaxUploadMB)).Render(r.Context(), w) + _ = errMsg + return + } + http.Error(w, "bad request", http.StatusBadRequest) + return + } + + file, header, err := r.FormFile("file") + if err != nil { + http.Error(w, "bad request: missing file field", http.StatusBadRequest) + return + } + defer file.Close() + + fileUUID := uuid.New() + s3Key := "files/" + tablo.ID.String() + "/" + fileUUID.String() // D-04 + + contentType, bytesWritten, err := deps.Files.Upload(r.Context(), s3Key, file) + if err != nil { + slog.Default().Error("files upload: Upload failed", "tablo_id", tablo.ID, "err", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return + } + + _, err = deps.Queries.InsertTabloFile(r.Context(), sqlc.InsertTabloFileParams{ + TabloID: tablo.ID, + S3Key: s3Key, + Filename: header.Filename, + ContentType: contentType, + SizeBytes: bytesWritten, + }) + if err != nil { + slog.Default().Error("files upload: InsertTabloFile failed", "tablo_id", tablo.ID, "err", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return + } + + updatedFiles, err := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID) + if err != nil { + slog.Default().Error("files upload: ListFilesByTablo failed", "tablo_id", tablo.ID, "err", err) + updatedFiles = []sqlc.TabloFile{} + } + if updatedFiles == nil { + updatedFiles = []sqlc.TabloFile{} + } + + if r.Header.Get("HX-Request") == "true" { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("HX-Retarget", "#tab-content") + w.Header().Set("HX-Reswap", "innerHTML") + _ = templates.FilesTabFragment(tablo, updatedFiles, csrf.Token(r)).Render(r.Context(), w) + return + } + http.Redirect(w, r, "/tablos/"+tablo.ID.String()+"/files", http.StatusSeeOther) + } +} + +// formatMBError formats the too-large error message with the max MB limit. +func formatMBError(maxMB int) string { + return "File too large (max " + itoa(maxMB) + " MB)." +} + +// itoa converts an integer to a string without importing strconv in this file. +func itoa(n int) string { + if n == 0 { + return "0" + } + neg := false + if n < 0 { + neg = true + n = -n + } + buf := make([]byte, 0, 10) + for n > 0 { + buf = append([]byte{byte('0' + n%10)}, buf...) + n /= 10 + } + if neg { + buf = append([]byte{'-'}, buf...) + } + return string(buf) +} + +// FileDownloadHandler handles GET /tablos/{id}/files/{file_id}/download. +// Stub — returns 501 until Plan 03. +func FileDownloadHandler(deps FilesDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "not implemented", http.StatusNotImplemented) + } +} + +// FileDeleteConfirmHandler handles GET /tablos/{id}/files/{file_id}/delete-confirm. +// Stub — returns 501 until Plan 03. +func FileDeleteConfirmHandler(deps FilesDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "not implemented", http.StatusNotImplemented) + } +} + +// FileDeleteHandler handles POST /tablos/{id}/files/{file_id}/delete. +// Stub — returns 501 until Plan 03. +func FileDeleteHandler(deps FilesDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "not implemented", http.StatusNotImplemented) + } +}