Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(files): serve a plugin the files a trip keeps while Documents is off

Maurice4cd3f3d6503c
diff --git a/server/src/nest/files/files.rpc.ts b/server/src/nest/files/files.rpc.ts
index 7dbd776a7..6f153d539 100644
--- a/server/src/nest/files/files.rpc.ts
+++ b/server/src/nest/files/files.rpc.ts
@@ -1,19 +1,21 @@
import { ADDON_IDS } from '../../addons';
import { readEnv } from '../../app-config';
import { Users } from '../../db/entities/Users.entity';
+import type { TripFileRow } from '../../db/repositories/TripFiles.repository';
import type { UsersRepository } from '../../db/repositories/Users.repository';
-import { PluginGuards, type RpcAddon } from '../../nest-rpc/plugin-guards.service';
+import { PluginGuards } from '../../nest-rpc/plugin-guards.service';
import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors';
import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators';
import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';
import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params';
+import { AddonsService } from '../addons/addons.service';
import { isDemoEmail } from '../common/demo';
import { RealtimeService } from '../realtime/realtime.service';
import { StorageService } from '../storage/storage.service';
import { BLOCKED_EXTENSIONS } from './files.constants';
// The read cap is the same number on both byte paths, so the upload side of
// this surface reads it off the service that owns the read side.
-import { FilesService, FileContentError, FILE_CONTENT_MAX as CONTENT_MAX } from './files.service';
+import { FilesService, FileContentError, FILE_CONTENT_MAX as CONTENT_MAX, attachesFile } from './files.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { randomUUID } from 'node:crypto';
@@ -34,9 +36,6 @@ type CreateInput = {
reservation_id?: number;
};
-/** Every read and write here belongs to the documents addon and follows it per trip. */
-const FILES_ADDON: RpcAddon = { addonId: ADDON_IDS.DOCUMENTS, noun: 'documents' };
-
/**
* The file surface a plugin may reach (#plugins).
*
@@ -49,6 +48,10 @@ const FILES_ADDON: RpcAddon = { addonId: ADDON_IDS.DOCUMENTS, noun: 'documents'
* through the storage layer, so `ctx.files` behaves identically whether the backend
* is local disk, S3, or a mirrored pair. The extension blocklist and size cap still
* run before the put, and a demo user is refused outright.
+ *
+ * Documents gates it the way it gates the REST routes: while the trip has it off,
+ * the list leaves out the files only the file manager shows, and a call on such a
+ * file is refused unless it attaches the file. Uploads and deletes stay open.
*/
@PluginController()
export class FilesRpc {
@@ -58,26 +61,31 @@ export class FilesRpc {
@InjectRepository(Users) private readonly users: UsersRepository,
private readonly guards: PluginGuards,
private readonly storage: StorageService,
+ private readonly addons: AddonsService,
) {}
+ private documentsOn(tripId: number): Promise<boolean> {
+ return this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS);
+ }
+
+ private async requireReachable(tripId: number, file: TripFileRow, targets: Parameters<typeof attachesFile>[0] = {}) {
+ if (attachesFile(targets) || (await this.documentsOn(tripId)) || (await this.files.isAttached(file))) return;
+ throw new ForbiddenResource('the documents addon is disabled');
+ }
+
@PluginMethod('files.list', { permission: 'db:read:files' })
async list(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
// Trash excluded, the same view the files tab shows.
- return await this.guards.tripRead(
- params,
- ctx,
- async () => this.files.listFiles(rowIdParam(params.tripId, 'tripId'), false),
- FILES_ADDON,
- );
+ return await this.guards.tripRead(params, ctx, async () => {
+ const tripId = rowIdParam(params.tripId, 'tripId');
+ return this.files.listFiles(tripId, false, !(await this.documentsOn(tripId)));
+ });
}
@PluginMethod('files.getContent', { permission: 'db:read:files:content' })
getContent(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
- return this.guards.tripRead(
- params,
- ctx,
- () => this.readContent(rowIdParam(params.tripId, 'tripId'), rowIdParam(params.fileId, 'fileId')),
- FILES_ADDON,
+ return this.guards.tripRead(params, ctx, () =>
+ this.readContent(rowIdParam(params.tripId, 'tripId'), rowIdParam(params.fileId, 'fileId')),
);
}
@@ -89,6 +97,8 @@ export class FilesRpc {
* caused (too large) is BAD_PARAMS, everything else RESOURCE_FORBIDDEN.
*/
private async readContent(tripId: number, fileId: number): Promise<unknown> {
+ const file = await this.files.getFileById(fileId, tripId);
+ if (file) await this.requireReachable(tripId, file);
try {
const { name, mimetype, bytes } = await this.files.readContent(tripId, fileId);
return { name, mimetype, size: bytes.length, content_base64: bytes.toString('base64') };
@@ -116,7 +126,7 @@ export class FilesRpc {
if (input.content_base64.length > 14 * 1024 * 1024) {
throw new BadParams('file exceeds the 10MB plugin upload cap');
}
- await this.guards.requireTripEdit(tripId, actor, UPLOAD_ACTION, FILES_ADDON);
+ await this.guards.requireTripEdit(tripId, actor, UPLOAD_ACTION);
return this.writeFile(tripId, input as unknown as CreateInput, actor);
}
@@ -168,10 +178,11 @@ export class FilesRpc {
const tripId = rowIdParam(params.tripId, 'tripId');
const fileId = rowIdParam(params.fileId, 'fileId');
const actor = this.guards.requireActor(ctx, 'file link');
- await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION, FILES_ADDON);
- if (!(await this.files.getFileById(fileId, tripId)))
- throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
+ await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION);
+ const file = await this.files.getFileById(fileId, tripId);
+ if (!file) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
const opts = asPayload(params.opts) as { reservation_id?: number; assignment_id?: number; place_id?: number };
+ await this.requireReachable(tripId, file, opts);
// A link target on another trip would otherwise attach this trip's file to it.
const foreign = await this.files.findForeignLinkTarget(tripId, opts);
if (foreign) throw new ForbiddenResource(`${foreign} does not belong to trip ${tripId}`);
@@ -187,7 +198,7 @@ export class FilesRpc {
const tripId = rowIdParam(params.tripId, 'tripId');
const fileId = rowIdParam(params.fileId, 'fileId');
const actor = this.guards.requireActor(ctx, 'file');
- await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION, FILES_ADDON);
+ await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION);
const current = await this.files.getFileById(fileId, tripId);
if (!current) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
const input = asPayload(params.input) as {
@@ -195,6 +206,7 @@ export class FilesRpc {
place_id?: number | null;
reservation_id?: number | null;
};
+ await this.requireReachable(tripId, current, input);
const foreign = await this.files.findForeignLinkTarget(tripId, {
reservation_id: input.reservation_id ?? null,
place_id: input.place_id ?? null,
@@ -216,7 +228,7 @@ export class FilesRpc {
const tripId = rowIdParam(params.tripId, 'tripId');
const fileId = rowIdParam(params.fileId, 'fileId');
const actor = this.guards.requireActor(ctx, 'file');
- await this.guards.requireTripEdit(tripId, actor, DELETE_ACTION, FILES_ADDON);
+ await this.guards.requireTripEdit(tripId, actor, DELETE_ACTION);
if (!(await this.files.getFileById(fileId, tripId)))
throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);
await this.files.softDeleteFile(fileId);
diff --git a/server/tests/helpers/plugin-host.ts b/server/tests/helpers/plugin-host.ts
index 0c4d44597..e54e2455c 100644
--- a/server/tests/helpers/plugin-host.ts
+++ b/server/tests/helpers/plugin-host.ts
@@ -584,7 +584,7 @@ export async function createPluginRpcHostParts(
new TodoRpc(todos, realtime, guards),
new DayNotesRpc(dayNotes, realtime, guards),
new PackingRpc(packing, realtime, guards),
- new FilesRpc(files, realtime, usersRepo, guards, generalStorage),
+ new FilesRpc(files, realtime, usersRepo, guards, generalStorage, addons),
new PlacesRpc(places, journey, realtime, guards, placeOriginsStub()),
new DaysRpc(
days,
diff --git a/server/tests/helpers/rpc-host-deps.ts b/server/tests/helpers/rpc-host-deps.ts
index 9fde90e75..44699895b 100644
--- a/server/tests/helpers/rpc-host-deps.ts
+++ b/server/tests/helpers/rpc-host-deps.ts
@@ -67,7 +67,7 @@ export function allRpcControllers(): object[] {
new TodoRpc(anyService(), anyService(), anyService()),
new DayNotesRpc(anyService(), anyService(), anyService()),
new PackingRpc(anyService(), anyService(), anyService()),
- new FilesRpc(anyService(), anyService(), anyService(), anyService(), anyService()),
+ new FilesRpc(anyService(), anyService(), anyService(), anyService(), anyService(), anyService()),
new PlacesRpc(anyService(), anyService(), anyService(), anyService(), anyService()),
new DaysRpc(anyService(), anyService(), anyService(), anyService()),
new ItineraryRpc(anyService(), anyService(), anyService()),
diff --git a/server/tests/unit/files/files.rpc.test.ts b/server/tests/unit/files/files.rpc.test.ts
index c9ffd4780..9431d3870 100644
--- a/server/tests/unit/files/files.rpc.test.ts
+++ b/server/tests/unit/files/files.rpc.test.ts
@@ -38,9 +38,15 @@ const req = (method: string, params: Record<string, unknown> = {}): RpcRequest =
const b64 = (s: string) => Buffer.from(s).toString('base64');
-/** File 2 sits on trip 1, which belongs to user 42. */
+/** File 2 sits on trip 1, which belongs to user 42. `documents` is the trip's Documents switch, `attached` whether file 2 belongs to something. */
function build(
- opts: { file?: Record<string, unknown> | undefined; foreign?: string | null; allow?: (a: string) => boolean } = {},
+ opts: {
+ file?: Record<string, unknown> | undefined;
+ foreign?: string | null;
+ allow?: (a: string) => boolean;
+ documents?: boolean;
+ attached?: boolean;
+ } = {},
) {
const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
const files = {
@@ -61,7 +67,12 @@ function build(
createFileLink: vi.fn(() => [{ file_id: 2 }]),
updateFile: vi.fn((id: number) => ({ id })),
softDeleteFile: vi.fn(),
+ isAttached: vi.fn(async () => opts.attached ?? false),
} as unknown as FilesService & Record<string, ReturnType<typeof vi.fn>>;
+ const addons = {
+ isAddonEnabled: vi.fn(() => true),
+ isEnabledForTrip: vi.fn(async () => opts.documents ?? true),
+ } as unknown as AddonsService;
const db = {
findAccessible: vi.fn(async (tripId: number, userId: number) =>
tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,
@@ -77,12 +88,7 @@ function build(
const permissions = {
checkPermission: vi.fn((action: string) => (opts.allow ? opts.allow(action) : true)),
} as unknown as PermissionsService;
- const guards = new PluginGuards(
- db,
- permissions,
- { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
- usersRepo,
- );
+ const guards = new PluginGuards(db, permissions, addons, usersRepo);
const storage = {
getStream: vi.fn(async () => ({
stream: Readable.from(Buffer.from('hi')),
@@ -96,7 +102,7 @@ function build(
// keep exercising that code rather than a stub of it.
(files as unknown as { readContent: FilesService['readContent'] }).readContent =
FilesService.prototype.readContent.bind({ getFileById: files.getFileById, storage } as unknown as FilesService);
- const rpc = new FilesRpc(files, realtime, usersRepo, guards, storage);
+ const rpc = new FilesRpc(files, realtime, usersRepo, guards, storage, addons);
const host = (...grants: string[]) =>
new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc]));
return { files, realtime, permissions, storage, host };
@@ -107,7 +113,7 @@ describe('FilesRpc reads', () => {
const f = build();
const host = f.host('db:read:files');
expect((await host.dispatch(req('files.list', { tripId: 1 }), 42)).ok).toBe(true);
- expect(f.files.listFiles).toHaveBeenCalledWith(1, false);
+ expect(f.files.listFiles).toHaveBeenCalledWith(1, false, false);
expect(((await host.dispatch(req('files.list', { tripId: 2 }), 42)) as RpcError).error.code).toBe(
'RESOURCE_FORBIDDEN',
);
@@ -222,6 +228,48 @@ describe('FilesRpc reads', () => {
});
});
+describe('FilesRpc with Documents off for the trip', () => {
+ const forbidden = async (res: Promise<unknown>) => ((await res) as RpcError).error;
+
+ it('FILES-RPC-022 lists only attached files and reads an attached one, a loose one is refused', async () => {
+ const attached = build({ documents: false, attached: true });
+ expect((await attached.host('db:read:files').dispatch(req('files.list', { tripId: 1 }), 42)).ok).toBe(true);
+ expect(attached.files.listFiles).toHaveBeenCalledWith(1, false, true);
+ const read = (await attached
+ .host('db:read:files:content')
+ .dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42)) as RpcResponse;
+ expect(read.result).toMatchObject({ name: 'visa.pdf', content_base64: b64('hi') });
+
+ const loose = build({ documents: false, attached: false });
+ expect(
+ await forbidden(
+ loose.host('db:read:files:content').dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42),
+ ),
+ ).toMatchObject({ code: 'RESOURCE_FORBIDDEN', message: 'the documents addon is disabled' });
+ });
+
+ it('FILES-RPC-023 uploads and deletes stay open, a write on a loose file only when it attaches it', async () => {
+ const f = build({ documents: false, attached: false });
+ const host = f.host('db:write:files');
+ const create = { tripId: 1, input: { name: 'a.pdf', content_base64: b64('x'), reservation_id: 4 } };
+ expect((await host.dispatch(req('files.create', create), 42)).ok).toBe(true);
+ expect((await host.dispatch(req('files.softDelete', { tripId: 1, fileId: 2 }), 42)).ok).toBe(true);
+
+ const describeOnly = req('files.update', { tripId: 1, fileId: 2, input: { description: 'x' } });
+ expect(await forbidden(host.dispatch(describeOnly, 42))).toMatchObject({ code: 'RESOURCE_FORBIDDEN' });
+ expect(
+ await forbidden(host.dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: {} }), 42)),
+ ).toMatchObject({ code: 'RESOURCE_FORBIDDEN' });
+ expect(f.files.updateFile).not.toHaveBeenCalled();
+
+ const attach = req('files.update', { tripId: 1, fileId: 2, input: { reservation_id: 4 } });
+ expect((await host.dispatch(attach, 42)).ok).toBe(true);
+ expect((await host.dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: { place_id: 3 } }), 42)).ok).toBe(
+ true,
+ );
+ });
+});
+
describe('FilesRpc writes', () => {
it('FILES-RPC-006 each operation asks for its own right', async () => {
const seen: string[] = [];
@@ -431,7 +479,14 @@ describe('FilesRpc writes', () => {
const usersRepo = {
getEmail: vi.fn(async (id: number) => (id === 9 ? '[email protected]' : '[email protected]')),
} as unknown as UsersRepository;
- const rpc = new FilesRpc(files, { broadcast: vi.fn() } as unknown as RealtimeService, usersRepo, guards, storage);
+ const rpc = new FilesRpc(
+ files,
+ { broadcast: vi.fn() } as unknown as RealtimeService,
+ usersRepo,
+ guards,
+ storage,
+ { isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
+ );
const host = new PluginRpcHost('p', new Set(['db:write:files']), makeDeps(), createTestPluginRegistry([rpc]));
const input = { name: 'a.pdf', content_base64: b64('x') };
const denied = (await host.dispatch(req('files.create', { tripId: 1, input }), 9)) as RpcError;
diff --git a/server/tests/unit/plugins/rpc-fallbacks.test.ts b/server/tests/unit/plugins/rpc-fallbacks.test.ts
index e5331646f..7aa220762 100644
--- a/server/tests/unit/plugins/rpc-fallbacks.test.ts
+++ b/server/tests/unit/plugins/rpc-fallbacks.test.ts
@@ -90,6 +90,8 @@ function guardsFor() {
}
const realtime = () => ({ broadcast: vi.fn() }) as never;
+/** Documents on for the trip, so the file writes below reach their service call. */
+const documentsOn = { isEnabledForTrip: vi.fn(async () => true) } as never;
describe('optional fields fall back rather than reaching the service as undefined', () => {
it('FALLBACK-001 a tag update without name or colour forwards undefined for both', async () => {
@@ -138,7 +140,7 @@ describe('optional fields fall back rather than reaching the service as undefine
'p',
ALL,
makeDeps(),
- createTestPluginRegistry([new FilesRpc(files, realtime(), {} as never, guards, {} as never)]),
+ createTestPluginRegistry([new FilesRpc(files, realtime(), {} as never, guards, {} as never, documentsOn)]),
);
await host.dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: {} }), 42);
expect(createFileLink).toHaveBeenCalledWith(2, { reservation_id: null, assignment_id: null, place_id: null });
@@ -152,7 +154,7 @@ describe('optional fields fall back rather than reaching the service as undefine
'p',
ALL,
makeDeps(),
- createTestPluginRegistry([new FilesRpc(files, realtime(), {} as never, guards, {} as never)]),
+ createTestPluginRegistry([new FilesRpc(files, realtime(), {} as never, guards, {} as never, documentsOn)]),
);
await host.dispatch(
req('files.update', { tripId: 1, fileId: 2, input: { reservation_id: null, place_id: 7 } }),