Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 1 addition & 125 deletions app/api/cron/join-fleet-cases/route.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
*
Expand Down Expand Up @@ -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<TenantJoinResult> {
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 };
}
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
2 changes: 1 addition & 1 deletion fleet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
138 changes: 138 additions & 0 deletions lib/fleet-case-store.ts
Original file line number Diff line number Diff line change
@@ -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<TenantJoinResult> {
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 };
}
2 changes: 1 addition & 1 deletion lib/fleet-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading