Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/api/auth/authMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Request, Response, NextFunction } from 'express';
import { User } from 'api/users/usersModel';
import { UserSchema } from 'shared/types/userType';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
declare global {
namespace Express {
export interface Request {
user: User;
user: User & { groups?: UserSchema['groups'] };
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions app/api/core/application/FileDelete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ import { Thumbnail } from '../domain/files/Thumbnail';
import { AbstractUseCase } from '../libs/UseCase';
import { FilesDataSource } from './contracts/FilesDataSource';
import { FilesService } from './FilesService';
import { EntityPermissionChecker } from '../domain/entity/EntityPermissionChecker';
import { createError } from 'api/utils';

type Output = Omit<fileDBO, '_id'> & { _id: string };

type Deps = {
filesDS: FilesDataSource;
filesService: FilesService;
entityPermissions: EntityPermissionChecker;
};

const fileUploadInputSchema = z.object({
Expand All @@ -30,6 +33,14 @@ class FileDelete extends AbstractUseCase<Input, Output, Deps> {
thumbnails = await this.deps.filesDS.getThumbnails([file]).all();
}

if (
!(
await this.deps.entityPermissions.checkWritePermission(file, this.getActor())
).getDataOrThrow()
) {
throw createError('file not found', 404);
}

await this.transactionManager.run(async () => {
await this.deps.filesService.delete([file, ...thumbnails]);
});
Expand Down
3 changes: 3 additions & 0 deletions app/api/core/domain/entity/EntityPermissionChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { User } from 'api/users.v2/model/User';
import { ResultType } from 'api/core/libs/Result';
import { AccessLevel } from './AccessLevel';
import { PermissionType } from './PermissionType';
import { BaseFile } from '../files/BaseFile';

type SpecificationProps = {
type: PermissionType;
Expand Down Expand Up @@ -45,6 +46,8 @@ interface EntityPermissionChecker {
sharedIds: string[],
specification: Specification
): Promise<ResultType<string[], Error>>;
checkReadPermission(sharedId: string, user?: User): Promise<ResultType<boolean, Error>>;
checkWritePermission(file: BaseFile, user?: User): Promise<ResultType<boolean, Error>>;
}

export { Specification };
Expand Down
90 changes: 40 additions & 50 deletions app/api/core/infrastructure/express/DownloadFileController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@ import { createError } from 'api/utils';

import { AbstractController, Dependencies } from 'api/common.v2/infrastructure/AbstractController';
import { FileStorage } from 'api/core/application/contracts/FileStorage';
import { BaseFile } from 'api/core/domain/files/BaseFile';
import { FileStorageFactory } from 'api/core/infrastructure/files/FileStorageFactory';
import { fileDBO } from 'api/core/infrastructure/mongodb/files/schemas/filesTypes';
import { tenants } from 'api/tenants';
import { User } from 'api/users.v2/model/User';
import { Request, Response } from 'express';
import { FileType } from 'shared/types/fileType';
import { Readable } from 'stream';
import { z } from 'zod';
import { FilesDataSourceFactory } from '../factories/FilesDataSourceFactory';
import { SettingsDataSourceFactory } from '../factories/SettingsDataSourceFactory';
import { TransactionManagerFactory } from '../factories/TransactionManagerFactory';
import { getConnection } from '../mongodb/common/getConnectionForCurrentTenant';
import { MongoEntityPermissionChecker } from '../mongodb/entity/MongoEntityPermissionChecker';

const timestampToHTTPDate = (timestamp: number): string => new Date(timestamp).toUTCString();

Expand All @@ -24,60 +26,28 @@ const requestSchema = z.object({
}),
});

const getCacheControlHeader = (
isPubliclyAccessible: boolean,
isPrivateInstance: boolean
): string => {
if (isPrivateInstance) {
return 'private, max-age=3600';
}

if (isPubliclyAccessible) {
return 'public, no-cache';
}

return 'private, max-age=3600';
};

type Deps = Dependencies & {
typesAllowed: fileDBO['type'][];
checkFilePermissions: (file: FileType) => Promise<boolean>;
isFilePubliclyAccessible: (file: FileType, isPrivateInstance: boolean) => Promise<boolean>;
};

class DownloadFileController extends AbstractController {
private typesAllowed: fileDBO['type'][];

private checkFilePermissions: (file: FileType) => Promise<boolean>;

private fileStorage: FileStorage;

private isFilePubliclyAccessible: (
file: FileType,
isPrivateInstance: boolean
) => Promise<boolean>;

constructor(dependencies: Deps) {
const { typesAllowed, checkFilePermissions, isFilePubliclyAccessible, ...rest } = dependencies;
const { typesAllowed, ...rest } = dependencies;
super(rest);
this.typesAllowed = typesAllowed;
this.checkFilePermissions = checkFilePermissions;
this.isFilePubliclyAccessible = isFilePubliclyAccessible;
this.fileStorage = FileStorageFactory.default();
}

static customHandler(
typesAllowed: fileDBO['type'][],
checkFilePermissions: (file: FileType) => Promise<boolean>,
isFilePubliclyAccessible: (file: FileType, isPrivateInstance: boolean) => Promise<boolean>
) {
static customHandler(typesAllowed: fileDBO['type'][]) {
return async (request: Request, response: Response) =>
new DownloadFileController({
request,
response,
typesAllowed,
checkFilePermissions,
isFilePubliclyAccessible,
}).handleAsync();
}

Expand All @@ -96,12 +66,12 @@ class DownloadFileController extends AbstractController {
this.addContentHeaders(file.originalname || file.filename, query, file.mimetype);

const stream = Readable.from(
(
await this.fileStorage.getFile({
this.fileStorage
.getFile({
filename: file.filename,
type: file.type,
})
).read()
.read()
);
this.response.on('close', () => {
stream.destroy();
Expand All @@ -120,24 +90,20 @@ class DownloadFileController extends AbstractController {
}

const filev2 = fileResult.getData();
const file = filev2.toDTO();
if (!(await this.fileStorage.fileExists(filev2)) || !(await this.checkFilePermissions(file))) {
if (
!(await this.fileStorage.fileExists(filev2)) ||
!(await this.checkFileReadPermissions(filev2))
) {
throw createError('file not found', 404);
}
return file;
return filev2;
}

private async addFileCacheHeaders(file: FileType) {
private async addFileCacheHeaders(file: BaseFile) {
if (this.request.user) {
this.response.setHeader('Cache-Control', 'private, max-age=3600');
} else {
const settingsDS = SettingsDataSourceFactory.default(TransactionManagerFactory.default());
const isPrivateInstance = (await settingsDS.get()).private || false;

const isPublic = await this.isFilePubliclyAccessible(file, isPrivateInstance);

const cacheControl = getCacheControlHeader(isPublic, isPrivateInstance);
this.response.setHeader('Cache-Control', cacheControl);
this.response.setHeader('Cache-Control', 'public, no-cache');
}

if (file.creationDate) {
Expand All @@ -164,6 +130,30 @@ class DownloadFileController extends AbstractController {
}
this.response.setHeader('Content-Type', mimetype || 'application/octet-stream');
}

private async checkFileReadPermissions(file: BaseFile): Promise<boolean> {
if (!file.isEntityFile()) {
return true;
}

const entityPermissionChecker = new MongoEntityPermissionChecker(
getConnection(),
TransactionManagerFactory.default()
);

return (
await entityPermissionChecker.checkReadPermission(
file.entity,
this.request.user
? User.createFrom({
id: this.request.user._id.toString(),
role: this.request.user.role,
groups: (this.request.user.groups || []).map(g => g._id.toString()),
})
: undefined
)
).getDataOrThrow();
}
}

export { DownloadFileController };
18 changes: 13 additions & 5 deletions app/api/core/infrastructure/express/files/FileDeleteController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { LoggerFactory } from '../../factories/LoggerFactory';
import { TransactionManagerFactory } from '../../factories/TransactionManagerFactory';
import { FileStorageFactory } from '../../files/FileStorageFactory';
import { DeleteFileFromStorageJobHandler } from '../../jobs/DeleteFileFromStorageJobHandler';
import { MongoEntityPermissionChecker } from '../../mongodb/entity/MongoEntityPermissionChecker';
import { getConnection } from '../../mongodb/common/getConnectionForCurrentTenant';
import { permissionsContext } from 'api/permissions/permissionsContext';
import { tenants } from 'api/tenants';

class FileDeleteController extends AbstractController {
protected async handle(): Promise<void> {
Expand Down Expand Up @@ -54,11 +58,15 @@ class FileDeleteController extends AbstractController {
});
}

return new FileDelete({
filesDS: FilesDataSourceFactory.default(transactionManager),
filesService: FilesServiceFactory.default(transactionManager, { jobsDispatcher }),
transactionManager,
});
return new FileDelete(
{
filesDS: FilesDataSourceFactory.default(transactionManager),
filesService: FilesServiceFactory.default(transactionManager, { jobsDispatcher }),
entityPermissions: new MongoEntityPermissionChecker(getConnection(), transactionManager),
transactionManager,
},
{ actor: permissionsContext.getUserInContext()!, tenant: tenants.current() }
);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
Specification,
} from 'api/core/domain/entity/EntityPermissionChecker';
import { Result, ResultType } from 'api/core/libs/Result';
import { User } from 'api/users.v2/model/User';
import { MongoEntityDAO } from './MongoEntityDAO';
import { BaseFile } from 'api/core/domain/files/BaseFile';
import { instanceOf } from 'prop-types';

Check failure on line 9 in app/api/core/infrastructure/mongodb/entity/MongoEntityPermissionChecker.ts

View workflow job for this annotation

GitHub Actions / eslint

'instanceOf' is defined but never used
import { shared1 } from 'api/migrations/migrations/6-connections_sanitizing/specs/fixtures';

Check failure on line 10 in app/api/core/infrastructure/mongodb/entity/MongoEntityPermissionChecker.ts

View workflow job for this annotation

GitHub Actions / eslint

'shared1' is defined but never used

class MongoEntityPermissionChecker extends MongoEntityDAO implements EntityPermissionChecker {
async filterEntities(
Expand Down Expand Up @@ -65,6 +69,64 @@

return Result.ok(grantedEntities);
}

async checkReadPermission(sharedId: string, user?: User): Promise<ResultType<boolean, Error>> {
const [entity] = await this.getCollection()
.aggregate([
{ $match: { sharedId } },
{
$group: {
_id: '$sharedId',
sharedId: { $first: '$sharedId' },
template: { $first: '$template' },
permissions: { $first: '$permissions' },
published: { $first: '$published' },
},
},
])
.toArray();

if (!entity) {
return Result.fail(new Error(`Entity not found: ${sharedId}`));
}

if (entity.published || user?.isPrivileged()) {
return Result.ok(true);
}

if (user) {
const userRefIds = [user._id, ...user.groups];
const userRefIdsAsStrings = userRefIds.map(id => id.toString());
return Result.ok(
entity.permissions?.some((perm: any) => userRefIdsAsStrings.includes(perm.refId.toString()))
);
}
return Result.ok(false);
}

async checkWritePermission(file: BaseFile, user?: User): Promise<ResultType<boolean, Error>> {
if (!user || !user.isPrivileged()) {
return Result.ok(false);
}
if (file.isEntityFile()) {
const [entity] = await this.getCollection()

Check failure on line 112 in app/api/core/infrastructure/mongodb/entity/MongoEntityPermissionChecker.ts

View workflow job for this annotation

GitHub Actions / eslint

'entity' is assigned a value but never used
.aggregate([
{ $match: { sharedId: file.entity } },
{
$group: {
_id: '$sharedId',
sharedId: { $first: '$sharedId' },
template: { $first: '$template' },
permissions: { $first: '$permissions' },
published: { $first: '$published' },
},
},
])
.toArray();
return Result.ok(true);
}
return Result.ok(true);
}
}

export { MongoEntityPermissionChecker };
2 changes: 1 addition & 1 deletion app/api/core/libs/UseCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ abstract class AbstractUseCase<Input, Output, ExtendedDeps = {}, Args extends an
return User.createFrom({
id: this.context?.actor?._id?.toString(),
role: this.context?.actor?.role,
groups: this.context?.actor?.groups?.map(g => g._id.toString()),
groups: (this.context?.actor?.groups || []).map(g => g._id.toString()),
});
}

Expand Down
Loading
Loading