Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(marketplace): make the catalogue and its Install control tell the truth (#995)
Beenu Arorafdbaeed92b1d
diff --git a/apps/web/public/marketplace/index.json b/apps/web/public/marketplace/index.jsonindex 697c151aa..8124abbe9 100644--- a/apps/web/public/marketplace/index.json+++ b/apps/web/public/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-09-28T17:40:28Z",+ "generated": "2026-09-28T22:12:26Z","categories": [{"id": "playbooks",@@ -235424,33 +235424,6 @@"path": "playbooks/packs/v1/container-escape/container-escape-response.playbook.json","sha256": "9b06b45cb15df5b6fd9a186d4486c9ba75411fc3a72e2bea4fe3a0a7190c0440"},- {- "id": "container-escape-response-v1",- "type": "playbook",- "name": "Container Escape Response",- "description": "Responds to detected container escape attempts or privileged container misuse. Terminates the offending container, cordons the node, captures runtime forensics, and alerts the platform security team.",- "version": "1.0.0",- "author": "Beenu - [email protected]",- "tags": [- "container",- "kubernetes",- "docker",- "escape",- "runtime-security"- ],- "severity": "critical",- "trigger": null,- "steps": 8,- "category": "playbooks",- "mitre_techniques": [],- "verified": true,- "source": "core",- "tier": "stable",- "pack": false,- "enabled": true,- "path": "detections/playbooks/container-escape-response.yaml",- "sha256": "176f2c07b9553b44dd41d85b85b2a8e55c3a4e0f6e18ac22f0d4a3ff61d261aa"- },{"id": "critical-vulnerability-response-v1","type": "playbook",@@ -236696,6 +236669,60 @@"path": "detections/playbooks/s3-bucket-exposure-response.yaml","sha256": "260e61e4a08c5a30fcddb01364e62d26b5e67d8661a5db47c5a33586e4dee696"},+ {+ "id": "standalone-container-escape-response-v1",+ "type": "playbook",+ "name": "Container Escape Response",+ "description": "Responds to detected container escape attempts or privileged container misuse. Terminates the offending container, cordons the node, captures runtime forensics, and alerts the platform security team.",+ "version": "1.0.0",+ "author": "Beenu - [email protected]",+ "tags": [+ "container",+ "kubernetes",+ "docker",+ "escape",+ "runtime-security"+ ],+ "severity": "critical",+ "trigger": null,+ "steps": 8,+ "category": "playbooks",+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "pack": false,+ "enabled": true,+ "path": "detections/playbooks/container-escape-response.yaml",+ "sha256": "0391348632c3831ebdc5207f1b817844da10334e4ef214564af79b141e8ac42a"+ },+ {+ "id": "standalone-suspicious-signin-response-v1",+ "type": "playbook",+ "name": "Suspicious Sign-In Response",+ "description": "Responds to suspicious sign-in events including impossible travel, new country logins, known bad IP addresses, or sign-ins outside business hours. Triggers step-up authentication or session termination based on risk score.",+ "version": "1.0.0",+ "author": "Beenu - [email protected]",+ "tags": [+ "sign-in",+ "identity",+ "authentication",+ "impossible-travel",+ "conditional-access"+ ],+ "severity": "critical",+ "trigger": null,+ "steps": 8,+ "category": "playbooks",+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "pack": false,+ "enabled": true,+ "path": "detections/playbooks/suspicious-signin-response.yaml",+ "sha256": "91616904b93c07d67e6896b6a9c01e177439ff51d5969d23294ede2c2285b0d2"+ },{"id": "supply-chain-compromise-v1","type": "playbook",@@ -236881,33 +236908,6 @@"path": "playbooks/packs/v1/suspicious-signin/suspicious-signin-response.playbook.json","sha256": "f9475a1dcf7a0f93cb06a35bf567a08147b329fbc971cacd1e19ebeaac4a0e51"},- {- "id": "suspicious-signin-response-v1",- "type": "playbook",- "name": "Suspicious Sign-In Response",- "description": "Responds to suspicious sign-in events including impossible travel, new country logins, known bad IP addresses, or sign-ins outside business hours. Triggers step-up authentication or session termination based on risk score.",- "version": "1.0.0",- "author": "Beenu - [email protected]",- "tags": [- "sign-in",- "identity",- "authentication",- "impossible-travel",- "conditional-access"- ],- "severity": "critical",- "trigger": null,- "steps": 8,- "category": "playbooks",- "mitre_techniques": [],- "verified": true,- "source": "core",- "tier": "stable",- "pack": false,- "enabled": true,- "path": "detections/playbooks/suspicious-signin-response.yaml",- "sha256": "9c537ac853cef10087b88b56ba6bb401f2decae392a1dbd27118b9c02e3745f8"- },{"id": "token-theft-response-v1","type": "playbook",diff --git a/apps/web/src/components/marketplace/MarketplaceGridHeaderParity.test.tsx b/apps/web/src/components/marketplace/MarketplaceGridHeaderParity.test.tsxnew file mode 100644index 000000000..8cf31b648--- /dev/null+++ b/apps/web/src/components/marketplace/MarketplaceGridHeaderParity.test.tsx@@ -0,0 +1,170 @@+/**+ * The grid must render exactly what its header says it rendered.+ *+ * `marketplace/index.json` shipped two entries whose `type:id` collided with+ * two others — `container-escape-response-v1` and+ * `suspicious-signin-response-v1` each appeared twice, once from+ * `playbooks/packs/v1/**` and once from `detections/playbooks/*.yaml`. The+ * grid keys its children on `type:id`, so two siblings shared a key.+ *+ * React does not merely warn about that. `mapRemainingChildren` keys the old+ * fibers by key, and a second fiber with the same key overwrites the first in+ * that map, so the overwritten fiber is never handed to `deleteChild`. It+ * stays mounted through every subsequent re-render. Switching the filter to+ * `Reference only` therefore left two installable playbooks in a view that by+ * definition holds only uninstallable content, and the grid rendered two more+ * children than its own header claimed.+ *+ * Counting grid children rather than asserting on names on purpose: the+ * symptom is an arithmetic disagreement between two surfaces reading the same+ * array, and that is what the assertion should be about.+ */+import { describe, expect, it, vi, beforeEach } from 'vitest';+import { render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { MarketplaceItem } from './MarketplaceView';++const swrCalls = vi.hoisted(() => new Map<string, unknown>());+vi.mock('swr', () => ({+ __esModule: true,+ default: (key: string) => ({+ data: swrCalls.get(key),+ error: undefined,+ isLoading: false,+ mutate: vi.fn(async () => undefined),+ }),+}));++import { MarketplaceView } from './MarketplaceView';++function playbook(id: string, name: string): MarketplaceItem {+ return {+ id,+ type: 'playbook',+ name,+ description: 'Contains the blast radius and collects evidence.',+ version: '1.0.0',+ author: 'AiSOC',+ tags: ['ransomware'],+ tier: 'stable',+ source: 'core',+ verified: true,+ };+}++function detection(id: string, name: string, executable: boolean): MarketplaceItem {+ return {+ id,+ type: 'detection',+ name,+ description: 'Detects the technique on the host.',+ version: '1.0.0',+ author: 'AiSOC',+ tags: ['endpoint'],+ tier: 'stable',+ source: executable ? 'core' : 'chronicle-detection-rules',+ verified: executable,+ executable,+ quarantine_reason: executable ? undefined : 'upstream query language not executable by the engine yet',+ category: executable ? 'endpoint' : '_quarantine',+ };+}++/**+ * The collision the real index carried, reduced to the smallest shape that+ * reproduces it: same `type` and `id`, different `name`, both installable.+ */+const COLLIDING_A = playbook('container-escape-response-v1', 'Container Escape Response');+const COLLIDING_B = playbook('container-escape-response-v1', 'Container Escape: Runtime Breach Response');++const EXECUTABLE_RULE = detection('aws-root-console-login', 'AWS root console login', true);+const REFERENCE_RULE = detection('chronicle-scheduled-task', 'a_scheduled_task_was_created', false);++beforeEach(() => {+ swrCalls.clear();+ swrCalls.set('/api/v1/marketplace/installed', { total: 0, items: [] });+});++function setIndex(items: MarketplaceItem[]) {+ swrCalls.set('/marketplace/index.json', {+ version: '1',+ generated: '2026-09-28T00:00:00Z',+ items,+ });+}++/** The children of the card grid — what a reader actually counts on screen. */+function renderedCardCount(container: HTMLElement): number {+ const grid = container.querySelector('div.grid.grid-cols-1');+ return grid ? grid.children.length : 0;+}++/**+ * The runs-filter chip group. Scoped rather than queried globally because the+ * type filter also has a button labelled `All`.+ */+function runsFilter(container: HTMLElement) {+ const group = container.querySelector('[title^="Executable = loaded by the detection engine"]');+ if (!group) throw new Error('runs filter group not found');+ return within(group as HTMLElement);+}++/** The figure the sort bar publishes: `Showing N of M`. */+function headerShowingCount(): number {+ const label = screen.getByText(/Showing \d+ of \d+/);+ const m = /Showing (\d+) of (\d+)/.exec(label.textContent ?? '');+ if (!m) throw new Error(`could not parse header count from ${label.textContent}`);+ return Number(m[1]);+}++describe('the grid agrees with its own header under every filter', () => {+ it('keeps count when two entries share a type:id', async () => {+ // Every entry here is `tier: stable`, which is the default tier filter,+ // so all four are in scope before the runs filter narrows them.+ setIndex([COLLIDING_A, COLLIDING_B, EXECUTABLE_RULE, REFERENCE_RULE]);+ const user = userEvent.setup();+ const { container } = render(<MarketplaceView />);++ // `All` — the landing view.+ expect(renderedCardCount(container)).toBe(headerShowingCount());++ // `Executable` — the two playbooks plus the one loadable rule.+ await user.click(runsFilter(container).getByRole('button', { name: /^Executable\s*\(\d+\)$/ }));+ expect(renderedCardCount(container)).toBe(headerShowingCount());++ // `Reference only` — the filter where the orphaned children showed up as+ // installable playbooks inside a view of uninstallable content.+ await user.click(runsFilter(container).getByRole('button', { name: /^Reference only\s*\(\d+\)$/ }));+ expect(headerShowingCount()).toBe(1);+ expect(renderedCardCount(container)).toBe(1);++ // And back, so a stale child cannot hide behind a one-way transition.+ await user.click(runsFilter(container).getByRole('button', { name: /^All$/ }));+ expect(renderedCardCount(container)).toBe(headerShowingCount());+ });++ it('offers no Install control inside the reference-only view', async () => {+ setIndex([COLLIDING_A, COLLIDING_B, EXECUTABLE_RULE, REFERENCE_RULE]);+ const user = userEvent.setup();+ const { container } = render(<MarketplaceView />);++ await user.click(runsFilter(container).getByRole('button', { name: /^Reference only\s*\(\d+\)$/ }));++ // The whole point of the filter: nothing in it can be installed.+ expect(screen.queryAllByRole('button', { name: /^install$/i })).toHaveLength(0);+ expect(screen.queryByText('Container Escape Response')).toBeNull();+ expect(screen.queryByText('Container Escape: Runtime Breach Response')).toBeNull();+ });++ it('keeps count across the type filter too', async () => {+ setIndex([COLLIDING_A, COLLIDING_B, EXECUTABLE_RULE, REFERENCE_RULE]);+ const user = userEvent.setup();+ const { container } = render(<MarketplaceView />);++ await user.click(screen.getByRole('button', { name: /^Detections$/ }));+ expect(renderedCardCount(container)).toBe(headerShowingCount());++ await user.click(screen.getByRole('button', { name: /^Playbooks$/ }));+ expect(renderedCardCount(container)).toBe(headerShowingCount());+ });+});diff --git a/apps/web/src/components/marketplace/MarketplaceInstallControl.test.tsx b/apps/web/src/components/marketplace/MarketplaceInstallControl.test.tsxnew file mode 100644index 000000000..329552c74--- /dev/null+++ b/apps/web/src/components/marketplace/MarketplaceInstallControl.test.tsx@@ -0,0 +1,139 @@+/**+ * The Install button must not report a success it did not achieve.+ *+ * Measured against a real API — the published `aisoc-core-api` image, a real+ * account, a real session — clicking Install produced:+ *+ * POST /api/v1/marketplace/install -> HTTP 401 {"detail":"Not authenticated"}+ * GET /api/v1/marketplace/installed -> {"total":0,"items":[]}+ *+ * and the card flipped to **Installed** with the page header counting+ * "1 installed". Nothing had been installed.+ *+ * Two faults stacked. The three marketplace calls sent `credentials:+ * 'include'` and no `Authorization` header, while the API authenticates a+ * bearer JWT held in localStorage — so every one of them was anonymous. And+ * the handler listed 401 and 404 as statuses to ignore, so the optimistic+ * flag set before the request was never rolled back: the one status the+ * missing header produced was the one status that could not fail the call.+ *+ * Both directions. A button that never reports success would pass the+ * assertions about lying and be just as useless.+ */+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { AUTH_TOKEN_KEY } from '@/lib/api';+import type { MarketplaceItem } from './MarketplaceView';++const swrCalls = vi.hoisted(() => new Map<string, unknown>());+vi.mock('swr', () => ({+ __esModule: true,+ default: (key: string) => ({+ data: swrCalls.get(key),+ error: undefined,+ isLoading: false,+ mutate: vi.fn(async () => undefined),+ }),+}));++import { MarketplaceView } from './MarketplaceView';++const RULE: MarketplaceItem = {+ id: 'det-application-005',+ type: 'detection',+ name: 'Log4Shell JNDI Pattern in HTTP Header',+ description: 'Triggers on the application signal.',+ version: '1.0.0',+ author: 'AiSOC',+ tags: ['application'],+ tier: 'stable',+ source: 'core',+ verified: true,+ executable: true,+ category: 'application',+};++let fetchMock: ReturnType<typeof vi.fn>;++beforeEach(() => {+ swrCalls.clear();+ swrCalls.set('/marketplace/index.json', { version: '1', generated: '2026-09-28T00:00:00Z', items: [RULE] });+ swrCalls.set('/api/v1/marketplace/installed', { total: 0, items: [] });+ window.localStorage.setItem(AUTH_TOKEN_KEY, 'a.real.session');+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ cleanup();+ window.localStorage.clear();+ vi.unstubAllGlobals();+});++function card() {+ const heading = screen.getByText(RULE.name);+ return within(heading.closest('div.flex-col') as HTMLElement);+}++describe('the Install control', () => {+ it('does not claim to have installed anything when the API refuses', async () => {+ fetchMock.mockResolvedValue({+ ok: false,+ status: 401,+ json: async () => ({ detail: 'Not authenticated' }),+ });+ const user = userEvent.setup();+ render(<MarketplaceView />);++ await user.click(card().getByRole('button', { name: /^Install$/ }));++ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());+ expect(screen.getByRole('alert')).toHaveTextContent(/Not authenticated/);+ // The optimistic flag has to come back off, on the card and in the header.+ expect(card().getByRole('button', { name: /^Install$/ })).toBeInTheDocument();+ expect(card().queryByText(/^Installed$/)).toBeNull();+ expect(screen.queryByText(/\d+ installed/)).toBeNull();+ });++ it('does not claim to have installed a reference-only rule the API refused', async () => {+ fetchMock.mockResolvedValue({+ ok: false,+ status: 409,+ json: async () => ({ detail: 'det-x is reference-only — the detection engine does not load it.' }),+ });+ const user = userEvent.setup();+ render(<MarketplaceView />);++ await user.click(card().getByRole('button', { name: /^Install$/ }));++ await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(/reference-only/));+ expect(card().getByRole('button', { name: /^Install$/ })).toBeInTheDocument();+ });++ it('sends the session the rest of the console authenticates with', async () => {+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({ id: RULE.id }) });+ const user = userEvent.setup();+ render(<MarketplaceView />);++ await user.click(card().getByRole('button', { name: /^Install$/ }));++ await waitFor(() => expect(fetchMock).toHaveBeenCalled());+ const [url, init] = fetchMock.mock.calls.find(([u]) => String(u).includes('/marketplace/install'))!;+ expect(String(url)).toContain('/api/v1/marketplace/install');+ expect((init as RequestInit).headers).toMatchObject({ Authorization: 'Bearer a.real.session' });+ });++ it('reports success when the install actually succeeded', async () => {+ // The other direction: a control that always refuses would pass the two+ // assertions above and install nothing, forever.+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({ id: RULE.id }) });+ const user = userEvent.setup();+ render(<MarketplaceView />);++ await user.click(card().getByRole('button', { name: /^Install$/ }));++ await waitFor(() => expect(card().getByText(/^Installed$/)).toBeInTheDocument());+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/apps/web/src/components/marketplace/MarketplaceView.tsx b/apps/web/src/components/marketplace/MarketplaceView.tsxindex d256b97a6..01379299e 100644--- a/apps/web/src/components/marketplace/MarketplaceView.tsx+++ b/apps/web/src/components/marketplace/MarketplaceView.tsx@@ -5,6 +5,8 @@ import useSWR from 'swr';import clsx from 'clsx';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { ErrorState } from '@/components/ui/ErrorState';+import { formatTagLabel } from './tagLabel';+import { AUTH_TOKEN_KEY } from '@/lib/api';// ── Types ────────────────────────────────────────────────────────────────────@@ -441,17 +443,23 @@ function ItemCard({ item, installed, busy, onInstall, onUninstall }: ItemCardPro</div></div>- {/* Tags */}+ {/* Tags. The builder flattens the importers' structured tag block into+ dotted keys for downstream code; `formatTagLabel` is what turns that+ encoding back into something a person reads. */}{item.tags && item.tags.length > 0 && (<div className="flex flex-wrap gap-1">- {item.tags.slice(0, 4).map((tag) => (- <span- key={tag}- className="rounded bg-zinc-700/60 px-1.5 py-0.5 text-xs text-zinc-400"- >- {tag}- </span>- ))}+ {item.tags.slice(0, 4).map((tag) => {+ const { label, title } = formatTagLabel(tag);+ return (+ <span+ key={tag}+ title={title}+ className="rounded bg-zinc-700/60 px-1.5 py-0.5 text-xs text-zinc-400"+ >+ {label}+ </span>+ );+ })}{item.tags.length > 4 && (<span className="rounded bg-zinc-700/60 px-1.5 py-0.5 text-xs text-zinc-500">+{item.tags.length - 4}@@ -481,12 +489,50 @@ type TierFilter = 'all' | 'stable' | 'beta' | 'imported' | 'community';// smaller than it is; the stat cards and the per-card banner carry the split.type RunsFilter = 'all' | 'executable' | 'reference';-// Fetch the installed-set, but treat 401/404 as "not signed in / API offline"-// so the marketplace stays usable in static demos and unauthenticated previews.+/**+ * The bearer token the rest of the console authenticates with.+ *+ * These three calls sent `credentials: 'include'` and nothing else. The API+ * authenticates a `Authorization: Bearer` JWT held in localStorage, not a+ * cookie, so every one of them was anonymous: install answered 401, the+ * installed-set answered 401, and neither said so.+ */+function authHeaders(): Record<string, string> {+ if (typeof window === 'undefined') return {};+ try {+ const token = window.localStorage.getItem(AUTH_TOKEN_KEY);+ return token ? { Authorization: `Bearer ${token}` } : {};+ } catch {+ return {};+ }+}++/** Whether this browser holds a session at all. */+function signedIn(): boolean {+ return Boolean(authHeaders().Authorization);+}++/** The API's `detail`, when it sent one, so a refusal can say why. */+async function failureDetail(res: Response): Promise<string> {+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (typeof body.detail === 'string' && body.detail) return body.detail;+ } catch {+ /* not JSON */+ }+ return `HTTP ${res.status}`;+}++/**+ * Fetch the installed-set. A 401 with no session is "nobody is signed in",+ * which is the static-preview case and not an error; a 401 *with* a session+ * is a real failure and must not be flattened into an empty list.+ */async function fetchInstalled(url: string): Promise<InstalledResponse | null> {- const res = await fetch(url, { credentials: 'include' });- if (res.status === 401 || res.status === 404) return null;- if (!res.ok) throw new Error(`installed: HTTP ${res.status}`);+ const res = await fetch(url, { credentials: 'include', headers: authHeaders() });+ if (res.status === 404) return null;+ if (res.status === 401 && !signedIn()) return null;+ if (!res.ok) throw new Error(`installed: ${await failureDetail(res)}`);return (await res.json()) as InstalledResponse;}@@ -552,13 +598,16 @@ export function MarketplaceView() {try {const res = await fetch('/api/v1/marketplace/install', {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', ...authHeaders() },credentials: 'include',body: JSON.stringify({ type: item.type, id: item.id }),});- if (!res.ok && res.status !== 401 && res.status !== 404) {- throw new Error(`install: HTTP ${res.status}`);- }+ // 401 and 404 used to be swallowed here, and the optimistic flag was+ // never rolled back — so against a real API the button answered 401,+ // the card said "Installed", the header counted it, and nothing had+ // been installed. A control that reports success it did not achieve+ // is worse than one that is greyed out.+ if (!res.ok) throw new Error(await failureDetail(res));await refreshInstalled();} catch (err) {// Roll the optimistic flag back; surface a one-line toast.@@ -593,10 +642,12 @@ export function MarketplaceView() {const url = `/api/v1/marketplace/install?type=${encodeURIComponent(item.type,)}&id=${encodeURIComponent(item.id)}`;- const res = await fetch(url, { method: 'DELETE', credentials: 'include' });- if (!res.ok && res.status !== 401 && res.status !== 404) {- throw new Error(`uninstall: HTTP ${res.status}`);- }+ const res = await fetch(url, {+ method: 'DELETE',+ credentials: 'include',+ headers: authHeaders(),+ });+ if (!res.ok) throw new Error(await failureDetail(res));await refreshInstalled();} catch (err) {setLocalInstalled((prev) => {@@ -616,6 +667,37 @@ export function MarketplaceView() {[refreshInstalled, setBusyKey],);+ /**+ * One entry per `type:id` — the identity the grid keys its children on, and+ * the identity `POST /v1/marketplace/install` resolves by first match.+ *+ * The shipped index carried two collisions between the v1 playbook pack and+ * the standalone response playbooks, and React does not simply warn about a+ * repeated key: reconciliation maps the old fibers by key, a second fiber+ * with the same key overwrites the first in that map, and the overwritten+ * one is never handed to `deleteChild`. It stayed mounted through every+ * later render, so two installable playbooks survived into the+ * `Reference only` view — which by definition holds nothing installable —+ * and the grid rendered more children than the header beneath it counted.+ *+ * `scripts/build_marketplace.py` now refuses to emit a colliding index, but+ * this file is served from `public/` and a deployment can serve its own, so+ * the console settles it at the boundary rather than trusting the feed.+ * First match wins, which is the entry the install API would have resolved.+ */+ const { catalogue, duplicateCount } = useMemo(() => {+ const source = data?.items ?? [];+ const seen = new Set<string>();+ const unique: MarketplaceItem[] = [];+ for (const item of source) {+ const key = installedKey(item.type, item.id);+ if (seen.has(key)) continue;+ seen.add(key);+ unique.push(item);+ }+ return { catalogue: unique, duplicateCount: source.length - unique.length };+ }, [data]);+const [search, setSearch] = useState('');const [typeFilter, setTypeFilter] = useState<'all' | 'playbook' | 'detection' | 'plugin'>('all');const [severityFilter, setSeverityFilter] = useState<string>('all');@@ -635,9 +717,9 @@ export function MarketplaceView() {// Build distinct, sorted MITRE technique list (with item counts) for the filter.const mitreOptions = useMemo(() => {- if (!data?.items) return [] as { id: string; count: number }[];+ if (catalogue.length === 0) return [] as { id: string; count: number }[];const byId = new Map<string, number>();- for (const it of data.items) {+ for (const it of catalogue) {for (const tid of it.mitre_techniques ?? []) {byId.set(tid, (byId.get(tid) ?? 0) + 1);}@@ -645,17 +727,17 @@ export function MarketplaceView() {return Array.from(byId.entries()).map(([id, count]) => ({ id, count })).sort((a, b) => a.id.localeCompare(b.id));- }, [data]);+ }, [catalogue]);// Distinct content categories (detection.category + playbook.category) for filter.const categoryOptions = useMemo(() => {- if (!data?.items) return [] as string[];+ if (catalogue.length === 0) return [] as string[];const set = new Set<string>();- for (const it of data.items) {+ for (const it of catalogue) {if (it.category) set.add(it.category);}return Array.from(set).sort();- }, [data]);+ }, [catalogue]);// Counts per tier so chips can show "Stable (865)" etc. — helps users// understand at a glance that imported content dwarfs native content.@@ -667,19 +749,19 @@ export function MarketplaceView() {imported: 0,community: 0,};- if (!data?.items) return counts;- counts.all = data.items.length;- for (const it of data.items) {+ if (catalogue.length === 0) return counts;+ counts.all = catalogue.length;+ for (const it of catalogue) {const tier = (it.tier ?? 'stable') as TierFilter;if (tier in counts) counts[tier]++;}return counts;- }, [data]);+ }, [catalogue]);const items = useMemo(() => {- if (!data?.items) return [];+ if (catalogue.length === 0) return [];- const filtered = data.items.filter((item) => {+ const filtered = catalogue.filter((item) => {if (typeFilter !== 'all' && item.type !== typeFilter) return false;if (severityFilter !== 'all' && item.severity !== severityFilter) return false;if (categoryFilter !== 'all' && item.category !== categoryFilter) return false;@@ -742,7 +824,7 @@ export function MarketplaceView() {return filtered;}, [- data,+ catalogue,search,typeFilter,severityFilter,@@ -762,26 +844,26 @@ export function MarketplaceView() {// engine does not load — so the published figure and the truth table's// were two numbers nothing compared.const executableCount = useMemo(- () => (data?.items ?? []).filter((i) => i.executable !== false).length,- [data],+ () => catalogue.filter((i) => i.executable !== false).length,+ [catalogue],);const referenceOnlyCount = useMemo(- () => (data?.items ?? []).filter((i) => i.executable === false).length,- [data],+ () => catalogue.filter((i) => i.executable === false).length,+ [catalogue],);const stats = useMemo(() => {if (!data?.items) return null;if (data.stats) return data.stats;return {- total: data.items.length,- playbooks: data.items.filter((i) => i.type === 'playbook').length,- detections: data.items.filter((i) => i.type === 'detection').length,- plugins: data.items.filter((i) => i.type === 'plugin').length,- verified: data.items.filter((i) => i.verified).length,- community: data.items.filter((i) => i.source === 'community').length,+ total: catalogue.length,+ playbooks: catalogue.filter((i) => i.type === 'playbook').length,+ detections: catalogue.filter((i) => i.type === 'detection').length,+ plugins: catalogue.filter((i) => i.type === 'plugin').length,+ verified: catalogue.filter((i) => i.verified).length,+ community: catalogue.filter((i) => i.source === 'community').length,};- }, [data]);+ }, [data, catalogue]);const toggleSort = (field: SortOption) => {if (sortBy === field) {@@ -852,6 +934,20 @@ export function MarketplaceView() {</div>)}+ {/* A collapsed collision is the sort of thing that should cost a+ sentence rather than happen quietly: the catalogue a reader is+ looking at is smaller than the file behind it, and they are entitled+ to know which way the console resolved it. */}+ {duplicateCount > 0 && (+ <p className="rounded-lg border border-amber-700/40 bg-amber-950/30 px-4 py-2 text-sm text-amber-200/90">+ {duplicateCount === 1+ ? 'One entry in this index repeats a type and id that another entry already uses, so it is not listed.'+ : `${duplicateCount} entries in this index repeat a type and id that another entry already uses, so they are not listed.`}{' '}+ Install resolves the first match, so the listing is what an install would act on. Regenerate with{' '}+ <code className="text-amber-200">pnpm marketplace:sync</code>.+ </p>+ )}+{/* Stats.`Executable` and `Reference only` lead, and they partition thecatalogue: every entry is one or the other and the two sum to@@ -1060,7 +1156,7 @@ export function MarketplaceView() {</button>))}<span className="ml-auto text-xs text-zinc-500">- Showing {items.length} of {data?.items.length ?? 0}+ Showing {items.length} of {catalogue.length}</span></div>diff --git a/apps/web/src/components/marketplace/tagLabel.test.ts b/apps/web/src/components/marketplace/tagLabel.test.tsnew file mode 100644index 000000000..4110e2b7f--- /dev/null+++ b/apps/web/src/components/marketplace/tagLabel.test.ts@@ -0,0 +1,114 @@+/**+ * No machine key may reach a card as a label.+ *+ * `categories.endpoint` rendered as literal text at the bottom of 5,197+ * marketplace cards, and `tlp.white` on 878 more — the dotted form+ * `normalise_tags()` produces so that downstream code gets a `string[]`,+ * shown to a reader unchanged.+ *+ * The gate runs against the real index rather than a fixture, because the+ * thing that drifts is the data: a new importer adds a namespace, the+ * builder flattens it, and no one looks at a card again. It reads the+ * formatter's declared namespaces, so shipping a new one means deciding on a+ * label for it here first.+ *+ * Scope is `tags[]` and `category` — the two fields the card renders as+ * labels. Deliberately not `name` or `description`: those are prose, a+ * sentence may legitimately contain `winlogbeat.json` or a hostname, and a+ * gate that read them would be the false-positive machine the narrow one+ * avoids being.+ */+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import {+ formatTagLabel,+ KNOWN_TAG_NAMESPACES,+ LITERAL_DOTTED_TAGS,+ RAW_KEY_SHAPE,+} from './tagLabel';++const here = dirname(fileURLToPath(import.meta.url));+const INDEX_PATH = resolve(here, '../../../public/marketplace/index.json');++interface IndexItem {+ id: string;+ tags?: string[];+ category?: string;+ name?: string;+ description?: string;+}++const index = JSON.parse(readFileSync(INDEX_PATH, 'utf8')) as { items: IndexItem[] };++describe('the formatter', () => {+ it('turns the builder’s dotted encoding into text', () => {+ expect(formatTagLabel('categories.endpoint')).toEqual({ label: 'endpoint', title: 'categories.endpoint' });+ expect(formatTagLabel('tlp.white')).toEqual({ label: 'TLP:WHITE', title: 'tlp.white' });+ expect(formatTagLabel('data_source.osquery')).toEqual({ label: 'osquery', title: 'data_source.osquery' });+ });++ it('leaves dotted text that is not a known namespace alone', () => {+ // The other direction, and the one that matters. Satisfying the gate by+ // stripping everything before the first dot would pass every assertion+ // above and destroy each of these.+ for (const literal of ['example.com', 'winlogbeat.json', 'host.example.internal', 'v1.2.3']) {+ expect(formatTagLabel(literal).label).toBe(literal);+ }+ });++ it('leaves an undotted tag alone', () => {+ for (const plain of ['ransomware', 'kubernetes', 'runtime-security']) {+ expect(formatTagLabel(plain).label).toBe(plain);+ }+ });++ it('keeps the raw tag reachable rather than discarding it', () => {+ expect(formatTagLabel('categories.cloud').title).toBe('categories.cloud');+ });+});++describe('the shipped catalogue renders no machine keys', () => {+ it('has a label for every dotted tag namespace it ships', () => {+ const unknown = new Map<string, string>();+ for (const item of index.items) {+ for (const tag of item.tags ?? []) {+ if (!tag.includes('.') || LITERAL_DOTTED_TAGS.has(tag)) continue;+ const namespace = tag.slice(0, tag.indexOf('.'));+ if (!KNOWN_TAG_NAMESPACES.includes(namespace)) unknown.set(namespace, `${item.id} → ${tag}`);+ }+ }+ expect(+ Array.from(unknown, ([ns, where]) => `${ns} (first seen on ${where})`),+ 'add a label in tagLabel.ts, or declare the tag literal',+ ).toEqual([]);+ });++ it('renders no tag that still looks like a machine key', () => {+ const leaking: string[] = [];+ for (const item of index.items) {+ for (const tag of item.tags ?? []) {+ const { label } = formatTagLabel(tag);+ if (RAW_KEY_SHAPE.test(label)) leaking.push(`${item.id} → ${tag} renders as "${label}"`);+ }+ }+ expect(leaking.slice(0, 10)).toEqual([]);+ expect(leaking).toHaveLength(0);+ });++ it('renders no category that looks like a machine key', () => {+ // The card's metadata row prints `item.category` with no formatter at+ // all, so a dotted value there would leak the same way.+ const leaking = index.items+ .filter((item) => item.category && RAW_KEY_SHAPE.test(item.category))+ .map((item) => `${item.id} → ${item.category}`);+ expect(leaking.slice(0, 10)).toEqual([]);+ });++ it('is actually looking at the shipped catalogue', () => {+ // A gate that silently read an empty array would pass forever.+ expect(index.items.length).toBeGreaterThan(1000);+ expect(index.items.some((i) => (i.tags ?? []).some((t) => t.includes('.')))).toBe(true);+ });+});diff --git a/apps/web/src/components/marketplace/tagLabel.ts b/apps/web/src/components/marketplace/tagLabel.tsnew file mode 100644index 000000000..c89e9ce09--- /dev/null+++ b/apps/web/src/components/marketplace/tagLabel.ts@@ -0,0 +1,76 @@+/**+ * Display labels for the marketplace's dotted tag encoding.+ *+ * `scripts/build_marketplace.py` flattens the detection importers' structured+ * tag block — `{'categories': ['endpoint'], 'tlp': ['white']}` — into dotted+ * strings, because everything downstream of it expects `string[]`. That form+ * is an internal encoding and was never meant to be read by a person, but the+ * marketplace card rendered `item.tags` verbatim, so `categories.endpoint`+ * appeared as the only text at the bottom of 5,197 cards and `tlp.white` on+ * 878 more.+ *+ * The namespace decides the label, not a pattern over the string: `tlp.white`+ * is TLP:WHITE, a real classification that would be destroyed by stripping+ * the prefix, while `categories.endpoint` is just the category. An unknown+ * namespace is returned untouched rather than guessed at — that is what makes+ * `tagLabel.test.ts` able to notice a new encoding instead of quietly+ * rendering it, and why this must not become a blanket "strip everything+ * before the first dot".+ */++/** The raw tag and the text a reader should see for it. */+export interface TagLabel {+ label: string;+ /** The raw tag, when it differs — carried as a tooltip so nothing is lost. */+ title?: string;+}++/**+ * Known namespaces from `normalise_tags()`. A namespace listed here has been+ * looked at by a person and given a display form; one that is not listed+ * fails `tagLabel.test.ts` rather than reaching a card.+ */+const NAMESPACE_LABELS: Record<string, (value: string) => string> = {+ // The rule's content category. The card already shows bare category names+ // in its metadata row, so the bare value is the consistent form.+ categories: (value) => value,+ // Traffic Light Protocol. `white` alone would read as a colour.+ tlp: (value) => `TLP:${value.toUpperCase()}`,+ // Which telemetry stream the rule reads.+ data_source: (value) => value,+};++/**+ * Dotted tags that are literal text rather than a namespaced key, so they+ * should render as-is. Empty today; an entry here is a deliberate statement+ * that the dot is part of the value (a hostname, a filename, a version).+ */+const LITERAL_TAGS = new Set<string>();++export function formatTagLabel(tag: string): TagLabel {+ if (LITERAL_TAGS.has(tag)) return { label: tag };+ const dot = tag.indexOf('.');+ if (dot <= 0) return { label: tag };+ const namespace = tag.slice(0, dot);+ const value = tag.slice(dot + 1);+ const render = NAMESPACE_LABELS[namespace];+ if (!render || value === '') return { label: tag };+ const label = render(value);+ return label === tag ? { label } : { label, title: tag };+}++/** The namespaces with a display form, for the gate to read. */+export const KNOWN_TAG_NAMESPACES: readonly string[] = Object.keys(NAMESPACE_LABELS);++/** Declared-literal dotted tags, for the gate to read. */+export const LITERAL_DOTTED_TAGS: ReadonlySet<string> = LITERAL_TAGS;++/**+ * The shape of a machine key that has escaped into user-visible text:+ * a lowercase-initial identifier followed by at least one dotted segment.+ *+ * Broader than `^[a-z][a-zA-Z]*(\.[a-zA-Z]+)+$` by allowing digits and+ * underscores inside a segment, because `data_source.osquery` is exactly the+ * same defect and the narrower form does not match it.+ */+export const RAW_KEY_SHAPE = /^[a-z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)+$/;diff --git a/detections/playbooks/container-escape-response.yaml b/detections/playbooks/container-escape-response.yamlindex 5176684a6..47d255784 100644--- a/detections/playbooks/container-escape-response.yaml+++ b/detections/playbooks/container-escape-response.yaml@@ -1,4 +1,9 @@-id: container-escape-response-v1+# `standalone-` because `playbooks/packs/v1/container-escape/` ships a+# different playbook that had claimed `container-escape-response-v1` too. The+# pack tree keeps the plain id: it is what the agents PlaybookStore loads and+# what `GET /api/v1/playbooks` serves, while this tree is indexed only by the+# marketplace builder.+id: standalone-container-escape-response-v1name: Container Escape Responsedescription: >Responds to detected container escape attempts or privileged containerdiff --git a/detections/playbooks/suspicious-signin-response.yaml b/detections/playbooks/suspicious-signin-response.yamlindex 9157cf46e..121a817f6 100644--- a/detections/playbooks/suspicious-signin-response.yaml+++ b/detections/playbooks/suspicious-signin-response.yaml@@ -1,4 +1,9 @@-id: suspicious-signin-response-v1+# `standalone-` because `playbooks/packs/v1/suspicious-signin/` ships a+# different playbook that had claimed `suspicious-signin-response-v1` too. The+# pack tree keeps the plain id: it is what the agents PlaybookStore loads and+# what `GET /api/v1/playbooks` serves, while this tree is indexed only by the+# marketplace builder.+id: standalone-suspicious-signin-response-v1name: Suspicious Sign-In Responsedescription: >Responds to suspicious sign-in events including impossible travel, new countrydiff --git a/marketplace/index.json b/marketplace/index.jsonindex 697c151aa..8124abbe9 100644--- a/marketplace/index.json+++ b/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-09-28T17:40:28Z",+ "generated": "2026-09-28T22:12:26Z","categories": [{"id": "playbooks",@@ -235424,33 +235424,6 @@"path": "playbooks/packs/v1/container-escape/container-escape-response.playbook.json","sha256": "9b06b45cb15df5b6fd9a186d4486c9ba75411fc3a72e2bea4fe3a0a7190c0440"},- {- "id": "container-escape-response-v1",- "type": "playbook",- "name": "Container Escape Response",- "description": "Responds to detected container escape attempts or privileged container misuse. Terminates the offending container, cordons the node, captures runtime forensics, and alerts the platform security team.",- "version": "1.0.0",- "author": "Beenu - [email protected]",- "tags": [- "container",- "kubernetes",- "docker",- "escape",- "runtime-security"- ],- "severity": "critical",- "trigger": null,- "steps": 8,- "category": "playbooks",- "mitre_techniques": [],- "verified": true,- "source": "core",- "tier": "stable",- "pack": false,- "enabled": true,- "path": "detections/playbooks/container-escape-response.yaml",- "sha256": "176f2c07b9553b44dd41d85b85b2a8e55c3a4e0f6e18ac22f0d4a3ff61d261aa"- },{"id": "critical-vulnerability-response-v1","type": "playbook",@@ -236696,6 +236669,60 @@"path": "detections/playbooks/s3-bucket-exposure-response.yaml","sha256": "260e61e4a08c5a30fcddb01364e62d26b5e67d8661a5db47c5a33586e4dee696"},+ {+ "id": "standalone-container-escape-response-v1",+ "type": "playbook",+ "name": "Container Escape Response",+ "description": "Responds to detected container escape attempts or privileged container misuse. Terminates the offending container, cordons the node, captures runtime forensics, and alerts the platform security team.",+ "version": "1.0.0",+ "author": "Beenu - [email protected]",+ "tags": [+ "container",+ "kubernetes",+ "docker",+ "escape",+ "runtime-security"+ ],+ "severity": "critical",+ "trigger": null,+ "steps": 8,+ "category": "playbooks",+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "pack": false,+ "enabled": true,+ "path": "detections/playbooks/container-escape-response.yaml",+ "sha256": "0391348632c3831ebdc5207f1b817844da10334e4ef214564af79b141e8ac42a"+ },+ {+ "id": "standalone-suspicious-signin-response-v1",+ "type": "playbook",+ "name": "Suspicious Sign-In Response",+ "description": "Responds to suspicious sign-in events including impossible travel, new country logins, known bad IP addresses, or sign-ins outside business hours. Triggers step-up authentication or session termination based on risk score.",+ "version": "1.0.0",+ "author": "Beenu - [email protected]",+ "tags": [+ "sign-in",+ "identity",+ "authentication",+ "impossible-travel",+ "conditional-access"+ ],+ "severity": "critical",+ "trigger": null,+ "steps": 8,+ "category": "playbooks",+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "pack": false,+ "enabled": true,+ "path": "detections/playbooks/suspicious-signin-response.yaml",+ "sha256": "91616904b93c07d67e6896b6a9c01e177439ff51d5969d23294ede2c2285b0d2"+ },{"id": "supply-chain-compromise-v1","type": "playbook",@@ -236881,33 +236908,6 @@"path": "playbooks/packs/v1/suspicious-signin/suspicious-signin-response.playbook.json","sha256": "f9475a1dcf7a0f93cb06a35bf567a08147b329fbc971cacd1e19ebeaac4a0e51"},- {- "id": "suspicious-signin-response-v1",- "type": "playbook",- "name": "Suspicious Sign-In Response",- "description": "Responds to suspicious sign-in events including impossible travel, new country logins, known bad IP addresses, or sign-ins outside business hours. Triggers step-up authentication or session termination based on risk score.",- "version": "1.0.0",- "author": "Beenu - [email protected]",- "tags": [- "sign-in",- "identity",- "authentication",- "impossible-travel",- "conditional-access"- ],- "severity": "critical",- "trigger": null,- "steps": 8,- "category": "playbooks",- "mitre_techniques": [],- "verified": true,- "source": "core",- "tier": "stable",- "pack": false,- "enabled": true,- "path": "detections/playbooks/suspicious-signin-response.yaml",- "sha256": "9c537ac853cef10087b88b56ba6bb401f2decae392a1dbd27118b9c02e3745f8"- },{"id": "token-theft-response-v1","type": "playbook",diff --git a/scripts/build_marketplace.py b/scripts/build_marketplace.pyindex 9877f383d..59ea9d0a6 100644--- a/scripts/build_marketplace.py+++ b/scripts/build_marketplace.py@@ -649,9 +649,43 @@ def _attach_content_hashes(items: list[dict[str, Any]]) -> None:item["sha256"] = hashlib.sha256(source.read_bytes()).hexdigest() if source.is_file() else None+def _assert_unique_identities(items: list[dict[str, Any]]) -> None:+ """Refuse to emit an index where two entries answer to the same identity.++ ``(type, id)`` is the identity every consumer keys on, and two entries+ sharing one breaks all of them in different ways. The console keys its+ grid children on it, and React maps old fibers by key when it reconciles:+ a second fiber with the same key overwrites the first in that map, so the+ overwritten one is never handed to ``deleteChild`` and stays mounted+ through every later render. Two installable playbooks therefore survived+ into the ``Reference only`` view, which by definition holds nothing+ installable, and the grid rendered more children than its own header+ counted. ``POST /v1/marketplace/install`` resolves ``(type, id)`` by first+ match, so the entry a reader clicked was not necessarily the one that got+ installed — a different document, a different step count, a different+ content hash.++ Both collisions in the shipped index were between the v1 pack tree and the+ standalone response playbooks under ``detections/playbooks/``, which use+ the same ``<slug>-v1`` convention in slug spaces that happened to overlap.+ """+ seen: dict[tuple[str, str], str] = {}+ collisions: list[str] = []+ for item in items:+ identity = (str(item.get("type")), str(item.get("id")))+ path = str(item.get("path") or "<no path>")+ if identity in seen:+ collisions.append(f" {identity[0]}:{identity[1]}\n {seen[identity]}\n {path}")+ else:+ seen[identity] = path+ if collisions:+ raise SystemExit("marketplace: two entries share a (type, id); every consumer keys on it.\n" + "\n".join(collisions))++def build_index() -> dict[str, Any]:items = collect_items()items.sort(key=lambda i: (i["type"], i.get("id", "")))+ _assert_unique_identities(items)_attach_content_hashes(items)return {"$schema": "https://example.com/schemas/marketplace/v1.json",diff --git a/services/api/app/api/v1/endpoints/marketplace.py b/services/api/app/api/v1/endpoints/marketplace.pyindex e78f0a509..da92fb507 100644--- a/services/api/app/api/v1/endpoints/marketplace.py+++ b/services/api/app/api/v1/endpoints/marketplace.py@@ -375,6 +375,23 @@ async def install_marketplace_item(detail=f"Marketplace item not found: {body.type}:{body.id}",)+ # 4,388 of the 7,155 catalogue entries are rules the detection engine does+ # not load. Installing one flips a per-tenant flag over a rule that can+ # never match, which is a no-op wearing the costume of an action. The+ # console says "Cannot install" and offers no button — but that was the+ # only thing stopping it: a POST straight at this route installed a+ # reference-only rule and answered 200, so the control was styled as+ # prevented rather than prevented. The catalogue decides, not the caller.+ if match.get("executable") is False:+ raise HTTPException(+ status_code=409,+ detail=(+ f"{body.type}:{body.id} is reference-only — the detection engine does not "+ "load it, so installing it would enable nothing."+ + (f" Reason: {match['quarantine_reason']}" if match.get("quarantine_reason") else "")+ ),+ )+sha = _content_sha256(match)tenant_id = str(current_user.tenant_id)diff --git a/services/api/app/data/marketplace/index.json b/services/api/app/data/marketplace/index.jsonindex 697c151aa..8124abbe9 100644--- a/services/api/app/data/marketplace/index.json+++ b/services/api/app/data/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-09-28T17:40:28Z",+ "generated": "2026-09-28T22:12:26Z","categories": [{"id": "playbooks",@@ -235424,33 +235424,6 @@"path": "playbooks/packs/v1/container-escape/container-escape-response.playbook.json","sha256": "9b06b45cb15df5b6fd9a186d4486c9ba75411fc3a72e2bea4fe3a0a7190c0440"},- {- "id": "container-escape-response-v1",- "type": "playbook",- "name": "Container Escape Response",- "description": "Responds to detected container escape attempts or privileged container misuse. Terminates the offending container, cordons the node, captures runtime forensics, and alerts the platform security team.",- "version": "1.0.0",- "author": "Beenu - [email protected]",- "tags": [- "container",- "kubernetes",- "docker",- "escape",- "runtime-security"- ],- "severity": "critical",- "trigger": null,- "steps": 8,- "category": "playbooks",- "mitre_techniques": [],- "verified": true,- "source": "core",- "tier": "stable",- "pack": false,- "enabled": true,- "path": "detections/playbooks/container-escape-response.yaml",- "sha256": "176f2c07b9553b44dd41d85b85b2a8e55c3a4e0f6e18ac22f0d4a3ff61d261aa"- },{"id": "critical-vulnerability-response-v1","type": "playbook",@@ -236696,6 +236669,60 @@"path": "detections/playbooks/s3-bucket-exposure-response.yaml","sha256": "260e61e4a08c5a30fcddb01364e62d26b5e67d8661a5db47c5a33586e4dee696"},+ {+ "id": "standalone-container-escape-response-v1",+ "type": "playbook",+ "name": "Container Escape Response",+ "description": "Responds to detected container escape attempts or privileged container misuse. Terminates the offending container, cordons the node, captures runtime forensics, and alerts the platform security team.",+ "version": "1.0.0",+ "author": "Beenu - [email protected]",+ "tags": [+ "container",+ "kubernetes",+ "docker",+ "escape",+ "runtime-security"+ ],+ "severity": "critical",+ "trigger": null,+ "steps": 8,+ "category": "playbooks",+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "pack": false,+ "enabled": true,+ "path": "detections/playbooks/container-escape-response.yaml",+ "sha256": "0391348632c3831ebdc5207f1b817844da10334e4ef214564af79b141e8ac42a"+ },+ {+ "id": "standalone-suspicious-signin-response-v1",+ "type": "playbook",+ "name": "Suspicious Sign-In Response",+ "description": "Responds to suspicious sign-in events including impossible travel, new country logins, known bad IP addresses, or sign-ins outside business hours. Triggers step-up authentication or session termination based on risk score.",+ "version": "1.0.0",+ "author": "Beenu - [email protected]",+ "tags": [+ "sign-in",+ "identity",+ "authentication",+ "impossible-travel",+ "conditional-access"+ ],+ "severity": "critical",+ "trigger": null,+ "steps": 8,+ "category": "playbooks",+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "pack": false,+ "enabled": true,+ "path": "detections/playbooks/suspicious-signin-response.yaml",+ "sha256": "91616904b93c07d67e6896b6a9c01e177439ff51d5969d23294ede2c2285b0d2"+ },{"id": "supply-chain-compromise-v1","type": "playbook",@@ -236881,33 +236908,6 @@"path": "playbooks/packs/v1/suspicious-signin/suspicious-signin-response.playbook.json","sha256": "f9475a1dcf7a0f93cb06a35bf567a08147b329fbc971cacd1e19ebeaac4a0e51"},- {- "id": "suspicious-signin-response-v1",- "type": "playbook",- "name": "Suspicious Sign-In Response",- "description": "Responds to suspicious sign-in events including impossible travel, new country logins, known bad IP addresses, or sign-ins outside business hours. Triggers step-up authentication or session termination based on risk score.",- "version": "1.0.0",- "author": "Beenu - [email protected]",- "tags": [- "sign-in",- "identity",- "authentication",- "impossible-travel",- "conditional-access"- ],- "severity": "critical",- "trigger": null,- "steps": 8,- "category": "playbooks",- "mitre_techniques": [],- "verified": true,- "source": "core",- "tier": "stable",- "pack": false,- "enabled": true,- "path": "detections/playbooks/suspicious-signin-response.yaml",- "sha256": "9c537ac853cef10087b88b56ba6bb401f2decae392a1dbd27118b9c02e3745f8"- },{"id": "token-theft-response-v1","type": "playbook",diff --git a/services/api/tests/test_marketplace_install_refuses_reference_only.py b/services/api/tests/test_marketplace_install_refuses_reference_only.pynew file mode 100644index 000000000..328670d81--- /dev/null+++ b/services/api/tests/test_marketplace_install_refuses_reference_only.py@@ -0,0 +1,118 @@+"""A reference-only rule must be refused by the endpoint, not only by the UI.++4,388 of the 7,155 catalogue entries are rules the detection engine does not+load. Installing one flips a per-tenant flag over a rule that can never match+— a no-op wearing the costume of an action, which is why the console renders+"Cannot install" and offers no button for them.++That was the *only* thing stopping it. Measured against a running stack, a+POST straight at ``/api/v1/marketplace/install`` for+``chronicle-detection-rules-a-scheduled-task-was-created`` — badged+REFERENCE ONLY in the console a moment earlier — answered **HTTP 200** and+recorded the install. The control was styled as prevented rather than+prevented, and anything not going through that particular button (a script,+the docs' curl example, a second console) walked straight past it.++Asserted in both directions: an executable entry must still install, or a+route that refuses everything would pass the first half of this file.+"""++from __future__ import annotations++import asyncio+import uuid+from collections.abc import Callable+from typing import Any++import pytest+from app.api.v1.endpoints import marketplace+from fastapi import HTTPException+++class _Principal:+ """The authenticated caller, reduced to the three fields install reads."""++ def __init__(self) -> None:+ self.tenant_id = uuid.UUID("00000000-0000-0000-0000-000000000001")+ self.user_id = uuid.uuid4()+ self.email = "[email protected]"+++def _index() -> dict[str, Any]:+ return marketplace._load_index()+++def _first(predicate: Callable[[dict[str, Any]], bool]) -> dict[str, Any]:+ # One exit, because `pytest.skip` raises and a trailing call to it reads+ # to a static analyser as a path that falls off the end without returning.+ items: list[dict[str, Any]] = _index().get("items") or []+ match: dict[str, Any] | None = next((item for item in items if predicate(item)), None)+ if match is None:+ # `pytest.skip()` raises, but it is not typed `NoReturn`, so a type+ # checker reads the line below as returning `None`. Raising the very+ # exception it raises says the same thing in a way both tools follow.+ raise pytest.skip.Exception("catalogue has no entry of this kind")+ return match+++def _install(item: dict[str, Any]):+ return asyncio.run(+ marketplace.install_marketplace_item(+ marketplace.InstallRequest(type=item["type"], id=item["id"]),+ _Principal(),+ )+ )++[email protected](autouse=True)+def _clean_install_store():+ marketplace._installed.clear()+ yield+ marketplace._installed.clear()+++class TestReferenceOnlyIsRefused:+ def test_the_catalogue_still_contains_reference_only_entries(self) -> None:+ """Without this the rest of the file could pass against an empty set."""+ count = sum(1 for i in _index()["items"] if i.get("executable") is False)+ assert count > 0, "no reference-only entries — this suite proves nothing"++ def test_installing_one_is_refused(self) -> None:+ item = _first(lambda i: i.get("executable") is False)+ with pytest.raises(HTTPException) as caught:+ _install(item)+ assert caught.value.status_code == 409+ assert "reference-only" in str(caught.value.detail).lower()++ def test_the_refusal_says_why(self) -> None:+ item = _first(lambda i: i.get("executable") is False and bool(i.get("quarantine_reason")))+ with pytest.raises(HTTPException) as caught:+ _install(item)+ assert item["quarantine_reason"] in str(caught.value.detail)++ def test_nothing_is_recorded_when_it_is_refused(self) -> None:+ # A refusal that still wrote the marker would leave the console+ # showing "Installed" for a rule that cannot fire.+ item = _first(lambda i: i.get("executable") is False)+ with pytest.raises(HTTPException):+ _install(item)+ assert marketplace._installed == {}+++class TestExecutableStillInstalls:+ def test_an_executable_rule_installs(self) -> None:+ # The other direction. Refusing everything would satisfy the class+ # above and break the marketplace.+ item = _first(lambda i: bool(i["type"] == "detection") and i.get("executable") is True)+ result = _install(item)+ assert result.id == item["id"]+ assert result.already_installed is False+ assert len(marketplace._installed) == 1++ def test_an_entry_with_no_executable_field_installs(self) -> None:+ # Playbooks and plugins are not engine rules and carry no+ # `executable`. `is False` rather than falsiness is what keeps them+ # installable, so pin it.+ item = _first(lambda i: bool(i["type"] == "playbook") and "executable" not in i)+ result = _install(item)+ assert result.id == item["id"]