mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-21 06:11:45 +00:00
test: expand test suite to 87.3% backend coverage
Add new integration test files covering previously untested routes: - categories.test.ts — GET /api/categories - oidc.test.ts — full OIDC login flow (callback, state, errors) - settings.test.ts — GET/PUT /api/settings, bulk save - tags.test.ts — CRUD for trip tags - todo.test.ts — todo items CRUD and reorder Add new unit test files covering service-layer logic: - adminService.test.ts — user/invite management, packing templates, OIDC settings - atlasService.test.ts — atlas search and place enrichment - authServiceDb.test.ts — DB-backed auth helpers (login, register, MFA) - backupService.test.ts — export/import/restore logic - categoryService.test.ts — category CRUD - dayService.test.ts — day management and accommodation helpers - mapsService.test.ts — route/directions helpers - oidcService.test.ts — OIDC state, auth code, role resolution, user upsert - packingService.test.ts — packing item/bag/template operations - placeService.test.ts — place CRUD and tag attachment - settingsService.test.ts — settings get/set/bulk - tagService.test.ts — tag CRUD - todoService.test.ts — todo CRUD and reorder - tripService.test.ts — trip CRUD, member management, archiving - vacayService.test.ts — vacay integration helpers - tripAccess.test.ts (middleware) — requireTripAccess middleware Expand existing integration and unit test files with additional cases across admin, atlas, auth, backup, collab, days, files, maps, memories (Immich/Synology), notifications, places, reservations, share, vacay, weather, auth middleware, ephemeral tokens, notification preferences, permissions, SSRF guard, and WebSocket connection tests. Update test helpers (factories.ts, test-db.ts) with new factory functions and seed data required by the expanded suite. Fix minor issues in server/src/routes/reservations.ts and server/src/services/atlasService.ts surfaced by new test coverage. Update sonar-project.properties to reflect new coverage thresholds.
This commit is contained in:
@@ -1,11 +1,13 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ get: vi.fn(), all: vi.fn() }) },
|
||||
db: { prepare: vi.fn(() => ({ get: vi.fn(), all: vi.fn() })) },
|
||||
}));
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
|
||||
|
||||
import { extractToken, authenticate, adminOnly } from '../../../src/middleware/auth';
|
||||
import { db } from '../../../src/db/database';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
function makeReq(overrides: {
|
||||
@@ -82,6 +84,56 @@ describe('authenticate', () => {
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-003: calls next() and sets req.user for a valid JWT', () => {
|
||||
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user' };
|
||||
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
|
||||
|
||||
const token = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
|
||||
const req = makeReq({ cookies: { trek_session: token } });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
|
||||
authenticate(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect((req as any).user).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it('AUTH-MW-004: returns 401 for a valid JWT when user does not exist in DB', () => {
|
||||
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => undefined), all: vi.fn() } as any);
|
||||
|
||||
const token = jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
|
||||
authenticate(makeReq({ cookies: { trek_session: token } }), res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-005: returns 401 for an expired JWT', () => {
|
||||
const expiredToken = jwt.sign(
|
||||
{ id: 1, exp: Math.floor(Date.now() / 1000) - 3600 },
|
||||
'test-secret',
|
||||
{ algorithm: 'HS256' }
|
||||
);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
authenticate(makeReq({ cookies: { trek_session: expiredToken } }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-006: returns 401 for a JWT signed with the wrong secret', () => {
|
||||
const tamperedToken = jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
authenticate(makeReq({ cookies: { trek_session: tamperedToken } }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── adminOnly ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Unit tests for requireTripAccess and requireTripOwner middleware.
|
||||
* TRIP-ACCESS-001 through TRIP-ACCESS-010.
|
||||
* canAccessTrip and isOwner are mocked; no DB required.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
const mockCanAccessTrip = vi.fn();
|
||||
const mockIsOwner = vi.fn();
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
canAccessTrip: (...args: any[]) => mockCanAccessTrip(...args),
|
||||
isOwner: (...args: any[]) => mockIsOwner(...args),
|
||||
}));
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
|
||||
|
||||
import { requireTripAccess, requireTripOwner } from '../../../src/middleware/tripAccess';
|
||||
|
||||
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
|
||||
const json = vi.fn();
|
||||
const status = vi.fn(() => ({ json }));
|
||||
const res = { status } as unknown as Response;
|
||||
return { res, status, json };
|
||||
}
|
||||
|
||||
function makeReq(params: Record<string, string> = {}, userId = 1): Request {
|
||||
return {
|
||||
params,
|
||||
user: { id: userId },
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockCanAccessTrip.mockReset();
|
||||
mockIsOwner.mockReset();
|
||||
});
|
||||
|
||||
// ── requireTripAccess ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireTripAccess', () => {
|
||||
it('TRIP-ACCESS-001: returns 400 when no tripId param', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripAccess(makeReq({}), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(400);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-002: returns 404 when canAccessTrip returns null (not a member)', () => {
|
||||
mockCanAccessTrip.mockReturnValue(null);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripAccess(makeReq({ tripId: '42' }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(404);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-003: calls next and attaches trip when user has access', () => {
|
||||
const fakeTrip = { id: 42, user_id: 1 };
|
||||
mockCanAccessTrip.mockReturnValue(fakeTrip);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
const req = makeReq({ tripId: '42' }, 1);
|
||||
requireTripAccess(req, res, next);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect((req as any).trip).toEqual(fakeTrip);
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-004: accepts req.params.id as fallback when tripId is absent', () => {
|
||||
const fakeTrip = { id: 7, user_id: 2 };
|
||||
mockCanAccessTrip.mockReturnValue(fakeTrip);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripAccess(makeReq({ id: '7' }), res, next);
|
||||
expect(mockCanAccessTrip).toHaveBeenCalledWith(7, expect.any(Number));
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-005: passes numeric tripId to canAccessTrip', () => {
|
||||
mockCanAccessTrip.mockReturnValue({ id: 99, user_id: 3 });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripAccess(makeReq({ tripId: '99' }, 3), res, next);
|
||||
expect(mockCanAccessTrip).toHaveBeenCalledWith(99, 3);
|
||||
});
|
||||
});
|
||||
|
||||
// ── requireTripOwner ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireTripOwner', () => {
|
||||
it('TRIP-ACCESS-006: returns 400 when no tripId param', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripOwner(makeReq({}), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(400);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-007: returns 403 when user is not the owner', () => {
|
||||
mockIsOwner.mockReturnValue(false);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripOwner(makeReq({ tripId: '10' }, 2), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(403);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-008: calls next when user is the owner', () => {
|
||||
mockIsOwner.mockReturnValue(true);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripOwner(makeReq({ tripId: '10' }, 1), res, next);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-009: accepts req.params.id as fallback when tripId is absent', () => {
|
||||
mockIsOwner.mockReturnValue(true);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripOwner(makeReq({ id: '5' }, 1), res, next);
|
||||
expect(mockIsOwner).toHaveBeenCalledWith(5, 1);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-010: passes numeric tripId to isOwner', () => {
|
||||
mockIsOwner.mockReturnValue(true);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripOwner(makeReq({ tripId: '77' }, 4), res, next);
|
||||
expect(mockIsOwner).toHaveBeenCalledWith(77, 4);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user