diff --git a/src/app/api/v1/berths/[id]/waiting-list/route.ts b/src/app/api/v1/berths/[id]/waiting-list/route.ts index 755a109..a702cc5 100644 --- a/src/app/api/v1/berths/[id]/waiting-list/route.ts +++ b/src/app/api/v1/berths/[id]/waiting-list/route.ts @@ -8,7 +8,7 @@ import { reorderWaitingListSchema } from '@/lib/validators/interests'; import { getWaitingList, updateWaitingList } from '@/lib/services/berths.service'; import { errorResponse, NotFoundError } from '@/lib/errors'; import { db } from '@/lib/db'; -import { berthWaitingList } from '@/lib/db/schema/berths'; +import { berths, berthWaitingList } from '@/lib/db/schema/berths'; // GET /api/v1/berths/[id]/waiting-list export const GET = withAuth( @@ -47,11 +47,17 @@ export const PATCH = withAuth( const body = await parseBody(req, reorderWaitingListSchema); const berthId = params.id!; + // Tenant scope: refuse to reorder a foreign-port berth's waiting + // list. The route's URL id and the entry id are otherwise enough + // for any user with manage_waiting_list to mutate any tenant's + // queue ordering. + const berthRow = await db.query.berths.findFirst({ + where: and(eq(berths.id, berthId), eq(berths.portId, ctx.portId)), + }); + if (!berthRow) throw new NotFoundError('Berth'); + const entry = await db.query.berthWaitingList.findFirst({ - where: and( - eq(berthWaitingList.id, body.entryId), - eq(berthWaitingList.berthId, berthId), - ), + where: and(eq(berthWaitingList.id, body.entryId), eq(berthWaitingList.berthId, berthId)), }); if (!entry) throw new NotFoundError('Waiting list entry'); diff --git a/src/app/api/v1/custom-fields/[entityId]/route.ts b/src/app/api/v1/custom-fields/[entityId]/route.ts index d137447..212dcfa 100644 --- a/src/app/api/v1/custom-fields/[entityId]/route.ts +++ b/src/app/api/v1/custom-fields/[entityId]/route.ts @@ -1,45 +1,55 @@ import { NextRequest, NextResponse } from 'next/server'; -import { withAuth } from '@/lib/api/helpers'; +import { withAuth, withPermission } from '@/lib/api/helpers'; import { errorResponse, NotFoundError } from '@/lib/errors'; import { setValuesSchema } from '@/lib/validators/custom-fields'; import { getValues, setValues } from '@/lib/services/custom-fields.service'; -export const GET = withAuth(async (_req: NextRequest, ctx, params) => { - try { - const { entityId } = params; - if (!entityId) throw new NotFoundError('Entity'); +// Custom-field values live on top of a port-scoped entity (client, yacht, +// interest, berth, company). Reading the values is in scope for any role +// that can view clients (the most common surface); writing requires the +// equivalent edit permission. The service-layer also re-validates the +// entityId against the field definition's entityType + portId so a +// caller cannot poke values onto an arbitrary or foreign-port entity. +export const GET = withAuth( + withPermission('clients', 'view', async (_req: NextRequest, ctx, params) => { + try { + const { entityId } = params; + if (!entityId) throw new NotFoundError('Entity'); - const data = await getValues(entityId, ctx.portId); - return NextResponse.json({ data }); - } catch (error) { - return errorResponse(error); - } -}); + const data = await getValues(entityId, ctx.portId); + return NextResponse.json({ data }); + } catch (error) { + return errorResponse(error); + } + }), +); -export const PUT = withAuth(async (req: NextRequest, ctx, params) => { - try { - const { entityId } = params; - if (!entityId) throw new NotFoundError('Entity'); +export const PUT = withAuth( + withPermission('clients', 'edit', async (req: NextRequest, ctx, params) => { + try { + const { entityId } = params; + if (!entityId) throw new NotFoundError('Entity'); - const body = await req.json(); - const { values } = setValuesSchema.parse(body); + const body = await req.json(); + const { values } = setValuesSchema.parse(body); - const result = await setValues( - entityId, - ctx.portId, - ctx.userId, - values as Array<{ fieldId: string; value: unknown }>, - { - userId: ctx.userId, - portId: ctx.portId, - ipAddress: ctx.ipAddress, - userAgent: ctx.userAgent, - }, - ); + const result = await setValues( + entityId, + ctx.portId, + ctx.userId, + values as Array<{ fieldId: string; value: unknown }>, + { + userId: ctx.userId, + portId: ctx.portId, + ipAddress: ctx.ipAddress, + userAgent: ctx.userAgent, + }, + ); - return NextResponse.json({ data: result }); - } catch (error) { - return errorResponse(error); - } -}); + return NextResponse.json({ data: result }); + } catch (error) { + return errorResponse(error); + } + }), +); diff --git a/src/lib/services/berths.service.ts b/src/lib/services/berths.service.ts index 9015d50..92fe229 100644 --- a/src/lib/services/berths.service.ts +++ b/src/lib/services/berths.service.ts @@ -2,10 +2,11 @@ import { and, eq, gte, lte, inArray } from 'drizzle-orm'; import { db } from '@/lib/db'; import { berths, berthTags, berthWaitingList, berthMaintenanceLog } from '@/lib/db/schema/berths'; +import { clients } from '@/lib/db/schema/clients'; import { tags } from '@/lib/db/schema/system'; import { createAuditLog, type AuditMeta } from '@/lib/audit'; import { diffEntity } from '@/lib/entity-diff'; -import { NotFoundError } from '@/lib/errors'; +import { NotFoundError, ValidationError } from '@/lib/errors'; import { buildListQuery } from '@/lib/db/query-builder'; import { emitToRoom } from '@/lib/socket/server'; import { setEntityTags } from '@/lib/services/entity-tags.helper'; @@ -401,6 +402,21 @@ export async function updateWaitingList( }); if (!existing) throw new NotFoundError('Berth'); + // Validate every supplied clientId belongs to portId. Without this + // check, a port-A admin could insert port-B clientIds into the + // waiting list — corrupting reportable data and creating a join + // surface that hydrates foreign-tenant client rows. + if (data.entries.length > 0) { + const clientIds = [...new Set(data.entries.map((e) => e.clientId))]; + const validClients = await db + .select({ id: clients.id }) + .from(clients) + .where(and(inArray(clients.id, clientIds), eq(clients.portId, portId))); + if (validClients.length !== clientIds.length) { + throw new ValidationError('One or more clients are not in this port'); + } + } + // Replace entire waiting list await db.delete(berthWaitingList).where(eq(berthWaitingList.berthId, id)); diff --git a/src/lib/services/custom-fields.service.ts b/src/lib/services/custom-fields.service.ts index 605c31d..0e661de 100644 --- a/src/lib/services/custom-fields.service.ts +++ b/src/lib/services/custom-fields.service.ts @@ -266,6 +266,57 @@ export async function setValues( throw new ValidationError('Custom field validation failed', errors); } + // Tenant scope: verify entityId actually points at a port-scoped row of + // the entity type the field definitions target. Without this gate, any + // authenticated user could write custom-field rows pointing at arbitrary + // entityIds (or none at all) — polluting customFieldValues and creating + // a join surface that could later leak data. + const entityTypes = new Set( + values + .map((v) => definitionMap.get(v.fieldId)?.entityType) + .filter((t): t is string => Boolean(t)), + ); + for (const entityType of entityTypes) { + const { eq: drizzleEq, and: drizzleAnd } = await import('drizzle-orm'); + let exists = false; + if (entityType === 'client') { + const { clients } = await import('@/lib/db/schema/clients'); + const row = await db.query.clients.findFirst({ + where: drizzleAnd(drizzleEq(clients.id, entityId), drizzleEq(clients.portId, portId)), + }); + exists = Boolean(row); + } else if (entityType === 'interest') { + const { interests } = await import('@/lib/db/schema/interests'); + const row = await db.query.interests.findFirst({ + where: drizzleAnd(drizzleEq(interests.id, entityId), drizzleEq(interests.portId, portId)), + }); + exists = Boolean(row); + } else if (entityType === 'berth') { + const { berths } = await import('@/lib/db/schema/berths'); + const row = await db.query.berths.findFirst({ + where: drizzleAnd(drizzleEq(berths.id, entityId), drizzleEq(berths.portId, portId)), + }); + exists = Boolean(row); + } else if (entityType === 'yacht') { + const { yachts } = await import('@/lib/db/schema/yachts'); + const row = await db.query.yachts.findFirst({ + where: drizzleAnd(drizzleEq(yachts.id, entityId), drizzleEq(yachts.portId, portId)), + }); + exists = Boolean(row); + } else if (entityType === 'company') { + const { companies } = await import('@/lib/db/schema/companies'); + const row = await db.query.companies.findFirst({ + where: drizzleAnd(drizzleEq(companies.id, entityId), drizzleEq(companies.portId, portId)), + }); + exists = Boolean(row); + } else { + throw new ValidationError(`Unsupported custom-field entity type: ${entityType}`); + } + if (!exists) { + throw new ValidationError(`${entityType} not found in this port`); + } + } + // Upsert all values const results = await Promise.all( values.map(async ({ fieldId, value }) => { diff --git a/src/lib/services/entity-tags.helper.ts b/src/lib/services/entity-tags.helper.ts index acf5279..c79b3f6 100644 --- a/src/lib/services/entity-tags.helper.ts +++ b/src/lib/services/entity-tags.helper.ts @@ -13,11 +13,14 @@ * the audit-log payload to `newValue: { tagIds }` across all entity types. */ -import { eq, type Column } from 'drizzle-orm'; +import { and, eq, inArray, type Column } from 'drizzle-orm'; import type { PgTable } from 'drizzle-orm/pg-core'; +import { db } from '@/lib/db'; +import { tags } from '@/lib/db/schema/system'; import { withTransaction } from '@/lib/db/utils'; import { createAuditLog, type AuditMeta } from '@/lib/audit'; +import { ValidationError } from '@/lib/errors'; import { emitToRoom } from '@/lib/socket/server'; interface SetEntityTagsArgs { @@ -51,6 +54,23 @@ export async function setEntityTags( ): Promise<{ entityId: string; tagIds: string[] }> { const { joinTable, entityColumn, tagColumn, entityId, portId, tagIds, meta, entityType } = args; + // Tenant scope: every supplied tagId must belong to the caller's port. + // The tags table is per-port (`tags.port_id`) but the join tables only + // have a single-column FK to `tags.id` — without this guard, a port-A + // caller could splice a port-B tag UUID onto their own entity. The + // entity's GET handler joins `tags ON join.tag_id = tags.id` with no + // port filter, so the foreign tag's name and color render in port A. + if (tagIds.length > 0) { + const uniqueTagIds = [...new Set(tagIds)]; + const validTags = await db + .select({ id: tags.id }) + .from(tags) + .where(and(inArray(tags.id, uniqueTagIds), eq(tags.portId, portId))); + if (validTags.length !== uniqueTagIds.length) { + throw new ValidationError('One or more tags are not in this port'); + } + } + await withTransaction(async (tx) => { await tx.delete(joinTable).where(eq(entityColumn, entityId)); if (tagIds.length > 0) { diff --git a/src/lib/services/recommendations.ts b/src/lib/services/recommendations.ts index f6bb94e..70f3c64 100644 --- a/src/lib/services/recommendations.ts +++ b/src/lib/services/recommendations.ts @@ -147,7 +147,16 @@ export async function generateRecommendations(interestId: string, portId: string // ─── List Recommendations ───────────────────────────────────────────────────── -export async function listRecommendations(interestId: string, _portId: string) { +export async function listRecommendations(interestId: string, portId: string) { + // Verify the interest belongs to the caller's port. Without this gate, + // any user with `interests:view` could pass a foreign-port interestId + // and receive that tenant's recommended berths (mooring numbers, + // dimensions, status — operational data they should not see). + const interest = await db.query.interests.findFirst({ + where: and(eq(interests.id, interestId), eq(interests.portId, portId)), + }); + if (!interest) throw new NotFoundError('Interest'); + const rows = await db .select({ id: berthRecommendations.id, @@ -167,7 +176,7 @@ export async function listRecommendations(interestId: string, _portId: string) { }) .from(berthRecommendations) .innerJoin(berths, eq(berthRecommendations.berthId, berths.id)) - .where(eq(berthRecommendations.interestId, interestId)) + .where(and(eq(berthRecommendations.interestId, interestId), eq(berths.portId, portId))) .orderBy(berthRecommendations.matchScore); return rows.reverse(); // highest score first diff --git a/src/lib/services/reminders.service.ts b/src/lib/services/reminders.service.ts index e40cecf..8a13241 100644 --- a/src/lib/services/reminders.service.ts +++ b/src/lib/services/reminders.service.ts @@ -2,6 +2,7 @@ import { and, eq, lte, gte, desc, asc, inArray, sql, isNull } from 'drizzle-orm' import { db } from '@/lib/db'; import { reminders, interests, clients } from '@/lib/db/schema'; +import { berths } from '@/lib/db/schema/berths'; import { createAuditLog, type AuditMeta } from '@/lib/audit'; import { NotFoundError, ValidationError } from '@/lib/errors'; import { emitToRoom } from '@/lib/socket/server'; @@ -107,6 +108,50 @@ export async function getUpcomingReminders(portId: string, days: number = 14) { .orderBy(asc(reminders.dueAt)); } +/** + * Validate that the supplied subject FKs (clientId / interestId / berthId) + * all point at rows inside the caller's port. Without this guard, a + * reminder created with a foreign-port FK would later be hydrated with + * `with: { client, interest, berth }` joins (no port filter on the + * relation) — leaking the foreign-tenant rows back to the attacker. + */ +async function assertReminderFksInPort( + portId: string, + fks: { clientId?: string | null; interestId?: string | null; berthId?: string | null }, +): Promise { + const checks: Array> = []; + if (fks.clientId) { + checks.push( + db.query.clients + .findFirst({ where: and(eq(clients.id, fks.clientId), eq(clients.portId, portId)) }) + .then((row) => { + if (!row) throw new ValidationError('clientId not found in this port'); + }), + ); + } + if (fks.interestId) { + checks.push( + db.query.interests + .findFirst({ + where: and(eq(interests.id, fks.interestId), eq(interests.portId, portId)), + }) + .then((row) => { + if (!row) throw new ValidationError('interestId not found in this port'); + }), + ); + } + if (fks.berthId) { + checks.push( + db.query.berths + .findFirst({ where: and(eq(berths.id, fks.berthId), eq(berths.portId, portId)) }) + .then((row) => { + if (!row) throw new ValidationError('berthId not found in this port'); + }), + ); + } + await Promise.all(checks); +} + // ─── CRUD ──────────────────────────────────────────────────────────────────── export async function getReminder(id: string, portId: string) { @@ -119,6 +164,12 @@ export async function getReminder(id: string, portId: string) { } export async function createReminder(portId: string, data: CreateReminderInput, meta: AuditMeta) { + await assertReminderFksInPort(portId, { + clientId: data.clientId, + interestId: data.interestId, + berthId: data.berthId, + }); + const [reminder] = await db .insert(reminders) .values({ @@ -186,6 +237,13 @@ export async function updateReminder( if (data.interestId !== undefined) updates.interestId = data.interestId; if (data.berthId !== undefined) updates.berthId = data.berthId; + // Re-validate any subject-FK changes against the caller's port. + await assertReminderFksInPort(portId, { + clientId: data.clientId, + interestId: data.interestId, + berthId: data.berthId, + }); + const [updated] = await db .update(reminders) .set(updates) diff --git a/tests/unit/custom-field-validation.test.ts b/tests/unit/custom-field-validation.test.ts index 0e81097..fd583db 100644 --- a/tests/unit/custom-field-validation.test.ts +++ b/tests/unit/custom-field-validation.test.ts @@ -12,6 +12,13 @@ vi.mock('@/lib/db', () => ({ db: { query: { customFieldDefinitions: { findMany: vi.fn(), findFirst: vi.fn() }, + // Entity-port-scope checks added by the security fix; default to a + // truthy row so existing assertions still focus on validation logic. + clients: { findFirst: vi.fn().mockResolvedValue({ id: 'entity-1', portId: 'port-1' }) }, + interests: { findFirst: vi.fn().mockResolvedValue({ id: 'entity-1', portId: 'port-1' }) }, + berths: { findFirst: vi.fn().mockResolvedValue({ id: 'entity-1', portId: 'port-1' }) }, + yachts: { findFirst: vi.fn().mockResolvedValue({ id: 'entity-1', portId: 'port-1' }) }, + companies: { findFirst: vi.fn().mockResolvedValue({ id: 'entity-1', portId: 'port-1' }) }, }, insert: vi.fn(), update: vi.fn(), @@ -20,6 +27,12 @@ vi.mock('@/lib/db', () => ({ }, })); +vi.mock('@/lib/db/schema/clients', () => ({ clients: {} })); +vi.mock('@/lib/db/schema/interests', () => ({ interests: {} })); +vi.mock('@/lib/db/schema/berths', () => ({ berths: {} })); +vi.mock('@/lib/db/schema/yachts', () => ({ yachts: {} })); +vi.mock('@/lib/db/schema/companies', () => ({ companies: {} })); + vi.mock('@/lib/audit', () => ({ createAuditLog: vi.fn().mockResolvedValue(undefined), })); @@ -84,7 +97,11 @@ beforeEach(() => { }); /** Convenience: call setValues with a single field/value pair. */ -async function validate(fieldType: string, value: unknown, extras?: { isRequired?: boolean; selectOptions?: string[] }) { +async function validate( + fieldType: string, + value: unknown, + extras?: { isRequired?: boolean; selectOptions?: string[] }, +) { (db.query.customFieldDefinitions.findMany as ReturnType).mockResolvedValue([ makeDefinition(fieldType, extras), ]); @@ -182,7 +199,9 @@ describe('custom field validation — select', () => { }); it('rejects an option not in the list', async () => { - await expect(validate('select', 'XL', { selectOptions: options })).rejects.toBeInstanceOf(ValidationError); + await expect(validate('select', 'XL', { selectOptions: options })).rejects.toBeInstanceOf( + ValidationError, + ); }); it('error message lists the valid options', async () => { @@ -203,11 +222,15 @@ describe('custom field validation — select', () => { describe('custom field validation — required vs optional null', () => { it('required field: null value → throws ValidationError', async () => { - await expect(validate('text', null, { isRequired: true })).rejects.toBeInstanceOf(ValidationError); + await expect(validate('text', null, { isRequired: true })).rejects.toBeInstanceOf( + ValidationError, + ); }); it('required field: undefined value → throws ValidationError', async () => { - await expect(validate('text', undefined, { isRequired: true })).rejects.toBeInstanceOf(ValidationError); + await expect(validate('text', undefined, { isRequired: true })).rejects.toBeInstanceOf( + ValidationError, + ); }); it('non-required field: null value → succeeds (no error)', async () => {