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
86 changes: 86 additions & 0 deletions src/elastic/service/alertsService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,92 @@ describe("AlertsService", () => {
alerts: [],
});
});

// Regression test for a real bug: some ECS alert fields (host.name,
// user.name/domain, process.name/executable, source.ip, destination.ip)
// come back from Elasticsearch as arrays instead of scalars for certain
// correlated/network-derived alerts, even though `SecurityAlert._source`
// types them as scalars. Downstream sort/group logic in the Alert Triage
// view (useAlertSort.ts) assumed a scalar and threw on `.localeCompare()`
// when it got an array, crashing the whole widget to a blank panel with
// no error boundary to catch it. getAlerts() must normalize these fields
// before returning so every caller sees the scalar shape the type promises.
it("normalizes array-shaped ECS entity/IP fields to scalars", async () => {
const alertsClient = createMockAlertsClient();
vi.mocked(alertsClient.searchAlerts).mockResolvedValueOnce({
hits: {
total: { value: 1 },
hits: [
{
_id: "a1",
_index: ".alerts-security.alerts-default",
_source: {
"@timestamp": "2024-01-01T00:00:00Z",
"kibana.alert.rule.name": "R",
"kibana.alert.rule.uuid": "r",
"kibana.alert.severity": "low",
"kibana.alert.risk_score": 21,
"kibana.alert.workflow_status": "open",
"kibana.alert.reason": "x",
host: { name: ["sa-da-vm-lls-01"] },
user: { name: ["root"], domain: ["CORP"] },
process: {
name: ["python3.9"],
executable: ["/usr/bin/python3.9"],
parent: { name: ["bash"] },
},
source: { ip: ["10.132.0.108"] },
destination: { ip: ["35.195.130.253"] },
} as unknown as SecurityAlert["_source"],
},
],
},
});

const service = new AlertsService({ alertsClient });
const out = await service.getAlerts();

expect(out.alerts).toHaveLength(1);
const src = out.alerts[0]._source;
expect(src.host?.name).toBe("sa-da-vm-lls-01");
expect(src.user?.name).toBe("root");
expect(src.user?.domain).toBe("CORP");
expect(src.process?.name).toBe("python3.9");
expect(src.process?.executable).toBe("/usr/bin/python3.9");
expect(src.process?.parent?.name).toBe("bash");
expect(src.source?.ip).toBe("10.132.0.108");
expect(src.destination?.ip).toBe("35.195.130.253");
});

it("leaves already-scalar ECS entity fields untouched", async () => {
const alertsClient = createMockAlertsClient();
vi.mocked(alertsClient.searchAlerts).mockResolvedValueOnce({
hits: {
total: { value: 1 },
hits: [
{
_id: "a2",
_index: ".alerts-security.alerts-default",
_source: {
"@timestamp": "2024-01-01T00:00:00Z",
"kibana.alert.rule.name": "R",
"kibana.alert.rule.uuid": "r",
"kibana.alert.severity": "high",
"kibana.alert.risk_score": 47,
"kibana.alert.workflow_status": "open",
"kibana.alert.reason": "x",
host: { name: "sa-da-ingest-01" },
},
},
],
},
});

const service = new AlertsService({ alertsClient });
const out = await service.getAlerts();

expect(out.alerts[0]._source.host?.name).toBe("sa-da-ingest-01");
});
});

describe("getAlertContext", () => {
Expand Down
54 changes: 53 additions & 1 deletion src/elastic/service/alertsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
SecurityAlert,
} from "../../shared/types.js";
import type { AlertsClient } from "../client/alertsClient.js";
import { toScalar } from "../../shared/field-utils.js";

/** Time window (ms) on either side of an alert used to gather host context. */
const CONTEXT_WINDOW_MS = 5 * 60 * 1000;
Expand Down Expand Up @@ -116,7 +117,7 @@ export class AlertsService {
name: b.key,
count: b.doc_count,
})),
alerts: response.hits.hits,
alerts: response.hits.hits.map(normalizeAlertEntityFields),
};
}

Expand Down Expand Up @@ -242,6 +243,57 @@ export class AlertsService {
}
}

/**
* Some ECS fields (`host.name`, `user.name`, `process.name`, `source.ip`, ...)
* come back as arrays instead of scalars for certain correlated/network-
* derived alerts, even though {@link SecurityAlert}'s `_source` types them as
* scalars — Elasticsearch does not enforce that shape at the document level.
* Downstream code (sorting/grouping in the Alert Triage view) assumes a
* scalar and throws (`TypeError: ... .localeCompare is not a function`) if it
* gets an array, so normalize once here at the boundary rather than
* defensively at every read site.
*
* The `Record<string, unknown>` reads below reflect reality: this is raw JSON
* off the wire, not yet as trustworthy as the `SecurityAlert` type the rest of
* the codebase assumes. `host.ip` is intentionally left untouched — it's
* already typed and consumed as `string[]`.
*/
function normalizeAlertEntityFields(alert: SecurityAlert): SecurityAlert {
const src = alert._source as Record<string, unknown>;
const scalar = (value: unknown): string | undefined =>
toScalar(value as string | string[] | undefined);

const host = src.host as Record<string, unknown> | undefined;
const user = src.user as Record<string, unknown> | undefined;
const proc = src.process as Record<string, unknown> | undefined;
const parent = proc?.parent as Record<string, unknown> | undefined;
const file = src.file as Record<string, unknown> | undefined;
const source = src.source as Record<string, unknown> | undefined;
const destination = src.destination as Record<string, unknown> | undefined;

return {
...alert,
_source: {
...alert._source,
host: host ? { ...host, name: scalar(host.name) } : host,
user: user ? { ...user, name: scalar(user.name), domain: scalar(user.domain) } : user,
process: proc
? {
...proc,
name: scalar(proc.name),
executable: scalar(proc.executable),
parent: parent
? { ...parent, name: scalar(parent.name), executable: scalar(parent.executable) }
: parent,
}
: proc,
file: file ? { ...file, name: scalar(file.name), path: scalar(file.path) } : file,
source: source ? { ...source, ip: scalar(source.ip) } : source,
destination: destination ? { ...destination, ip: scalar(destination.ip) } : destination,
} as SecurityAlert["_source"],
};
}

function buildHostEventQuery(
hostName: string,
timeRange: TimeRange
Expand Down
7 changes: 4 additions & 3 deletions src/elastic/service/entityDetailService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import type { EntityDetailClient } from "../client/entityDetailClient.js";
import type { EntityDetail } from "../client/entityDetailClient.js";
import { toScalar } from "../../shared/field-utils.js";

interface EntityDetailServiceOptions {
readonly entityDetailClient: EntityDetailClient;
Expand Down Expand Up @@ -184,11 +185,11 @@ export class EntityDetailService {
if (firstProc) {
const os = firstProc["host.os.name"] || firstProc["host.os.platform"];
if (os) fields.push({ label: "OS", value: String(os) });
const ips = firstProc["host.ip"];
if (ips) {
const ip = toScalar(firstProc["host.ip"] as string | string[] | undefined);
if (ip) {
fields.push({
label: "IP",
value: String(Array.isArray(ips) ? ips[0] : ips),
value: String(ip),
mono: true,
});
}
Expand Down
55 changes: 55 additions & 0 deletions src/shared/components/ErrorBoundary/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from "react";
import { EmptyState } from "../States/States";

export interface ErrorBoundaryProps {
/** Replaces the default fallback message. */
fallback?: React.ReactNode;
children: React.ReactNode;
}

interface ErrorBoundaryState {
error: Error | null;
}

/**
* Catches render-time exceptions anywhere in `children` and shows a fallback
* instead of letting React unmount the whole tree to a blank screen.
*
* MCP app views render inside a host-provided webview with no dev console
* visible to the end user — an uncaught render error otherwise looks
* identical to "nothing loaded," with no indication anything went wrong.
* Wrap each view's root render in this boundary so an unexpected data shape
* degrades to a visible message instead of a silent blank panel.
*/
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { error: null };

static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { error };
}

componentDidCatch(error: Error, info: React.ErrorInfo): void {
console.error("Unhandled render error:", error, info.componentStack);
}

render(): React.ReactNode {
if (this.state.error) {
return (
this.props.fallback ?? (
<EmptyState>
Something went wrong rendering this view. Try reloading — if it keeps
happening, the underlying data may be in an unexpected shape.
</EmptyState>
)
);
}
return this.props.children;
}
}
3 changes: 3 additions & 0 deletions src/shared/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ export type { KpiStripProps, KpiTileProps, KpiAccent } from "./KpiStrip/KpiStrip
export { LoadingState, EmptyState } from "./States/States";
export type { LoadingStateProps, EmptyStateProps } from "./States/States";

export { ErrorBoundary } from "./ErrorBoundary/ErrorBoundary";
export type { ErrorBoundaryProps } from "./ErrorBoundary/ErrorBoundary";

export { DetailPane } from "./DetailPane/DetailPane";
export type { DetailPaneProps } from "./DetailPane/DetailPane";

Expand Down
27 changes: 27 additions & 0 deletions src/shared/field-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { describe, expect, it } from "vitest";
import { toScalar } from "./field-utils.js";

describe("toScalar", () => {
it("returns a scalar value unchanged", () => {
expect(toScalar("sa-da-vm-lls-01")).toBe("sa-da-vm-lls-01");
});

it("returns the first element of a non-empty array", () => {
expect(toScalar(["sa-da-vm-lls-01", "sa-da-ingest-01"])).toBe("sa-da-vm-lls-01");
});

it("returns undefined for an empty array", () => {
expect(toScalar([])).toBeUndefined();
});

it("returns undefined for undefined", () => {
expect(toScalar(undefined)).toBeUndefined();
});
});
25 changes: 25 additions & 0 deletions src/shared/field-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

/**
* Coerce an ECS field that may come back as either a scalar or an array (a
* multi-valued field, common on correlated/network-derived alerts) into a
* single scalar.
*
* Elasticsearch does not enforce single- vs. multi-valued fields at the
* document level, so the *same* mapped field can be a plain string on one
* document and a `string[]` on another. Code that expects a scalar (e.g.
* grouping/sorting by `host.name`) must normalize at the boundary rather than
* assume the shape declared in a TypeScript type actually holds at runtime.
*
* @returns the first element for a non-empty array, `undefined` for an empty
* array, or the value unchanged if it isn't an array.
*/
export function toScalar<T>(value: T | T[] | undefined): T | undefined {
if (!Array.isArray(value)) return value;
return value.length > 0 ? value[0] : undefined;
}
Loading
Loading