From a16489973635223c0d01c9b69a9de44c8a88eb3f Mon Sep 17 00:00:00 2001 From: SherlockOmss <209794074+SherlockOmss@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:08:19 +0100 Subject: [PATCH] refactor(fleet): move the fleet-case join persistence out of the cron route (#61) `joinOneTenant` and `upsertGroup` move from `app/api/cron/join-fleet-cases/route.ts` to `lib/fleet-case-store.ts`, as `groupOneTenant` lives in `lib/case-grouping-store.ts`. The route keeps the lock key, the label and the runner call. No logic change; the 18 integration tests of the cron pass unchanged. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: SherlockOmss <209794074+SherlockOmss@users.noreply.github.com> --- app/api/cron/join-fleet-cases/route.ts | 126 +--------------------- docs/architecture.md | 2 +- fleet/README.md | 2 +- lib/fleet-case-store.ts | 138 +++++++++++++++++++++++++ lib/fleet-case.ts | 2 +- 5 files changed, 142 insertions(+), 128 deletions(-) create mode 100644 lib/fleet-case-store.ts diff --git a/app/api/cron/join-fleet-cases/route.ts b/app/api/cron/join-fleet-cases/route.ts index 20f8996..e00455f 100644 --- a/app/api/cron/join-fleet-cases/route.ts +++ b/app/api/cron/join-fleet-cases/route.ts @@ -1,14 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; -import { Prisma } from "@prisma/client"; import { verifyCronRequest } from "@/lib/cron-auth"; import { prisma } from "@/lib/prisma"; -import { - candidateHashes, - type FleetGroup, - joinDetections, -} from "@/lib/fleet-case"; -import { ranksAtLeast } from "@/lib/severity"; -import { loadFleetPrevalence } from "@/lib/fleet-prevalence"; +import { joinOneTenant } from "@/lib/fleet-case-store"; import { perTenantResponse, runPerTenant } from "@/lib/cron/per-tenant"; /** Fixed first key of this cron's per-tenant advisory lock (`lib/cron/per-tenant.ts`): two @@ -18,21 +11,6 @@ const JOIN_LOCK_KEY = 62_262_001; /** Names this cron in its log lines. */ const JOIN_LABEL = "Fleet case join"; -/** How far back detections are read: the join window is a day, so a week leaves room for a late - * detection to join an older sighting without the sweep reading the whole table. */ -const JOIN_LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000; - -/** Per-tenant cap on detections read in one invocation, newest first (the same reasoning as - * `GROUPING_BATCH_SIZE`: a bounded transaction, and the next tick continues). */ -const JOIN_BATCH_SIZE = 5000; - -interface TenantJoinResult { - fleetCasesCreated: number; - fleetCasesMerged: number; - detectionsJoined: number; - moreWorkLikely: boolean; -} - /** * GET /api/cron/join-fleet-cases * @@ -66,105 +44,3 @@ export async function GET(req: NextRequest) { return NextResponse.json({ error: "Internal server error" }, { status: 500 }); } } - -async function joinOneTenant(tx: Prisma.TransactionClient, tenantId: string): Promise { - const detections = await tx.detection.findMany({ - where: { tenantId, timestamp: { gte: new Date(Date.now() - JOIN_LOOKBACK_MS) } }, - select: { id: true, agentId: true, timestamp: true, severity: true, event: true, fleetCaseId: true }, - orderBy: { timestamp: "desc" }, - take: JOIN_BATCH_SIZE, - }); - const moreWorkLikely = detections.length === JOIN_BATCH_SIZE; - const prevalence = await loadFleetPrevalence(tx, tenantId, candidateHashes(detections)); - const groups = joinDetections(detections, prevalence); - - let fleetCasesCreated = 0; - let fleetCasesMerged = 0; - let detectionsJoined = 0; - for (const group of groups) { - const outcome = await upsertGroup(tx, tenantId, group); - fleetCasesCreated += outcome.created ? 1 : 0; - fleetCasesMerged += outcome.merged; - detectionsJoined += outcome.detectionsJoined; - } - return { fleetCasesCreated, fleetCasesMerged, detectionsJoined, moreWorkLikely }; -} - -async function upsertGroup(tx: Prisma.TransactionClient, tenantId: string, group: FleetGroup) { - const known = await tx.fleetCaseEntity.findMany({ - where: { tenantId, OR: group.entities.map((e) => ({ kind: e.kind, key: e.key })) }, - select: { fleetCaseId: true }, - }); - const existingIds = Array.from(new Set(known.map((k) => k.fleetCaseId))); - - let targetId: string; - let created = false; - let merged = 0; - if (existingIds.length === 0) { - const row = await tx.fleetCase.create({ - data: { - tenantId, - severity: group.severity, - agentCount: group.agentIds.length, - firstAt: group.firstAt, - lastAt: group.lastAt, - }, - }); - targetId = row.id; - created = true; - } else { - const [oldest, ...others] = await tx.fleetCase.findMany({ - where: { id: { in: existingIds } }, - orderBy: [{ createdAt: "asc" }, { id: "asc" }], - }); - targetId = oldest.id; - if (others.length > 0) { - const otherIds = others.map((o) => o.id); - await tx.detection.updateMany({ where: { fleetCaseId: { in: otherIds } }, data: { fleetCaseId: targetId } }); - await tx.fleetCaseEntity.updateMany({ where: { fleetCaseId: { in: otherIds } }, data: { fleetCaseId: targetId } }); - await tx.fleetCase.deleteMany({ where: { id: { in: otherIds } } }); - merged = others.length; - } - } - - await tx.fleetCaseEntity.createMany({ - data: group.entities.map((e) => ({ tenantId, fleetCaseId: targetId, kind: e.kind, key: e.key })), - skipDuplicates: true, - }); - // Only the detections not already on this case, so a rerun does not bump `updatedAt` (the - // staleness of a case narrative compares against it). - const linked = await tx.detection.updateMany({ - where: { - tenantId, - id: { in: group.detectionIds }, - OR: [{ fleetCaseId: null }, { fleetCaseId: { not: targetId } }], - }, - data: { fleetCaseId: targetId }, - }); - - // Recomputed from every detection of the case, not only this batch: it may be wider. - const members = await tx.detection.findMany({ - where: { tenantId, fleetCaseId: targetId }, - select: { agentId: true, timestamp: true, severity: true }, - }); - const current = await tx.fleetCase.findUniqueOrThrow({ where: { id: targetId } }); - const times = members.map((m) => m.timestamp.getTime()); - const next = { - agentCount: new Set(members.map((m) => m.agentId)).size, - firstAt: new Date(Math.min(...times)), - lastAt: new Date(Math.max(...times)), - severity: members.reduce( - (top, m) => (ranksAtLeast(m.severity, top) ? m.severity : top), - current.severity - ), - }; - if ( - next.agentCount !== current.agentCount || - next.firstAt.getTime() !== current.firstAt.getTime() || - next.lastAt.getTime() !== current.lastAt.getTime() || - next.severity !== current.severity - ) { - await tx.fleetCase.update({ where: { id: targetId }, data: next }); - } - return { created, merged, detectionsJoined: linked.count }; -} diff --git a/docs/architecture.md b/docs/architecture.md index 5ebdfc5..e35f9ca 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -103,7 +103,7 @@ that implement it; the module note has the design and status. | --- | --- | --- | --- | --- | | Ingest | Accepts events, detections, heartbeats and decoy registrations from enrolled agents | `app/api/ingest/*`, `app/api/v1/ingest/*` | [`detection-payload.ts`](../lib/detection-payload.ts), [`health-beacon.ts`](../lib/health-beacon.ts), [`ingest-stats.ts`](../lib/ingest-stats.ts), [`decoy.ts`](../lib/decoy.ts) | [ingest](../ingest/README.md) | | Cases | Groups one host's detections into cases; opens a case for a silent agent | `app/api/cases/*`, `app/api/cron/group-detections`, `app/api/cron/detect-silent-agents` | [`case-grouping.ts`](../lib/case-grouping.ts), [`case-grouping-store.ts`](../lib/case-grouping-store.ts), [`silent-agent-case.ts`](../lib/silent-agent-case.ts), [`case-detail.ts`](../lib/case-detail.ts) | [assistant](../assistant/README.md) | -| Fleet correlation | Joins cases of several hosts that share a file hash or a signed-in identity into fleet cases | `app/api/fleet-cases/*`, `app/api/cron/join-fleet-cases` | [`fleet-case.ts`](../lib/fleet-case.ts), [`fleet-case-load.ts`](../lib/fleet-case-load.ts) | [fleet](../fleet/README.md) | +| Fleet correlation | Joins cases of several hosts that share a file hash or a signed-in identity into fleet cases | `app/api/fleet-cases/*`, `app/api/cron/join-fleet-cases` | [`fleet-case.ts`](../lib/fleet-case.ts), [`fleet-case-store.ts`](../lib/fleet-case-store.ts), [`fleet-case-load.ts`](../lib/fleet-case-load.ts) | [fleet](../fleet/README.md) | | Prevalence | Per-tenant first-seen, last-seen and host counts for hashes, paths, parent-child pairs and domains; the signed common-set snapshot | `app/api/prevalence`, `app/api/snapshot/*`, `app/api/cron/prune-prevalence`, `app/api/cron/build-snapshots` | [`prevalence.ts`](../lib/prevalence.ts), [`common-set-snapshot.ts`](../lib/common-set-snapshot.ts), [`snapshot-publish.ts`](../lib/snapshot-publish.ts) | [prevalence](../prevalence/README.md) | | Entity graph | A case's subgraph and pivots from a hash, path or domain to every host that showed it, computed on read | `app/api/cases/[id]/graph`, `app/api/graph/pivot` | [`graph.ts`](../lib/graph.ts) | [graph](../graph/README.md) | | Hunting | Saved and scheduled hunts, ad-hoc search over detections, cases and the archive, drafts of Sigma rules and IOC sets | `app/api/hunts/*`, `app/api/cron/run-hunts` | [`hunt.ts`](../lib/hunt.ts), [`hunt-search.ts`](../lib/hunt-search.ts), [`hunt-runner.ts`](../lib/hunt-runner.ts), [`hunt-graduation.ts`](../lib/hunt-graduation.ts) | [hunt](../hunt/README.md) | diff --git a/fleet/README.md b/fleet/README.md index fda84c4..f573ab0 100644 --- a/fleet/README.md +++ b/fleet/README.md @@ -14,6 +14,6 @@ a computed set of related hosts (same subnet, same identity, recent lateral peer policy overlay: lower model thresholds, wider telemetry, a shorter heartbeat interval. A posture only ever heightens, never disables, and expires on its own, enforced by the server. -Code: `lib/fleet-case.ts`, `app/api/cron/join-fleet-cases/`, `app/api/fleet-cases/`, +Code: `lib/fleet-case.ts`, `lib/fleet-case-store.ts`, `app/api/cron/join-fleet-cases/`, `app/api/fleet-cases/`, `app/console/fleet-cases/`. Tests: `tests/unit/fleet-case.test.ts`, `tests/integration/join-fleet-cases-cron.test.ts`, `fleet-cases-console.test.ts`. diff --git a/lib/fleet-case-store.ts b/lib/fleet-case-store.ts new file mode 100644 index 0000000..633a7cf --- /dev/null +++ b/lib/fleet-case-store.ts @@ -0,0 +1,138 @@ +import type { Prisma } from "@prisma/client"; +import { candidateHashes, type FleetGroup, joinDetections } from "@/lib/fleet-case"; +import { loadFleetPrevalence } from "@/lib/fleet-prevalence"; +import { ranksAtLeast } from "@/lib/severity"; + +/** + * The database side of the fleet-case join cron (issue #62, box 1): read one tenant's recent + * detections, let `joinDetections` (`lib/fleet-case.ts`) group them by shared entity, then write + * the groups as fleet cases, as `lib/case-grouping-store.ts` does for #50. Every function runs + * inside the transaction and advisory lock `runPerTenant` holds for the tenant. + */ + +/** How far back detections are read: the join window is a day, so a week leaves room for a late + * detection to join an older sighting without the sweep reading the whole table. */ +const JOIN_LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000; + +/** Per-tenant cap on detections read in one invocation, newest first (the same reasoning as + * `GROUPING_BATCH_SIZE`: a bounded transaction, and the next tick continues). */ +const JOIN_BATCH_SIZE = 5000; + +/** One tenant's join pass. */ +export interface TenantJoinResult { + fleetCasesCreated: number; + fleetCasesMerged: number; + detectionsJoined: number; + moreWorkLikely: boolean; +} + +/** + * One tenant's join pass: read its last week of detections (at most `JOIN_BATCH_SIZE`, newest first), + * group them, and upsert each group as a fleet case. + */ +export async function joinOneTenant(tx: Prisma.TransactionClient, tenantId: string): Promise { + const detections = await tx.detection.findMany({ + where: { tenantId, timestamp: { gte: new Date(Date.now() - JOIN_LOOKBACK_MS) } }, + select: { id: true, agentId: true, timestamp: true, severity: true, event: true, fleetCaseId: true }, + orderBy: { timestamp: "desc" }, + take: JOIN_BATCH_SIZE, + }); + const moreWorkLikely = detections.length === JOIN_BATCH_SIZE; + const prevalence = await loadFleetPrevalence(tx, tenantId, candidateHashes(detections)); + const groups = joinDetections(detections, prevalence); + + let fleetCasesCreated = 0; + let fleetCasesMerged = 0; + let detectionsJoined = 0; + for (const group of groups) { + const outcome = await upsertGroup(tx, tenantId, group); + fleetCasesCreated += outcome.created ? 1 : 0; + fleetCasesMerged += outcome.merged; + detectionsJoined += outcome.detectionsJoined; + } + return { fleetCasesCreated, fleetCasesMerged, detectionsJoined, moreWorkLikely }; +} + +/** + * Writes one group: creates a fleet case, or grows the oldest case that already holds one of the + * group's entities and merges the others into it, then links the detections and recomputes the + * case's counts, window and severity (never lowered). + */ +async function upsertGroup(tx: Prisma.TransactionClient, tenantId: string, group: FleetGroup) { + const known = await tx.fleetCaseEntity.findMany({ + where: { tenantId, OR: group.entities.map((e) => ({ kind: e.kind, key: e.key })) }, + select: { fleetCaseId: true }, + }); + const existingIds = Array.from(new Set(known.map((k) => k.fleetCaseId))); + + let targetId: string; + let created = false; + let merged = 0; + if (existingIds.length === 0) { + const row = await tx.fleetCase.create({ + data: { + tenantId, + severity: group.severity, + agentCount: group.agentIds.length, + firstAt: group.firstAt, + lastAt: group.lastAt, + }, + }); + targetId = row.id; + created = true; + } else { + const [oldest, ...others] = await tx.fleetCase.findMany({ + where: { id: { in: existingIds } }, + orderBy: [{ createdAt: "asc" }, { id: "asc" }], + }); + targetId = oldest.id; + if (others.length > 0) { + const otherIds = others.map((o) => o.id); + await tx.detection.updateMany({ where: { fleetCaseId: { in: otherIds } }, data: { fleetCaseId: targetId } }); + await tx.fleetCaseEntity.updateMany({ where: { fleetCaseId: { in: otherIds } }, data: { fleetCaseId: targetId } }); + await tx.fleetCase.deleteMany({ where: { id: { in: otherIds } } }); + merged = others.length; + } + } + + await tx.fleetCaseEntity.createMany({ + data: group.entities.map((e) => ({ tenantId, fleetCaseId: targetId, kind: e.kind, key: e.key })), + skipDuplicates: true, + }); + // Only the detections not already on this case, so a rerun does not bump `updatedAt` (the + // staleness of a case narrative compares against it). + const linked = await tx.detection.updateMany({ + where: { + tenantId, + id: { in: group.detectionIds }, + OR: [{ fleetCaseId: null }, { fleetCaseId: { not: targetId } }], + }, + data: { fleetCaseId: targetId }, + }); + + // Recomputed from every detection of the case, not only this batch: it may be wider. + const members = await tx.detection.findMany({ + where: { tenantId, fleetCaseId: targetId }, + select: { agentId: true, timestamp: true, severity: true }, + }); + const current = await tx.fleetCase.findUniqueOrThrow({ where: { id: targetId } }); + const times = members.map((m) => m.timestamp.getTime()); + const next = { + agentCount: new Set(members.map((m) => m.agentId)).size, + firstAt: new Date(Math.min(...times)), + lastAt: new Date(Math.max(...times)), + severity: members.reduce( + (top, m) => (ranksAtLeast(m.severity, top) ? m.severity : top), + current.severity + ), + }; + if ( + next.agentCount !== current.agentCount || + next.firstAt.getTime() !== current.firstAt.getTime() || + next.lastAt.getTime() !== current.lastAt.getTime() || + next.severity !== current.severity + ) { + await tx.fleetCase.update({ where: { id: targetId }, data: next }); + } + return { created, merged, detectionsJoined: linked.count }; +} diff --git a/lib/fleet-case.ts b/lib/fleet-case.ts index 79c70e1..8ad81f3 100644 --- a/lib/fleet-case.ts +++ b/lib/fleet-case.ts @@ -3,7 +3,7 @@ import { outranks } from "@/lib/severity"; /** * The cross-host join of #62's first box, as pure decision logic over detections already read - * (the Prisma calls are in `app/api/cron/join-fleet-cases/route.ts`, as `lib/case-grouping.ts` + * (the Prisma calls are in `lib/fleet-case-store.ts`, as `lib/case-grouping.ts` * does for #50). * * Two detections of different agents belong to one fleet case when they carry the same entity: