Files
TREK/server/tests/unit/nest/addon-guard.test.ts
T
Maurice 3f38621024 feat(server): let a trip owner switch trip addons for one trip
A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
2026-11-21 13:23:09 +01:00

174 lines
7.6 KiB
TypeScript

/**
* The addon route gate.
*
* Three hand-written guards (collections, airtrail, journey) did the same thing
* and differed only in the addon id they read and the word leading the 404. They
* are one guard plus a @RequireAddon decorator now.
*
* The last describe matters as much as the first: with the addon id in a
* decorator, nothing in a controller's own tests notices if the decorator is
* dropped or points at the wrong addon. These assertions are what keeps the
* three route groups gated, and gated on the right thing.
*/
import { ADDON_IDS } from '../../../src/addons';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { RequireAddon, REQUIRE_ADDON, type RequireAddonMeta } from '../../../src/nest/addons/require-addon.decorator';
import { CollectionsController } from '../../../src/nest/collections/collections.controller';
import { AirtrailController } from '../../../src/nest/integrations/airtrail.controller';
import { JourneyController } from '../../../src/nest/journey/journey.controller';
import { ReservationImportController } from '../../../src/nest/reservation-import/reservation-import.controller';
import { HttpException } from '@nestjs/common';
import type { ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { describe, it, expect, vi } from 'vitest';
/** A context whose handler/class carry the decorator under test, for a request with or without a user. */
function ctxFor(handler: object, cls: object = class {}, user?: { id: number }): ExecutionContext {
return {
getHandler: () => handler,
getClass: () => cls,
switchToHttp: () => ({ getRequest: () => ({ user }) }),
} as unknown as ExecutionContext;
}
function addons(enabled: boolean, anywhere = false): AddonsService {
return {
isAddonEnabled: vi.fn(() => enabled),
isEnabledForUserAnywhere: vi.fn(() => enabled || anywhere),
} as unknown as AddonsService;
}
async function thrown(fn: () => unknown) {
try {
await fn();
return undefined;
} catch (err) {
return err instanceof HttpException ? { status: err.getStatus(), body: err.getResponse() } : err;
}
}
/** Apply @RequireAddon to a throwaway class the way a controller would. */
function decorated(addonId: string | readonly string[], label: string) {
class Gated {}
RequireAddon(addonId, label)(Gated);
return Gated;
}
describe('AddonGuard', () => {
it('ADDON-GUARD-001: 404s with the decorator label when the addon is disabled', async () => {
const cls = decorated(ADDON_IDS.JOURNEY, 'Journey');
const guard = new AddonGuard(addons(false), new Reflector());
expect(await thrown(() => guard.canActivate(ctxFor(() => {}, cls)))).toEqual({
status: 404,
body: { error: 'Journey addon is not enabled' },
});
});
it('ADDON-GUARD-002: passes when the addon is enabled, asking for the declared id', async () => {
const cls = decorated(ADDON_IDS.COLLECTIONS, 'Collections');
const svc = addons(true);
const guard = new AddonGuard(svc, new Reflector());
expect(await guard.canActivate(ctxFor(() => {}, cls))).toBe(true);
expect(svc.isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.COLLECTIONS);
});
it('ADDON-GUARD-007: a list of addons opens the route while any one of them is on', async () => {
const cls = decorated([ADDON_IDS.AI_ASSISTANT, ADDON_IDS.LLM_PARSING], 'AI assistant');
const isAddonEnabled = vi.fn(async (id: string) => id === ADDON_IDS.LLM_PARSING);
const guard = new AddonGuard({ isAddonEnabled } as unknown as AddonsService, new Reflector());
expect(await guard.canActivate(ctxFor(() => {}, cls))).toBe(true);
isAddonEnabled.mockResolvedValue(false);
expect(await thrown(() => guard.canActivate(ctxFor(() => {}, cls)))).toEqual({
status: 404,
body: { error: 'AI assistant addon is not enabled' },
});
});
it('ADDON-GUARD-003: is a no-op on a route that never asked for an addon', async () => {
const svc = addons(false);
const guard = new AddonGuard(svc, new Reflector());
expect(await guard.canActivate(ctxFor(() => {}, class {}))).toBe(true);
expect(svc.isAddonEnabled).not.toHaveBeenCalled();
});
it('ADDON-GUARD-004: a handler-level decorator overrides the controller-level one', async () => {
const cls = decorated(ADDON_IDS.JOURNEY, 'Journey');
const handler = () => {};
RequireAddon(ADDON_IDS.AIRTRAIL, 'AirTrail')(handler);
const svc = addons(false);
expect(await thrown(() => new AddonGuard(svc, new Reflector()).canActivate(ctxFor(handler, cls)))).toEqual({
status: 404,
body: { error: 'AirTrail addon is not enabled' },
});
expect(svc.isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.AIRTRAIL);
});
});
describe('AddonGuard once the user is known', () => {
it('ADDON-GUARD-008: opens for a user one of whose trips switched the addon on, although the instance has it off', async () => {
const cls = decorated(ADDON_IDS.TOURS, 'Tours');
const svc = addons(false, true);
const guard = new AddonGuard(svc, new Reflector());
expect(await guard.canActivate(ctxFor(() => {}, cls, { id: 7 }))).toBe(true);
expect(svc.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);
expect(svc.isAddonEnabled).not.toHaveBeenCalled();
});
it('ADDON-GUARD-009: stays shut for a user none of whose trips switched it on', async () => {
const cls = decorated(ADDON_IDS.ROADTRIP, 'Road trip');
const guard = new AddonGuard(addons(false, false), new Reflector());
expect(await thrown(() => guard.canActivate(ctxFor(() => {}, cls, { id: 7 })))).toEqual({
status: 404,
body: { error: 'Road trip addon is not enabled' },
});
});
it('ADDON-GUARD-010: without a user it reads the instance switch alone', async () => {
const cls = decorated(ADDON_IDS.TOURS, 'Tours');
const svc = addons(false, true);
expect(await thrown(() => new AddonGuard(svc, new Reflector()).canActivate(ctxFor(() => {}, cls)))).toEqual({
status: 404,
body: { error: 'Tours addon is not enabled' },
});
expect(svc.isEnabledForUserAnywhere).not.toHaveBeenCalled();
});
});
describe('the gated route groups still declare their addon', () => {
const metaOf = (cls: object): RequireAddonMeta | undefined => Reflect.getMetadata(REQUIRE_ADDON, cls);
const guardsOf = (cls: object): unknown[] => Reflect.getMetadata('__guards__', cls) ?? [];
it.each([
['JourneyController', JourneyController, ADDON_IDS.JOURNEY, 'Journey'],
['CollectionsController', CollectionsController, ADDON_IDS.COLLECTIONS, 'Collections'],
['AirtrailController', AirtrailController, ADDON_IDS.AIRTRAIL, 'AirTrail'],
])('ADDON-GUARD-005: %s gates on the right addon, with AddonGuard first', (_name, cls, addonId, label) => {
expect(metaOf(cls)).toEqual({ addonId, label });
// Order is the contract: a disabled addon has to answer 404 to anonymous
// callers, so the addon check must run before the 401.
expect(guardsOf(cls)[0]).toBe(AddonGuard);
});
it('ADDON-GUARD-006: the merged import controller gates AirTrail per handler, not per class', () => {
// A class-level requirement here would 404 the four file-upload routes
// whenever the AirTrail addon happens to be off. AddonGuard still runs first
// in the chain, so the 404 keeps beating the 401.
expect(metaOf(ReservationImportController)).toBeUndefined();
expect(Reflect.getMetadata(REQUIRE_ADDON, ReservationImportController.prototype.importAirtrail)).toEqual({
addonId: ADDON_IDS.AIRTRAIL,
label: 'AirTrail',
});
expect(guardsOf(ReservationImportController)[0]).toBe(AddonGuard);
});
});