fix(storage): stop deleting covers, place images and journey photos another row may still show

Replacing a trip or list cover, changing or deleting a place or saved-place
image and deleting a journey photo removed the bytes at once, without asking
whether a trip copy, a journey, a saved place or another photo row still
named them (#2924). Those paths now leave the object in place and the reclaim
job removes it once no row names it. A journey photo the user deletes takes
its local photo row with it when nothing else links it, so its bytes become
reclaimable instead of being kept by a row nobody sees.

A place image copied from a trip file is still dropped at once when the
update that would name it fails: that copy was never anyone else's.

Size and warning baselines follow the shrunk files.
This commit is contained in:
Maurice
2026-11-01 13:59:28 +01:00
parent 095bed2db8
commit db0fbc1ccd
19 changed files with 101 additions and 317 deletions
+3 -2
View File
@@ -1301,7 +1301,7 @@ describe('Trip cover upload parity', () => {
expect(fsMod.existsSync(pathMod.join(coversDir, diskName))).toBe(true);
});
it('TRIP-P02 — re-upload deletes the previous cover file', async () => {
it('TRIP-P02 — re-upload keeps the previous cover file for the storage reclaim job (#2924)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -1317,7 +1317,8 @@ describe('Trip cover upload parity', () => {
.set('Cookie', authCookie(user.id))
.attach('cover', FIXTURE_IMG, 'two.jpg');
expect(second.status).toBe(201);
expect(fsMod.existsSync(pathMod.join(coversDir, firstName))).toBe(false);
// A trip copy or a journey may show the same object, so the replace leaves it.
expect(fsMod.existsSync(pathMod.join(coversDir, firstName))).toBe(true);
});
it('TRIP-P03 — no file → 400 "No image uploaded"', async () => {
@@ -846,7 +846,7 @@ describe('custom saved-place image', () => {
expect(updated.image_url).toBe('/uploads/places/col-set.jpg');
});
it('COLLECTIONS-SVC-061: setPlaceImage stores the url and reclaims a replaced upload', async () => {
it('COLLECTIONS-SVC-061: setPlaceImage stores the url and leaves a replaced upload to the reclaim job', async () => {
const u = createUser(testDb).user;
const col = await svc.createCollection(u.id, { name: 'Photos' });
const p = (await svc.savePlace(u.id, { collection_id: col.id, name: 'Pic' })).place!;
@@ -856,10 +856,12 @@ describe('custom saved-place image', () => {
const res = await svc.setPlaceImage(u.id, p.id, '/uploads/places/col-replace-b.jpg');
expect(res.image_url).toBe('/uploads/places/col-replace-b.jpg');
expect(fs.existsSync(fileA)).toBe(false);
// A trip copy may still show it; the storage reclaim job decides (#2924).
expect(fs.existsSync(fileA)).toBe(true);
fs.unlinkSync(fileA);
});
it('COLLECTIONS-SVC-062: deletePlace reclaims the uploaded image when unreferenced', async () => {
it('COLLECTIONS-SVC-062: deletePlace leaves the uploaded image to the reclaim job', async () => {
const u = createUser(testDb).user;
const col = await svc.createCollection(u.id, { name: 'Photos' });
const p = (await svc.savePlace(u.id, { collection_id: col.id, name: 'Pic', image_url: '/uploads/places/col-delete.jpg' })).place!;
@@ -867,7 +869,8 @@ describe('custom saved-place image', () => {
expect(fs.existsSync(fileA)).toBe(true);
await svc.deletePlace(u.id, p.id);
expect(fs.existsSync(fileA)).toBe(false);
expect(fs.existsSync(fileA)).toBe(true);
fs.unlinkSync(fileA);
});
});
@@ -8,7 +8,6 @@ import type { JourneyPhotoLinksService } from '../../../src/nest/journey/journey
import { JourneyPublicController } from '../../../src/nest/journey/journey-public.controller';
import { JourneyController } from '../../../src/nest/journey/journey.controller';
import type { JourneyService } from '../../../src/nest/journey/journey.service';
import { journeyThumbName } from '../../../src/nest/memories/thumbnail.service';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import type { User } from '../../../src/types';
import { HttpException } from '@nestjs/common';
@@ -706,31 +705,14 @@ describe('JourneyController', () => {
expect(updatePhoto).toHaveBeenCalledWith(7, 1, { caption: 'x' }, 'sock-1');
});
it('DELETE photo removes the storage object when a path exists', async () => {
expect(
await ctl(
svc({ deletePhoto: vi.fn().mockReturnValue({ id: 7, file_path: 'journey/a.jpg' }) } as Partial<JourneyService>),
).deletePhoto(user, '7'),
).toEqual({ success: true });
expect(storageStub.delete).toHaveBeenCalledWith('journey', 'a.jpg');
// ...and the derived thumb goes with it (spec fix #2).
expect(storageStub.delete).toHaveBeenCalledWith('journey', journeyThumbName('journey/a.jpg'));
// a vanished object is swallowed
(storageStub.delete as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ENOENT'));
expect(
await ctl(
svc({ deletePhoto: vi.fn().mockReturnValue({ id: 8, file_path: 'journey/b.jpg' }) } as Partial<JourneyService>),
).deletePhoto(user, '8'),
).toEqual({ success: true });
// a file_path outside the journey category never reaches storage
it('DELETE photo leaves the bytes to the storage reclaim job (#2924)', async () => {
(storageStub.delete as ReturnType<typeof vi.fn>).mockClear();
expect(
await ctl(
svc({
deletePhoto: vi.fn().mockReturnValue({ id: 9, file_path: 'elsewhere/x.jpg' }),
} as Partial<JourneyService>),
).deletePhoto(user, '9'),
).toEqual({ success: true });
const deletePhoto = vi.fn().mockReturnValue({ id: 7, file_path: 'journey/a.jpg', thumbnail_path: 'journey/p.jpg' });
expect(await ctl(svc({ deletePhoto } as Partial<JourneyService>)).deletePhoto(user, '7')).toEqual({
success: true,
});
expect(deletePhoto).toHaveBeenCalledWith(7, 1);
// Another row may name the same object: the photo row going is what frees it.
expect(storageStub.delete).not.toHaveBeenCalled();
});
@@ -761,7 +743,7 @@ describe('JourneyController', () => {
expect(await ctl(svc()).galleryProviderPhotos(user, '9', { provider: 'immich', asset_id: 'a' })).toEqual({ id: 3 });
});
it('DELETE gallery photo: 404, then removes the object when present', async () => {
it('DELETE gallery photo: 404, then leaves the bytes and the poster to the reclaim job', async () => {
expect(
await thrownAsync(() =>
ctl(svc({ deleteGalleryPhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).deleteGalleryPhoto(
@@ -770,41 +752,15 @@ describe('JourneyController', () => {
),
),
).toEqual({ status: 404, body: { error: 'Photo not found or not allowed' } });
// no file_path → nothing to delete, returns void
expect(
await ctl(
svc({ deleteGalleryPhoto: vi.fn().mockReturnValue({ id: 7, file_path: null }) } as Partial<JourneyService>),
).deleteGalleryPhoto(user, '7'),
).toBeUndefined();
await ctl(
svc({
deleteGalleryPhoto: vi.fn().mockReturnValue({ id: 8, file_path: 'journey/g.jpg' }),
} as Partial<JourneyService>),
).deleteGalleryPhoto(user, '8');
expect(storageStub.delete).toHaveBeenCalledWith('journey', 'g.jpg');
expect(storageStub.delete).toHaveBeenCalledWith('journey', journeyThumbName('journey/g.jpg'));
(storageStub.delete as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ENOENT'));
expect(
await ctl(
svc({
deleteGalleryPhoto: vi.fn().mockReturnValue({ id: 9, file_path: 'journey/h.jpg' }),
} as Partial<JourneyService>),
).deleteGalleryPhoto(user, '9'),
).toBeUndefined();
});
it('DELETE gallery video also reclaims its uploaded poster (spec fix #2 extension)', async () => {
(storageStub.delete as ReturnType<typeof vi.fn>).mockClear();
await ctl(
svc({
deleteGalleryPhoto: vi
.fn()
.mockReturnValue({ id: 10, file_path: 'journey/clip.mp4', thumbnail_path: 'journey/poster.jpg' }),
} as Partial<JourneyService>),
).deleteGalleryPhoto(user, '10');
expect(storageStub.delete).toHaveBeenCalledWith('journey', 'clip.mp4');
expect(storageStub.delete).toHaveBeenCalledWith('journey', journeyThumbName('journey/clip.mp4'));
expect(storageStub.delete).toHaveBeenCalledWith('journey', 'poster.jpg');
const deleteGalleryPhoto = vi
.fn()
.mockReturnValue({ id: 10, file_path: 'journey/clip.mp4', thumbnail_path: 'journey/poster.jpg' });
expect(
await ctl(svc({ deleteGalleryPhoto } as Partial<JourneyService>)).deleteGalleryPhoto(user, '10'),
).toBeUndefined();
expect(deleteGalleryPhoto).toHaveBeenCalledWith(10, 1);
expect(storageStub.delete).not.toHaveBeenCalled();
});
it('PATCH /:id returns the updated journey on success', async () => {
@@ -1498,16 +1498,16 @@ describe('importKmlPlaces — full stored row and atomicity (M2/L2)', () => {
});
});
// ── Custom place image reclaim (#1136) ──────────────────────────────────────────
// ── Custom place images stay for the storage reclaim job (#1136, #2924) ──────────────────────────────────────────
describe('custom place image reclaim', () => {
describe('custom place images', () => {
function writePlaceImage(name: string): string {
const filePath = path.join(placesStorageFx.root, name);
fs.writeFileSync(filePath, 'jpeg-bytes');
return filePath;
}
it('PLACE-SVC-046 — replacing image_url unlinks the previous upload once unreferenced', async () => {
it('PLACE-SVC-046 — replacing image_url keeps the previous upload for the reclaim job', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
@@ -1516,10 +1516,10 @@ describe('custom place image reclaim', () => {
expect(fs.existsSync(fileA)).toBe(true);
await svc.update(String(trip.id), String(place.id), { image_url: '/uploads/places/svc-replace-b.jpg' });
expect(fs.existsSync(fileA)).toBe(false);
expect(fs.existsSync(fileA)).toBe(true);
});
it('PLACE-SVC-047 — clearing image_url to null unlinks the previous upload', async () => {
it('PLACE-SVC-047 — clearing image_url to null keeps the previous upload', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
@@ -1528,10 +1528,10 @@ describe('custom place image reclaim', () => {
expect(fs.existsSync(fileA)).toBe(true);
await svc.update(String(trip.id), String(place.id), { image_url: null } as any);
expect(fs.existsSync(fileA)).toBe(false);
expect(fs.existsSync(fileA)).toBe(true);
});
it('PLACE-SVC-048 — remove unlinks the uploaded image', async () => {
it('PLACE-SVC-048 — remove keeps the uploaded image', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
@@ -1540,7 +1540,7 @@ describe('custom place image reclaim', () => {
expect(fs.existsSync(fileA)).toBe(true);
await svc.remove(String(trip.id), String(place.id));
expect(fs.existsSync(fileA)).toBe(false);
expect(fs.existsSync(fileA)).toBe(true);
});
it('PLACE-SVC-049 — a collection_places reference keeps the file when the trip place is deleted', async () => {
@@ -272,6 +272,22 @@ describe('TrekPhotoRegistrationService.deleteIfOrphan (PH10-11)', () => {
await repo.deleteIfOrphan(id);
expect(await rawRow(id)).not.toBeNull();
});
it('TREKPHOTO-064: a LOCAL photo the user deleted goes once nothing links it, so its bytes can be reclaimed', async () => {
const id = await repo.getOrCreateLocal('journey/deleted-by-user.jpg');
await repo.deleteIfOrphan(id, { local: true });
expect(await rawRow(id)).toBeNull();
});
it('TREKPHOTO-065: a deleted LOCAL photo another trip still links stays', async () => {
const { user } = createUser(testDb);
const id = await repo.getOrCreateLocal('journey/still-on-a-trip.jpg');
const trip = createTrip(testDb, user.id);
await insertRow(t, TripPhotos, { trip: trip.id, user: user.id, photo: id, shared: 1 });
await repo.deleteIfOrphan(id, { local: true });
expect(await rawRow(id)).not.toBeNull();
});
});
describe('M1: TripAlbumLinksRepository/TripPhotosRepository onConflict + empty-array branches', () => {
@@ -448,10 +448,8 @@ describe('TripsController (parity with the legacy /api/trips route)', async () =
const update = vi
.fn()
.mockReturnValue({ updatedTrip: { id: 9 }, changes: {}, newTitle: 'b', newReminder: 0, oldReminder: 0 });
const deleteOldCover = vi.fn();
const s = svc({
update,
deleteOldCover,
getRaw: vi.fn().mockReturnValue({ cover_image: null }),
} as Partial<TripsService>);
await tc(s).update(user, '9', { cover_image: 'https://images.unsplash.com/photo-123?w=1080' }, req);
@@ -591,16 +589,15 @@ describe('TripsController (parity with the legacy /api/trips route)', async () =
),
),
).toEqual({ status: 400, body: { error: 'No image uploaded' } });
const deleteOldCover = vi.fn();
const updateCoverImage = vi.fn();
const s = svc({
getRaw: vi.fn().mockReturnValue({ cover_image: '/old.jpg' }),
deleteOldCover,
updateCoverImage,
} as Partial<TripsService>);
expect(await tc(s).cover(user, '9', file)).toEqual({ cover_image: '/uploads/covers/abc.jpg' });
expect(storageStub.put).toHaveBeenCalledWith('covers', 'abc.jpg', { tmpPath: undefined });
expect(deleteOldCover).toHaveBeenCalledWith('/old.jpg');
// The replaced cover is left to the storage reclaim job: a copy may share it (#2924).
expect(storageStub.put).toHaveBeenCalledTimes(1);
expect(updateCoverImage).toHaveBeenCalledWith('9', '/uploads/covers/abc.jpg');
});
@@ -68,8 +68,6 @@ import { JourneyEntries } from '../../../src/db/entities/JourneyEntries.entity';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import fs from 'fs';
import path from 'path';
import { notificationsStub } from '../../helpers/notifications';
import { EphemeralTokenService } from '../../../src/nest/auth-core/ephemeral-token.service';
import {
@@ -855,45 +853,6 @@ describe('generateDays', () => {
});
});
// ── deleteOldCover — path containment ──────────────────────────────────────────
describe('deleteOldCover', () => {
it('TRIP-SVC-COVER-001: never deletes outside the covers category for a crafted cover_image', async () => {
// Attacker-controlled values aimed at auth-gated sibling upload dirs — the
// basename + category addressing keeps every delete inside covers/.
const filesDir = path.join(coversFx.root, 'files');
const avatarsDir = path.join(coversFx.root, 'avatars');
fs.mkdirSync(filesDir, { recursive: true });
fs.mkdirSync(avatarsDir, { recursive: true });
const secret = path.join(filesDir, 'secret.pdf');
const someone = path.join(avatarsDir, 'someone.png');
fs.writeFileSync(secret, 'pdf');
fs.writeFileSync(someone, 'png');
await svc.deleteOldCover('/uploads/files/secret.pdf');
await svc.deleteOldCover('/uploads/covers/../files/secret.pdf');
await svc.deleteOldCover('/uploads/avatars/someone.png');
expect(fs.existsSync(secret)).toBe(true);
expect(fs.existsSync(someone)).toBe(true);
});
it('TRIP-SVC-COVER-002: deletes a legitimate cover file', async () => {
const coversDir = path.join(coversFx.root, 'covers');
fs.mkdirSync(coversDir, { recursive: true });
const cover = path.join(coversDir, 'abc123.jpg');
fs.writeFileSync(cover, 'jpeg');
await svc.deleteOldCover('/uploads/covers/abc123.jpg');
expect(fs.existsSync(cover)).toBe(false);
});
it('TRIP-SVC-COVER-003: an external https cover URL is tolerated (no throw)', async () => {
await expect(svc.deleteOldCover('https://example.com/some/pic.jpg')).resolves.toBeUndefined();
await expect(svc.deleteOldCover(null)).resolves.toBeUndefined();
});
});
describe('resyncReservationDays (#1288)', () => {
const dayFor = async (tripId: number, date: string) =>
(await storedFields(Days, { trip: tripId, date }, ['id']) as { id: number }).id;