mirror of
https://github.com/immich-app/immich.git
synced 2026-05-18 03:10:24 +03:00
c0898b96ca
* 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 commitc1bd7a116b. * Revert "refactor(server)!: sanitize error messages to avoid leaking resource and permission details" This reverts commitb96421a083. * 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 commitbb06990957. * shorten comment * add log messages * format * one more
162 lines
5.7 KiB
TypeScript
162 lines
5.7 KiB
TypeScript
import { BadRequestException, ForbiddenException, Injectable } from '@nestjs/common';
|
|
import { SALT_ROUNDS } from 'src/constants';
|
|
import { AssetStatsDto, AssetStatsResponseDto, mapStats } from 'src/dtos/asset.dto';
|
|
import { AuthDto } from 'src/dtos/auth.dto';
|
|
import { SessionResponseDto, mapSession } from 'src/dtos/session.dto';
|
|
import { UserPreferencesResponseDto, UserPreferencesUpdateDto, mapPreferences } from 'src/dtos/user-preferences.dto';
|
|
import {
|
|
UserAdminCreateDto,
|
|
UserAdminDeleteDto,
|
|
UserAdminResponseDto,
|
|
UserAdminSearchDto,
|
|
UserAdminUpdateDto,
|
|
mapUserAdmin,
|
|
} from 'src/dtos/user.dto';
|
|
import { JobName, UserMetadataKey, UserStatus } from 'src/enum';
|
|
import { UserFindOptions } from 'src/repositories/user.repository';
|
|
import { BaseService } from 'src/services/base.service';
|
|
import { getPreferences, getPreferencesPartial, mergePreferences } from 'src/utils/preferences';
|
|
|
|
@Injectable()
|
|
export class UserAdminService extends BaseService {
|
|
async search(auth: AuthDto, dto: UserAdminSearchDto): Promise<UserAdminResponseDto[]> {
|
|
const users = await this.userRepository.getList({
|
|
id: dto.id,
|
|
withDeleted: dto.withDeleted,
|
|
});
|
|
return users.map((user) => mapUserAdmin(user));
|
|
}
|
|
|
|
async create(dto: UserAdminCreateDto): Promise<UserAdminResponseDto> {
|
|
const { notify, ...userDto } = dto;
|
|
const config = await this.getConfig({ withCache: false });
|
|
if (!config.oauth.enabled && !userDto.password) {
|
|
throw new BadRequestException('password is required');
|
|
}
|
|
|
|
const user = await this.createUser(userDto);
|
|
|
|
await this.eventRepository.emit('UserSignup', {
|
|
notify: !!notify,
|
|
id: user.id,
|
|
password: userDto.password,
|
|
});
|
|
|
|
return mapUserAdmin(user);
|
|
}
|
|
|
|
async get(auth: AuthDto, id: string): Promise<UserAdminResponseDto> {
|
|
const user = await this.findOrFail(id, { withDeleted: true });
|
|
return mapUserAdmin(user);
|
|
}
|
|
|
|
async update(auth: AuthDto, id: string, dto: UserAdminUpdateDto): Promise<UserAdminResponseDto> {
|
|
const user = await this.findOrFail(id, {});
|
|
|
|
if (dto.isAdmin !== undefined && dto.isAdmin !== auth.user.isAdmin && auth.user.id === id) {
|
|
throw new BadRequestException('Admin status can only be changed by another admin');
|
|
}
|
|
|
|
if (dto.quotaSizeInBytes && user.quotaSizeInBytes !== dto.quotaSizeInBytes) {
|
|
await this.userRepository.syncUsage(id);
|
|
}
|
|
|
|
if (dto.email) {
|
|
const duplicate = await this.userRepository.getByEmail(dto.email);
|
|
if (duplicate && duplicate.id !== id) {
|
|
this.logger.debug('Email already in use by another account');
|
|
throw new BadRequestException('Email is not available');
|
|
}
|
|
}
|
|
|
|
if (dto.storageLabel) {
|
|
const duplicate = await this.userRepository.getByStorageLabel(dto.storageLabel);
|
|
if (duplicate && duplicate.id !== id) {
|
|
throw new BadRequestException('Storage label already in use by another account');
|
|
}
|
|
}
|
|
|
|
if (dto.password) {
|
|
dto.password = await this.cryptoRepository.hashBcrypt(dto.password, SALT_ROUNDS);
|
|
}
|
|
|
|
if (dto.pinCode) {
|
|
dto.pinCode = await this.cryptoRepository.hashBcrypt(dto.pinCode, SALT_ROUNDS);
|
|
}
|
|
|
|
if (dto.storageLabel === '') {
|
|
dto.storageLabel = null;
|
|
}
|
|
|
|
const updatedUser = await this.userRepository.update(id, { ...dto, updatedAt: new Date() });
|
|
|
|
return mapUserAdmin(updatedUser);
|
|
}
|
|
|
|
async delete(auth: AuthDto, id: string, dto: UserAdminDeleteDto): Promise<UserAdminResponseDto> {
|
|
const { force } = dto;
|
|
await this.findOrFail(id, {});
|
|
if (auth.user.id === id) {
|
|
throw new ForbiddenException('Cannot delete your own account');
|
|
}
|
|
|
|
await this.albumRepository.softDeleteAll(id);
|
|
|
|
const status = force ? UserStatus.Removing : UserStatus.Deleted;
|
|
const user = await this.userRepository.update(id, { status, deletedAt: new Date() });
|
|
|
|
await this.eventRepository.emit('UserTrash', user);
|
|
|
|
if (force) {
|
|
await this.jobRepository.queue({ name: JobName.UserDelete, data: { id: user.id, force } });
|
|
}
|
|
|
|
return mapUserAdmin(user);
|
|
}
|
|
|
|
async restore(auth: AuthDto, id: string): Promise<UserAdminResponseDto> {
|
|
await this.findOrFail(id, { withDeleted: true });
|
|
await this.albumRepository.restoreAll(id);
|
|
const user = await this.userRepository.restore(id);
|
|
await this.eventRepository.emit('UserRestore', user);
|
|
return mapUserAdmin(user);
|
|
}
|
|
|
|
async getSessions(auth: AuthDto, id: string): Promise<SessionResponseDto[]> {
|
|
const sessions = await this.sessionRepository.getByUserId(id);
|
|
return sessions.map((session) => mapSession(session));
|
|
}
|
|
|
|
async getStatistics(auth: AuthDto, id: string, dto: AssetStatsDto): Promise<AssetStatsResponseDto> {
|
|
const stats = await this.assetRepository.getStatistics(id, dto);
|
|
return mapStats(stats);
|
|
}
|
|
|
|
async getPreferences(auth: AuthDto, id: string): Promise<UserPreferencesResponseDto> {
|
|
await this.findOrFail(id, { withDeleted: true });
|
|
const metadata = await this.userRepository.getMetadata(id);
|
|
return mapPreferences(getPreferences(metadata));
|
|
}
|
|
|
|
async updatePreferences(auth: AuthDto, id: string, dto: UserPreferencesUpdateDto) {
|
|
await this.findOrFail(id, { withDeleted: false });
|
|
const metadata = await this.userRepository.getMetadata(id);
|
|
const newPreferences = mergePreferences(getPreferences(metadata), dto);
|
|
|
|
await this.userRepository.upsertMetadata(id, {
|
|
key: UserMetadataKey.Preferences,
|
|
value: getPreferencesPartial(newPreferences),
|
|
});
|
|
|
|
return mapPreferences(newPreferences);
|
|
}
|
|
|
|
private async findOrFail(id: string, options: UserFindOptions) {
|
|
const user = await this.userRepository.get(id, options);
|
|
if (!user) {
|
|
throw new BadRequestException('User not found');
|
|
}
|
|
return user;
|
|
}
|
|
}
|