Files
CapaKraken/packages/api/src/router/allocation/demand.ts
T
Hartmut c0c5f762b8 security: bound JSONB inputs + whitelist batchUpdateCustomFields keys (#48)
batchUpdateCustomFields used $executeRaw to merge a manager-supplied
record straight into Resource.dynamicFields with no key whitelist —
so a manager could pollute the JSONB namespace with arbitrary keys
(e.g. ones admin tools later interpret). Separately, several user-facing
JSONB fields (allocation/demand metadata, dynamicFields) were typed as
unbounded z.record(z.string(), z.unknown()), letting clients ship
multi-MB payloads that flow into DB writes, audit logs, and SSE frames.

- Add BoundedJsonRecord helper (shared) — 64 keys / depth 4 /
  8 KB strings / 32 KB serialized total. Conservative defaults; call
  sites needing more should use a strict object schema.
- Apply BoundedJsonRecord to the highest-traffic untrusted JSONB inputs:
  allocation metadata (Create/CreateDemandRequirement/CreateAssignment),
  resource & project dynamicFields, and the createDemand router input.
- batchUpdateCustomFields:
    * Tighten input schema (key length, value bounds, max 100 keys).
    * Fetch each target resource and verify all input keys are in the
      union of (specific blueprint defs) ∪ (active global RESOURCE
      blueprint defs) for that resource. Empty whitelist → reject all
      keys (stricter than create/update, but appropriate for a bulk
      escape-hatch endpoint).
    * Run the existing per-key value validator afterwards.
    * 404 if any requested id does not exist (was silently skipped).
- New helper getAllowedDynamicFieldKeys() in blueprint-validation.
- 7 new BoundedJsonRecord tests, 2 new batchUpdateCustomFields tests
  covering the whitelist-rejection and not-found paths.

Covers EAPPS 3.2.7 (input bounds) / OWASP A03 (injection / mass assignment).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-17 08:44:11 +02:00

175 lines
5.5 KiB
TypeScript

import type { Prisma } from "@capakraken/db";
import {
deleteDemandRequirement,
fillOpenDemand,
updateDemandRequirement,
} from "@capakraken/application";
import {
BoundedJsonRecord,
CreateDemandRequirementSchema,
FillDemandRequirementSchema,
FillOpenDemandByAllocationSchema,
PermissionKey,
UpdateDemandRequirementSchema,
} from "@capakraken/shared";
import type {
CreateDemandRequirementInput,
FillDemandRequirementInput,
FillOpenDemandByAllocationInput,
} from "@capakraken/shared";
import { z } from "zod";
import { findUniqueOrThrow } from "../../db/helpers.js";
import {
emitAllocationCreated,
emitAllocationDeleted,
emitAllocationUpdated,
} from "../../sse/event-bus.js";
import {
checkBudgetThresholdsInBackground,
createDemandRequirementWithEffects,
dispatchAllocationWebhookInBackground,
fillDemandRequirementWithEffects,
invalidateDashboardCacheInBackground,
} from "./effects.js";
import { DEMAND_INCLUDE } from "./shared.js";
import { buildCreateDemandRequirementInput, getDemandRequirementByIdOrThrow } from "./support.js";
import { managerProcedure, requirePermission } from "../../trpc.js";
export const allocationDemandProcedures = {
createDemandRequirement: managerProcedure
.input(CreateDemandRequirementSchema as z.ZodType<CreateDemandRequirementInput>)
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
return createDemandRequirementWithEffects(ctx.db, input);
}),
createDemand: managerProcedure
.input(
z.object({
projectId: z.string(),
role: z.string().optional(),
roleId: z.string().optional(),
headcount: z.number().int().positive().default(1),
hoursPerDay: z.number().min(0.5).max(24),
startDate: z.coerce.date(),
endDate: z.coerce.date(),
budgetCents: z.number().int().min(0).optional(),
metadata: BoundedJsonRecord.optional(),
}),
)
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
return createDemandRequirementWithEffects(ctx.db, buildCreateDemandRequirementInput(input));
}),
updateDemandRequirement: managerProcedure
.input(z.object({ id: z.string(), data: UpdateDemandRequirementSchema }))
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
const updated = await ctx.db.$transaction(async (tx) => {
return updateDemandRequirement(
tx as unknown as Parameters<typeof updateDemandRequirement>[0],
input.id,
input.data,
);
});
emitAllocationUpdated({
id: updated.id,
projectId: updated.projectId,
resourceId: null,
});
invalidateDashboardCacheInBackground();
checkBudgetThresholdsInBackground(ctx.db, updated.projectId);
return updated;
}),
deleteDemandRequirement: managerProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
const existing = await findUniqueOrThrow(
ctx.db.demandRequirement.findUnique({
where: { id: input.id },
include: DEMAND_INCLUDE,
}),
"Demand requirement",
);
await ctx.db.$transaction(async (tx) => {
await deleteDemandRequirement(
tx as unknown as Parameters<typeof deleteDemandRequirement>[0],
input.id,
);
await tx.auditLog.create({
data: {
entityType: "DemandRequirement",
entityId: input.id,
action: "DELETE",
changes: { before: existing } as unknown as Prisma.InputJsonValue,
},
});
});
emitAllocationDeleted(existing.id, existing.projectId);
dispatchAllocationWebhookInBackground(ctx.db, "allocation.deleted", {
id: existing.id,
projectId: existing.projectId,
});
invalidateDashboardCacheInBackground();
checkBudgetThresholdsInBackground(ctx.db, existing.projectId);
return { success: true };
}),
fillDemandRequirement: managerProcedure
.input(FillDemandRequirementSchema as z.ZodType<FillDemandRequirementInput>)
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
return fillDemandRequirementWithEffects(ctx.db, input);
}),
assignResourceToDemand: managerProcedure
.input(
z.object({
demandRequirementId: z.string(),
resourceId: z.string(),
}),
)
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
const result = await fillDemandRequirementWithEffects(ctx.db, input);
const demandRequirement = await getDemandRequirementByIdOrThrow(
ctx.db,
input.demandRequirementId,
);
return {
...result,
demandRequirement,
};
}),
fillOpenDemandByAllocation: managerProcedure
.input(FillOpenDemandByAllocationSchema as z.ZodType<FillOpenDemandByAllocationInput>)
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
const result = await fillOpenDemand(ctx.db, input);
emitAllocationCreated(result.createdAllocation);
if (result.updatedAllocation) {
emitAllocationUpdated(result.updatedAllocation);
}
invalidateDashboardCacheInBackground();
checkBudgetThresholdsInBackground(ctx.db, result.createdAllocation.projectId as string);
return result;
}),
};