From 9dffab9af7372d39aef55f27f079f405b06bac58 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Fri, 27 Nov 2026 14:14:33 +0100 Subject: [PATCH] docs(37): add code review report --- .../37-media-library-album/37-REVIEW.md | 269 ++++++++++++++++++ 1 file changed, 269 insertions(+) create mode 100644 .planning/phases/37-media-library-album/37-REVIEW.md diff --git a/.planning/phases/37-media-library-album/37-REVIEW.md b/.planning/phases/37-media-library-album/37-REVIEW.md new file mode 100644 index 00000000..2ec59c03 --- /dev/null +++ b/.planning/phases/37-media-library-album/37-REVIEW.md @@ -0,0 +1,269 @@ +--- +phase: 37-media-library-album +reviewed: 2026-11-27T13:13:00Z +depth: standard +files_reviewed: 74 +files_reviewed_list: + - modules/album/album.go + - modules/album/backfill.go + - modules/album/http.go + - modules/album/migrations.go + - modules/album/models.go + - modules/album/service.go + - modules/album/tokens.go + - modules/album/variants.go + - modules/album/README.md + - modules/album/example_test.go + - modules/album/album_test.go + - modules/album/album_smoke_test.go + - modules/album/album_postgres_test.go + - modules/cabana/admin_openapi.go + - modules/cabana/backend_screens.go + - modules/cabana/csrf.go + - modules/cabana/field_file.go + - modules/cabana/field_media.go + - modules/cabana/form_schema.go + - modules/cabana/http.go + - modules/cabana/mail_admin.go + - modules/cabana/mail_routes.go + - modules/cabana/media_mcp.go + - modules/cabana/media_routes.go + - modules/cabana/schema_types.go + - modules/cabana/token_commands.go + - modules/cabana/media_routes_test.go + - modules/cabana/media_postgres_test.go + - modules/cabana/openapi_conformance_test.go + - modules/cabana/security_coverage_test.go + - modules/cabana/datepicker_smoke_test.go + - modules/cabana/datepicker_test.go + - modules/cabana/phase10_coverage_test.go + - modules/cabana/phase10_csrf_test.go + - modules/cabana/phase121_schema_boot_test.go + - modules/cabana/token_routes_test.go + - modules/surf/media.go + - modules/surf/media_test.go + - modules/surf/pier_on.go + - modules/surf/router.go + - modules/pier/dispatch.go + - modules/pier/pier.go + - modules/pier/README.md + - modules/pier/endpoint_guards_test.go + - modules/pier/media_mcp_test.go + - modules/lagoon/migrations.go + - admin/src/api/media.ts + - admin/src/api/types.ts + - admin/src/app/pageTitle.ts + - admin/src/app/router.ts + - admin/src/components/form/fields/MediaFinderField.vue + - admin/src/components/form/fields/PluginField.vue + - admin/src/components/form/formContext.ts + - admin/src/components/form/registry.ts + - admin/src/components/mail/MailImagePicker.vue + - admin/src/components/media/MediaBrowser.vue + - admin/src/components/media/MediaFolderTree.vue + - admin/src/components/media/MediaInspector.vue + - admin/src/components/media/MediaPickerModal.vue + - admin/src/components/shell/Breadcrumbs.vue + - admin/src/components/shell/PluginRail.vue + - admin/src/main.ts + - admin/src/state/useAuth.ts + - admin/src/state/useMediaAccess.ts + - admin/src/views/LoginView.vue + - admin/src/views/MediaView.vue + - admin/tests/form/MediaFinderField.test.ts + - admin/tests/helpers.ts + - admin/tests/media/MediaBrowser.test.ts + - admin/tests/media/MediaPickerModal.test.ts + - docs/backend/forms.md + - docs/services/media-library.md + - README.md + - scripts/check-phase37.sh +findings: + critical: 2 + warning: 5 + info: 3 + total: 10 +status: issues_found +--- + +# Phase 37: Code Review Report + +**Reviewed:** 2026-11-27T13:13:00Z +**Depth:** standard +**Files Reviewed:** 74 +**Status:** issues_found + +## Summary + +Reviewed the Phase 37 Media Library (`modules/album`) implementation across the Go backend (`album`, `cabana`, `surf`, `pier`, `lagoon`), Vue 3 admin SPA (`admin/src/`), tests, docs, and verification script. + +The core `album` architecture (immutable `media//.` keys, zero-DB-hit `StaticHandler` with strict segment validation and `nosniff`/CSP/`attachment` headers, atomic single-use `UPDATE ... RETURNING` upload tokens, and `lagoon.AfterCommit` blob deletion) is well-structured. However, adversarial review uncovered **2 critical defects** and **5 warnings** that must be fixed before verification and release: + +1. **All 5 write Media Library MCP tools (`media_prepare_upload`, `media_upload`, `media_update`, `media_delete`, `media_create_folder`) fail with `403 Forbidden` in production** because `pier` dispatches in-process requests without `Authorization` or `X-Requested-With`, while `cabana` wraps all write media routes in `requireAjax` and `csrfSafe` does not exempt `bouncer.Dispatched` / `pact.MCPCallFrom` requests. +2. **Authorization and media-type bypass in `GET /mail/images/{id}` and `MailBrandSetting` logo validation**: a mail-only admin (without `media.view_media`) can read any item in the entire Media Library (outside the `mail` folder, including non-image PDFs/archives), and `MailBrandSetting.LogoFileID` accepts non-image items from any folder. + +## Narrative Findings (AI reviewer) + +## Critical Issues + +### CR-01: All 5 write Media Library MCP tools fail with 403 Forbidden in production due to `requireAjax` + +**File:** `modules/cabana/csrf.go:32-41` (also `modules/cabana/http.go:379-389`, `modules/pier/dispatch.go:215-253`, `modules/pier/media_mcp_test.go:139-148`) +**Issue:** Every state-changing Media Library route in `cabana` (`POST /media/folders`, `PUT /media/folders/{id}`, `DELETE /media/folders/{id}`, `POST /media/items`, `POST /media/items/base64`, `PUT /media/items/{id}`, `DELETE /media/items/{id}`, `POST /media/uploads/prepare`) is wrapped with `requireAjax(...)`. However, when `pier` dispatches an MCP tool call in-process (`modules/pier/dispatch.go:215-253`), it creates a synthetic `http.Request` carrying `pact.WithMCPCall` and `bouncer.WithDispatch`, and intentionally omits both `Authorization` and `X-Requested-With` headers. `csrfSafe(r)` only checks safe HTTP methods, `bearerToken(r) != ""`, and `isAjax(r)` (`X-Requested-With: XMLHttpRequest`). As a result, all 5 write MCP tools (`media_prepare_upload`, `media_upload`, `media_update`, `media_delete`, `media_create_folder`) are unconditionally rejected with `403 Forbidden` when dispatched against the real `cabana` routes. `modules/pier/media_mcp_test.go` did not catch this because its `mediaStubRoutesPlugin` registers stub handlers without `requireAjax`. +**Fix:** +In `modules/cabana/csrf.go`, treat in-process `bouncer.Dispatched(r.Context(), "backend")` requests as CSRF-safe (an in-process dispatch marker cannot be set by any external HTTP/browser request and is only constructed after bearer authentication in `pier`), and add a regression test exercising `requireAjax` with a `bouncer.WithDispatch` request: +```go +func csrfSafe(r *http.Request) bool { + switch r.Method { + case http.MethodGet, http.MethodHead, http.MethodOptions: + return true + } + if _, ok := bouncer.Dispatched(r.Context(), "backend"); ok { + return true + } + if bearerToken(r) != "" { + return true + } + return isAjax(r) +} +``` + +### CR-02: Authorization and media-type bypass in `GET /mail/images/{id}` and `MailBrandSetting` logo lookup + +**File:** `modules/cabana/mail_routes.go:198-203` (also `modules/cabana/mail_routes.go:729-736`, `modules/cabana/mail_admin.go:1844-1848`) +**Issue:** `mailImagesShow` (`GET /mail/images/{id}`) authorizes callers holding `system.manage_mail_templates` or `system.manage_mail_layouts` — it does **not** require `media.view_media`. Unlike `mailImagesList` (lines 123–146), which properly restricts results to the root `"mail"` virtual folder and `Type: "image"`, `mailImagesShow` queries `summer_media_items` globally with `Where("id = ? OR legacy_file_id = ?", id, id)` without checking `folder_id` or `IsImage()`. A mail-only administrator without `media.view_media` can enumerate arbitrary Media Library items from any folder (including non-image documents such as PDFs or ZIPs) via `GET /mail/images/{id}`. The same unscoped query appears in `mailLogoAbsoluteURL` (`modules/cabana/mail_routes.go:729-736`) and `MailBrandSetting.BeforeValidate` (`modules/cabana/mail_admin.go:1844-1848`), allowing non-image files from arbitrary folders to be configured as the email brand logo. +**Fix:** +Scope `album.Item` lookups in `mailImagesShow`, `mailLogoAbsoluteURL`, and `MailBrandSetting.BeforeValidate` to the root `"mail"` folder and inline image items only: +```go +// Helper shared by mailImagesShow and mailLogoAbsoluteURL: +var mailFolder album.Folder +if err := db.WithContext(ctx).Where("parent_id IS NULL AND slug = ?", "mail").First(&mailFolder).Error; err == nil { + var aItem album.Item + err = db.WithContext(ctx). + Where("folder_id = ? AND (id = ? OR legacy_file_id = ?)", mailFolder.ID, id, id). + Order("CASE WHEN id = " + strconv.FormatUint(id, 10) + " THEN 0 ELSE 1 END"). + Take(&aItem).Error + if err == nil && aItem.IsImage() { + // allowed + } +} +``` +Apply the same `folder_id` (root `"mail"` folder) and image `content_type` filter in `MailBrandSetting.BeforeValidate` (`modules/cabana/mail_admin.go:1844-1848`). + +## Warnings + +### WR-01: `SignedUploadHandler` ignores `UploadToken.ExpectedContentType` + +**File:** `modules/album/http.go:242-251` +**Issue:** `PrepareUpload` accepts `ExpectedContentType`, validates it against `disallowedSniffed`, and stores it in `summer_media_upload_tokens.expected_content_type`, and `ConsumeUploadToken` returns it. However, `SignedUploadHandler` never checks `tok.ExpectedContentType` against the uploaded file's sniffed content type, and `UploadInput` has no field to enforce it. A caller that mints a token with `content_type: "application/pdf"` or `"image/png"` will silently accept a different allowed content type (e.g. a `.txt` payload uploaded under a `.pdf` filename, or a JPEG uploaded under a `.png` token). +**Fix:** +Add `ExpectedContentType string` to `album.UploadInput`, pass `tok.ExpectedContentType` in `SignedUploadHandler`, and reject mismatches in `Service.Upload` before writing the blob: +```go +if expected := baseMediaType(in.ExpectedContentType); expected != "" && contentType != expected { + return nil, fmt.Errorf("%w: expected %s, got %s", ErrFileType, expected, contentType) +} +``` + +### WR-02: `cabana.mediaItemView` serves stale persisted variant URLs instead of recomputing from `v.Key` + +**File:** `modules/cabana/media_routes.go:188-196` +**Issue:** `GenerateWebPVariants` persists `v.URL` into the JSONB `variants` column at upload time. `album.Item.Srcset(cfg)`, `album.NewItemResponse(cfg, item)`, and `cabana.mailImageFromAlbumItem` all recompute each variant URL from `v.Key` using the current `cfg` whenever `v.Key != ""`. By contrast, `cabana.mediaItemView` checks `if vURL == "" && v.Key != ""`, so it always prefers the stored upload-time `v.URL`. If an application later changes `media.public_path_prefix` or enables a CDN via `storage.uploads.public_url`, `AdminMediaItem.URL` and `AdminMediaItem.Srcset` update immediately while `ThumbURL` and `Variants[i].URL` remain permanently stuck on the stale URL. +**Fix:** +Recompute from `v.Key` first, matching `album.NewItemResponse`: +```go +for _, v := range sorted { + vURL := v.URL + if v.Key != "" { + vURL = album.Item{BlobKey: v.Key}.PublicURL(cfg) + } + if thumbURL == "" && vURL != "" { + thumbURL = vURL + } +``` + +### WR-03: Duplicate folder slug returns HTTP 500 instead of 409 Conflict + +**File:** `modules/album/service.go:394-401` (also `modules/album/service.go:455-457`, `modules/cabana/media_routes.go:232-246`) +**Issue:** `summer_media_folders` enforces a unique index on `(COALESCE(parent_id, 0), slug)`. Neither `CreateFolder` nor `UpdateFolder` checks for an existing sibling slug or maps Postgres unique-constraint violations (`SQLSTATE 23505`) to a sentinel error. Creating or renaming a folder to a colliding name/slug (e.g., `"Press Kit"` and `"press-kit"` under the same parent) returns an unhandled error that `writeMediaError` routes to `writeCRUDError` -> `500 Internal Server Error`. +**Fix:** +Add `ErrFolderExists = errors.New("album: folder already exists")` in `modules/album/service.go`, check for sibling slug collisions (and/or detect pgx `23505` unique violation on `summer_media_folders_parent_slug_uidx`) in `CreateFolder` and `UpdateFolder`, and map `album.ErrFolderExists` to `409 Conflict` in `writeMediaError`: +```go +case errors.Is(err, album.ErrFolderNotEmpty), errors.Is(err, album.ErrFolderExists): + WriteError(w, http.StatusConflict, "conflict", err.Error()) +``` + +### WR-04: Drag-and-drop upload in `MediaBrowser.vue` bypasses `mode="image"` restriction and moving an item out of a folder leaves `meta.total` stale + +**File:** `admin/src/components/media/MediaBrowser.vue:351-395` (also `admin/src/components/media/MediaBrowser.vue:568-575`) +**Issue:** +1. When `MediaBrowser` is embedded in `MediaPickerModal` with `mode="image"` (for example, `type: mediafinder` in image mode), `` hints images for file-dialog uploads, but `onDrop` passes dropped files directly to `uploadFiles`, which posts to `POST /media/items` (accepting all `DefaultFileExtensions`, including PDFs and ZIPs). The uploaded non-image item is then prepended to `items.value` and auto-selected via `toggleSelect(uploaded)`, allowing a non-image URL to be inserted into an `image`-only `mediafinder` field. +2. In `onSaveItem` (lines 568–575), when an item is moved out of the currently viewed folder (`!stillMatchesFolder`), it is filtered out of `items.value` without decrementing `meta.value.total` (unlike `onDeleteItem` on line 600), leaving pagination totals out of sync. +**Fix:** +In `uploadFiles`, reject non-image files when `props.mode === 'image'` (or only prepend/auto-select items matching the active `mode`/`typeFilter`, and show `uploadError` when a non-image is dropped in image-only mode). In `onSaveItem`, decrement `meta.value.total` when removing a moved item from the active folder view: +```ts +if (stillMatchesFolder) { + items.value = items.value.map((i) => (i.id === updated.id ? updated : i)) +} else { + items.value = items.value.filter((i) => i.id !== updated.id) + if (inspectedId.value === updated.id) { + inspectedId.value = null + } + if (meta.value) { + meta.value = { ...meta.value, total: Math.max(0, meta.value.total - 1) } + } +} +``` + +### WR-05: `album.StaticHandler` opens full `bucket.NewReader` on `HEAD` requests and omits `Content-Length` + +**File:** `modules/album/http.go:66-92` +**Issue:** `StaticHandler` calls `bucket.Attributes(r.Context(), key)` and then unconditionally calls `bucket.NewReader(r.Context(), key, nil)` even when `r.Method == http.MethodHead`. On object stores (S3/GCS), `NewReader` issues a full `GetObject` request whose body is immediately discarded. In addition, `Content-Length` is never set from `attrs.Size`, so `HEAD` responses omit `Content-Length`. +**Fix:** +Use `attrs.ContentType` and `attrs.Size` for `HEAD` requests and return before opening a reader: +```go +ct := strings.TrimSpace(attrs.ContentType) +if ct == "" { + ct = defaultStaticContentType +} +w.Header().Set("Cache-Control", MediaCacheControl) +w.Header().Set("Content-Type", ct) +if attrs.Size >= 0 { + w.Header().Set("Content-Length", strconv.FormatInt(attrs.Size, 10)) +} +if !attach.IsInlineContentType(ct) { + w.Header().Set("Content-Disposition", "attachment") +} else if cd := safeDisposition(attrs.ContentDisposition); cd != "" { + w.Header().Set("Content-Disposition", cd) +} +if r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return +} +reader, err := bucket.NewReader(r.Context(), key, nil) +``` + +## Info + +### IN-01: `UpdateFolder` cycle detection silently exits at depth 64 + +**File:** `modules/album/service.go:432-449` +**Issue:** The ancestor walk loop `for depth := 0; depth < 64; depth++` breaks when `anc.ParentID == nil`, but if a hierarchy exceeds 64 levels the loop finishes without error and proceeds to update `parent_id`, potentially allowing a cycle. +**Fix:** Track `reachedRoot := false` when `anc.ParentID == nil` and return `fmt.Errorf("%w: folder hierarchy exceeds maximum depth", ErrInvalidFolder)` if `!reachedRoot` after the loop. + +### IN-02: Unescaped SQL `ILIKE` wildcards in `album.Service.ListItems` + +**File:** `modules/album/service.go:537-540` +**Issue:** `like := "%" + term + "%"` does not escape literal `%`, `_`, or `\` characters in the user's search term, so searching for a filename containing `_` or `%` acts as a wildcard. +**Fix:** Escape `\`, `%`, and `_` with `strings.NewReplacer("\\", "\\\\", "%", "\\%", "_", "\\_").Replace(term)` and add `ESCAPE '\'` to the `ILIKE` predicates. + +### IN-03: No cleanup of expired or consumed `summer_media_upload_tokens` rows + +**File:** `modules/album/tokens.go:97-108` +**Issue:** `summer_media_upload_tokens` creates an index on `expires_at`, but neither `PrepareUpload` nor any maintenance helper purges expired/used rows, so the table grows indefinitely. +**Fix:** Periodically or opportunistically prune old expired rows (for example, `DELETE FROM summer_media_upload_tokens WHERE expires_at < NOW() - INTERVAL '1 day'`) or expose a `PruneUploadTokens` helper for scheduled cleanup. + +--- + +_Reviewed: 2026-11-27T13:13:00Z_ +_Reviewer: Antigravity (msd-code-reviewer)_ +_Depth: standard_