Files
immich/server/src/services/user.service.spec.ts
T
Timon c0898b96ca refactor(server)!: sanitize error messages to avoid leaking resource details (#28154)
* refactor(server)!: sanitize error messages to avoid leaking resource and permission details

* fix e2e tests

* fix(server): prevent login timing oracle by always running bcrypt

Always call compareBcrypt in the login path regardless of whether the
email is registered. When no user is found, a dummy hash is used so the
bcrypt KDF still runs and response latency is constant, making it
impossible to enumerate valid email addresses by measuring response time.

* fix(server): collapse OAuth callback messages to prevent email-existence oracle

Two distinct error messages in the OAuth callback endpoint revealed
whether an email address was already registered in the database.
An attacker controlling the OAuth provider's email claim could probe
the user table without authentication. Both cases now return the same
generic message.

* fix(server): replace email-in-use messages to prevent user-existence oracle

Error messages on registration and profile-update that named whether an
email address was already taken allowed callers to enumerate registered
accounts. All three sites now return the same generic message regardless
of whether the address is in use.

* fix(server): hide slug uniqueness constraint to prevent shared-link probe

Surfacing the Postgres unique-constraint name in the error response let
any authenticated user brute-force whether a custom slug was already in
use by another user's shared link, leaking the existence of other links.

* fix(server): unify profile image errors to prevent user-existence oracle via status code

GET /users/:id/profile-image returned HTTP 400 for an unknown user ID
but HTTP 404 when the user existed without a photo, letting callers
distinguish the two cases. Both now return 404 so the response is
identical regardless of whether the UUID maps to an account.

* fix(server): replace album user-not-found message to prevent UUID-existence oracle

Album owners could probe arbitrary UUIDs via the add-user endpoint and
determine whether they belonged to registered accounts by receiving
'User not found'. The message is now ambiguous about whether the ID was
unrecognised or the user is inactive.

* Revert "fix e2e tests"

This reverts commit c1bd7a116b3f0fccf3d2530c8e34b13c1d862989.

* Revert "refactor(server)!: sanitize error messages to avoid leaking resource and permission details"

This reverts commit b96421a08387340fbb77913ca89b0717bcd9945d.

* fix(server): use 403 instead of 400 for access-denied errors

requireAccess threw BadRequestException which is incorrect HTTP semantics.
Access denial is a client authorization problem (403 Forbidden), not a
malformed request (400 Bad Request). Keep the descriptive permission name
in the message since the full permission set is public API surface.

* Revert "fix(server): use 403 instead of 400 for access-denied errors"

This reverts commit bb069909571f4e514e7d050ddf588c017ee5a029.

* shorten comment

* add log messages

* format

* one more
2026-05-01 10:00:18 -04:00

360 lines
13 KiB
TypeScript

import { BadRequestException, InternalServerErrorException, NotFoundException } from '@nestjs/common';
import { UserAdmin } from 'src/database';
import { CacheControl, JobName, UserMetadataKey } from 'src/enum';
import { UserService } from 'src/services/user.service';
import { ImmichFileResponse } from 'src/utils/file';
import { AuthFactory } from 'test/factories/auth.factory';
import { UserFactory } from 'test/factories/user.factory';
import { authStub } from 'test/fixtures/auth.stub';
import { systemConfigStub } from 'test/fixtures/system-config.stub';
import { userStub } from 'test/fixtures/user.stub';
import { newTestService, ServiceMocks } from 'test/utils';
const makeDeletedAt = (daysAgo: number) => {
const deletedAt = new Date();
deletedAt.setDate(deletedAt.getDate() - daysAgo);
return deletedAt;
};
describe(UserService.name, () => {
let sut: UserService;
let mocks: ServiceMocks;
beforeEach(() => {
({ sut, mocks } = newTestService(UserService));
mocks.user.get.mockImplementation((userId) =>
Promise.resolve([userStub.admin, userStub.user1].find((user) => user.id === userId) ?? undefined),
);
});
describe('getAll', () => {
it('admin should get all users', async () => {
const user = UserFactory.create();
const auth = AuthFactory.create(user);
mocks.user.getList.mockResolvedValue([user]);
await expect(sut.search(auth)).resolves.toEqual([expect.objectContaining({ id: user.id, email: user.email })]);
expect(mocks.user.getList).toHaveBeenCalledWith({ withDeleted: false });
});
it('non-admin should get all users when publicUsers enabled', async () => {
const user = UserFactory.create();
const auth = AuthFactory.create(user);
mocks.user.getList.mockResolvedValue([user]);
await expect(sut.search(auth)).resolves.toEqual([expect.objectContaining({ id: user.id, email: user.email })]);
expect(mocks.user.getList).toHaveBeenCalledWith({ withDeleted: false });
});
it('non-admin user should only receive itself when publicUsers is disabled', async () => {
mocks.user.getList.mockResolvedValue([userStub.user1]);
mocks.systemMetadata.get.mockResolvedValue(systemConfigStub.publicUsersDisabled);
await expect(sut.search(authStub.user1)).resolves.toEqual([
expect.objectContaining({
id: authStub.user1.user.id,
email: authStub.user1.user.email,
}),
]);
expect(mocks.user.getList).not.toHaveBeenCalledWith({ withDeleted: false });
});
});
describe('get', () => {
it('should get a user by id', async () => {
mocks.user.get.mockResolvedValue(userStub.admin);
await sut.get(authStub.admin.user.id);
expect(mocks.user.get).toHaveBeenCalledWith(authStub.admin.user.id, { withDeleted: false });
});
it('should throw an error if a user is not found', async () => {
mocks.user.get.mockResolvedValue(void 0);
await expect(sut.get(authStub.admin.user.id)).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.user.get).toHaveBeenCalledWith(authStub.admin.user.id, { withDeleted: false });
});
});
describe('getMe', () => {
it("should get the auth user's info", async () => {
const user = authStub.admin.user;
await expect(sut.getMe(authStub.admin)).resolves.toMatchObject({
id: user.id,
email: user.email,
});
});
});
describe('createProfileImage', () => {
it('should throw an error if the user does not exist', async () => {
const file = { path: '/profile/path' } as Express.Multer.File;
mocks.user.get.mockResolvedValue(void 0);
mocks.user.update.mockResolvedValue({ ...userStub.admin, profileImagePath: file.path });
await expect(sut.createProfileImage(authStub.admin, file)).rejects.toThrowError(BadRequestException);
});
it('should throw an error if the user profile could not be updated with the new image', async () => {
const file = { path: '/profile/path' } as Express.Multer.File;
const user = UserFactory.create({ profileImagePath: '/path/to/profile.jpg' });
mocks.user.get.mockResolvedValue(user);
mocks.user.update.mockRejectedValue(new InternalServerErrorException('mocked error'));
await expect(sut.createProfileImage(authStub.admin, file)).rejects.toThrowError(InternalServerErrorException);
});
it('should throw BadRequestException and clean up raw upload when thumbnail processing fails', async () => {
const file = { path: '/profile/path' } as Express.Multer.File;
const user = UserFactory.create({ profileImagePath: '/path/to/profile.jpg' });
mocks.user.get.mockResolvedValue(user);
mocks.media.generateThumbnail.mockRejectedValue(new Error('not an image'));
await expect(sut.createProfileImage(authStub.admin, file)).rejects.toThrowError(BadRequestException);
expect(mocks.user.update).not.toHaveBeenCalled();
expect(mocks.job.queue.mock.calls).toEqual([[{ name: JobName.FileDelete, data: { files: [file.path] } }]]);
});
it('should delete the raw upload and the previous profile image', async () => {
const user = UserFactory.create({ profileImagePath: '/path/to/profile.jpg' });
const file = { path: '/profile/path' } as Express.Multer.File;
mocks.user.get.mockResolvedValue(user);
mocks.user.update.mockResolvedValue({ ...userStub.admin, profileImagePath: file.path });
await sut.createProfileImage(authStub.admin, file);
expect(mocks.job.queue.mock.calls).toEqual([
[{ name: JobName.FileDelete, data: { files: [file.path, user.profileImagePath] } }],
]);
});
it('should delete only the raw upload if no previous profile image is set', async () => {
const file = { path: '/profile/path' } as Express.Multer.File;
mocks.user.get.mockResolvedValue(userStub.admin);
mocks.user.update.mockResolvedValue({ ...userStub.admin, profileImagePath: file.path });
await sut.createProfileImage(authStub.admin, file);
expect(mocks.job.queue.mock.calls).toEqual([[{ name: JobName.FileDelete, data: { files: [file.path] } }]]);
expect(mocks.job.queueAll).not.toHaveBeenCalled();
});
});
describe('deleteProfileImage', () => {
it('should send an http error has no profile image', async () => {
mocks.user.get.mockResolvedValue(userStub.admin);
await expect(sut.deleteProfileImage(authStub.admin)).rejects.toBeInstanceOf(BadRequestException);
expect(mocks.job.queue).not.toHaveBeenCalled();
expect(mocks.job.queueAll).not.toHaveBeenCalled();
});
it('should delete the profile image if user has one', async () => {
const user = UserFactory.create({ profileImagePath: '/path/to/profile.jpg' });
const files = [user.profileImagePath];
mocks.user.get.mockResolvedValue(user);
await sut.deleteProfileImage(authStub.admin);
expect(mocks.job.queue.mock.calls).toEqual([[{ name: JobName.FileDelete, data: { files } }]]);
});
});
describe('getUserProfileImage', () => {
it('should throw an error if the user does not exist', async () => {
mocks.user.get.mockResolvedValue(void 0);
await expect(sut.getProfileImage(userStub.admin.id)).rejects.toBeInstanceOf(NotFoundException);
expect(mocks.user.get).toHaveBeenCalledWith(userStub.admin.id, {});
});
it('should throw an error if the user does not have a picture', async () => {
mocks.user.get.mockResolvedValue(userStub.admin);
await expect(sut.getProfileImage(userStub.admin.id)).rejects.toBeInstanceOf(NotFoundException);
expect(mocks.user.get).toHaveBeenCalledWith(userStub.admin.id, {});
});
it('should return the profile picture', async () => {
const user = UserFactory.create({ profileImagePath: '/path/to/profile.jpg' });
mocks.user.get.mockResolvedValue(user);
await expect(sut.getProfileImage(user.id)).resolves.toEqual(
new ImmichFileResponse({
path: '/path/to/profile.jpg',
contentType: 'image/jpeg',
cacheControl: CacheControl.None,
}),
);
expect(mocks.user.get).toHaveBeenCalledWith(user.id, {});
});
it('should return the profile picture with the content-type matching the stored file', async () => {
const user = UserFactory.create({ profileImagePath: '/path/to/profile.webp' });
mocks.user.get.mockResolvedValue(user);
await expect(sut.getProfileImage(user.id)).resolves.toEqual(
new ImmichFileResponse({
path: '/path/to/profile.webp',
contentType: 'image/webp',
cacheControl: CacheControl.None,
}),
);
});
});
describe('handleQueueUserDelete', () => {
it('should skip users not ready for deletion', async () => {
mocks.user.getDeletedAfter.mockResolvedValue([]);
await sut.handleUserDeleteCheck();
expect(mocks.user.getDeletedAfter).toHaveBeenCalled();
expect(mocks.job.queue).not.toHaveBeenCalled();
expect(mocks.job.queueAll).toHaveBeenCalledWith([]);
});
it('should queue user ready for deletion', async () => {
const user = UserFactory.create();
mocks.user.getDeletedAfter.mockResolvedValue([{ id: user.id }]);
await sut.handleUserDeleteCheck();
expect(mocks.user.getDeletedAfter).toHaveBeenCalled();
expect(mocks.job.queueAll).toHaveBeenCalledWith([{ name: JobName.UserDelete, data: { id: user.id } }]);
});
});
describe('handleUserDelete', () => {
it('should skip users not ready for deletion', async () => {
const user = { id: 'user-1', deletedAt: makeDeletedAt(5) } as UserAdmin;
mocks.user.get.mockResolvedValue(user);
await sut.handleUserDelete({ id: user.id });
expect(mocks.storage.unlinkDir).not.toHaveBeenCalled();
expect(mocks.user.delete).not.toHaveBeenCalled();
});
it('should delete the user and associated assets', async () => {
const user = { id: 'deleted-user', deletedAt: makeDeletedAt(10) } as UserAdmin;
const options = { force: true, recursive: true };
mocks.user.get.mockResolvedValue(user);
await sut.handleUserDelete({ id: user.id });
expect(mocks.storage.unlinkDir).toHaveBeenCalledWith(
expect.stringContaining('/data/library/deleted-user'),
options,
);
expect(mocks.storage.unlinkDir).toHaveBeenCalledWith(
expect.stringContaining('/data/upload/deleted-user'),
options,
);
expect(mocks.storage.unlinkDir).toHaveBeenCalledWith(
expect.stringContaining('/data/profile/deleted-user'),
options,
);
expect(mocks.storage.unlinkDir).toHaveBeenCalledWith(
expect.stringContaining('/data/thumbs/deleted-user'),
options,
);
expect(mocks.storage.unlinkDir).toHaveBeenCalledWith(
expect.stringContaining('/data/encoded-video/deleted-user'),
options,
);
expect(mocks.album.deleteAll).toHaveBeenCalledWith(user.id);
expect(mocks.user.delete).toHaveBeenCalledWith(user, true);
});
it('should delete the library path for a storage label', async () => {
const user = { id: 'deleted-user', deletedAt: makeDeletedAt(10), storageLabel: 'admin' } as UserAdmin;
mocks.user.get.mockResolvedValue(user);
await sut.handleUserDelete({ id: user.id });
const options = { force: true, recursive: true };
expect(mocks.storage.unlinkDir).toHaveBeenCalledWith(expect.stringContaining('data/library/admin'), options);
});
});
describe('setLicense', () => {
it('should save client license if valid', async () => {
const license = { licenseKey: 'IMCL-license-key', activationKey: 'activation-key' };
mocks.user.upsertMetadata.mockResolvedValue();
await sut.setLicense(authStub.user1, license);
expect(mocks.user.upsertMetadata).toHaveBeenCalledWith(authStub.user1.user.id, {
key: UserMetadataKey.License,
value: expect.any(Object),
});
});
it('should save server license as client if valid', async () => {
const license = { licenseKey: 'IMSV-license-key', activationKey: 'activation-key' };
mocks.user.upsertMetadata.mockResolvedValue();
await sut.setLicense(authStub.user1, license);
expect(mocks.user.upsertMetadata).toHaveBeenCalledWith(authStub.user1.user.id, {
key: UserMetadataKey.License,
value: expect.any(Object),
});
});
it('should not save license if invalid', async () => {
const license = { licenseKey: 'license-key', activationKey: 'activation-key' };
const call = sut.setLicense(authStub.admin, license);
mocks.user.upsertMetadata.mockResolvedValue();
await expect(call).rejects.toThrowError('Invalid license key');
expect(mocks.user.upsertMetadata).not.toHaveBeenCalled();
});
});
describe('deleteLicense', () => {
it('should delete license', async () => {
mocks.user.upsertMetadata.mockResolvedValue();
await sut.deleteLicense(authStub.admin);
expect(mocks.user.upsertMetadata).not.toHaveBeenCalled();
});
});
describe('handleUserSyncUsage', () => {
it('should sync usage', async () => {
await sut.handleUserSyncUsage();
expect(mocks.user.syncUsage).toHaveBeenCalledTimes(1);
});
});
});