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(web): read the MSSP console from the portfolio API, and close the gate that missed it (#801)
Beenu Arorad195f17d4958
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 48fe0290a..257e9befb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -137,6 +137,68 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The MSSP console showed six invented tenants and made no API call at all.**+ `MSSPDashboardView.tsx` declared `const TENANTS = [...]` — "Acme Financial",+ "GlobalRetail Corp", "MedSecure Health" and three more, with invented alert+ counts, MTTD/MTTR figures, risk scores, analyst headcounts and ARR — handed+ it to `useState`, and never fetched anything. Every operator on every+ deployment saw the same six rows, permanently, with no state in which they+ would not. The "Export Report" button raised a success toast and did nothing.++ It now reads `GET /api/v1/mssp/portfolio` and+ `GET /api/v1/mssp/portfolio/alerts` with no sample-data fallback and no SWR+ `fallbackData` (supplying it disables revalidation, so a placeholder becomes+ what the view permanently shows). Four states, each saying which it is:+ loading; a `403` explained as "you do not manage any tenants" rather than an+ outage; a portfolio failure surfaced with its message and a retry; and an+ empty portfolio that distinguishes "this organisation manages no tenants"+ from "you were granted none" using `portfolio_wide` and `scoped_tenants`,+ because those have different fixes. The alert feed has its own states so a+ failure there does not claim the portfolio is down. Export now writes a CSV+ of the rows on screen — a real action rather than a toast.++ **ARR, risk score and analyst allocation are gone, not sourced.** There is no+ revenue, composite-risk or analyst-allocation data anywhere in this product.+ A column of nulls would still imply the measurement exists.++- **The fabricated-data gate could not see either of the two worst cases.**+ `scripts/check_mock_data_gated.py` recognised only mock data that announces+ itself: all three of its patterns required a `MOCK_` / `DEMO_` name *and* an+ assignment through a state setter or SWR `fallbackData`, which models one+ situation — a view that fetches and substitutes a sample when the fetch+ fails. A dataset written inline under an ordinary name, in a component with+ no fetch at all, matched nothing; and with no fetch there was no real path+ for a fallback to fall back *from*, which is the worse defect, not the+ lesser one. The gate reported "All sample-data fallbacks are gated behind+ demo mode" while both fabricated tables shipped.++ A third check looks for what makes fabricated domain data harmful rather+ than for what an author happened to call it: a module-scope array of records+ that names an entity a customer would recognise — a company, a person, a+ host, an IP, an address — *and* attaches numbers to it. Numeric keys that+ describe how something is drawn are excluded, which is what keeps it quiet:+ 93 module-scope object arrays in the console, 7 matched, and the 4 already+ behind `demoFallback()` were the mocks. It newly caught+ `MSSPDashboardView.tsx` and `TeamAnalyticsView.tsx`.++ The reviewed-exception list is checked in **both** directions: an entry that+ no longer matches anything fails the gate, so an exemption cannot outlive the+ code it excused and become cover for whatever is written next under that+ name. One entry, `MitreStrip.tsx` — a public landing-page illustration whose+ visible copy already tells the reader the tiles are illustrative.+ `tests/test_mock_data_gate.py` covers both properties, including that filter+ lists, graph stylesheets, decorative SVG coordinates and pricing copy stay+ unflagged; a gate that cries wolf on every configuration array gets deleted,+ which is worse than the gap.++- **`/analytics/team` ranked six invented analysts by invented accuracy.**+ "Sarah Chen, 47 cases closed, 96.2% accuracy, score 945" and five more, plus+ a highlights feed of things that never happened. Nothing in the platform+ measures per-analyst performance — no route, no table, no column — so the+ sample is confined to the hosted demo via `canUseDemoData()` and everyone+ else is told plainly that the measurement does not exist yet. The aggregate+ tiles read `—` rather than dividing by zero.+- **The OpenAPI gate's documented escape hatch did not exist.** The workflowheader told a maintainer to "re-run with `--allow-breaking`" and`scripts/openapi_diff.py` claimed the flag was what "the release flow uses" —diff --git a/apps/docs/docs/concepts/multi-tenancy.md b/apps/docs/docs/concepts/multi-tenancy.mdindex acd78bd92..c8d587ffa 100644--- a/apps/docs/docs/concepts/multi-tenancy.md+++ b/apps/docs/docs/concepts/multi-tenancy.md@@ -109,6 +109,36 @@ tenant's own rows, and two consequences are worth stating plainly:excluded from the headline figures, so a demo install reads "0 real, 15synthetic" rather than reporting fixtures as a customer's posture.+## The console view++`/mssp` reads `GET /api/v1/mssp/portfolio` and+`GET /api/v1/mssp/portfolio/alerts` and shows nothing it did not receive.+There is no sample-data fallback: it has four states and each one tells you+which it is.++| State | What you see |+| --- | --- |+| Loading | "Loading portfolio…" and no figures at all |+| Not an operator (`403`) | "You do not manage any tenants", with how to be added |+| Portfolio API failed | The failure and its message, with a retry |+| Empty portfolio | Whether *the organisation* manages none, or *you* were granted none |++The two empty cases are distinguished by `portfolio_wide` and+`scoped_tenants` from the payload, because the fixes differ: one needs a+tenant to accept an invitation, the other needs an owner to grant you access.++The alert feed has its own states, so a failure there does not claim the+whole portfolio is down.++Columns are per-tenant open alerts, criticals, untriaged, open cases, cases+past SLA, MTTR, connector health and last event time — every one counted+from the tenant's own rows. An unmeasured MTTR renders as `—`, never `0`.++There is **no revenue, risk-score or analyst-allocation column**. The view+used to carry all three against six hardcoded companies. None of them has a+source anywhere in the product, so they are gone rather than nulled: a+column of blanks still implies the measurement exists.+## Limits and headroomA provider's most expensive failure is a quiet one. A tenant that hits a capdiff --git a/apps/web/src/components/analytics/TeamAnalyticsView.tsx b/apps/web/src/components/analytics/TeamAnalyticsView.tsxindex 96f959c26..4e8d0dec6 100644--- a/apps/web/src/components/analytics/TeamAnalyticsView.tsx+++ b/apps/web/src/components/analytics/TeamAnalyticsView.tsx@@ -3,6 +3,7 @@import { useState } from 'react';import { clsx } from 'clsx';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';+import { canUseDemoData } from '@/lib/demoFallback';interface Analyst {id: string;@@ -32,7 +33,7 @@ const BADGE_COLORS: Record<string, { bg: string; text: string; border: string }>'Newcomer Rising': { bg: 'bg-rose-500/15', text: 'text-rose-300', border: 'border-rose-500/30' },};-const ANALYSTS: Analyst[] = [+const SAMPLE_ANALYSTS: Analyst[] = [{ id: 'sc', name: 'Sarah Chen', initials: 'SC', avatarColor: 'bg-violet-500', casesClosed: 47, avgResolutionMin: 18, accuracy: 96.2, score: 945, badges: ['MITRE Master', 'Speed Demon'] },{ id: 'mr', name: 'Marcus Rivera', initials: 'MR', avatarColor: 'bg-sky-500', casesClosed: 42, avgResolutionMin: 22, accuracy: 94.8, score: 892, badges: ['Zero FP', 'Night Owl'] },{ id: 'ap', name: 'Aisha Patel', initials: 'AP', avatarColor: 'bg-emerald-500',casesClosed: 39, avgResolutionMin: 15, accuracy: 97.1, score: 878, badges: ['Precision Strike', 'MITRE Master'] },@@ -41,7 +42,7 @@ const ANALYSTS: Analyst[] = [{ id: 'dk', name: 'David Kim', initials: 'DK', avatarColor: 'bg-orange-500', casesClosed: 28, avgResolutionMin: 28, accuracy: 89.7, score: 721, badges: ['Newcomer Rising'] },];-const ACHIEVEMENTS: Achievement[] = [+const SAMPLE_ACHIEVEMENTS: Achievement[] = [{ text: 'Sarah Chen earned MITRE Master badge', timeAgo: '2 hours ago', icon: 'badge' },{ text: 'Marcus Rivera achieved Zero FP streak (30 days)', timeAgo: '5 hours ago', icon: 'streak' },{ text: 'Team closed 50 cases this week — new record!', timeAgo: '1 day ago', icon: 'record' },@@ -90,12 +91,20 @@ export function TeamAnalyticsView() {const [sortBy, setSortBy] = useState<SortKey>('score');const [search, setSearch] = useState('');- const totalCases = ANALYSTS.reduce((s, a) => s + a.casesClosed, 0);- const avgResolution = Math.round(ANALYSTS.reduce((s, a) => s + a.avgResolutionMin, 0) / ANALYSTS.length);- const teamAccuracy = (ANALYSTS.reduce((s, a) => s + a.accuracy, 0) / ANALYSTS.length).toFixed(1);- const totalBadges = ANALYSTS.reduce((s, a) => s + a.badges.length, 0);+ // Nothing in the platform measures per-analyst performance: there is no+ // route, no table and no column behind any of the figures below. Until one+ // exists this view has a shape and no source, so the sample is confined to+ // the hosted demo and everyone else gets told the truth.+ const analysts = canUseDemoData() ? SAMPLE_ANALYSTS : [];+ const achievements = canUseDemoData() ? SAMPLE_ACHIEVEMENTS : [];+ const hasData = analysts.length > 0;- const sorted = [...ANALYSTS]+ const totalCases = analysts.reduce((s, a) => s + a.casesClosed, 0);+ const avgResolution = hasData ? Math.round(analysts.reduce((s, a) => s + a.avgResolutionMin, 0) / analysts.length) : null;+ const teamAccuracy = hasData ? (analysts.reduce((s, a) => s + a.accuracy, 0) / analysts.length).toFixed(1) : null;+ const totalBadges = analysts.reduce((s, a) => s + a.badges.length, 0);++ const sorted = [...analysts].filter((a) => !search.trim() || a.name.toLowerCase().includes(search.toLowerCase())).sort((a, b) => {switch (sortBy) {@@ -123,10 +132,10 @@ export function TeamAnalyticsView() {{/* Aggregate stats */}<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">{[- { label: 'Cases Closed This Month', value: totalCases.toString(), accent: 'text-emerald-400' },- { label: 'Avg Resolution Time', value: `${avgResolution} min`, accent: 'text-sky-400' },- { label: 'Team Accuracy Rate', value: `${teamAccuracy}%`, accent: 'text-violet-400' },- { label: 'Total Badges Earned', value: totalBadges.toString(), accent: 'text-amber-400' },+ { label: 'Cases Closed This Month', value: hasData ? totalCases.toString() : '—', accent: 'text-emerald-400' },+ { label: 'Avg Resolution Time', value: avgResolution === null ? '—' : `${avgResolution} min`, accent: 'text-sky-400' },+ { label: 'Team Accuracy Rate', value: teamAccuracy === null ? '—' : `${teamAccuracy}%`, accent: 'text-violet-400' },+ { label: 'Total Badges Earned', value: hasData ? totalBadges.toString() : '—', accent: 'text-amber-400' },].map((stat) => (<div key={stat.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-5 space-y-4"><p className="text-xs font-medium uppercase tracking-wider text-gray-400">{stat.label}</p>@@ -165,7 +174,13 @@ export function TeamAnalyticsView() {</div></div>- {sorted.length === 0 ? (+ {!hasData ? (+ <EmptyState+ icon={EmptyStateIcons.search}+ title="No analyst performance data"+ description="AiSOC does not yet measure per-analyst cases closed, resolution time or accuracy, so there is nothing to rank. This view is a placeholder for that measurement rather than a report of it."+ />+ ) : sorted.length === 0 ? (<EmptyStateicon={EmptyStateIcons.search}title="No analysts match your search"@@ -263,8 +278,11 @@ export function TeamAnalyticsView() {{/* Team Highlights */}<div className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-5 space-y-4"><h2 className="text-lg font-semibold text-white">Team Highlights</h2>+ {achievements.length === 0 ? (+ <p className="text-sm text-gray-500">No team milestones are recorded yet.</p>+ ) : (<div className="space-y-3">- {ACHIEVEMENTS.map((ach, i) => (+ {achievements.map((ach, i) => (<divkey={i}className="flex items-start gap-3 rounded-lg border border-gray-800/40 bg-black/20 p-3.5"@@ -279,6 +297,7 @@ export function TeamAnalyticsView() {</div>))}</div>+ )}</div></div>);diff --git a/apps/web/src/components/mssp/MSSPDashboardView.test.tsx b/apps/web/src/components/mssp/MSSPDashboardView.test.tsxnew file mode 100644index 000000000..2e673a3b8--- /dev/null+++ b/apps/web/src/components/mssp/MSSPDashboardView.test.tsx@@ -0,0 +1,302 @@+/**+ * Data-honesty gate for the managed-portfolio console.+ *+ * This view was a hardcoded table of six companies with invented alert counts,+ * MTTD/MTTR figures, risk scores, analyst headcounts and ARR, and it made no+ * API call at all. Every operator on every deployment saw the same six rows.+ *+ * The tests assert on **first paint** as well as the error branch. The error+ * branch returns early, so a regression injected there is unreachable from the+ * states that matter — and first paint (data undefined, no error yet) is+ * exactly where the previous generation of this bug lived across the console:+ * sample data wrapped in `demoFallback()` and then reinstated by+ * `const resolved = isValid ? data : MOCK`.+ *+ * The assertions are negative — these strings must never reach the DOM — which+ * is the form that stays meaningful as the component grows.+ */++import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import { cleanup, render, screen } from '@testing-library/react';++const swrData = vi.hoisted(() => new Map<string, unknown>());+const swrErrors = vi.hoisted(() => new Map<string, unknown>());++vi.mock('swr', () => ({+ __esModule: true,+ default: (key: unknown) => {+ const k = typeof key === 'string' ? key : JSON.stringify(key);+ return {+ data: swrData.get(k),+ error: swrErrors.get(k),+ isLoading: !swrData.has(k) && !swrErrors.has(k),+ mutate: vi.fn(),+ };+ },+}));++// `ApiError` must be the same class the component's `instanceof` sees, so the+// mock owns it rather than re-exporting a second copy.+const apiMock = vi.hoisted(() => {+ class ApiError extends Error {+ status: number;+ body: string;+ constructor(message: string, status: number, body = '') {+ super(message);+ this.name = 'ApiError';+ this.status = status;+ this.body = body;+ }+ }+ return { ApiError };+});++vi.mock('@/lib/api', () => ({+ __esModule: true,+ ApiError: apiMock.ApiError,+ msspApi: {+ getPortfolio: vi.fn(),+ listPortfolioAlerts: vi.fn(),+ },+}));++vi.mock('next/link', () => ({+ __esModule: true,+ default: ({ children, href }: { children: React.ReactNode; href: string }) => <a href={href}>{children}</a>,+}));++import { ApiError } from '@/lib/api';+import MSSPDashboardView from './MSSPDashboardView';++/** Verbatim from the `TENANTS` array this view used to render. */+const FABRICATED_TENANTS = [+ 'Acme Financial',+ 'GlobalRetail Corp',+ 'MedSecure Health',+ 'NovaTech Industries',+ 'Pinnacle Energy',+ 'Stratos Logistics',+];++/** The invented revenue figures, and the columns that had no source at all. */+const FABRICATED_FIGURES = ['Total ARR', '$1290K', '$185K', 'Risk Score', 'Analysts', 'MTTD'];++function expectNoFabrication() {+ for (const name of [...FABRICATED_TENANTS, ...FABRICATED_FIGURES]) {+ expect(+ screen.queryByText(new RegExp(name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')),+ `"${name}" was fabricated and must never render`,+ ).toBeNull();+ }+}++const REAL_TENANT = {+ tenant_id: '11111111-1111-1111-1111-111111111111',+ name: 'Northwind Manufacturing',+ slug: 'northwind',+ relationship: 'owner',+ is_active: true,+ open_alerts: 7,+ critical_alerts: 2,+ high_alerts: 3,+ untriaged_alerts: 4,+ synthetic_alerts: 0,+ open_cases: 3,+ sla_breached_cases: 1,+ mttr_minutes: 45,+ connectors: { total: 4, healthy: 3, stale: 1, error: 0 },+ last_event_at: '2026-09-20T10:00:00Z',+ limits: [],+ limits_exhausted: 0,+ limits_warning: 0,+};++const REAL_SUMMARY = {+ tenants: 1,+ tenants_active: 1,+ open_alerts: 7,+ critical_alerts: 2,+ high_alerts: 3,+ untriaged_alerts: 4,+ synthetic_alerts: 0,+ open_cases: 3,+ sla_breached_cases: 1,+ mttr_minutes: 45,+ connectors_total: 4,+ connectors_healthy: 3,+ connectors_stale: 1,+ connectors_error: 0,+ tenants_with_exhausted_limits: 0,+ tenants_with_limit_warnings: 0,+ tenants_without_connectors: 0,+};++function portfolio(overrides: Record<string, unknown> = {}) {+ return {+ org_id: '22222222-2222-2222-2222-222222222222',+ org_slug: 'acme-mssp',+ org_name: 'Example Operator',+ org_role: 'owner',+ portfolio_wide: true,+ scoped_tenants: 1,+ summary: REAL_SUMMARY,+ tenants: [REAL_TENANT],+ ...overrides,+ };+}++beforeEach(() => {+ swrData.clear();+ swrErrors.clear();+});++afterEach(() => cleanup());++describe('first paint — before any response has arrived', () => {+ it('renders a loading state rather than a table of invented tenants', () => {+ // Nothing seeded: `data` is undefined and there is no error, which is the+ // state the old code filled with six hardcoded companies.+ render(<MSSPDashboardView />);++ expectNoFabrication();+ expect(screen.getByRole('status')).toBeTruthy();+ expect(screen.getByText(/Loading portfolio/i)).toBeTruthy();+ });++ it('publishes no summary figures it has not received', () => {+ render(<MSSPDashboardView />);++ // The old KPI strip computed these from the hardcoded array.+ expect(screen.queryByText('6')).toBeNull();+ expect(screen.queryByText('31')).toBeNull();+ expect(screen.queryByText('67%')).toBeNull();+ });+});++describe('the API failed', () => {+ it('surfaces the failure instead of substituting sample data', () => {+ swrErrors.set('mssp-portfolio', new Error('503 Service Unavailable'));++ render(<MSSPDashboardView />);++ expectNoFabrication();+ expect(screen.getAllByText(/503 Service Unavailable/i).length).toBeGreaterThan(0);+ });+});++describe('the caller manages no tenants', () => {+ it('explains the 403 rather than reporting an outage', () => {+ swrErrors.set('mssp-portfolio', new ApiError('API 403 Forbidden', 403, ''));++ render(<MSSPDashboardView />);++ expect(screen.getByText(/You do not manage any tenants/i)).toBeTruthy();+ // A 403 here is a statement about the caller, not a broken backend.+ expect(screen.queryByRole('alert')).toBeNull();+ expectNoFabrication();+ });+});++describe('the portfolio is real but empty', () => {+ it('distinguishes an organisation with no tenants from a member with no grants', () => {+ swrData.set('mssp-portfolio', portfolio({ tenants: [], scoped_tenants: 0, summary: { ...REAL_SUMMARY, tenants: 0 } }));+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ expect(screen.getByText(/This organisation manages no tenants yet/i)).toBeTruthy();+ expectNoFabrication();+ });++ it('tells a scoped member their grants are empty, not that the org is', () => {+ swrData.set(+ 'mssp-portfolio',+ portfolio({ tenants: [], scoped_tenants: 0, portfolio_wide: false, summary: { ...REAL_SUMMARY, tenants: 0 } }),+ );+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ expect(screen.getByText(/You have not been granted access to any tenants/i)).toBeTruthy();+ });+});++describe('real data', () => {+ it('renders the tenants the API returned and nothing else', () => {+ swrData.set('mssp-portfolio', portfolio());+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ expect(screen.getByText('Northwind Manufacturing')).toBeTruthy();+ expect(screen.getByText('Example Operator')).toBeTruthy();+ expectNoFabrication();+ });++ it('shows an unmeasured MTTR as not-measured, never as zero', () => {+ swrData.set(+ 'mssp-portfolio',+ portfolio({+ tenants: [{ ...REAL_TENANT, mttr_minutes: null }],+ summary: { ...REAL_SUMMARY, mttr_minutes: null },+ }),+ );+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ // 0m would rank a tenant that has closed nothing top of the table.+ expect(screen.queryByText('0m')).toBeNull();+ expect(screen.getAllByText('—').length).toBeGreaterThan(0);+ });++ it('counts seeded demo rows apart from the tenant posture', () => {+ swrData.set(+ 'mssp-portfolio',+ portfolio({+ tenants: [{ ...REAL_TENANT, synthetic_alerts: 15 }],+ summary: { ...REAL_SUMMARY, synthetic_alerts: 15 },+ }),+ );+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ // Both the per-tenant badge and the portfolio banner say so.+ expect(screen.getAllByText(/15 seeded/i).length).toBeGreaterThan(0);+ expect(screen.getByText(/counted separately/i)).toBeTruthy();+ });++ it('never renders a revenue column, because no revenue data exists', () => {+ swrData.set('mssp-portfolio', portfolio());+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ expect(screen.queryByText(/ARR/)).toBeNull();+ expect(screen.queryByText(/\$\d/)).toBeNull();+ });+});++describe('the alert feed has its own states', () => {+ it('reports its own failure without claiming the portfolio failed', () => {+ swrData.set('mssp-portfolio', portfolio());+ swrErrors.set('mssp-portfolio-alerts', new Error('alert feed timeout'));++ render(<MSSPDashboardView />);++ expect(screen.getByText('Northwind Manufacturing')).toBeTruthy();+ expect(screen.getByText(/alert feed timeout/i)).toBeTruthy();+ });++ it('says there are no open alerts rather than inventing incidents', () => {+ swrData.set('mssp-portfolio', portfolio());+ swrData.set('mssp-portfolio-alerts', []);++ render(<MSSPDashboardView />);++ expect(screen.getByText(/No open alerts/i)).toBeTruthy();+ // Names from the deleted CrossTenantIncident sample.+ expect(screen.queryByText(/Wayne Enterprises/i)).toBeNull();+ });+});diff --git a/apps/web/src/components/mssp/MSSPDashboardView.tsx b/apps/web/src/components/mssp/MSSPDashboardView.tsxindex 2903f5e7f..38a24e0bb 100644--- a/apps/web/src/components/mssp/MSSPDashboardView.tsx+++ b/apps/web/src/components/mssp/MSSPDashboardView.tsx@@ -1,117 +1,317 @@'use client';-import { useState } from 'react';+/**+ * Managed portfolio console, read from `/api/v1/mssp/portfolio`.+ *+ * This view used to be a hardcoded table of six companies — "Acme Financial",+ * "GlobalRetail Corp" — with invented alert counts, MTTD/MTTR figures, risk+ * scores, analyst headcounts and ARR. It made no API call at all, so what an+ * operator saw was the same six rows on every deployment, including their own.+ *+ * Two of those columns could not be sourced and are gone rather than nulled:+ * there is no revenue data anywhere in this product, and no analyst-allocation+ * or composite risk score either. Inventing a number is worse than omitting it;+ * a column of nulls would still imply the measurement exists.+ *+ * Nothing here falls back to sample data. First paint renders a loading state,+ * a failure renders the failure, and an empty portfolio says so — because those+ * are the three states a self-hoster with a fresh backend actually spends their+ * time in, and each is a different problem with a different fix.+ */++import { useMemo, useState } from 'react';+import useSWR from 'swr';import { clsx } from 'clsx';-import toast from 'react-hot-toast';+import Link from 'next/link';+import { ApiError, msspApi, type Portfolio, type PortfolioAlert, type PortfolioTenant } from '@/lib/api';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';+import { ErrorState } from '@/components/ui/ErrorState';-interface Tenant {- name: string;- activeAlerts: number;- openCases: number;- mttd: number;- mttr: number;- riskScore: number;- slaStatus: 'compliant' | 'warning' | 'breach';- arr: number;- analystAllocation: number;-}+type TenantFilter = 'all' | 'critical' | 'sla' | 'no-connectors';-const TENANTS: Tenant[] = [- { name: 'Acme Financial', activeAlerts: 12, openCases: 3, mttd: 4.2, mttr: 28, riskScore: 72, slaStatus: 'compliant', arr: 185000, analystAllocation: 2 },- { name: 'GlobalRetail Corp', activeAlerts: 47, openCases: 11, mttd: 8.7, mttr: 65, riskScore: 89, slaStatus: 'breach', arr: 320000, analystAllocation: 4 },- { name: 'MedSecure Health', activeAlerts: 8, openCases: 2, mttd: 3.1, mttr: 19, riskScore: 45, slaStatus: 'compliant', arr: 140000, analystAllocation: 1 },- { name: 'NovaTech Industries',activeAlerts: 23, openCases: 6, mttd: 6.5, mttr: 42, riskScore: 78, slaStatus: 'warning', arr: 260000, analystAllocation: 3 },- { name: 'Pinnacle Energy', activeAlerts: 5, openCases: 1, mttd: 2.8, mttr: 15, riskScore: 31, slaStatus: 'compliant', arr: 110000, analystAllocation: 1 },- { name: 'Stratos Logistics', activeAlerts: 31, openCases: 8, mttd: 7.9, mttr: 55, riskScore: 84, slaStatus: 'warning', arr: 275000, analystAllocation: 3 },+const FILTERS: { key: TenantFilter; label: string; hint: string }[] = [+ { key: 'all', label: 'All', hint: 'Every tenant in the portfolio' },+ { key: 'critical', label: 'Critical alerts', hint: 'At least one open critical alert' },+ { key: 'sla', label: 'SLA breached', hint: 'At least one case past its SLA' },+ { key: 'no-connectors', label: 'No connectors', hint: 'No data source connected' },];-const SLA_STYLES: Record<Tenant['slaStatus'], { bg: string; text: string; label: string }> = {- compliant: { bg: 'bg-green-500/20', text: 'text-green-400', label: 'Compliant' },- warning: { bg: 'bg-amber-500/20', text: 'text-amber-400', label: 'Warning' },- breach: { bg: 'bg-red-500/20', text: 'text-red-400', label: 'Breach' },+function matches(tenant: PortfolioTenant, filter: TenantFilter): boolean {+ switch (filter) {+ case 'all':+ return true;+ case 'critical':+ return tenant.critical_alerts > 0;+ case 'sla':+ return tenant.sla_breached_cases > 0;+ case 'no-connectors':+ return tenant.connectors.total === 0;+ default: {+ const exhaustive: never = filter;+ return exhaustive;+ }+ }+}++/** `null` means "not measured", which must never render as a confident 0. */+function formatMinutes(value: number | null): string {+ if (value === null || value === undefined) return '—';+ if (value < 60) return `${Math.round(value)}m`;+ return `${(value / 60).toFixed(1)}h`;+}++function formatTimestamp(value: string | null): string {+ if (!value) return 'No events yet';+ const parsed = new Date(value);+ if (Number.isNaN(parsed.getTime())) return '—';+ return parsed.toLocaleString();+}++const SEVERITY_STYLES: Record<string, string> = {+ critical: 'bg-red-500/20 text-red-300',+ high: 'bg-orange-500/20 text-orange-300',+ medium: 'bg-amber-500/20 text-amber-300',+ low: 'bg-sky-500/20 text-sky-300',+ info: 'bg-gray-500/20 text-gray-300',};-function kpiCards(tenants: Tenant[]) {- const totalTenants = tenants.length;- const totalOpenCases = tenants.reduce((s, t) => s + t.openCases, 0);- const avgMTTD = tenants.reduce((s, t) => s + t.mttd, 0) / totalTenants;- const avgMTTR = tenants.reduce((s, t) => s + t.mttr, 0) / totalTenants;- const compliant = tenants.filter((t) => t.slaStatus === 'compliant').length;- const slaCompliance = Math.round((compliant / totalTenants) * 100);- const totalARR = tenants.reduce((s, t) => s + t.arr, 0);+function connectorTone(tenant: PortfolioTenant): string {+ if (tenant.connectors.total === 0) return 'text-gray-500';+ if (tenant.connectors.error > 0) return 'text-red-400';+ if (tenant.connectors.stale > 0) return 'text-amber-400';+ return 'text-green-400';+}- return [- { label: 'Total Tenants', value: totalTenants },- { label: 'Total Open Cases', value: totalOpenCases },- { label: 'Avg MTTD', value: `${avgMTTD.toFixed(1)} min` },- { label: 'Avg MTTR', value: `${avgMTTR.toFixed(0)} min` },- { label: 'SLA Compliance', value: `${slaCompliance}%` },- { label: 'Total ARR', value: `$${(totalARR / 1000).toFixed(0)}K` },+/**+ * CSV of exactly the rows on screen, built from data already in memory.+ *+ * The button here used to raise a success toast and do nothing else. A control+ * that reports success without acting is worse than no control.+ */+function downloadCsv(rows: PortfolioTenant[]): void {+ const header = [+ 'tenant',+ 'slug',+ 'active',+ 'open_alerts',+ 'critical_alerts',+ 'high_alerts',+ 'untriaged_alerts',+ 'synthetic_alerts',+ 'open_cases',+ 'sla_breached_cases',+ 'mttr_minutes',+ 'connectors_total',+ 'connectors_healthy',+ 'connectors_stale',+ 'connectors_error',+ 'last_event_at',];+ const escape = (value: string | number | boolean | null): string => {+ if (value === null || value === undefined) return '';+ const text = String(value);+ return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;+ };+ const body = rows.map((t) =>+ [+ t.name,+ t.slug,+ t.is_active,+ t.open_alerts,+ t.critical_alerts,+ t.high_alerts,+ t.untriaged_alerts,+ t.synthetic_alerts,+ t.open_cases,+ t.sla_breached_cases,+ t.mttr_minutes,+ t.connectors.total,+ t.connectors.healthy,+ t.connectors.stale,+ t.connectors.error,+ t.last_event_at,+ ]+ .map(escape)+ .join(','),+ );+ const blob = new Blob([[header.join(','), ...body].join('\n')], { type: 'text/csv;charset=utf-8;' });+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = `portfolio-${new Date().toISOString().slice(0, 10)}.csv`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);}-type SLAFilter = 'all' | 'compliant' | 'warning' | 'breach';+function summaryCards(portfolio: Portfolio): { label: string; value: string; hint?: string }[] {+ const s = portfolio.summary;+ return [+ { label: 'Tenants', value: String(s.tenants), hint: `${s.tenants_active} active` },+ { label: 'Open alerts', value: String(s.open_alerts), hint: `${s.critical_alerts} critical, ${s.high_alerts} high` },+ { label: 'Untriaged', value: String(s.untriaged_alerts), hint: 'Awaiting a first verdict' },+ { label: 'Open cases', value: String(s.open_cases), hint: `${s.sla_breached_cases} past SLA` },+ { label: 'MTTR', value: formatMinutes(s.mttr_minutes), hint: 'Cases closed in the last 30 days' },+ {+ label: 'Connectors',+ value: `${s.connectors_healthy}/${s.connectors_total}`,+ hint: s.connectors_total === 0 ? 'None connected' : `${s.connectors_stale} stale, ${s.connectors_error} error`,+ },+ ];+}export default function MSSPDashboardView() {- const [tenants] = useState(TENANTS);- const [slaFilter, setSlaFilter] = useState<SLAFilter>('all');- const cards = kpiCards(tenants);+ const [filter, setFilter] = useState<TenantFilter>('all');++ // No `fallbackData`: supplying it disables SWR revalidation, so a placeholder+ // becomes what the view permanently shows rather than a first paint.+ const {+ data: portfolio,+ error: portfolioError,+ isLoading,+ mutate,+ } = useSWR<Portfolio>('mssp-portfolio', () => msspApi.getPortfolio(), { refreshInterval: 60_000 });++ const { data: alerts, error: alertsError } = useSWR<PortfolioAlert[]>('mssp-portfolio-alerts', () =>+ msspApi.listPortfolioAlerts({ limit: 25 }),+ );++ const tenants = useMemo(() => portfolio?.tenants ?? [], [portfolio]);+ const visible = useMemo(() => tenants.filter((t) => matches(t, filter)), [tenants, filter]);++ const notAMember = portfolioError instanceof ApiError && portfolioError.status === 403;++ const header = (+ <div>+ <h1 className="text-2xl font-bold text-white">Managed portfolio</h1>+ <p className="text-gray-400 mt-1">+ {portfolio?.org_name ? (+ <>+ Tenants managed by{' '}+ <span className="text-gray-200">{portfolio.org_name}</span>+ </>+ ) : (+ 'Security posture across the tenants you manage'+ )}+ </p>+ </div>+ );++ if (notAMember) {+ return (+ <div className="space-y-8 p-6 max-w-7xl mx-auto">+ {header}+ <EmptyState+ icon={EmptyStateIcons.shield}+ title="You do not manage any tenants"+ description="This view is for operators who manage tenants on behalf of others. Your account belongs to no operator organisation, so there is no portfolio to show. An organisation owner can add you from their settings."+ />+ </div>+ );+ }++ if (portfolioError) {+ return (+ <div className="space-y-8 p-6 max-w-7xl mx-auto">+ {header}+ <ErrorState+ title="Could not load the portfolio"+ description="The portfolio API did not answer. Nothing below is being substituted for it."+ error={portfolioError}+ onRetry={() => void mutate()}+ />+ </div>+ );+ }- const filteredTenants = slaFilter === 'all' ? tenants : tenants.filter((t) => t.slaStatus === slaFilter);+ if (isLoading || !portfolio) {+ return (+ <div className="space-y-8 p-6 max-w-7xl mx-auto">+ {header}+ <p className="text-sm text-gray-500" role="status">+ Loading portfolio…+ </p>+ </div>+ );+ }++ const hasTenants = tenants.length > 0;return (<div className="space-y-8 p-6 max-w-7xl mx-auto">- <div>- <h1 className="text-2xl font-bold text-white">MSSP Executive Dashboard</h1>- <p className="text-gray-400 mt-1">Cross-tenant security operations overview</p>- </div>+ {header}++ {portfolio.summary.synthetic_alerts > 0 && (+ <p className="rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-2 text-sm text-amber-300">+ {portfolio.summary.synthetic_alerts} seeded demo alert(s) are counted separately and excluded from the+ figures above.+ </p>+ )}- {/* KPI Cards */}<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">- {cards.map((c) => (+ {summaryCards(portfolio).map((c) => (<div key={c.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4"><p className="text-xs text-gray-400 uppercase tracking-wider">{c.label}</p><p className="mt-1 text-2xl font-semibold text-white">{c.value}</p>+ {c.hint && <p className="mt-1 text-xs text-gray-500">{c.hint}</p>}</div>))}</div>- {/* Tenant Table */}- <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">+ <section className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden"><div className="px-5 py-4 border-b border-gray-800/60 flex flex-wrap items-center justify-between gap-3">- <h2 className="text-lg font-semibold text-white">Tenant Overview</h2>+ <h2 className="text-lg font-semibold text-white">Tenants</h2><div className="flex items-center gap-3">- <span className="text-xs font-medium uppercase tracking-wider text-gray-500">SLA</span>- {(['all', 'compliant', 'warning', 'breach'] as SLAFilter[]).map((f) => (+ {FILTERS.map((f) => (<button- key={f}- onClick={() => setSlaFilter(f)}+ key={f.key}+ type="button"+ title={f.hint}+ aria-pressed={filter === f.key}+ onClick={() => setFilter(f.key)}className={clsx(- 'rounded-md px-2.5 py-1 text-xs font-medium capitalize transition',- slaFilter === f ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300',+ 'rounded-md px-2.5 py-1 text-xs font-medium transition',+ filter === f.key ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300',)}>- {f}+ {f.label}</button>))}<button- onClick={() => toast.success('Report exported for all tenants')}- className="text-sm px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-500 text-white transition-colors"+ type="button"+ disabled={visible.length === 0}+ onClick={() => downloadCsv(visible)}+ className="text-sm px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-500 disabled:opacity-40 disabled:hover:bg-blue-600 text-white transition-colors">- Export Report+ Export CSV</button></div></div>- {filteredTenants.length === 0 ? (++ {!hasTenants ? (<EmptyStateicon={EmptyStateIcons.shield}- title="No tenants match this SLA filter"- description="Try a different status filter to view tenants."+ title={+ portfolio.portfolio_wide+ ? 'This organisation manages no tenants yet'+ : 'You have not been granted access to any tenants'+ }+ description={+ portfolio.portfolio_wide+ ? 'Once a tenant accepts an invitation from this organisation, its posture appears here.'+ : 'Your role reaches only the tenants explicitly granted to you, and none have been. An organisation owner can grant them from their settings.'+ }+ />+ ) : visible.length === 0 ? (+ <EmptyState+ icon={EmptyStateIcons.shield}+ title="No tenants match this filter"+ description="Every tenant in the portfolio is outside the selected filter."action={<buttontype="button"- onClick={() => setSlaFilter('all')}+ onClick={() => setFilter('all')}className="rounded-lg bg-gray-800 px-4 py-2 text-sm text-gray-200 hover:bg-gray-700 transition-colors">Show all tenants@@ -119,49 +319,98 @@ export default function MSSPDashboardView() {}/>) : (- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b border-gray-800/60 text-left text-gray-400">- <th className="px-5 py-3 font-medium">Tenant</th>- <th className="px-5 py-3 font-medium text-right">Active Alerts</th>- <th className="px-5 py-3 font-medium text-right">Open Cases</th>- <th className="px-5 py-3 font-medium text-right">MTTD (min)</th>- <th className="px-5 py-3 font-medium text-right">MTTR (min)</th>- <th className="px-5 py-3 font-medium text-right">Risk Score</th>- <th className="px-5 py-3 font-medium text-right">ARR</th>- <th className="px-5 py-3 font-medium text-right">Analysts</th>- <th className="px-5 py-3 font-medium text-center">SLA Status</th>- </tr>- </thead>- <tbody>- {filteredTenants.map((t) => {- const sla = SLA_STYLES[t.slaStatus];- return (- <tr key={t.name} className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">- <td className="px-5 py-3 font-medium text-white">{t.name}</td>- <td className="px-5 py-3 text-right text-gray-300">{t.activeAlerts}</td>- <td className="px-5 py-3 text-right text-gray-300">{t.openCases}</td>- <td className="px-5 py-3 text-right text-gray-300">{t.mttd.toFixed(1)}</td>- <td className="px-5 py-3 text-right text-gray-300">{t.mttr}</td>- <td className={clsx('px-5 py-3 text-right font-medium', t.riskScore >= 80 ? 'text-red-400' : t.riskScore >= 60 ? 'text-amber-400' : 'text-green-400')}>- {t.riskScore}+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-gray-800/60 text-left text-gray-400">+ <th scope="col" className="px-5 py-3 font-medium">Tenant</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">Open alerts</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">Critical</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">Untriaged</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">Open cases</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">Past SLA</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">MTTR</th>+ <th scope="col" className="px-5 py-3 font-medium text-right">Connectors</th>+ <th scope="col" className="px-5 py-3 font-medium">Last event</th>+ </tr>+ </thead>+ <tbody>+ {visible.map((t) => (+ <tr key={t.tenant_id} className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">+ <td className="px-5 py-3 font-medium text-white">+ {t.name}+ {!t.is_active && <span className="ml-2 text-xs text-gray-500">(inactive)</span>}+ {t.synthetic_alerts > 0 && (+ <span className="ml-2 rounded px-1.5 py-0.5 text-[10px] uppercase tracking-wide bg-amber-500/15 text-amber-300">+ {t.synthetic_alerts} seeded+ </span>+ )}+ </td>+ <td className="px-5 py-3 text-right text-gray-300">{t.open_alerts}</td>+ <td className={clsx('px-5 py-3 text-right font-medium', t.critical_alerts > 0 ? 'text-red-400' : 'text-gray-500')}>+ {t.critical_alerts}+ </td>+ <td className="px-5 py-3 text-right text-gray-300">{t.untriaged_alerts}</td>+ <td className="px-5 py-3 text-right text-gray-300">{t.open_cases}</td>+ <td className={clsx('px-5 py-3 text-right', t.sla_breached_cases > 0 ? 'text-amber-400' : 'text-gray-500')}>+ {t.sla_breached_cases}</td>- <td className="px-5 py-3 text-right text-gray-300">${(t.arr / 1000).toFixed(0)}K</td>- <td className="px-5 py-3 text-right text-gray-300">{t.analystAllocation}</td>- <td className="px-5 py-3 text-center">- <span className={clsx('inline-block px-2.5 py-0.5 rounded-full text-xs font-medium', sla.bg, sla.text)}>- {sla.label}- </span>+ <td className="px-5 py-3 text-right text-gray-300">{formatMinutes(t.mttr_minutes)}</td>+ <td className={clsx('px-5 py-3 text-right', connectorTone(t))}>+ {t.connectors.total === 0 ? 'None' : `${t.connectors.healthy}/${t.connectors.total}`}</td>+ <td className="px-5 py-3 text-gray-400">{formatTimestamp(t.last_event_at)}</td></tr>- );- })}- </tbody>- </table>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </section>++ <section className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">+ <div className="px-5 py-4 border-b border-gray-800/60">+ <h2 className="text-lg font-semibold text-white">Open alerts across the portfolio</h2></div>+ {alertsError ? (+ <ErrorState+ title="Could not load portfolio alerts"+ description="The alert feed did not answer. No placeholder is being shown in its place."+ error={alertsError}+ className="m-5"+ />+ ) : !alerts ? (+ <p className="px-5 py-6 text-sm text-gray-500" role="status">+ Loading alerts…+ </p>+ ) : alerts.length === 0 ? (+ <EmptyState+ icon={EmptyStateIcons.alert}+ title="No open alerts"+ description="No tenant in this portfolio has an open alert right now."+ />+ ) : (+ <ul className="divide-y divide-gray-800/40">+ {alerts.map((a) => (+ <li key={a.alert_id} className="px-5 py-3 flex items-center gap-4">+ <span+ className={clsx(+ 'rounded-full px-2.5 py-0.5 text-xs font-medium capitalize shrink-0',+ SEVERITY_STYLES[a.severity] ?? SEVERITY_STYLES.info,+ )}+ >+ {a.severity}+ </span>+ <Link href={`/alerts/${a.alert_id}`} className="text-sm text-gray-200 hover:text-white truncate">+ {a.title}+ </Link>+ <span className="ml-auto text-xs text-gray-500 shrink-0">{a.tenant_name}</span>+ <span className="text-xs text-gray-600 shrink-0">{formatTimestamp(a.event_time ?? a.created_at)}</span>+ </li>+ ))}+ </ul>)}- </div>+ </section></div>);}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 0fd2140a7..8f68aa31e 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -429,10 +429,125 @@ export const tenantsApi = {},};+// The managed-portfolio read surface. Every figure below is counted from the+// tenant's own rows by `services/api/app/services/mssp_portfolio.py`; there is+// no revenue, risk-score or analyst-allocation data anywhere in this product,+// so the console does not have columns for them.++export interface PortfolioConnectorHealth {+ total: number;+ healthy: number;+ stale: number;+ error: number;+}++export interface PortfolioLimitHeadroom {+ key: string;+ label: string;+ used: number;+ limit: number | null;+ remaining: number | null;+ pct_used: number | null;+ /** unlimited | ok | warning | exhausted */+ state: string;+}++export interface PortfolioTenant {+ tenant_id: string;+ name: string;+ slug: string;+ relationship: string;+ is_active: boolean;+ open_alerts: number;+ critical_alerts: number;+ high_alerts: number;+ untriaged_alerts: number;+ /** Seeded demo rows, counted apart from the figures above. */+ synthetic_alerts: number;+ open_cases: number;+ sla_breached_cases: number;+ /** Null when this tenant closed no cases in the trailing window. */+ mttr_minutes: number | null;+ connectors: PortfolioConnectorHealth;+ last_event_at: string | null;+ limits: PortfolioLimitHeadroom[];+ limits_exhausted: number;+ limits_warning: number;+}++export interface PortfolioSummary {+ tenants: number;+ tenants_active: number;+ open_alerts: number;+ critical_alerts: number;+ high_alerts: number;+ untriaged_alerts: number;+ synthetic_alerts: number;+ open_cases: number;+ sla_breached_cases: number;+ mttr_minutes: number | null;+ connectors_total: number;+ connectors_healthy: number;+ connectors_stale: number;+ connectors_error: number;+ tenants_with_exhausted_limits: number;+ tenants_with_limit_warnings: number;+ tenants_without_connectors: number;+}++export interface Portfolio {+ org_id: string | null;+ org_slug: string | null;+ org_name: string | null;+ org_role: string | null;+ /** True when the caller's role reaches the whole portfolio rather than explicit grants. */+ portfolio_wide: boolean;+ /**+ * How many tenants the caller is scoped to. Distinguishes "your organisation+ * manages none" from "you were granted none" — different problems, and a bare+ * zero row count tells them apart for nobody.+ */+ scoped_tenants: number;+ summary: PortfolioSummary;+ tenants: PortfolioTenant[];+}++export interface PortfolioAlert {+ alert_id: string;+ tenant_id: string;+ tenant_name: string;+ title: string;+ severity: string;+ status: string;+ category: string | null;+ created_at: string | null;+ event_time: string | null;+ case_id: string | null;+ is_synthetic: boolean;+}+export const msspApi = {async listChildren(): Promise<ChildTenant[]> {return request<ChildTenant[]>('/api/v1/mssp/children');},++ /**+ * Managed portfolio: per-tenant posture plus derived totals.+ *+ * Throws `ApiError` with status 403 when the caller belongs to no operator+ * organisation. That is not an error state in the console — cross-tenant+ * reads simply are not theirs to make — so callers should branch on it.+ */+ async getPortfolio(): Promise<Portfolio> {+ return request<Portfolio>('/api/v1/mssp/portfolio');+ },++ /** Open alerts across the portfolio. Excludes seeded demo rows by default. */+ async listPortfolioAlerts(params: { severity?: string; limit?: number } = {}): Promise<PortfolioAlert[]> {+ return request<PortfolioAlert[]>('/api/v1/mssp/portfolio/alerts', {+ params: { severity: params.severity, limit: params.limit ?? 25 },+ });+ },};// ─── Alerts ─────────────────────────────────────────────────────────────────diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 904aca774..a1e4ad1d7 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -84,7 +84,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Entity-graph reads are scoped to the querying tenant | `apps/docs/docs/architecture/graph-schema.md` | `ci.yml :: api tests` (`test_graph_tenant_isolation.py` — asserts `tenant_id` is actually bound to the driver, and that every node of every blast-radius path is scoped; `tenant_id IS NULL` is not accepted anywhere) | GATED | - || Analysts can hunt the events AiSOC itself ingested | README (hunt surface) | `ci.yml :: api tests` (`test_lake_hunt.py` — the translator IR compiles to parameterised ClickHouse SQL with the tenant predicate generated rather than rewritten in; no question text reaches the SQL string) | GATED | - || Business-context rules authored in the console affect triage | `apps/docs/docs/console/` (business context) | `ci.yml` agents tests (`test_business_context_per_tenant.py` — rules resolve per tenant from Postgres, one tenant's suppression cannot affect another, and an outage serves last-known rules rather than silently un-suppressing) | GATED | - |-| Seeded sample data never renders as a tenant's real state | Standing honesty rule (synthetic vs real) | `ci.yml :: python-lint` (`check_mock_data_gated.py` — fails the build on a `fallbackData` receiving sample data un-wrapped, or sample data assigned to state with no demo-mode check) | GATED | - |+| Seeded sample data never renders as a tenant's real state | Standing honesty rule (synthetic vs real) | `ci.yml :: python-lint` (`check_mock_data_gated.py` — fails the build on a `fallbackData` receiving sample data un-wrapped, on sample data assigned to state with no demo-mode check, and on a module-scope array of named entities carrying measurements in a component with no demo gate; the reviewed-exception list is checked in both directions so a stale exemption fails) + `tests/test_mock_data_gate.py` | GATED | the first two patterns needed a `MOCK_`/`DEMO_` name *and* a setter or `fallbackData`, so a fabricated table written inline under an ordinary name in a component that never fetched matched nothing — `MSSPDashboardView` and `TeamAnalyticsView` both shipped under a green gate until the third pattern was added; the check remains shape-based and cannot prove a view is honest || Published executable-detection count matches what the engine loads | `docs/detections/truth-table.md` | `validate-detections.yml` (`detection_truth_table.py --check` now derives `executable` from `detection_ruleset.json` membership rather than file path and body keys; the old heuristic published 947 while the engine loaded 825, counted 77 Sigma rules with no evaluator, and would have certified a bulk un-quarantine as a no-op) | GATED | - || A detection rule matches on fields that exist in telemetry | (implied by the detection corpus) | `validate-detections.yml` (`check_detection_fields.py` — ratchets rules depending on computed fields such as sliding-window counters and allowlist booleans, which no connector can supply; fixture replay cannot catch these because fixtures are synthesized from the rule under test) | GATED (ratchet) | ratchet to 0 || Vendor fields nested under `raw_event` are visible to detections | (implied by the detection corpus) | `ci.yml` fusion tests (`test_detection_field_namespace.py` — 663 of 825 loaded rules referenced an invisible field before this; both the stateless and windowed engines now merge the payload identically) | GATED | - |diff --git a/scripts/check_mock_data_gated.py b/scripts/check_mock_data_gated.pyindex 91dd46e54..98fa322fc 100644--- a/scripts/check_mock_data_gated.py+++ b/scripts/check_mock_data_gated.py@@ -12,16 +12,40 @@ was unreachable. And SWR v2 disables `revalidateOnMount` whenever `fallbackData`is supplied, so a component passing a mock unconditionally may never fetch atall: the sample data is not a placeholder, it is what the view shows.-This gate checks the two mechanical shapes that caused it:+This gate checks the mechanical shapes that caused it:* `fallbackData:` receiving a bare `MOCK_*` / `DEMO_*` reference rather than onewrapped in `demoFallback(...)`.* A `catch` block assigning a `MOCK_*` / `DEMO_*` value with no `canUseDemoData`check anywhere in the file.+* A module-scope array of fabricated *records* — named entities carrying+ measurements — rendered by a component with no demo gate.-It is deliberately shallow. It cannot prove a view is honest — only that these-two regressions have not reappeared. The reviewable property is that adding a-new ungated mock fallback fails here rather than shipping.+That third check exists because the first two only recognise mock data that+announces itself. Both require the `MOCK_` / `DEMO_` naming convention *and* an+assignment through a state setter or SWR, which models one situation: a view+that fetches, and substitutes a sample when the fetch fails.++`MSSPDashboardView.tsx` was the worse case and was invisible to all of it. It+declared `const TENANTS = [...]` — six companies with invented alert counts,+MTTD/MTTR figures, risk scores, analyst headcounts and ARR — passed it straight+to `useState`, and **made no API call at all**. No mock-ish name, no setter, no+`fallbackData`, so nothing matched; and because there was no fetch, there was no+real path for a fallback to fall back *from*. Every operator on every deployment+saw the same six rows, permanently. `TeamAnalyticsView.tsx` had the same shape+with six named analysts and their accuracy scores.++So the third check is name-agnostic. It looks for what makes fabricated domain+data harmful rather than for what an author happened to call it: records that+name an entity a customer would recognise (a company, a person, a host, an IP,+an address) *and* attach numbers to it. UI configuration — filter lists, sort+options, language menus, marketing copy — carries neither, which is what keeps+the check quiet: 93 module-scope object arrays in the console at the time of+writing, 7 matched, and the 4 already behind `demoFallback()` were the mocks.++It remains deliberately shallow. It cannot prove a view is honest — only that+these regressions have not reappeared. The reviewable property is that adding a+new ungated mock fails here rather than shipping.Usage:python scripts/check_mock_data_gated.py [--root apps/web/src]@@ -78,6 +102,104 @@ def _is_exempt_name(line: str) -> bool:return any(name in line for name in EXEMPT_NAMES)+# ── Fabricated records declared inline ──────────────────────────────────────++#: Any module-scope `const NAME = [` / `const NAME: T[] = [`. Anchored at column+#: zero so a filter list built inside a component body is out of scope; what+#: this check is after is a dataset baked into the module.+MODULE_ARRAY = re.compile(r"^(?:export\s+)?const\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]*)?=\s*\[")++#: `key: 42` / `key: 3.5`. The *measurements*.+NUMERIC_KEY = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\s*:\s*-?\d+(?:[._]\d+)*\b")++#: `key: 'some string'`. The candidate *identities*.+STRING_VALUE = re.compile(r"\b[A-Za-z_][A-Za-z0-9_]*\s*:\s*'([^']{2,60})'")++#: Keys whose numbers describe how something is *drawn*, not what it measures.+#: Without this a cytoscape stylesheet (`width: 40, height: 40`) and the+#: decorative SVG node coordinates on the landing page both match.+LAYOUT_KEYS = frozenset(+ """x y cx cy r rx ry dx dy width height size top left right bottom opacity duration delay scale rotate+ zindex z index order weight strokewidth fontsize radius angle offset speed step cols rows span gap+ padding margin col row min max position""".split()+)++#: "Acme Financial", "Sarah Chen", "GlobalRetail Corp" — a name a customer would+#: read as one of their own entities. Single capitalised words are excluded:+#: "Starter", "Critical" and "Execution" are labels, not identities.+PROPER_NOUN = re.compile(r"^[A-Z][A-Za-z.&]*(?:[ -][A-Z][A-Za-z.&]*)+$")++#: WIN-DC01, srv-01.corp.local, 10.0.0.4, [email protected].+ESTATE_IDENTIFIER = re.compile(+ r"^(?:[A-Z]{2,}-[A-Z0-9-]{2,}|[a-z][\w-]*-\d+\.[a-z][\w.-]+|\d{1,3}(?:\.\d{1,3}){3}|[\w.+-]+@[\w-]+\.\w+)$"+)++#: Any of these in the file means the author considered demo mode.+DEMO_GATE = re.compile(r"demoFallback|canUseDemoData|isDemoMode")++#: Reviewed exceptions: fabricated-looking records that are not, and never+#: render as, a tenant's state. Keyed on (path suffix, const name) so an+#: exemption cannot silently widen to a different constant in the same file.+#:+#: Checked in *both* directions — `--check-allowlist` fails when an entry no+#: longer matches anything, so a stale exemption is removed rather than+#: accumulating as cover for whatever is written next under that name.+ALLOWED_ILLUSTRATIVE: dict[tuple[str, str], str] = {+ (+ "components/landing/MitreStrip.tsx",+ "TACTICS",+ ): "Public landing page, not tenant state. The visible copy already tells the reader "+ "'the tiles below are illustrative; numbers depend on which detection packs you enable'.",+}+++def _array_body(lines: list[str], start: int) -> str:+ """Lines from `start` to the bracket that closes the array."""+ depth = 0+ body: list[str] = []+ for index in range(start, min(start + 500, len(lines))):+ body.append(lines[index])+ depth += lines[index].count("[") - lines[index].count("]")+ if index > start and depth <= 0:+ break+ return "\n".join(body)+++def _looks_fabricated(blob: str) -> bool:+ """A set of records that names entities and attaches numbers to them."""+ if blob.count("{") < 3:+ return False+ measurements = {key for key in NUMERIC_KEY.findall(blob) if key.lower() not in LAYOUT_KEYS}+ if len(measurements) < 2:+ return False+ return any(PROPER_NOUN.match(value) or ESTATE_IDENTIFIER.match(value) for value in STRING_VALUE.findall(blob))+++def find_inline_records(root: pathlib.Path) -> list[tuple[str, int, str, bool]]:+ """Every module-scope fabricated-record array: (path, line, name, gated)."""+ found: list[tuple[str, int, str, bool]] = []+ for path in sorted(root.rglob("*.tsx")):+ if path.name.endswith(EXEMPT_SUFFIXES):+ continue+ text = path.read_text(encoding="utf-8", errors="replace")+ gated = bool(DEMO_GATE.search(text))+ lines = text.split("\n")+ for number, line in enumerate(lines):+ match = MODULE_ARRAY.match(line)+ if not match or _is_exempt_name(line):+ continue+ if _looks_fabricated(_array_body(lines, number)):+ found.append((str(path.relative_to(root.parent.parent.parent)), number + 1, match.group(1), gated))+ return found+++def _allowlist_key(rel_path: str, name: str) -> tuple[str, str] | None:+ for (suffix, const), _reason in ALLOWED_ILLUSTRATIVE.items():+ if rel_path.endswith(suffix) and const == name:+ return (suffix, const)+ return None++def scan(root: pathlib.Path) -> list[str]:problems: list[str] = []@@ -112,12 +234,37 @@ def scan(root: pathlib.Path) -> list[str]:f"canUseDemoData() check in this file. Show an error or empty state instead.")+ for rel, number, name, gated in find_inline_records(root):+ if gated or _allowlist_key(rel, name) is not None:+ continue+ problems.append(+ f"{rel}:{number}: `{name}` is a module-scope array of named entities with "+ f"measurements attached, in a component with no demo gate. If it is a tenant's "+ f"state, read it from the API; if it is a sample, gate it with canUseDemoData()."+ )+return problems+def stale_allowlist_entries(root: pathlib.Path) -> list[str]:+ """Allow-list entries that no longer match anything in the tree.++ The direction the first version of this gate would have missed. An+ exemption that outlives the code it excused is cover for whatever is+ written next under that name.+ """+ live = {_allowlist_key(rel, name) for rel, _n, name, _g in find_inline_records(root)}+ return [f"{suffix} :: {const}" for (suffix, const) in ALLOWED_ILLUSTRATIVE if (suffix, const) not in live]++def main() -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--root", default="apps/web/src", help="directory to scan")+ parser.add_argument(+ "--list-records",+ action="store_true",+ help="list every module-scope fabricated-record array and whether it is gated",+ )args = parser.parse_args()root = pathlib.Path(args.root)@@ -125,7 +272,21 @@ def main() -> int:print(f"error: {root} is not a directory", file=sys.stderr)return 2+ if args.list_records:+ for rel, number, name, gated in find_inline_records(root):+ state = "gated" if gated else ("allow-listed" if _allowlist_key(rel, name) else "UNGATED")+ print(f"[{state}] {rel}:{number} const {name}")+ return 0+problems = scan(root)++ stale = stale_allowlist_entries(root)+ if stale:+ print(f"{len(stale)} stale allow-list entry(ies) in ALLOWED_ILLUSTRATIVE:\n", file=sys.stderr)+ for entry in stale:+ print(f" {entry} — no longer matches anything; remove it", file=sys.stderr)+ return 1+if problems:print(f"{len(problems)} ungated sample-data site(s):\n", file=sys.stderr)for problem in problems:diff --git a/tests/test_mock_data_gate.py b/tests/test_mock_data_gate.pynew file mode 100644index 000000000..468617b10--- /dev/null+++ b/tests/test_mock_data_gate.py@@ -0,0 +1,213 @@+"""Tests for the fabricated-data gate, `scripts/check_mock_data_gated.py`.++The gate's first two checks only recognise mock data that announces itself:+they need a `MOCK_` / `DEMO_` name *and* an assignment through a state setter+or SWR `fallbackData`. `MSSPDashboardView.tsx` had neither — `const TENANTS =+[...]` passed straight to `useState`, with no API call anywhere in the file —+so six invented companies with invented ARR shipped under a green gate.++Two properties matter for the replacement check and both are asserted here:+it catches that shape, and it stays quiet on the UI configuration that makes+up the large majority of module-scope object arrays in this console. A gate+that flags every filter list gets deleted, which is worse than the gap.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_REPO = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(_REPO / "scripts"))++import check_mock_data_gated as gate # noqa: E402+++def _tree(tmp_path: Path, relative: str, source: str) -> Path:+ """A fake `apps/web/src` so `find_inline_records` reports real-looking paths."""+ root = tmp_path / "apps" / "web" / "src"+ target = root / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(source, encoding="utf-8")+ return root+++# The verbatim shape that shipped.+FABRICATED_TENANTS = """\+'use client';+import { useState } from 'react';++const TENANTS: Tenant[] = [+ { name: 'Acme Financial', activeAlerts: 12, openCases: 3, mttr: 28, arr: 185000 },+ { name: 'GlobalRetail Corp', activeAlerts: 47, openCases: 11, mttr: 65, arr: 320000 },+ { name: 'MedSecure Health', activeAlerts: 8, openCases: 2, mttr: 19, arr: 140000 },+];++export default function View() {+ const [tenants] = useState(TENANTS);+ return <div>{tenants.length}</div>;+}+"""+++def test_it_catches_a_fabricated_table_that_never_calls_an_api(tmp_path):+ root = _tree(tmp_path, "components/mssp/View.tsx", FABRICATED_TENANTS)+ problems = gate.scan(root)+ assert len(problems) == 1+ assert "TENANTS" in problems[0]+++def test_the_older_name_based_checks_alone_would_have_missed_it(tmp_path):+ """Why the third check had to be name-agnostic.++ Nothing here is called `MOCK_*`, nothing is assigned through a setter, and+ nothing reaches `fallbackData` — so every pattern the gate shipped with+ finds zero.+ """+ root = _tree(tmp_path, "components/mssp/View.tsx", FABRICATED_TENANTS)+ text = (root / "components/mssp/View.tsx").read_text(encoding="utf-8")+ for line in text.split("\n"):+ assert not gate.FALLBACK_WITH_MOCK.search(line)+ assert not gate.MOCK_ASSIGN.search(line)+ assert not gate.MOCK_FACTORY_ASSIGN.search(line)+++def test_the_same_records_pass_once_demo_gated(tmp_path):+ gated = FABRICATED_TENANTS.replace(+ "const [tenants] = useState(TENANTS);",+ "const [tenants] = useState(canUseDemoData() ? TENANTS : []);",+ )+ root = _tree(tmp_path, "components/mssp/View.tsx", gated)+ assert gate.scan(root) == []+++def test_named_people_with_scores_are_caught(tmp_path):+ """The second live instance: an analyst leaderboard with no backend."""+ root = _tree(+ tmp_path,+ "components/analytics/Team.tsx",+ """\+const ANALYSTS: Analyst[] = [+ { name: 'Sarah Chen', casesClosed: 47, accuracy: 96.2, score: 945 },+ { name: 'Marcus Rivera', casesClosed: 42, accuracy: 94.8, score: 892 },+ { name: 'Aisha Patel', casesClosed: 39, accuracy: 97.1, score: 878 },+];+""",+ )+ assert len(gate.scan(root)) == 1+++def test_estate_identifiers_count_as_identities(tmp_path):+ """A hostname or an address is as recognisable as a company name."""+ root = _tree(+ tmp_path,+ "components/alerts/Hosts.tsx",+ """\+const ROWS = [+ { host: 'WIN-DC01', alerts: 4, risk: 88 },+ { host: 'WIN-SQL02', alerts: 2, risk: 61 },+ { host: 'WIN-APP07', alerts: 9, risk: 94 },+];+""",+ )+ assert len(gate.scan(root)) == 1+++# ── Must stay quiet on UI configuration ─────────────────────────────────────+++ "name,source",+ [+ (+ "filter buttons",+ "const SEVERITY_FILTERS = [\n"+ " { value: 'critical', label: 'Critical' },\n"+ " { value: 'high', label: 'High' },\n"+ " { value: 'low', label: 'Low' },\n"+ "];\n",+ ),+ (+ "a graph stylesheet",+ "const STYLE = [\n"+ " { selector: 'node', width: 40, height: 40, shape: 'ellipse' },\n"+ " { selector: 'edge', width: 2, height: 2, shape: 'line' },\n"+ " { selector: 'core', width: 1, height: 1, shape: 'none' },\n"+ "];\n",+ ),+ (+ "decorative svg coordinates",+ "const nodes = [\n"+ " { x: 10, y: 20, delay: 0 },\n"+ " { x: 30, y: 45, delay: 1 },\n"+ " { x: 55, y: 70, delay: 2 },\n"+ "];\n",+ ),+ (+ "pricing copy",+ "const TIERS = [\n"+ " { name: 'Starter', price: 0, seats: 3 },\n"+ " { name: 'Growth', price: 499, seats: 25 },\n"+ " { name: 'Enterprise', price: 1999, seats: 100 },\n"+ "];\n",+ ),+ ],+)+def test_ui_configuration_is_not_flagged(tmp_path, name, source):+ root = _tree(tmp_path, "components/misc/Config.tsx", source)+ assert gate.scan(root) == [], f"{name} is configuration, not a tenant's state"+++def test_an_array_inside_a_component_body_is_out_of_scope(tmp_path):+ """Indented declarations are local view state, not a baked-in dataset."""+ root = _tree(+ tmp_path,+ "components/misc/Local.tsx",+ """\+export function View({ rows }) {+ const derived = [+ { name: 'Acme Financial', alerts: 3, cases: 1 },+ { name: 'Globex Systems', alerts: 5, cases: 2 },+ { name: 'Initech Holdings', alerts: 1, cases: 0 },+ ];+ return <div>{derived.length}{rows}</div>;+}+""",+ )+ assert gate.scan(root) == []+++# ── The allow-list is checked in both directions ────────────────────────────+++def test_a_stale_allowlist_entry_fails(tmp_path, monkeypatch):+ """An exemption that outlives its code is cover for whatever is written+ next under that name, so it has to be removed rather than left."""+ root = _tree(tmp_path, "components/misc/Config.tsx", "const OPTIONS = [{ a: 1 }];\n")+ monkeypatch.setattr(gate, "ALLOWED_ILLUSTRATIVE", {("components/gone/Removed.tsx", "GHOSTS"): "no longer exists"})+ stale = gate.stale_allowlist_entries(root)+ assert stale == ["components/gone/Removed.tsx :: GHOSTS"]+++def test_a_live_allowlist_entry_is_not_stale(tmp_path, monkeypatch):+ root = _tree(+ tmp_path,+ "components/landing/Strip.tsx",+ """\+const TACTICS = [+ { name: 'Initial Access', covered: 9, total: 11 },+ { name: 'Defense Evasion', covered: 27, total: 42 },+ { name: 'Lateral Movement', covered: 8, total: 9 },+];+""",+ )+ monkeypatch.setattr(gate, "ALLOWED_ILLUSTRATIVE", {("components/landing/Strip.tsx", "TACTICS"): "illustrative"})+ assert gate.stale_allowlist_entries(root) == []+ assert gate.scan(root) == []+++def test_the_shipped_allowlist_entries_all_still_match():+ """Run against the real tree, not a fixture."""+ assert gate.stale_allowlist_entries(_REPO / "apps" / "web" / "src") == []