Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix(web): stop rendering fabricated security data as a tenant's real state (#671)

Beenu Arora7e7c7267403c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 838a39069..5d5c363fe 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -191,6 +191,14 @@ jobs:
# `python scripts/sync_vendored_nl_query.py` locally to fix.
- name: Verify vendored nl_query is in sync
run: python scripts/sync_vendored_nl_query.py --check
+ # Fabricated security data must never render as a tenant's real state.
+ # Around three dozen console components served a `MOCK_*` / `DEMO_*`
+ # array of plausible alerts, connectors and coverage numbers whenever the
+ # API call failed, none of it gated on demo mode — and because SWR v2
+ # disables `revalidateOnMount` when `fallbackData` is set, several never
+ # fetched at all. This gate fails the build if that shape reappears.
+ - name: Verify sample data is gated behind demo mode
+ run: python scripts/check_mock_data_gated.py
# Same story for the correlation-narrative builder. It lives canonically
# in `services/fusion/app/services/narrative.py` (called at fusion time
# to populate `FusedAlert.narrative`) and is mirrored into
diff --git a/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx b/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx
index a8cf2073a..368fc75b8 100644
--- a/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx
+++ b/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx
@@ -39,6 +39,7 @@ import cytoscape, { type Core, type ElementDefinition } from 'cytoscape';
import fcose from 'cytoscape-fcose';
import { clsx } from 'clsx';
import { safeFetcher } from '@/lib/fetcher';
+import { demoFallback } from '@/lib/demoFallback';
if (typeof window !== 'undefined') {
try {
@@ -351,7 +352,7 @@ export function EffectivePermissionsView() {
const { data: providerInfo } = useSWR<{ providers: ProviderInfo[] }>(
'/api/v1/identity/effective-permissions/providers',
safeFetcher,
- { fallbackData: { providers: DEMO_PROVIDERS } },
+ { fallbackData: demoFallback({ providers: DEMO_PROVIDERS }) },
);
const providers = providerInfo?.providers ?? DEMO_PROVIDERS;
const selectedProviderInfo = providers.find((p) => p.name === provider);
@@ -365,7 +366,8 @@ export function EffectivePermissionsView() {
apiUrl,
safeFetcher,
{
- fallbackData: provider === 'aws' && !isScaffoldProvider ? DEMO_RESULT : undefined,
+ fallbackData:
+ provider === 'aws' && !isScaffoldProvider ? demoFallback(DEMO_RESULT) : undefined,
shouldRetryOnError: false,
},
);
diff --git a/apps/web/src/app/(app)/purple-team/page.tsx b/apps/web/src/app/(app)/purple-team/page.tsx
index 605f17914..512b42c3c 100644
--- a/apps/web/src/app/(app)/purple-team/page.tsx
+++ b/apps/web/src/app/(app)/purple-team/page.tsx
@@ -2,6 +2,7 @@
import { useState } from 'react'
import useSWR from 'swr'
+import { demoFallback } from '@/lib/demoFallback';
// Same-origin by default — Next.js rewrites proxy `/api/v1/purple-team/*` to
// the purple-team service. Override with `NEXT_PUBLIC_PURPLE_TEAM_API` for
@@ -207,7 +208,7 @@ function CoverageHeatmap() {
const { data } = useSWR<CoverageMatrix>(
`${API}/api/v1/purple-team/coverage?tenant_id=${TENANT_ID}`,
fetcher,
- { refreshInterval: 30000, fallbackData: MOCK_COVERAGE }
+ { refreshInterval: 30000, fallbackData: demoFallback(MOCK_COVERAGE) }
)
const { data: drift, mutate: mutateDrift } = useSWR<DriftLatestResponse>(
diff --git a/apps/web/src/components/alerts/AlertDetailView.tsx b/apps/web/src/components/alerts/AlertDetailView.tsx
index dacb598c1..939f1cbd4 100644
--- a/apps/web/src/components/alerts/AlertDetailView.tsx
+++ b/apps/web/src/components/alerts/AlertDetailView.tsx
@@ -21,6 +21,7 @@ import { clsx } from 'clsx';
import { ContextualActions } from '@/components/copilot/ContextualActions';
import { ExplainDrawer } from '@/components/alerts/ExplainDrawer';
import { CreateCaseModal } from '@/components/alerts/CreateCaseModal';
+import { demoFallback } from '@/lib/demoFallback';
// ─── Helpers ──────────────────────────────────────────────────────────────────
@@ -767,7 +768,7 @@ export function AlertDetailView({ alertId }: { alertId: string }) {
const { data: alert, isLoading, mutate } = useSWR(
['alert', alertId],
() => alertsApi.get(alertId),
- { fallbackData: { ...MOCK_ALERT, id: alertId, status } }
+ { fallbackData: demoFallback({ ...MOCK_ALERT, id: alertId, status }) }
);
const handleStatusChange = async (newStatus: Alert['status']) => {
diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsx
index fe2f90b81..a098793a8 100644
--- a/apps/web/src/components/alerts/AlertsView.tsx
+++ b/apps/web/src/components/alerts/AlertsView.tsx
@@ -11,6 +11,7 @@ import { InvestigationRail } from './InvestigationRail';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
import { ErrorState } from '@/components/ui/ErrorState';
import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';
+import { demoFallback } from '@/lib/demoFallback';
// Wave 1 of the AiSOC v6 capability roadmap. The "entities" tab renders the
// rolled-up Risk-Based Alerting queue — alerts contribute time-decayed risk
@@ -266,12 +267,12 @@ export function AlertsView() {
['alerts', filters],
() => alertsApi.list(filters),
{
- fallbackData: {
+ fallbackData: demoFallback({
alerts: MOCK_ALERTS,
total: MOCK_ALERTS.length,
page: 1,
pageSize: 25,
- },
+ }),
refreshInterval: 30000,
}
);
diff --git a/apps/web/src/components/alerts/EntityRiskQueue.tsx b/apps/web/src/components/alerts/EntityRiskQueue.tsx
index 04ad483b0..a88261d6c 100644
--- a/apps/web/src/components/alerts/EntityRiskQueue.tsx
+++ b/apps/web/src/components/alerts/EntityRiskQueue.tsx
@@ -22,6 +22,7 @@ import {
type EntityRiskStats,
type EntityType,
} from '@/lib/api';
+import { demoFallback } from '@/lib/demoFallback';
// ─── Visual config ───────────────────────────────────────────────────────────
@@ -467,12 +468,15 @@ export function EntityRiskQueue() {
const { data: queue, error: queueError, isLoading: queueLoading } = useSWR(
['entity-risk-queue', promotedOnly],
() => entityRiskApi.queue({ limit: 50, promotedOnly }),
- { refreshInterval: 30000, fallbackData: { tenant_id: 'demo', entities: MOCK_ENTITIES, threshold: 80 } },
+ {
+ refreshInterval: 30000,
+ fallbackData: demoFallback({ tenant_id: 'demo', entities: MOCK_ENTITIES, threshold: 80 }),
+ },
);
const { data: stats } = useSWR<EntityRiskStats>(
'entity-risk-stats',
() => entityRiskApi.stats(),
- { refreshInterval: 30000, fallbackData: MOCK_ENTITY_STATS },
+ { refreshInterval: 30000, fallbackData: demoFallback(MOCK_ENTITY_STATS) },
);
const entities = queue?.entities ?? [];
diff --git a/apps/web/src/components/audit/AuditLogView.tsx b/apps/web/src/components/audit/AuditLogView.tsx
index 3d56d6da3..d1fc9c86d 100644
--- a/apps/web/src/components/audit/AuditLogView.tsx
+++ b/apps/web/src/components/audit/AuditLogView.tsx
@@ -6,6 +6,7 @@ import toast from 'react-hot-toast';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
import { ErrorState } from '@/components/ui/ErrorState';
import { auditApi, ApiError, type AuditExportFilters } from '@/lib/api';
+import { demoFallback } from '@/lib/demoFallback';
interface AuditEvent {
id: string;
@@ -87,10 +88,21 @@ export function AuditLogView() {
const { data: raw, error, isLoading } = useSWR<AuditListResponse>(
`/api/v1/audit?${params}`,
fetcher,
- { refreshInterval: 30_000, fallbackData: MOCK_AUDIT, shouldRetryOnError: false, errorRetryCount: 0, revalidateOnFocus: false }
+ {
+ refreshInterval: 30_000,
+ fallbackData: demoFallback(MOCK_AUDIT),
+ shouldRetryOnError: false,
+ errorRetryCount: 0,
+ revalidateOnFocus: false,
+ }
);
const isValid = raw && Array.isArray(raw.items) && typeof raw.total === 'number';
- const data = isValid ? raw : MOCK_AUDIT;
+ // An unexpected response shape used to fall through to fabricated entries
+ // regardless of demo mode, so a malformed payload produced a plausible
+ // audit trail. An audit log is the one surface that must never show events
+ // that did not happen.
+ const emptyAudit: AuditListResponse = { items: [], total: 0, page: 1, page_size: 0, total_pages: 0 };
+ const data = isValid ? raw : (demoFallback(MOCK_AUDIT) ?? emptyAudit);
const handleSearch = useCallback((e: React.FormEvent) => {
e.preventDefault();
diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsx
index 51f197216..8f27bb486 100644
--- a/apps/web/src/components/cases/CasesView.tsx
+++ b/apps/web/src/components/cases/CasesView.tsx
@@ -9,6 +9,7 @@ import { clsx } from 'clsx';
import { format } from 'date-fns';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';
+import { demoFallback } from '@/lib/demoFallback';
// WS-F3 — the saved-views API stores an opaque filter blob per view, so we
// flatten the three filter slices Cases tracks today into a single shape the
@@ -164,7 +165,7 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {
['cases', statusFilter, severityFilter],
() => casesApi.list({ status: statusFilter !== 'all' ? statusFilter : undefined }),
{
- fallbackData: fallback,
+ fallbackData: demoFallback(fallback),
}
);
diff --git a/apps/web/src/components/connectors/ConnectorsView.tsx b/apps/web/src/components/connectors/ConnectorsView.tsx
index 6e2a97248..25114e479 100644
--- a/apps/web/src/components/connectors/ConnectorsView.tsx
+++ b/apps/web/src/components/connectors/ConnectorsView.tsx
@@ -28,6 +28,7 @@ import {
import { AddConnectorModal } from './AddConnectorModal';
import { ConnectorInstanceList } from './ConnectorInstanceList';
import { InboxTokensPanel } from './InboxTokensPanel';
+import { demoFallback } from '@/lib/demoFallback';
const DEMO_CONNECTORS: Connector[] = [
{
@@ -74,7 +75,10 @@ export function ConnectorsView() {
const { data, error, isLoading, mutate } = useSWR(
'connectors',
() => connectorsApi.list(),
- { revalidateOnFocus: false, fallbackData: { connectors: DEMO_CONNECTORS, total: DEMO_CONNECTORS.length } },
+ {
+ revalidateOnFocus: false,
+ fallbackData: demoFallback({ connectors: DEMO_CONNECTORS, total: DEMO_CONNECTORS.length }),
+ },
);
// Health summary is a separate endpoint so the empty/error case is silent —
diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsx
index 04834ac73..1139daefa 100644
--- a/apps/web/src/components/dashboard/DashboardView.tsx
+++ b/apps/web/src/components/dashboard/DashboardView.tsx
@@ -26,6 +26,7 @@ import { DashboardWelcome } from './DashboardWelcome';
import { FunnelKpiBar } from './FunnelKpiBar';
import { EfficiencyReport } from './EfficiencyReport';
import { PipelineHealth } from './PipelineHealth';
+import { demoFallback } from '@/lib/demoFallback';
const RechartsArea = dynamic(
() => import('recharts').then((m) => {
@@ -377,7 +378,7 @@ export function DashboardView() {
'dashboard-metrics',
() => metricsApi.getDashboard(),
{
- fallbackData: MOCK_METRICS,
+ fallbackData: demoFallback(MOCK_METRICS),
refreshInterval: 60000,
revalidateOnMount: true,
revalidateOnFocus: false,
diff --git a/apps/web/src/components/dashboard/LiveFeedPanel.tsx b/apps/web/src/components/dashboard/LiveFeedPanel.tsx
index d37fbc0f7..e72dbe17b 100644
--- a/apps/web/src/components/dashboard/LiveFeedPanel.tsx
+++ b/apps/web/src/components/dashboard/LiveFeedPanel.tsx
@@ -18,6 +18,7 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import clsx from 'clsx';
import { useRealtimeChannel, type RealtimeStatus } from '@/lib/realtime';
+import { canUseDemoData } from '@/lib/demoFallback';
type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';
@@ -224,6 +225,12 @@ export function LiveFeedPanel() {
const hasReal = events.length > 0;
const visible = useMemo<LiveEvent[]>(() => {
if (hasReal) return events;
+ // An idle feed used to render a synthetic event stream with freshly
+ // stamped timestamps, so a tenant with no connected sources — or a broken
+ // realtime socket — watched fabricated detections scroll past as though
+ // the platform were live. Outside the hosted demo the panel now shows its
+ // real state, which the status pill already reports honestly.
+ if (!canUseDemoData()) return [];
// Refresh demo timestamps so they don't drift to "5h ago" while the dev
// sits on the page with no realtime backend running.
return DEMO_EVENTS.map((e, i) => ({
diff --git a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
index 303851c04..e175a666d 100644
--- a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
+++ b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
@@ -11,6 +11,7 @@ import {
type CalibrationBucket,
type CostAggregate,
} from "@/lib/api";
+import { demoFallback } from '@/lib/demoFallback';
const MOCK_SOC_METRICS: SOCMetrics = {
kpis: {
@@ -163,7 +164,7 @@ export function SOCMetricsDashboard() {
() => metricsApi.getSOC(),
{
refreshInterval: 60_000,
- fallbackData: MOCK_SOC_METRICS,
+ fallbackData: demoFallback(MOCK_SOC_METRICS),
shouldRetryOnError: true,
errorRetryCount: 3,
errorRetryInterval: 4000,
@@ -331,7 +332,7 @@ function CostTelemetryPanel() {
() => investigationsApi.getCostAggregate(30),
{
refreshInterval: 60_000,
- fallbackData: MOCK_COST_AGGREGATE,
+ fallbackData: demoFallback(MOCK_COST_AGGREGATE),
shouldRetryOnError: true,
errorRetryCount: 3,
errorRetryInterval: 4000,
diff --git a/apps/web/src/components/detections/DetectionCatalog.tsx b/apps/web/src/components/detections/DetectionCatalog.tsx
index cfad6fc77..c36fb96ed 100644
--- a/apps/web/src/components/detections/DetectionCatalog.tsx
+++ b/apps/web/src/components/detections/DetectionCatalog.tsx
@@ -2,6 +2,7 @@
import { useState, useEffect } from 'react';
import clsx from 'clsx';
+import { canUseDemoData } from '@/lib/demoFallback';
// ── Types ─────────────────────────────────────────────────────────────────────
@@ -246,9 +247,18 @@ export function DetectionCatalog() {
setRules(data.items ?? []);
setTotal(data.total ?? 0);
setFetched(true);
- } catch {
- setRules(MOCK_RULES);
- setTotal(MOCK_RULES.length);
+ } catch (err) {
+ // Outside the hosted demo a failed fetch must read as a failed fetch.
+ // Substituting a plausible catalog told an operator their detection
+ // coverage was fine when the service was unreachable.
+ if (canUseDemoData()) {
+ setRules(MOCK_RULES);
+ setTotal(MOCK_RULES.length);
+ } else {
+ setRules([]);
+ setTotal(0);
+ setError(err instanceof Error ? err.message : 'Could not load the detection catalog.');
+ }
setFetched(true);
} finally {
setLoading(false);
diff --git a/apps/web/src/components/detections/DetectionsView.tsx b/apps/web/src/components/detections/DetectionsView.tsx
index 8a6450147..688ae5d1a 100644
--- a/apps/web/src/components/detections/DetectionsView.tsx
+++ b/apps/web/src/components/detections/DetectionsView.tsx
@@ -18,6 +18,7 @@ import { ContributorLeaderboard } from './ContributorLeaderboard';
import { MitreRuleHeatmap } from './MitreRuleHeatmap';
import { ConfidenceTrends } from './ConfidenceTrends';
import { DriftInbox } from './DriftInbox';
+import { canUseDemoData } from '@/lib/demoFallback';
// ─── Demo fallback ────────────────────────────────────────────────────────────
@@ -177,7 +178,10 @@ export function DetectionsView() {
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
- const useFallback = !!error;
+ // Only the hosted demo substitutes sample rules on error. Elsewhere a
+ // load failure must show as a failure: a fabricated rule list tells an
+ // operator their detection coverage is fine when the service is down.
+ const useFallback = !!error && canUseDemoData();
// Memoise so `useMemo(filtered)` and selection helpers don't see a fresh
// array reference on every render — important because we feed `rules`
// into a downstream useMemo dep array.
diff --git a/apps/web/src/components/easm/EASMView.tsx b/apps/web/src/components/easm/EASMView.tsx
index 463a9804c..efb58c2df 100644
--- a/apps/web/src/components/easm/EASMView.tsx
+++ b/apps/web/src/components/easm/EASMView.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';
type RiskLevel = 'critical' | 'high' | 'medium' | 'low' | 'info';
type AssetType = 'domain' | 'ip' | 'cert' | 'subdomain' | 'service';
@@ -82,9 +83,46 @@ const SUMMARY = {
riskScore: 72,
};
+
+/**
+ * Honest state for a surface that has no backend yet.
+ *
+ * This view rendered fabricated domain data unconditionally and made no API
+ * call, so there was no request to fail — the fiction was the only thing it
+ * ever showed. Presenting it as tenant state is worse than showing nothing,
+ * because an operator cannot tell it apart from a real inventory.
+ */
+function NotYetWired({ title, description }: { title: string; description: string }) {
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-xl font-semibold text-gray-100">{title}</h1>
+ </div>
+ <div className="rounded-lg border border-gray-800 bg-gray-950/40 p-8 text-center">
+ <p className="text-sm font-medium text-gray-300">Not available yet</p>
+ <p className="mx-auto mt-2 max-w-lg text-sm text-gray-500">{description}</p>
+ </div>
+ </div>
+ );
+}
+
export function EASMView() {
const [assetFilter, setAssetFilter] = useState<Asset['status'] | 'all'>('all');
+ // No discovery backend exists for this surface yet, so everything below is
+ // seeded sample data. It stays in the hosted demo and is withheld elsewhere
+ // rather than being presented as a real external attack surface — an
+ // operator reading "riskScore 72" over invented assets would draw
+ // conclusions about exposure they do not have.
+ if (!canUseDemoData()) {
+ return (
+ <NotYetWired
+ title="External Attack Surface Management"
+ description="External asset discovery is not wired to a live scanner in this build, so there is nothing to show for your tenant. The sample inventory is available in the hosted demo."
+ />
+ );
+ }
+
const filteredAssets = assetFilter === 'all'
? MOCK_ASSETS
: MOCK_ASSETS.filter((a) => a.status === assetFilter);
diff --git a/apps/web/src/components/graph/AttackGraphView.tsx b/apps/web/src/components/graph/AttackGraphView.tsx
index 57c91bcb1..9e1270a61 100644
--- a/apps/web/src/components/graph/AttackGraphView.tsx
+++ b/apps/web/src/components/graph/AttackGraphView.tsx
@@ -32,6 +32,7 @@ import {
import { Skeleton } from '@/components/ui/Skeleton';
import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
+import { canUseDemoData } from '@/lib/demoFallback';
// Register fcose once on the client.
if (typeof window !== 'undefined') {
@@ -339,8 +340,12 @@ export function AttackGraphView() {
try {
return await graphApi.getOverview({ depth: 3 });
} catch (err) {
- // Fall back to demo data so the UI is always alive.
- return DEMO_GRAPH;
+ // "So the UI is always alive" meant a fabricated attack graph — named
+ // hosts, users and edges — rendered as the tenant's real estate
+ // whenever the graph backend was down. Re-throw so SWR surfaces the
+ // error; only the hosted demo substitutes sample topology.
+ if (canUseDemoData()) return DEMO_GRAPH;
+ throw err;
}
},
{ revalidateOnFocus: false, refreshInterval: 30_000 },
@@ -351,8 +356,11 @@ export function AttackGraphView() {
async () => {
try {
return await graphApi.getMitreCoverage();
- } catch {
- return buildDemoCoverage();
+ } catch (err) {
+ // Fabricated coverage is the worst kind to invent: it tells a customer
+ // which techniques they can detect.
+ if (canUseDemoData()) return buildDemoCoverage();
+ throw err;
}
},
{ revalidateOnFocus: false, refreshInterval: 60_000 },
diff --git a/apps/web/src/components/playbooks/PlaybooksView.tsx b/apps/web/src/components/playbooks/PlaybooksView.tsx
index e5d625af1..ca3c82f19 100644
--- a/apps/web/src/components/playbooks/PlaybooksView.tsx
+++ b/apps/web/src/components/playbooks/PlaybooksView.tsx
@@ -22,6 +22,7 @@ import { PlaybooksGallery, type PlaybookGalleryFilters } from './PlaybooksGaller
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';
import { DraftFromPromptDialog } from './DraftFromPromptDialog';
+import { demoFallback } from '@/lib/demoFallback';
/** Filter snapshot stored by the backend as a saved-view preset. */
type PlaybookFilterSnapshot = PlaybookGalleryFilters;
@@ -415,7 +416,7 @@ export function PlaybooksView() {
const [tab, setTab] = useState<'playbooks' | 'runs' | 'community'>('playbooks');
const { data, isLoading, error } = useSWR<Playbook[]>('/api/v1/playbooks', fetcher, {
refreshInterval: 30000,
- fallbackData: MOCK_PLAYBOOKS,
+ fallbackData: demoFallback(MOCK_PLAYBOOKS),
});
// WS-F3: track the active filter snapshot so SavedViewsBar can capture it,
diff --git a/apps/web/src/components/settings/RBACView.tsx b/apps/web/src/components/settings/RBACView.tsx
index 45ae32f23..9edb33777 100644
--- a/apps/web/src/components/settings/RBACView.tsx
+++ b/apps/web/src/components/settings/RBACView.tsx
@@ -3,6 +3,7 @@
import { useState } from 'react';
import useSWR, { mutate } from 'swr';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
+import { demoFallback } from '@/lib/demoFallback';
interface Permission {
id: string;
@@ -253,10 +254,10 @@ const MOCK_ROLES: Role[] = [
export function RBACView() {
const { data: roles, error: rolesError } = useSWR<Role[]>('/api/v1/rbac/roles', fetcher, {
- fallbackData: MOCK_ROLES,
+ fallbackData: demoFallback(MOCK_ROLES),
});
const { data: permissions } = useSWR<Permission[]>('/api/v1/rbac/permissions', fetcher, {
- fallbackData: MOCK_PERMISSIONS,
+ fallbackData: demoFallback(MOCK_PERMISSIONS),
});
const [showCreate, setShowCreate] = useState(false);
diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsx
index dd403671f..02551fb76 100644
--- a/apps/web/src/components/settings/SettingsView.tsx
+++ b/apps/web/src/components/settings/SettingsView.tsx
@@ -47,6 +47,7 @@ import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
import { AutonomyPolicyPanel } from '@/components/settings/AutonomyPolicy';
import { useTheme, type ThemePreference } from '@/components/theme/ThemeProvider';
+import { canUseDemoData } from '@/lib/demoFallback';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -755,7 +756,10 @@ function IntegrationsPanel() {
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
- const useFallback = !!error;
+ // Sample connectors only in the hosted demo. Showing three healthy,
+ // recently-synced connectors when the API is unreachable implies data is
+ // flowing into the platform when none is.
+ const useFallback = !!error && canUseDemoData();
const connectors = data?.connectors ?? (useFallback ? DEMO_CONNECTORS : []);
const counts = useMemo(() => {
@@ -2259,14 +2263,33 @@ function StatusPill({
// ─── Panel: Audit ─────────────────────────────────────────────────────────────
function AuditPanel() {
+ // This panel made no API call: it rendered a fixed list of administrative
+ // events directly, so every tenant saw the same invented history of key
+ // rotations and failed syncs. The searchable log at /audit is backed by
+ // /api/v1/audit and is the real thing, so outside the hosted demo this
+ // points there rather than inventing a summary.
+ const entries = canUseDemoData() ? DEMO_AUDIT : [];
return (
<div>
<PanelHeader
title="Audit log"
description="Recent administrative events. Full searchable audit history is available via the API."
/>
+ {entries.length === 0 ? (
+ <div className="px-6 py-8 text-center">
+ <p className="text-sm text-gray-400">
+ Administrative events are recorded in the searchable audit log.
+ </p>
+ <Link
+ href="/audit"
+ className="mt-2 inline-block text-sm text-blue-400 hover:text-blue-300"
+ >
+ Open the audit log
+ </Link>
+ </div>
+ ) : (
<ol className="divide-y divide-gray-800">
- {DEMO_AUDIT.map((a) => (
+ {entries.map((a) => (
<li key={a.id} className="flex items-start gap-3 px-6 py-4">
<span
aria-hidden
@@ -2292,6 +2315,7 @@ function AuditPanel() {
</li>
))}
</ol>
+ )}
</div>
);
}
diff --git a/apps/web/src/components/shifts/ShiftsView.tsx b/apps/web/src/components/shifts/ShiftsView.tsx
index 7fe354816..5ce763f1c 100644
--- a/apps/web/src/components/shifts/ShiftsView.tsx
+++ b/apps/web/src/components/shifts/ShiftsView.tsx
@@ -4,6 +4,7 @@ import { useState } from 'react';
import { clsx } from 'clsx';
import toast from 'react-hot-toast';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
+import { canUseDemoData } from '@/lib/demoFallback';
const SHIFT_START = '2026-05-07T06:00:00Z';
const SHIFT_END = '2026-05-07T18:00:00Z';
@@ -45,10 +46,45 @@ const SHIFT_SUMMARY = {
type PriorityFilter = HandoffItem['priority'] | 'all';
+
+/**
+ * Honest state for a surface that has no backend yet.
+ *
+ * This view rendered fabricated domain data unconditionally and made no API
+ * call, so there was no request to fail — the fiction was the only thing it
+ * ever showed. Presenting it as tenant state is worse than showing nothing,
+ * because an operator cannot tell it apart from a real inventory.
+ */
+function NotYetWired({ title, description }: { title: string; description: string }) {
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-xl font-semibold text-gray-100">{title}</h1>
+ </div>
+ <div className="rounded-lg border border-gray-800 bg-gray-950/40 p-8 text-center">
+ <p className="text-sm font-medium text-gray-300">Not available yet</p>
+ <p className="mx-auto mt-2 max-w-lg text-sm text-gray-500">{description}</p>
+ </div>
+ </div>
+ );
+}
+
export function ShiftsView() {
const [items] = useState(MOCK_HANDOFF_ITEMS);
const [priorityFilter, setPriorityFilter] = useState<PriorityFilter>('all');
+ // Shift handoff has no backend yet. A fabricated handoff board is
+ // particularly misleading: an incoming analyst would believe these are the
+ // items the previous shift actually escalated to them.
+ if (!canUseDemoData()) {
+ return (
+ <NotYetWired
+ title="Shift handoff"
+ description="Shift handoff is not backed by a live service in this build, so there is nothing to hand over for your tenant. The sample board is available in the hosted demo."
+ />
+ );
+ }
+
const filteredItems = priorityFilter === 'all'
? items
: items.filter((item) => item.priority === priorityFilter);
diff --git a/apps/web/src/components/sla/SLADashboard.tsx b/apps/web/src/components/sla/SLADashboard.tsx
index 63c3c970a..1fec60941 100644
--- a/apps/web/src/components/sla/SLADashboard.tsx
+++ b/apps/web/src/components/sla/SLADashboard.tsx
@@ -2,6 +2,7 @@
import { useState } from 'react';
import useSWR, { mutate } from 'swr';
+import { demoFallback } from '@/lib/demoFallback';
const fetcher = async (url: string) => {
const r = await fetch(url);
@@ -442,7 +443,7 @@ export function SLADashboard() {
fetcher,
{
refreshInterval: 60_000,
- fallbackData: MOCK_SLA_METRICS,
+ fallbackData: demoFallback(MOCK_SLA_METRICS),
shouldRetryOnError: false,
errorRetryCount: 0,
revalidateOnFocus: false,
@@ -456,7 +457,7 @@ export function SLADashboard() {
const metrics = isValidMetrics ? rawMetrics : MOCK_SLA_METRICS;
const { data: configs } = useSWR<SLAConfig[]>('/api/v1/sla/config', fetcher, {
- fallbackData: MOCK_SLA_CONFIGS,
+ fallbackData: demoFallback(MOCK_SLA_CONFIGS),
shouldRetryOnError: false,
errorRetryCount: 0,
revalidateOnFocus: false,
diff --git a/apps/web/src/components/threat-intel/ThreatIntelView.tsx b/apps/web/src/components/threat-intel/ThreatIntelView.tsx
index 36114c859..d13202552 100644
--- a/apps/web/src/components/threat-intel/ThreatIntelView.tsx
+++ b/apps/web/src/components/threat-intel/ThreatIntelView.tsx
@@ -11,6 +11,7 @@ import {
import { clsx } from 'clsx';
import { format } from 'date-fns';
import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
+import { demoFallback } from '@/lib/demoFallback';
// ─── Mock Data ────────────────────────────────────────────────────────────────
// Static timestamps avoid SSR/client hydration mismatches (React error #418)
@@ -235,7 +236,7 @@ export function ThreatIntelView() {
const { data } = useSWR(
'threat-intel-indicators',
() => threatIntelApi.list(),
- { fallbackData: { indicators: MOCK_INDICATORS, total: MOCK_INDICATORS.length } },
+ { fallbackData: demoFallback({ indicators: MOCK_INDICATORS, total: MOCK_INDICATORS.length }) },
);
const allIndicators = data?.indicators ?? MOCK_INDICATORS;
diff --git a/apps/web/src/lib/demoFallback.ts b/apps/web/src/lib/demoFallback.ts
new file mode 100644
index 000000000..8be6b18c1
--- /dev/null
+++ b/apps/web/src/lib/demoFallback.ts
@@ -0,0 +1,60 @@
+/**
+ * Gate for seeded sample data so it can never masquerade as tenant state.
+ *
+ * Across the console, roughly three dozen components carried a `MOCK_*` /
+ * `DEMO_*` array of plausible-looking security data — alerts on named hosts,
+ * connectors with last-sync times, SLA percentages, MITRE coverage cells — and
+ * served it whenever the API call failed or had not yet resolved. None of it
+ * was gated on demo mode.
+ *
+ * Two reasons that is worse than an empty state.
+ *
+ * A fabricated alert is indistinguishable from a real one. An operator seeing
+ * "Ransomware encryption behaviour on WIN-DC01" has no way to know the backend
+ * was unreachable, and acting on it, or reporting that the estate is clean
+ * because the fabricated numbers looked healthy, are both real outcomes.
+ *
+ * And it persists. SWR v2 disables `revalidateOnMount` whenever `fallbackData`
+ * is supplied, so a component that passes a mock unconditionally may never
+ * fetch at all — the sample data is not a first-paint placeholder, it is what
+ * the view shows until something else forces a revalidation.
+ *
+ * Passing `undefined` to `fallbackData` is equivalent to omitting it, so
+ * wrapping a mock in `demoFallback` restores normal fetch-and-error behaviour
+ * outside the hosted demo while leaving the demo itself populated.
+ */
+
+import { isDemoMode } from '@/lib/demoMode';
+
+/**
+ * Returns `mock` only in the hosted demo, otherwise `undefined`.
+ *
+ * Use for SWR `fallbackData` and for any initial state that would otherwise
+ * render fabricated domain data:
+ *
+ * ```ts
+ * const { data, error } = useSWR('/alerts', fetcher, {
+ * fallbackData: demoFallback(MOCK_ALERTS),
+ * });
+ * ```
+ */
+export function demoFallback<T>(mock: T): T | undefined {
+ return isDemoMode() ? mock : undefined;
+}
+
+/**
+ * Whether a caller may substitute sample data right now.
+ *
+ * For `catch` blocks and imperative paths, where the honest alternative is an
+ * error state rather than an absent value:
+ *
+ * ```ts
+ * catch (err) {
+ * if (canUseDemoData()) setRows(MOCK_ROWS);
+ * else setError('Could not load alerts.');
+ * }
+ * ```
+ */
+export function canUseDemoData(): boolean {
+ return isDemoMode();
+}
diff --git a/scripts/check_mock_data_gated.py b/scripts/check_mock_data_gated.py
new file mode 100644
index 000000000..5e33825ab
--- /dev/null
+++ b/scripts/check_mock_data_gated.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+"""CI gate: fabricated domain data must be gated behind demo mode.
+
+Roughly three dozen console components carried a `MOCK_*` / `DEMO_*` array of
+plausible-looking security data — alerts on named hosts, connectors with
+last-sync times, SLA percentages, MITRE coverage cells — and served it whenever
+the API call failed or had not yet resolved. None of it consulted demo mode.
+
+Two reasons that is worse than an empty state. A fabricated alert is
+indistinguishable from a real one, so an operator has no way to know the backend
+was unreachable. And SWR v2 disables `revalidateOnMount` whenever `fallbackData`
+is supplied, so a component passing a mock unconditionally may never fetch at
+all: the sample data is not a placeholder, it is what the view shows.
+
+This gate checks the two mechanical shapes that caused it:
+
+* `fallbackData:` receiving a bare `MOCK_*` / `DEMO_*` reference rather than one
+ wrapped in `demoFallback(...)`.
+* A `catch` block assigning a `MOCK_*` / `DEMO_*` value with no `canUseDemoData`
+ check anywhere in the file.
+
+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.
+
+Usage:
+ python scripts/check_mock_data_gated.py [--root apps/web/src]
+"""
+
+from __future__ import annotations
+
+import argparse
+import pathlib
+import re
+import sys
+
+MOCK_NAME = r"(?:MOCK|DEMO|SAMPLE|FALLBACK)_[A-Z0-9_]+"
+
+#: A `fallbackData:` whose value mentions sample data. Whether it is gated is
+#: decided separately by looking for `demoFallback(`, rather than with a
+#: lookahead: `fallbackData:\s*(?!demoFallback\()` looks correct and is not,
+#: because `\s*` backtracks to zero width and the lookahead then passes at the
+#: space, letting `.*` find the name inside the wrapper it was meant to accept.
+FALLBACK_WITH_MOCK = re.compile(rf"fallbackData:.*{MOCK_NAME}")
+
+#: An assignment of a mock inside a file, e.g. `setRules(MOCK_RULES)`.
+MOCK_ASSIGN = re.compile(rf"\bset[A-Z]\w*\(\s*{MOCK_NAME}")
+
+#: Files exempt by nature: the gate helper itself, tests, and stories.
+EXEMPT_SUFFIXES = (".test.ts", ".test.tsx", ".stories.tsx", "demoFallback.ts")
+
+#: Editor placeholder text is not data presented as tenant state.
+EXEMPT_NAMES = {
+ "SAMPLE_BODIES",
+ "SAMPLE_EVENT",
+ "SAMPLE_SIGMA",
+ "SAMPLE_KQL",
+ "SAMPLE_EQL",
+ "SAMPLE_SPL",
+ "SAMPLE_ESQL",
+ "SAMPLE_YAML",
+ "SAMPLE_QUERY",
+ "SAMPLE_RULE",
+ "DEMO_EMAIL",
+ "DEMO_PASSWORD",
+}
+
+
+def _is_exempt_name(line: str) -> bool:
+ return any(name in line for name in EXEMPT_NAMES)
+
+
+def scan(root: pathlib.Path) -> list[str]:
+ problems: list[str] = []
+
+ for path in sorted(root.rglob("*.ts*")):
+ if path.name.endswith(EXEMPT_SUFFIXES):
+ continue
+ text = path.read_text(encoding="utf-8", errors="replace")
+ rel = path.relative_to(root.parent.parent.parent)
+ lines = text.split("\n")
+ file_has_guard = "canUseDemoData" in text
+
+ for number, line in enumerate(lines, start=1):
+ stripped = line.strip()
+ if stripped.startswith(("*", "//", "/*")) or _is_exempt_name(line):
+ continue
+
+ if FALLBACK_WITH_MOCK.search(line) and "demoFallback(" not in line:
+ problems.append(
+ f"{rel}:{number}: fallbackData receives sample data directly. "
+ f"Wrap it in demoFallback(...) so it is withheld outside the hosted demo."
+ )
+
+ if MOCK_ASSIGN.search(line) and not file_has_guard:
+ problems.append(
+ f"{rel}:{number}: sample data assigned to state with no canUseDemoData() "
+ f"check in this file. Show an error or empty state instead."
+ )
+
+ return problems
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", default="apps/web/src", help="directory to scan")
+ args = parser.parse_args()
+
+ root = pathlib.Path(args.root)
+ if not root.is_dir():
+ print(f"error: {root} is not a directory", file=sys.stderr)
+ return 2
+
+ problems = scan(root)
+ if problems:
+ print(f"{len(problems)} ungated sample-data site(s):\n", file=sys.stderr)
+ for problem in problems:
+ print(f" {problem}", file=sys.stderr)
+ print(
+ "\nSee apps/web/src/lib/demoFallback.ts. Fabricated security data must " "never render as a tenant's real state.",
+ file=sys.stderr,
+ )
+ return 1
+
+ print("All sample-data fallbacks are gated behind demo mode.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())