Phase 5 hygiene: image ownership, real deletes, scan resilience

Images were readable by any signed-in user, not just their owner. Keys
are now namespaced per user in both shapes the app writes, the three
bar/ objects that predated that were migrated under the owner's prefix,
and the image route enforces the prefix - answering 404 rather than 403
so it does not confirm someone else's key exists. Barcode-mirrored
images now write under the user prefix too.

deleteImage existed but was never called, so deleting a drink, bar item
or scan removed the row and left the file in storage forever, still
fetchable. All three now clean up through one shared helper, after the
database work and best-effort, so a storage hiccup cannot block a delete
the user asked for or leave the row behind.

Menu scans are processed detached from the request, so every deploy
abandoned anything in flight and left the row PROCESSING forever with a
spinner that never resolved. They are now reaped lazily when a user
lists their scans - no scheduler needed. Concurrent extractions are
capped at two per process: each is a vision call with a four minute
timeout that costs real money, and nothing else bounded them.

MenuItem gains userId. Ownership was only ever transitive via scanId,
which held because nothing queries MenuItem directly, but left any
future direct query an IDOR with nothing to stop it.

Restore was correctly scoped but unbounded, so a crafted file could
create unlimited rows in one transaction against shared Postgres - self
harm with one user, denial of service with several. Capped, and imageUrl
from the CSV now goes through the same validation the API enforces
instead of reaching the column unchecked.

Members can delete their own account and data. Once the app holds other
people's history, including Rating.location, that is the minimum.

Registration rate limiting took the first x-forwarded-for hop, which the
client controls; it now takes the last, which our proxy appends.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
JP
2026-08-08 21:57:57 +00:00
parent 0ead1385f7
commit 70db6314e3
15 changed files with 364 additions and 27 deletions

View File

@@ -2,7 +2,7 @@ import { NextResponse } from "next/server"
import { z } from "zod"
import { requireOwner } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { deleteImage } from "@/lib/s3"
import { deleteImagesByUrl } from "@/lib/images"
import { revokeGatewayKey } from "@/lib/ai/switchboard-keys"
const patchSchema = z.object({
@@ -91,23 +91,19 @@ export async function DELETE(
// Best effort after the fact: never let storage or the gateway block a deletion
// the user asked for, and never leave the account half-deleted.
const keyPrefix = "/minio-images/"
const objectKeys = [...drinks, ...barItems, ...scans]
.map((r) => r.imageUrl)
.filter((u): u is string => !!u && u.startsWith(keyPrefix))
.map((u) => u.slice(keyPrefix.length))
const urls = [...drinks, ...barItems, ...scans].map((r) => r.imageUrl)
const gatewayKeyIds = keys
.map((k) => k.gatewayKeyId)
.filter((id): id is string => !!id)
await Promise.allSettled([
...objectKeys.map((k) => deleteImage(k)),
...keys
.map((k) => k.gatewayKeyId)
.filter((id): id is string => !!id)
.map((id) => revokeGatewayKey(id)),
const [imagesDeleted] = await Promise.all([
deleteImagesByUrl(urls),
Promise.allSettled(gatewayKeyIds.map((id) => revokeGatewayKey(id))),
])
return NextResponse.json({
success: true,
imagesDeleted: objectKeys.length,
gatewayKeysRevoked: keys.filter((k) => k.gatewayKeyId).length,
imagesDeleted,
gatewayKeysRevoked: gatewayKeyIds.length,
})
}

View File

@@ -26,9 +26,13 @@ const registerSchema = z.object({
export async function POST(request: Request) {
try {
// Rate limit: 5 registration attempts per IP per minute
// Rate limit: 5 registration attempts per IP per minute.
// Take the LAST hop, not the first: everything before it is client-supplied and
// can be forged to get a fresh bucket per request. The last entry is the one our
// own reverse proxy appended.
const forwarded = request.headers.get("x-forwarded-for")
const ip = forwarded?.split(",")[0]?.trim() ?? "unknown"
const hops = forwarded?.split(",").map((h) => h.trim()).filter(Boolean) ?? []
const ip = hops.length > 0 ? hops[hops.length - 1] : "unknown"
const rl = rateLimit(`register:${ip}`, 5, 60 * 1000)
if (!rl.success) {
return NextResponse.json(

View File

@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
import { barItemUpdateSchema } from "@/lib/validators"
export async function PUT(
@@ -65,7 +66,7 @@ export async function DELETE(
// Check ownership
const existing = await prisma.barItem.findUnique({
where: { id: params.id },
select: { userId: true },
select: { userId: true, imageUrl: true },
})
if (!existing) {
@@ -80,6 +81,9 @@ export async function DELETE(
where: { id: params.id },
})
// After the row is gone, so a storage hiccup cannot block the delete.
void deleteImagesByUrl([existing.imageUrl])
return NextResponse.json({ success: true })
} catch (error) {
console.error("DELETE /api/bar/[id] error:", error)

View File

@@ -29,7 +29,7 @@ function mapOffCategoryToDrinkType(tags: string[]): string | null {
return null
}
async function lookupOpenFoodFacts(barcode: string) {
async function lookupOpenFoodFacts(barcode: string, userId: string) {
try {
const res = await fetch(
`https://world.openfoodfacts.org/api/v2/product/${barcode}.json`,
@@ -48,8 +48,9 @@ async function lookupOpenFoodFacts(barcode: string) {
// item with no image beats one with an image that cannot render.
const remoteImage =
product.image_url || product.image_front_url || product.image_front_small_url || null
// Namespaced by user so the image route can enforce ownership by key prefix.
const imageUrl = remoteImage
? await mirrorExternalImage(remoteImage, `bar/${barcode}`)
? await mirrorExternalImage(remoteImage, `${userId}/bar/${barcode}`)
: null
// Extract ABV from alcohol_100g nutrient or nutriments
@@ -153,7 +154,7 @@ export async function POST(request: Request) {
}
// Try Open Food Facts first
const offResult = await lookupOpenFoodFacts(barcode)
const offResult = await lookupOpenFoodFacts(barcode, session.user.id)
if (offResult) {
return NextResponse.json({ ...offResult, barcode, source: "openfoodfacts" })
}

View File

@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
import { drinkUpdateSchema } from "@/lib/validators"
export async function GET(
@@ -113,7 +114,7 @@ export async function DELETE(
// Check ownership
const existing = await prisma.drink.findUnique({
where: { id: params.id },
select: { userId: true },
select: { userId: true, imageUrl: true },
})
if (!existing) {
@@ -128,6 +129,9 @@ export async function DELETE(
where: { id: params.id },
})
// After the row is gone, so a storage hiccup cannot block the delete.
void deleteImagesByUrl([existing.imageUrl])
return NextResponse.json({ success: true })
} catch (error) {
console.error("DELETE /api/drinks/[id] error:", error)

View File

@@ -1,6 +1,7 @@
import { NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
export async function GET(
request: Request,
@@ -61,5 +62,8 @@ export async function DELETE(
await prisma.menuScan.delete({ where: { id: params.id } })
// After the row is gone, so a storage hiccup cannot block the delete.
void deleteImagesByUrl([scan.imageUrl])
return NextResponse.json({ success: true })
}

View File

@@ -4,6 +4,11 @@ import { prisma } from "@/lib/prisma"
import { uploadImage } from "@/lib/s3"
import { rateLimit } from "@/lib/rate-limit"
import { randomUUID } from "crypto"
import {
reapStuckScans,
tryAcquireScanSlot,
releaseScanSlot,
} from "@/lib/scan-health"
export async function GET(request: Request) {
const session = await auth()
@@ -11,6 +16,10 @@ export async function GET(request: Request) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
// Lazy housekeeping: a deploy abandons in-flight scans and there is no queue to
// recover them, so mark the stale ones failed before listing.
await reapStuckScans(session.user.id)
const { searchParams } = new URL(request.url)
const page = parseInt(searchParams.get("page") || "1")
const limit = parseInt(searchParams.get("limit") || "20")
@@ -82,10 +91,26 @@ export async function POST(request: Request) {
},
})
if (!tryAcquireScanSlot()) {
// Fail fast rather than piling vision calls onto a busy process. The row is
// already created, so the user sees why instead of an endless spinner.
await prisma.menuScan.update({
where: { id: scan.id },
data: {
status: "FAILED",
errorMessage: "Too many scans are being processed right now. Please try again in a moment.",
},
})
return NextResponse.json(
{ error: "Busy processing other scans. Please try again in a moment." },
{ status: 503 }
)
}
// Kick off async processing - don't await
processMenuScan(scan.id, buffer, file.type, session.user.id).catch(
(error) => console.error("Scan processing error:", error)
)
processMenuScan(scan.id, buffer, file.type, session.user.id)
.catch((error) => console.error("Scan processing error:", error))
.finally(releaseScanSlot)
return NextResponse.json(scan, { status: 201 })
} catch (error) {
@@ -138,6 +163,7 @@ async function processMenuScan(
return {
scanId,
userId,
name: item.name,
type: item.type,
subType: item.subType,

View File

@@ -0,0 +1,62 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
import { revokeGatewayKey } from "@/lib/ai/switchboard-keys"
/**
* Self-service account deletion.
*
* Once the app holds other people's drink history - including Rating.location, which
* is a record of where they were - being able to delete it themselves is the minimum,
* rather than having to ask the owner.
*
* The owner cannot delete themselves this way: it would strand the deployment with
* no one able to issue invites or manage members.
*/
export async function DELETE() {
const session = await requireUser()
if (session instanceof NextResponse) return session
const userId = session.user.id
const user = await prisma.user.findUnique({
where: { id: userId },
select: { role: true },
})
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 })
if (user.role === "OWNER") {
return NextResponse.json(
{
error:
"The owner account cannot be deleted here. Transfer ownership first.",
},
{ status: 400 }
)
}
// Collected before the cascade makes them unreachable.
const [drinks, barItems, scans, keys] = await Promise.all([
prisma.drink.findMany({ where: { userId }, select: { imageUrl: true } }),
prisma.barItem.findMany({ where: { userId }, select: { imageUrl: true } }),
prisma.menuScan.findMany({ where: { userId }, select: { imageUrl: true } }),
prisma.userApiKey.findMany({ where: { userId }, select: { gatewayKeyId: true } }),
])
await prisma.user.delete({ where: { id: userId } })
// Best effort: storage or the gateway being unavailable must not leave the
// account half-deleted.
const gatewayKeyIds = keys
.map((k) => k.gatewayKeyId)
.filter((id): id is string => !!id)
await Promise.all([
deleteImagesByUrl([...drinks, ...barItems, ...scans].map((r) => r.imageUrl)),
Promise.allSettled(gatewayKeyIds.map((id) => revokeGatewayKey(id))),
])
// The jwt callback returns null once the user is gone, so the session ends on the
// next request without any extra step here.
return NextResponse.json({ success: true })
}

View File

@@ -19,6 +19,18 @@ import { getImage } from "@/lib/s3"
*/
export const dynamic = "force-dynamic"
/**
* Object keys are namespaced by the user who created them, in two shapes:
* <userId>/... uploads, and mirrored product images under <userId>/bar/
* scans/<userId>/... menu scan photos
*
* Anything else is unreachable by design - if a new writer appears that does not
* namespace its keys, its images 404 rather than becoming readable by everyone.
*/
function canReadKey(key: string, userId: string): boolean {
return key.startsWith(`${userId}/`) || key.startsWith(`scans/${userId}/`)
}
export async function GET(
_request: Request,
{ params }: { params: { key: string[] } }
@@ -33,6 +45,11 @@ export async function GET(
return new Response(null, { status: 400 })
}
// 404 rather than 403: do not confirm that someone else's key exists.
if (!canReadKey(key, session.user.id)) {
return new Response(null, { status: 404 })
}
try {
const object = await getImage(key)
if (!object.Body) return new Response(null, { status: 404 })