Files
TREK/server/tests/unit/nest/public-api.controller.test.ts
T
Maurice fd6381c814 feat(api): add a versioned read-only public API for integrations
TREK's REST surface is internal: it answers a session cookie, carries no
version, and changes with the client. That is fine for our own frontend and
useless for anyone building against us — the Dawarich integration people have
been asking for since April needs something it can rely on not moving.

So this adds a small one rather than opening the existing 549 endpoints:

  GET /api/v1/trips           the trips the caller can reach
  GET /api/v1/trips/:id       one trip, ?include= picks the sections

Auth reuses the trek_ tokens users already manage under Settings, via Bearer
or X-API-Key. No new credential type, no new table — the guard calls the same
hash lookup the MCP transport does. It deliberately refuses a session JWT and,
for now, OAuth bearers: a credential whose scopes this surface does not yet
interpret is worse than one it rejects outright.

Access is decided per trip against canAccessTrip, the same owner-or-member
predicate as everywhere else, and a trip the caller may not read answers 404
identically to one that does not exist — a 403 would confirm the id is real and
turn the endpoint into a way to count someone else's trips.

The payload is not the rows. Ids, foreign keys and order_index stay inside;
accommodation day ids resolve to ISO dates, places arrive in planned order, and
every dated thing carries its date so a consumer can join on days rather than
on ids it has no way to look up.
2026-08-28 15:23:05 +02:00

129 lines
4.8 KiB
TypeScript

/**
* PublicApiController — request shaping for /api/v1.
*
* The controller owns three decisions and the tests below pin all three: how a
* trip id is parsed, how `include` is validated, and what a caller is told about a
* trip they may not read (nothing that distinguishes it from one that does not
* exist).
*/
import { describe, it, expect, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import type { Request } from 'express';
import { PUBLIC_API_INCLUDES } from '@trek/shared';
import { PublicApiController } from '../../../src/nest/public-api/public-api.controller';
import type { PublicApiService } from '../../../src/nest/public-api/public-api.service';
const TRIP = {
id: 12,
title: 'Toskana',
description: null,
start_date: '2026-06-14',
end_date: '2026-06-22',
currency: 'EUR',
archived: false,
};
function makeController(svc: Partial<PublicApiService>) {
return new PublicApiController(svc as PublicApiService);
}
const req = (userId = 7) => ({ user: { id: userId } }) as Request;
/** A request the guard never touched — the shape the controller must refuse. */
const reqWithoutUser = () => ({}) as Request;
function thrown(fn: () => unknown): { status: number; body: unknown } {
try {
fn();
} catch (err) {
expect(err).toBeInstanceOf(HttpException);
const e = err as HttpException;
return { status: e.getStatus(), body: e.getResponse() };
}
throw new Error('expected the handler to throw');
}
describe('PublicApiController', () => {
describe('GET /api/v1/trips', () => {
it('returns the accessible trips for the token owner', () => {
const listTrips = vi.fn().mockReturnValue([TRIP]);
expect(makeController({ listTrips }).listTrips(req(7))).toEqual({ trips: [TRIP] });
expect(listTrips).toHaveBeenCalledWith(7);
});
it('returns an empty list rather than 404 when the user has no trips', () => {
const listTrips = vi.fn().mockReturnValue([]);
expect(makeController({ listTrips }).listTrips(req(7))).toEqual({ trips: [] });
});
it('401s if the guard was somehow bypassed and no user is attached', () => {
const listTrips = vi.fn();
expect(thrown(() => makeController({ listTrips }).listTrips(reqWithoutUser()))).toEqual({
status: 401,
body: { error: 'API token required', code: 'API_TOKEN_REQUIRED' },
});
expect(listTrips).not.toHaveBeenCalled();
});
});
describe('GET /api/v1/trips/:id', () => {
it('passes the parsed id and user through, and defaults include to every section', () => {
const getTrip = vi.fn().mockReturnValue(TRIP);
const res = makeController({ getTrip }).getTrip(req(7), '12', undefined);
expect(res).toEqual(TRIP);
expect(getTrip).toHaveBeenCalledWith(12, 7, [...PUBLIC_API_INCLUDES]);
});
it('treats an empty include the same as an absent one', () => {
const getTrip = vi.fn().mockReturnValue(TRIP);
makeController({ getTrip }).getTrip(req(7), '12', ' ');
expect(getTrip).toHaveBeenCalledWith(12, 7, [...PUBLIC_API_INCLUDES]);
});
it('narrows to the requested sections and tolerates spacing', () => {
const getTrip = vi.fn().mockReturnValue(TRIP);
makeController({ getTrip }).getTrip(req(7), '12', 'days, notes');
expect(getTrip).toHaveBeenCalledWith(12, 7, ['days', 'notes']);
});
/**
* The one that matters: a trip belonging to someone else answers exactly like a
* trip that was never created. Anything else turns the endpoint into a way to
* count another user's trips.
*/
it('404s for a trip the caller may not read, with no hint that it exists', () => {
const getTrip = vi.fn().mockReturnValue(null);
expect(thrown(() => makeController({ getTrip }).getTrip(req(7), '999', undefined))).toEqual({
status: 404,
body: { error: 'Trip not found' },
});
});
it.each([
['a non-numeric id', 'abc'],
['a numeric prefix', '12abc'],
['a negative id', '-1'],
['zero', '0'],
['a float', '1.5'],
['an empty id', ''],
['whitespace', ' 12 '],
['a sql fragment', "1 OR 1=1"],
['an id past the safe integer range', '9007199254740993'],
])('400s on %s without touching the service', (_label, raw) => {
const getTrip = vi.fn();
expect(thrown(() => makeController({ getTrip }).getTrip(req(7), raw, undefined)).status).toBe(400);
expect(getTrip).not.toHaveBeenCalled();
});
it.each([
['an unknown section', 'days,everything'],
['a typo', 'dayz'],
['only commas', ',,,'],
])('400s on %s rather than silently dropping it', (_label, include) => {
const getTrip = vi.fn();
const res = thrown(() => makeController({ getTrip }).getTrip(req(7), '12', include));
expect(res.status).toBe(400);
expect(getTrip).not.toHaveBeenCalled();
});
});
});