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(security+ux): resolve #131 + 13 issues from #130 review (#132)

Beenu Arora14b10e156823
diff --git a/.env.example b/.env.example
index c60d01a08..7aa544385 100644
--- a/.env.example
+++ b/.env.example
@@ -8,8 +8,9 @@
# ║ 2. POSTGRES_PASSWORD dev Postgres password (the default below works ║
# ║ out of the box; change for shared envs) ║
# ║ 3. AISOC_CREDENTIAL_KEY Fernet key for the connector credential vault. ║
-# ║ A dev-only key is pre-filled below — generate ║
-# ║ your own for any non-laptop deployment. ║
+# ║ REQUIRED. Generate one (see below) — there is ║
+# ║ no default; the app will fail to start without ║
+# ║ it. NEVER reuse a key from anywhere public. ║
# ║ ║
# ║ Everything else has sensible defaults for `docker compose -f ║
# ║ docker-compose.dev.yml up -d`. ║
@@ -30,9 +31,10 @@ SECRET_KEY=change-this-to-a-random-secret-key-at-least-32-chars
# Application-layer encryption key for connector credentials and other
# secret payloads stored in Postgres. Generate with:
# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
-# Required outside development. The value below is a DEV-ONLY key safe for
-# local laptop usage; rotate it (and remove from any image) before deploying.
-AISOC_CREDENTIAL_KEY=tpDDex4w7lO2lKbJ7O1uGoaGkfjQYvRBM3DrIESuXvI=
+# REQUIRED. There is no built-in default — generate your own key with the
+# command above and paste it here. Treat this value like a database password:
+# never commit it, never reuse it across environments, never share it.
+AISOC_CREDENTIAL_KEY=replace-me-with-a-freshly-generated-fernet-key
# Comma-separated list of previous credential keys to support zero-downtime
# rotation. Leave blank unless you are mid-rotation.
AISOC_CREDENTIAL_KEY_ROTATION_FROM=
diff --git a/apps/web/src/app/(admin)/costs/page.tsx b/apps/web/src/app/(admin)/costs/page.tsx
index 8fe65c4f9..0c8999df6 100644
--- a/apps/web/src/app/(admin)/costs/page.tsx
+++ b/apps/web/src/app/(admin)/costs/page.tsx
@@ -1,6 +1,6 @@
import { CostDashboardView } from '@/components/admin/CostDashboardView';
-export const metadata = { title: 'Cost Dashboard — AiSOC' };
+export const metadata = { title: 'Cost Dashboard' };
export default function CostDashboardPage() {
return <CostDashboardView />;
diff --git a/apps/web/src/app/(app)/alerts/[id]/page.tsx b/apps/web/src/app/(app)/alerts/[id]/page.tsx
index 35df7fcc9..ba6f1806e 100644
--- a/apps/web/src/app/(app)/alerts/[id]/page.tsx
+++ b/apps/web/src/app/(app)/alerts/[id]/page.tsx
@@ -3,7 +3,7 @@ import { ClientOnly } from '@/components/util/ClientOnly';
import { SkeletonCard } from '@/components/ui/Skeleton';
export const metadata = {
- title: 'Alert Detail | AiSOC',
+ title: 'Alert Detail',
};
export default async function AlertDetailPage({
diff --git a/apps/web/src/app/(app)/alerts/page.tsx b/apps/web/src/app/(app)/alerts/page.tsx
index 8184dfd53..de53bc4eb 100644
--- a/apps/web/src/app/(app)/alerts/page.tsx
+++ b/apps/web/src/app/(app)/alerts/page.tsx
@@ -1,7 +1,7 @@
import { AlertsView } from '@/components/alerts/AlertsView';
export const metadata = {
- title: 'Alerts | AiSOC',
+ title: 'Alerts',
};
export default function AlertsPage() {
diff --git a/apps/web/src/app/(app)/analytics/team/page.tsx b/apps/web/src/app/(app)/analytics/team/page.tsx
index 41c26680e..ab1cc7b8c 100644
--- a/apps/web/src/app/(app)/analytics/team/page.tsx
+++ b/apps/web/src/app/(app)/analytics/team/page.tsx
@@ -1,6 +1,6 @@
import { TeamAnalyticsView } from '@/components/analytics/TeamAnalyticsView';
-export const metadata = { title: 'Team Analytics — AiSOC' };
+export const metadata = { title: 'Team Analytics' };
export default function TeamAnalyticsPage() {
return (
diff --git a/apps/web/src/app/(app)/audit/page.tsx b/apps/web/src/app/(app)/audit/page.tsx
index d4705f9c1..4a643d256 100644
--- a/apps/web/src/app/(app)/audit/page.tsx
+++ b/apps/web/src/app/(app)/audit/page.tsx
@@ -1,6 +1,6 @@
import { AuditLogView } from '@/components/audit/AuditLogView';
-export const metadata = { title: 'Audit Log — AiSOC' };
+export const metadata = { title: 'Audit Log' };
export default function AuditLogPage() {
return <AuditLogView />;
diff --git a/apps/web/src/app/(app)/cases/[id]/page.tsx b/apps/web/src/app/(app)/cases/[id]/page.tsx
index 640b7bc66..6e314edb4 100644
--- a/apps/web/src/app/(app)/cases/[id]/page.tsx
+++ b/apps/web/src/app/(app)/cases/[id]/page.tsx
@@ -7,7 +7,7 @@ interface CasePageProps {
}
export const metadata = {
- title: 'Case workspace | AiSOC',
+ title: 'Case workspace',
};
export default async function CaseDetailPage({ params }: CasePageProps) {
diff --git a/apps/web/src/app/(app)/cases/page.tsx b/apps/web/src/app/(app)/cases/page.tsx
index 8e6697d6f..78a97d649 100644
--- a/apps/web/src/app/(app)/cases/page.tsx
+++ b/apps/web/src/app/(app)/cases/page.tsx
@@ -5,7 +5,7 @@ import {
} from '@/lib/api';
export const metadata = {
- title: 'Cases | AiSOC',
+ title: 'Cases',
};
// The /cases page must reflect the current state of the backend on every
diff --git a/apps/web/src/app/(app)/compliance/[framework]/page.tsx b/apps/web/src/app/(app)/compliance/[framework]/page.tsx
index 4c52d8fa1..d93eb4d79 100644
--- a/apps/web/src/app/(app)/compliance/[framework]/page.tsx
+++ b/apps/web/src/app/(app)/compliance/[framework]/page.tsx
@@ -17,7 +17,7 @@ const FRAMEWORK_NAMES: Record<string, string> = {
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { framework } = await params;
const name = FRAMEWORK_NAMES[framework] ?? framework.toUpperCase();
- return { title: `${name} Compliance — AiSOC` };
+ return { title: `${name} Compliance` };
}
export default async function ComplianceFrameworkPage({ params }: Props) {
diff --git a/apps/web/src/app/(app)/compliance/page.tsx b/apps/web/src/app/(app)/compliance/page.tsx
index eaf7068ed..257192238 100644
--- a/apps/web/src/app/(app)/compliance/page.tsx
+++ b/apps/web/src/app/(app)/compliance/page.tsx
@@ -2,7 +2,7 @@ import { Metadata } from 'next';
import Link from 'next/link';
export const metadata: Metadata = {
- title: 'Compliance — AiSOC',
+ title: 'Compliance',
};
const FRAMEWORKS = [
diff --git a/apps/web/src/app/(app)/compliance/soc2/page.tsx b/apps/web/src/app/(app)/compliance/soc2/page.tsx
index d449c5c52..964f7242f 100644
--- a/apps/web/src/app/(app)/compliance/soc2/page.tsx
+++ b/apps/web/src/app/(app)/compliance/soc2/page.tsx
@@ -1,6 +1,6 @@
import { SOC2View } from '@/components/compliance/SOC2View';
-export const metadata = { title: 'SOC 2 Compliance — AiSOC' };
+export const metadata = { title: 'SOC 2 Compliance' };
export default function SOC2Page() {
return <SOC2View />;
diff --git a/apps/web/src/app/(app)/connectors/page.tsx b/apps/web/src/app/(app)/connectors/page.tsx
index 3bb63f7a2..ee5a92847 100644
--- a/apps/web/src/app/(app)/connectors/page.tsx
+++ b/apps/web/src/app/(app)/connectors/page.tsx
@@ -1,7 +1,7 @@
import { ConnectorsView } from '@/components/connectors/ConnectorsView';
export const metadata = {
- title: 'Connectors | AiSOC',
+ title: 'Connectors',
};
export default function ConnectorsPage() {
diff --git a/apps/web/src/app/(app)/copilot/page.tsx b/apps/web/src/app/(app)/copilot/page.tsx
index 41b3923c9..cfd6be417 100644
--- a/apps/web/src/app/(app)/copilot/page.tsx
+++ b/apps/web/src/app/(app)/copilot/page.tsx
@@ -1,7 +1,7 @@
import { CopilotView } from '@/components/copilot/CopilotView';
export const metadata = {
- title: 'AI Copilot | AiSOC',
+ title: 'AI Copilot',
};
export default function CopilotPage() {
diff --git a/apps/web/src/app/(app)/coverage-advisor/page.tsx b/apps/web/src/app/(app)/coverage-advisor/page.tsx
index b61fbe031..0bf90c1f2 100644
--- a/apps/web/src/app/(app)/coverage-advisor/page.tsx
+++ b/apps/web/src/app/(app)/coverage-advisor/page.tsx
@@ -1,6 +1,6 @@
import CoverageAdvisorView from '@/components/coverage/CoverageAdvisorView';
-export const metadata = { title: 'Coverage Gap Advisor | AiSOC' };
+export const metadata = { title: 'Coverage Gap Advisor' };
export default function CoverageAdvisorPage() {
return <CoverageAdvisorView />;
diff --git a/apps/web/src/app/(app)/dashboard/page.tsx b/apps/web/src/app/(app)/dashboard/page.tsx
index 9c0747569..5279e9df8 100644
--- a/apps/web/src/app/(app)/dashboard/page.tsx
+++ b/apps/web/src/app/(app)/dashboard/page.tsx
@@ -1,7 +1,7 @@
import { DashboardView } from '@/components/dashboard/DashboardView';
export const metadata = {
- title: 'Dashboard | AiSOC',
+ title: 'Dashboard',
};
export default function DashboardPage() {
diff --git a/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx b/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx
index 2efdc4c99..70c888f88 100644
--- a/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx
+++ b/apps/web/src/app/(app)/dashboards/soc-insights/page.tsx
@@ -23,7 +23,7 @@
import { SOCInsightsView } from '@/components/soc-insights/SOCInsightsView';
export const metadata = {
- title: 'SOC Insights | AiSOC',
+ title: 'SOC Insights',
};
export default function SOCInsightsPage() {
diff --git a/apps/web/src/app/(app)/detection/[id]/page.tsx b/apps/web/src/app/(app)/detection/[id]/page.tsx
index f2cfc065a..c6d7320aa 100644
--- a/apps/web/src/app/(app)/detection/[id]/page.tsx
+++ b/apps/web/src/app/(app)/detection/[id]/page.tsx
@@ -7,7 +7,7 @@ interface DetectionEditPageProps {
}
export const metadata = {
- title: 'Detection rule | AiSOC',
+ title: 'Detection rule',
};
export default async function DetectionEditPage({
diff --git a/apps/web/src/app/(app)/detection/catalog/page.tsx b/apps/web/src/app/(app)/detection/catalog/page.tsx
index db7bbb83a..691d9d80e 100644
--- a/apps/web/src/app/(app)/detection/catalog/page.tsx
+++ b/apps/web/src/app/(app)/detection/catalog/page.tsx
@@ -1,6 +1,6 @@
import { DetectionCatalog } from '@/components/detections/DetectionCatalog';
-export const metadata = { title: 'Detection Catalog — AiSOC' };
+export const metadata = { title: 'Detection Catalog' };
export default function DetectionCatalogPage() {
return <DetectionCatalog />;
diff --git a/apps/web/src/app/(app)/detection/coverage/page.tsx b/apps/web/src/app/(app)/detection/coverage/page.tsx
index 734c1ffc9..4bde84fdd 100644
--- a/apps/web/src/app/(app)/detection/coverage/page.tsx
+++ b/apps/web/src/app/(app)/detection/coverage/page.tsx
@@ -1,7 +1,7 @@
import { CoverageView } from '@/components/detections/CoverageView';
export const metadata = {
- title: 'MITRE ATT&CK Coverage | AiSOC',
+ title: 'MITRE ATT&CK Coverage',
description:
"MITRE ATT&CK coverage matrix derived from AiSOC's shipped detections, broken down by tier (native, imported, community).",
};
diff --git a/apps/web/src/app/(app)/detection/new/page.tsx b/apps/web/src/app/(app)/detection/new/page.tsx
index 6b0c825ff..e5f9e0b5e 100644
--- a/apps/web/src/app/(app)/detection/new/page.tsx
+++ b/apps/web/src/app/(app)/detection/new/page.tsx
@@ -1,7 +1,7 @@
import { RuleEditor } from '@/components/detections/RuleEditor';
export const metadata = {
- title: 'New detection rule | AiSOC',
+ title: 'New detection rule',
};
export default function NewDetectionPage() {
diff --git a/apps/web/src/app/(app)/detection/page.tsx b/apps/web/src/app/(app)/detection/page.tsx
index cefb902ea..5f2a11a4d 100644
--- a/apps/web/src/app/(app)/detection/page.tsx
+++ b/apps/web/src/app/(app)/detection/page.tsx
@@ -1,7 +1,7 @@
import { DetectionsView } from '@/components/detections/DetectionsView';
export const metadata = {
- title: 'Detection rules | AiSOC',
+ title: 'Detection rules',
};
export default function DetectionPage() {
diff --git a/apps/web/src/app/(app)/detection/proposals/page.tsx b/apps/web/src/app/(app)/detection/proposals/page.tsx
index 5d84e2d53..b63711144 100644
--- a/apps/web/src/app/(app)/detection/proposals/page.tsx
+++ b/apps/web/src/app/(app)/detection/proposals/page.tsx
@@ -1,6 +1,6 @@
import { DetectionProposalsView } from '@/components/detections/DetectionProposalsView';
-export const metadata = { title: 'Detection proposals — AiSOC' };
+export const metadata = { title: 'Detection proposals' };
export default function DetectionProposalsPage() {
return <DetectionProposalsView />;
diff --git a/apps/web/src/app/(app)/detection/tuning/page.tsx b/apps/web/src/app/(app)/detection/tuning/page.tsx
index 2f2493e03..84a190f2e 100644
--- a/apps/web/src/app/(app)/detection/tuning/page.tsx
+++ b/apps/web/src/app/(app)/detection/tuning/page.tsx
@@ -1,7 +1,7 @@
import RuleTuningView from '@/components/detections/RuleTuningView';
export const metadata = {
- title: 'Detection Tuning | AiSOC',
+ title: 'Detection Tuning',
};
export default function DetectionTuningPage() {
diff --git a/apps/web/src/app/(app)/easm/page.tsx b/apps/web/src/app/(app)/easm/page.tsx
index 6aadc9b6f..d3ea12b4a 100644
--- a/apps/web/src/app/(app)/easm/page.tsx
+++ b/apps/web/src/app/(app)/easm/page.tsx
@@ -1,6 +1,6 @@
import { EASMView } from '@/components/easm/EASMView';
-export const metadata = { title: 'EASM — AiSOC' };
+export const metadata = { title: 'EASM' };
export default function EASMPage() {
return (
diff --git a/apps/web/src/app/(app)/fim/page.tsx b/apps/web/src/app/(app)/fim/page.tsx
index 313ff338f..d70fb8b7e 100644
--- a/apps/web/src/app/(app)/fim/page.tsx
+++ b/apps/web/src/app/(app)/fim/page.tsx
@@ -2,7 +2,7 @@ import type { Metadata } from 'next';
import { FimDashboard } from '@/components/fim/FimDashboard';
export const metadata: Metadata = {
- title: 'File Integrity Monitoring | AiSOC',
+ title: 'File Integrity Monitoring',
description:
'Real-time osquery file_events telemetry — track file creation, deletion, and modification across your fleet.',
};
diff --git a/apps/web/src/app/(app)/graph/page.tsx b/apps/web/src/app/(app)/graph/page.tsx
index 8be07c79f..6504add97 100644
--- a/apps/web/src/app/(app)/graph/page.tsx
+++ b/apps/web/src/app/(app)/graph/page.tsx
@@ -1,7 +1,7 @@
import AttackGraphClient from '@/components/graph/AttackGraphClient';
export const metadata = {
- title: 'Attack Graph | AiSOC',
+ title: 'Attack Graph',
};
export default function GraphPage() {
diff --git a/apps/web/src/app/(app)/honeytokens/layout.tsx b/apps/web/src/app/(app)/honeytokens/layout.tsx
new file mode 100644
index 000000000..d60065903
--- /dev/null
+++ b/apps/web/src/app/(app)/honeytokens/layout.tsx
@@ -0,0 +1,14 @@
+import type { Metadata } from 'next';
+
+// The honeytokens page itself is a client component (`"use client"`), so it
+// can't export `metadata` directly. Defining it on a colocated server layout
+// lets the page contribute a real <title> ("Honeytokens | AiSOC" via the root
+// layout's title template) instead of falling through to the global default.
+export const metadata: Metadata = {
+ title: 'Honeytokens',
+ description: 'Generate, deploy, and monitor honeytokens with first-touch alerting.',
+};
+
+export default function HoneytokensLayout({ children }: { children: React.ReactNode }) {
+ return <>{children}</>;
+}
diff --git a/apps/web/src/app/(app)/hunt/page.tsx b/apps/web/src/app/(app)/hunt/page.tsx
index 5a3dff23b..fc60c1c1c 100644
--- a/apps/web/src/app/(app)/hunt/page.tsx
+++ b/apps/web/src/app/(app)/hunt/page.tsx
@@ -1,7 +1,7 @@
import { HuntView } from '@/components/hunt/HuntView';
export const metadata = {
- title: 'Threat Hunting | AiSOC',
+ title: 'Threat Hunting',
};
export default function HuntPage() {
diff --git a/apps/web/src/app/(app)/identity/permissions/page.tsx b/apps/web/src/app/(app)/identity/permissions/page.tsx
index 532e68eab..0f40ec417 100644
--- a/apps/web/src/app/(app)/identity/permissions/page.tsx
+++ b/apps/web/src/app/(app)/identity/permissions/page.tsx
@@ -11,7 +11,7 @@
import EffectivePermissionsClient from './EffectivePermissionsClient';
export const metadata = {
- title: 'Effective Permissions | AiSOC',
+ title: 'Effective Permissions',
};
export default function EffectivePermissionsPage() {
diff --git a/apps/web/src/app/(app)/investigate/page.tsx b/apps/web/src/app/(app)/investigate/page.tsx
index 90baa5658..302da47b6 100644
--- a/apps/web/src/app/(app)/investigate/page.tsx
+++ b/apps/web/src/app/(app)/investigate/page.tsx
@@ -16,7 +16,7 @@
import { permanentRedirect } from "next/navigation";
export const metadata = {
- title: "Investigate | AiSOC",
+ title: "Investigate",
};
interface InvestigatePageProps {
diff --git a/apps/web/src/app/(app)/marketplace/page.tsx b/apps/web/src/app/(app)/marketplace/page.tsx
index e50fb72ca..c8c734b8c 100644
--- a/apps/web/src/app/(app)/marketplace/page.tsx
+++ b/apps/web/src/app/(app)/marketplace/page.tsx
@@ -1,7 +1,7 @@
import { MarketplaceView } from '@/components/marketplace/MarketplaceView';
export const metadata = {
- title: 'Marketplace | AiSOC',
+ title: 'Marketplace',
};
export default function MarketplacePage() {
diff --git a/apps/web/src/app/(app)/mssp/page.tsx b/apps/web/src/app/(app)/mssp/page.tsx
index 49250fa66..b006c836e 100644
--- a/apps/web/src/app/(app)/mssp/page.tsx
+++ b/apps/web/src/app/(app)/mssp/page.tsx
@@ -1,6 +1,6 @@
import MSSPDashboardView from '@/components/mssp/MSSPDashboardView';
-export const metadata = { title: 'MSSP Executive Dashboard | AiSOC' };
+export const metadata = { title: 'MSSP Executive Dashboard' };
export default function MSSPPage() {
return <MSSPDashboardView />;
diff --git a/apps/web/src/app/(app)/noise-tuning/page.tsx b/apps/web/src/app/(app)/noise-tuning/page.tsx
index 00b35d7d6..51a38d3fe 100644
--- a/apps/web/src/app/(app)/noise-tuning/page.tsx
+++ b/apps/web/src/app/(app)/noise-tuning/page.tsx
@@ -1,6 +1,6 @@
import { redirect } from 'next/navigation';
-export const metadata = { title: 'Alert Noise Tuning | AiSOC' };
+export const metadata = { title: 'Alert Noise Tuning' };
/**
* Back-compat redirect. The legacy `/noise-tuning` prototype has been
diff --git a/apps/web/src/app/(app)/onboarding/page.tsx b/apps/web/src/app/(app)/onboarding/page.tsx
index 8a2bfeda5..15fcd648b 100644
--- a/apps/web/src/app/(app)/onboarding/page.tsx
+++ b/apps/web/src/app/(app)/onboarding/page.tsx
@@ -2,7 +2,7 @@ import { Suspense } from 'react';
import { OnboardingView } from '@/components/onboarding/OnboardingView';
export const metadata = {
- title: 'Get started | AiSOC',
+ title: 'Get started',
};
// Onboarding has no static data — the catalog and any existing connectors
diff --git a/apps/web/src/app/(app)/playbooks/[id]/page.tsx b/apps/web/src/app/(app)/playbooks/[id]/page.tsx
index 9ea5e0764..0911961cc 100644
--- a/apps/web/src/app/(app)/playbooks/[id]/page.tsx
+++ b/apps/web/src/app/(app)/playbooks/[id]/page.tsx
@@ -3,7 +3,7 @@ import { ClientOnly } from '@/components/util/ClientOnly';
import { SkeletonCard } from '@/components/ui/Skeleton';
export const metadata = {
- title: 'Playbook Editor | AiSOC',
+ title: 'Playbook Editor',
};
export default async function PlaybookEditorPage({
diff --git a/apps/web/src/app/(app)/playbooks/page.tsx b/apps/web/src/app/(app)/playbooks/page.tsx
index c90e543bc..b503542bf 100644
--- a/apps/web/src/app/(app)/playbooks/page.tsx
+++ b/apps/web/src/app/(app)/playbooks/page.tsx
@@ -1,7 +1,7 @@
import { PlaybooksView } from '@/components/playbooks/PlaybooksView';
export const metadata = {
- title: 'Playbooks | AiSOC',
+ title: 'Playbooks',
};
export default function PlaybooksPage() {
diff --git a/apps/web/src/app/(app)/purple-team/layout.tsx b/apps/web/src/app/(app)/purple-team/layout.tsx
new file mode 100644
index 000000000..cc798ef19
--- /dev/null
+++ b/apps/web/src/app/(app)/purple-team/layout.tsx
@@ -0,0 +1,15 @@
+import type { Metadata } from 'next';
+
+// The purple-team page itself is a client component (`'use client'`), so it
+// can't export `metadata` directly. Defining it on a colocated server layout
+// lets the page contribute a real <title> ("Purple Team | AiSOC" via the root
+// layout's title template) instead of falling through to the global default.
+export const metadata: Metadata = {
+ title: 'Purple Team',
+ description:
+ 'Atomic Red Team execution, Caldera adversary emulation, ATT&CK coverage heatmap, and tabletop exercise simulator.',
+};
+
+export default function PurpleTeamLayout({ children }: { children: React.ReactNode }) {
+ return <>{children}</>;
+}
diff --git a/apps/web/src/app/(app)/queue/page.tsx b/apps/web/src/app/(app)/queue/page.tsx
index 4d3840231..3bc02968b 100644
--- a/apps/web/src/app/(app)/queue/page.tsx
+++ b/apps/web/src/app/(app)/queue/page.tsx
@@ -1,7 +1,7 @@
import { QueueView } from '@/components/queue/QueueView';
export const metadata = {
- title: 'Investigation Queue | AiSOC',
+ title: 'Investigation Queue',
};
export default function QueuePage() {
diff --git a/apps/web/src/app/(app)/reports/digest/page.tsx b/apps/web/src/app/(app)/reports/digest/page.tsx
index 96d6c3481..df54d87d5 100644
--- a/apps/web/src/app/(app)/reports/digest/page.tsx
+++ b/apps/web/src/app/(app)/reports/digest/page.tsx
@@ -1,6 +1,6 @@
import { ExecutiveDigest } from '@/components/reports/ExecutiveDigest';
-export const metadata = { title: 'Executive Digest — AiSOC' };
+export const metadata = { title: 'Executive Digest' };
export default function ExecutiveDigestPage() {
return (
diff --git a/apps/web/src/app/(app)/settings/business-context/page.tsx b/apps/web/src/app/(app)/settings/business-context/page.tsx
index b7420b4ec..c4c622ed9 100644
--- a/apps/web/src/app/(app)/settings/business-context/page.tsx
+++ b/apps/web/src/app/(app)/settings/business-context/page.tsx
@@ -20,7 +20,7 @@ import type { Metadata } from "next";
import { BusinessContextSettings } from "./BusinessContextSettings";
export const metadata: Metadata = {
- title: "Business Context Rules | Settings | AiSOC",
+ title: "Business Context Rules | Settings",
};
export default function BusinessContextSettingsPage() {
diff --git a/apps/web/src/app/(app)/settings/page.tsx b/apps/web/src/app/(app)/settings/page.tsx
index e662d5388..293dd207d 100644
--- a/apps/web/src/app/(app)/settings/page.tsx
+++ b/apps/web/src/app/(app)/settings/page.tsx
@@ -1,7 +1,7 @@
import { SettingsView } from '@/components/settings/SettingsView';
export const metadata = {
- title: 'Settings | AiSOC',
+ title: 'Settings',
};
export default function SettingsPage() {
diff --git a/apps/web/src/app/(app)/settings/rbac/page.tsx b/apps/web/src/app/(app)/settings/rbac/page.tsx
index dd54b6671..ff713b062 100644
--- a/apps/web/src/app/(app)/settings/rbac/page.tsx
+++ b/apps/web/src/app/(app)/settings/rbac/page.tsx
@@ -1,7 +1,7 @@
import { RBACView } from '@/components/settings/RBACView';
export const metadata = {
- title: 'Roles & Permissions | AiSOC',
+ title: 'Roles & Permissions',
};
export default function RBACPage() {
diff --git a/apps/web/src/app/(app)/shifts/page.tsx b/apps/web/src/app/(app)/shifts/page.tsx
index 4437a12fa..e006322f7 100644
--- a/apps/web/src/app/(app)/shifts/page.tsx
+++ b/apps/web/src/app/(app)/shifts/page.tsx
@@ -1,6 +1,6 @@
import { ShiftsView } from '@/components/shifts/ShiftsView';
-export const metadata = { title: 'Shifts — AiSOC' };
+export const metadata = { title: 'Shifts' };
export default function ShiftsPage() {
return (
diff --git a/apps/web/src/app/(app)/sla/page.tsx b/apps/web/src/app/(app)/sla/page.tsx
index aad9c7cb3..537c1fea2 100644
--- a/apps/web/src/app/(app)/sla/page.tsx
+++ b/apps/web/src/app/(app)/sla/page.tsx
@@ -1,6 +1,6 @@
import { SLADashboard } from '@/components/sla/SLADashboard';
-export const metadata = { title: 'SLA Tracking — AiSOC' };
+export const metadata = { title: 'SLA Tracking' };
export default function SLAPage() {
return (
diff --git a/apps/web/src/app/(app)/threat-intel/page.tsx b/apps/web/src/app/(app)/threat-intel/page.tsx
index 2c0e6b682..60a4b145e 100644
--- a/apps/web/src/app/(app)/threat-intel/page.tsx
+++ b/apps/web/src/app/(app)/threat-intel/page.tsx
@@ -1,7 +1,7 @@
import { ThreatIntelView } from '@/components/threat-intel/ThreatIntelView';
export const metadata = {
- title: 'Threat Intelligence | AiSOC',
+ title: 'Threat Intelligence',
};
export default function ThreatIntelPage() {
diff --git a/apps/web/src/app/(marketing)/blog/[slug]/page.tsx b/apps/web/src/app/(marketing)/blog/[slug]/page.tsx
index 16f4699af..bdbe5fb04 100644
--- a/apps/web/src/app/(marketing)/blog/[slug]/page.tsx
+++ b/apps/web/src/app/(marketing)/blog/[slug]/page.tsx
@@ -34,10 +34,10 @@ export async function generateMetadata({
}): Promise<Metadata> {
const { slug } = await params;
const post = getPostBySlug(slug);
- if (!post) return { title: 'Post not found — AiSOC' };
+ if (!post) return { title: 'Post not found' };
const fm = post.frontmatter;
return {
- title: `${fm.title} — AiSOC blog`,
+ title: fm.title,
description: fm.description,
alternates: { canonical: `/blog/${slug}` },
openGraph: {
diff --git a/apps/web/src/app/(marketing)/blog/page.tsx b/apps/web/src/app/(marketing)/blog/page.tsx
index 05d6db229..53c3bc725 100644
--- a/apps/web/src/app/(marketing)/blog/page.tsx
+++ b/apps/web/src/app/(marketing)/blog/page.tsx
@@ -15,7 +15,7 @@ import { formatPostDate, listPosts } from '@/lib/blog';
*/
export const metadata: Metadata = {
- title: 'Engineering blog — AiSOC',
+ title: 'Engineering blog',
description:
'Long-form, technical writing from the team building AiSOC: graph-at-ingest, sub-minute investigation latency, the L0–L4 SOC automation maturity model.',
alternates: { canonical: '/blog' },
diff --git a/apps/web/src/app/(marketing)/customers/[slug]/page.tsx b/apps/web/src/app/(marketing)/customers/[slug]/page.tsx
index af5547420..ee056efc9 100644
--- a/apps/web/src/app/(marketing)/customers/[slug]/page.tsx
+++ b/apps/web/src/app/(marketing)/customers/[slug]/page.tsx
@@ -39,11 +39,11 @@ export async function generateMetadata({
const { slug } = await params;
const study = getCustomerBySlug(slug);
if (!study) {
- return { title: 'Customer not found — AiSOC' };
+ return { title: 'Customer not found' };
}
const fm = study.frontmatter;
return {
- title: `${fm.title} — AiSOC customer story`,
+ title: `${fm.title} — customer story`,
description: fm.challenge,
alternates: { canonical: `/customers/${slug}` },
openGraph: {
diff --git a/apps/web/src/app/(marketing)/customers/page.tsx b/apps/web/src/app/(marketing)/customers/page.tsx
index ad9f3036e..7085b4085 100644
--- a/apps/web/src/app/(marketing)/customers/page.tsx
+++ b/apps/web/src/app/(marketing)/customers/page.tsx
@@ -12,7 +12,7 @@ import { listCustomers } from '@/lib/customers';
*/
export const metadata: Metadata = {
- title: 'Customers — AiSOC',
+ title: 'Customers',
description:
'Reference customers running AiSOC in production: who they are, the security challenge, and the measurable outcome.',
alternates: { canonical: '/customers' },
diff --git a/apps/web/src/app/(marketing)/sovereign/page.tsx b/apps/web/src/app/(marketing)/sovereign/page.tsx
index e0567b0d5..93fac2be9 100644
--- a/apps/web/src/app/(marketing)/sovereign/page.tsx
+++ b/apps/web/src/app/(marketing)/sovereign/page.tsx
@@ -21,7 +21,7 @@ import { Footer } from '@/components/landing/Footer';
*/
export const metadata: Metadata = {
- title: 'Sovereign + air-gap deployment — AiSOC',
+ title: 'Sovereign + air-gap deployment',
description:
'AiSOC runs anywhere: air-gapped, on-prem, hybrid, public cloud, or managed SaaS — with cloud LLM APIs, a local Ollama sidecar, or a bring-your-own LLM endpoint. EU, US, India, or custom data residency.',
alternates: { canonical: '/sovereign' },
diff --git a/apps/web/src/app/(responder)/responder/login/page.tsx b/apps/web/src/app/(responder)/responder/login/page.tsx
index 3caad8b2b..39c9b209b 100644
--- a/apps/web/src/app/(responder)/responder/login/page.tsx
+++ b/apps/web/src/app/(responder)/responder/login/page.tsx
@@ -26,10 +26,23 @@ type Phase = 'idle' | 'pending' | 'success' | 'error';
// the URL and is only ever reached interactively from a phone.
export const dynamic = 'force-dynamic';
+/**
+ * Sanitize ``?next=`` to a same-origin relative path. Protects against
+ * open-redirect via a crafted login link.
+ */
+function sanitizeNext(raw: string | null | undefined): string {
+ const fallback = '/responder/triage';
+ if (!raw) return fallback;
+ if (raw.startsWith('//') || raw.startsWith('\\\\')) return fallback;
+ if (!raw.startsWith('/')) return fallback;
+ if (raw.startsWith('/\\')) return fallback;
+ return raw;
+}
+
function ResponderLoginInner() {
const router = useRouter();
const search = useSearchParams();
- const next = search?.get('next') || '/responder/triage';
+ const next = sanitizeNext(search?.get('next'));
const [email, setEmail] = useState('');
const [phase, setPhase] = useState<Phase>('idle');
diff --git a/apps/web/src/app/benchmark/page.tsx b/apps/web/src/app/benchmark/page.tsx
index 86ae9f07f..1ccaebd95 100644
--- a/apps/web/src/app/benchmark/page.tsx
+++ b/apps/web/src/app/benchmark/page.tsx
@@ -11,7 +11,7 @@ import { KpiBar } from '@/components/benchmark/KpiBar';
import { CommunitySubmissions } from '@/components/benchmark/CommunitySubmissions';
export const metadata: Metadata = {
- title: 'Public benchmark scoreboard — AiSOC',
+ title: 'Public benchmark scoreboard',
description:
'A reproducible regression harness over the AiSOC substrate. Four CI gates over a 200-incident synthetic dataset (MITRE / completeness / response quality) plus a 1,000-alert noisy stream (alert reduction). Per-template macros, per-case means, alert-reduction %, the 2026 KPI bar, and a fixed-dataset community leaderboard. The page documents what each metric measures and what it does not.',
alternates: { canonical: '/benchmark' },
diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx
index 0414d534a..07d2747c9 100644
--- a/apps/web/src/app/login/page.tsx
+++ b/apps/web/src/app/login/page.tsx
@@ -24,10 +24,33 @@ export const dynamic = 'force-dynamic';
const DEMO_EMAIL = '[email protected]';
const DEMO_PASSWORD = 'aisoc-demo';
+/**
+ * Sanitize the ``?next=`` redirect target so a crafted link can't be used to
+ * bounce an authenticated user to an attacker-controlled host.
+ *
+ * Only same-origin relative paths are allowed. Anything that looks like an
+ * absolute URL (``http://``, ``//evil.com``), a JS scheme, or a path that
+ * doesn't start with a single ``/`` is replaced with the dashboard default.
+ */
+function sanitizeNext(raw: string | null | undefined): string {
+ const fallback = '/dashboard';
+ if (!raw) return fallback;
+ // Reject protocol-relative URLs (//evil.com) and backslash variants
+ // (some browsers normalize \\ to //).
+ if (raw.startsWith('//') || raw.startsWith('\\\\')) return fallback;
+ // Require a single leading slash. This rejects ``http://...``,
+ // ``javascript:...``, ``data:...``, ``mailto:...``, and bare paths
+ // like ``dashboard`` (which would resolve relative to the current URL).
+ if (!raw.startsWith('/')) return fallback;
+ // Reject ``/\evil.com`` style tricks.
+ if (raw.startsWith('/\\')) return fallback;
+ return raw;
+}
+
function LoginInner() {
const router = useRouter();
const search = useSearchParams();
- const next = search?.get('next') || '/dashboard';
+ const next = sanitizeNext(search?.get('next'));
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx
index 5212d48ee..48860a93b 100644
--- a/apps/web/src/app/page.tsx
+++ b/apps/web/src/app/page.tsx
@@ -20,7 +20,11 @@ import { StartHero } from '@/components/onboarding/StartHero';
*/
export const metadata: Metadata = {
- title: 'AiSOC — open-source AI Security Operations Center',
+ // Use `absolute` so the root layout's `template: '%s | AiSOC'` doesn't
+ // append a redundant " | AiSOC" to a title that already leads with the
+ // brand. Without this, the homepage tab renders
+ // `AiSOC — open-source AI Security Operations Center | AiSOC`.
+ title: { absolute: 'AiSOC — open-source AI Security Operations Center' },
description:
'Open-source AI SOC: 200-incident eval harness, 26 click-and-connect security sources, MITRE ATT&CK-mapped autonomous investigation. Try the live demo or self-host in under 5 minutes.',
alternates: { canonical: '/' },
diff --git a/apps/web/src/app/why-open-source/page.tsx b/apps/web/src/app/why-open-source/page.tsx
index 8a64f2d64..f2bec755b 100644
--- a/apps/web/src/app/why-open-source/page.tsx
+++ b/apps/web/src/app/why-open-source/page.tsx
@@ -4,12 +4,15 @@ import { LandingNav } from '@/components/landing/LandingNav';
import { Footer } from '@/components/landing/Footer';
export const metadata: Metadata = {
- title: 'Why AiSOC is open source',
+ // Use `absolute` so the root layout's `template: '%s | AiSOC'` doesn't
+ // append a redundant " | AiSOC" to a title that already leads with the
+ // brand name.
+ title: { absolute: 'Why AiSOC is open source' },
description:
'AiSOC is MIT-licensed and self-hostable, with the agent loop and prompt templates in the repo. This page explains why that posture matters for regulated buyers and what the trade-offs are.',
alternates: { canonical: '/why-open-source' },
openGraph: {
- title: 'Why AiSOC is open source — AiSOC',
+ title: 'Why AiSOC is open source',
description:
'AiSOC is MIT-licensed and self-hostable. The agent loop and prompts are in the repo, and a 200-incident eval harness runs in CI.',
type: 'article',
diff --git a/docker-compose.yml b/docker-compose.yml
index 9c6701415..bcde7b9b9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -487,12 +487,15 @@ services:
restart: unless-stopped
honeytokens:
+ # Gated behind the `extras` profile: image isn't published to GHCR yet, so
+ # `aisoc serve` skips it by default. Opt in with `--profile extras` and the
+ # local Dockerfile build will run.
+ profiles: ["extras"]
build:
context: ./services/honeytokens
dockerfile: Dockerfile
- # Not in publish-images.yml matrix yet — pull falls back to local build.
image: ghcr.io/beenuar/aisoc-honeytokens:${AISOC_VERSION:-latest}
- pull_policy: missing
+ pull_policy: build
container_name: aisoc-honeytokens
depends_on:
postgres:
@@ -513,12 +516,15 @@ services:
restart: unless-stopped
purple-team:
+ # Gated behind the `extras` profile: image isn't published to GHCR yet, so
+ # `aisoc serve` skips it by default. Opt in with `--profile extras` and the
+ # local Dockerfile build will run.
+ profiles: ["extras"]
build:
context: ./services/purple-team
dockerfile: Dockerfile
- # Not in publish-images.yml matrix yet — pull falls back to local build.
image: ghcr.io/beenuar/aisoc-purple-team:${AISOC_VERSION:-latest}
- pull_policy: missing
+ pull_policy: build
container_name: aisoc-purple-team
depends_on:
postgres:
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 405458b85..97fa0502b 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -10799,6 +10799,8 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/easm/assets:
get:
tags:
@@ -10809,7 +10811,11 @@ paths:
``tenant_id`` defaults to the authenticated user''s tenant, so the analyst
- console can hit ``/easm/assets`` without explicit tenant scoping.'
+ console can hit ``/easm/assets`` without explicit tenant scoping. A user
+
+ can never request another tenant''s assets — supplying a foreign
+
+ ``tenant_id`` returns 403.'
operationId: list_external_assets_api_v1_easm_assets_get
security:
- HTTPBearer: []
@@ -10861,7 +10867,12 @@ paths:
tags:
- easm
summary: List External Asset Drift
- description: List drift events (new ports, certs, sub-domains, etc.).
+ description: 'List drift events (new ports, certs, sub-domains, etc.).
+
+
+ A user can never request another tenant''s drift events — supplying a
+
+ foreign ``tenant_id`` returns 403.'
operationId: list_external_asset_drift_api_v1_easm_drift_get
security:
- HTTPBearer: []
diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.py
index 042872d6f..d46e69b82 100644
--- a/services/agents/app/playbook/engine.py
+++ b/services/agents/app/playbook/engine.py
@@ -30,7 +30,13 @@ from .ssrf_guard import SSRFError, validate_outbound_url
logger = logging.getLogger("aisoc.playbook.engine")
_REALTIME_URL = os.getenv("REALTIME_URL", "http://realtime:3001")
-_INTERNAL_TOKEN = os.getenv("REALTIME_INTERNAL_TOKEN", "changeme")
+# Internal token used to authenticate the agents service to the realtime
+# service. Previously this defaulted to the literal string ``"changeme"``,
+# which meant an operator who forgot to wire the secret would silently ship a
+# well-known token. We now default to empty and let the call sites treat an
+# empty token as "no internal auth" (skip the header) so a misconfigured
+# deployment fails closed instead of inheriting a public default.
+_INTERNAL_TOKEN = os.getenv("REALTIME_INTERNAL_TOKEN", "")
_API_URL = os.getenv("API_URL", "http://api:8000")
@@ -515,10 +521,17 @@ _HANDLERS = {
async def _emit(run_id: str, event_type: str, payload: dict, http: httpx.AsyncClient) -> None:
try:
+ headers: dict[str, str] = {}
+ # Only include the internal-auth header when an operator has actually
+ # configured a token. Sending a literal "changeme" used to make a
+ # misconfigured deployment look authenticated to anything that
+ # whitelisted the same string.
+ if _INTERNAL_TOKEN:
+ headers["x-internal-token"] = _INTERNAL_TOKEN
await http.post(
f"{_REALTIME_URL}/internal/agent-event",
json={"channel": f"playbook:{run_id}", "type": event_type, "data": payload},
- headers={"x-internal-token": _INTERNAL_TOKEN},
+ headers=headers,
timeout=3,
)
except Exception:
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index 25319d595..28d0f4ca9 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -431,7 +431,8 @@ async def list_cases(
rows = await db.execute(text(q).bindparams(**params))
return [_row_to_case(r) for r in rows.fetchall()]
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.post("", response_model=CaseResponse, status_code=status.HTTP_201_CREATED, summary="Create case")
@@ -476,7 +477,8 @@ async def create_case(body: CreateCaseRequest, db: DBSession, user: AuthUser) ->
await db.commit()
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
response = _row_to_case(row)
@@ -588,7 +590,8 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
await db.commit()
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
response = _row_to_case(row)
@@ -655,7 +658,8 @@ async def add_alerts(case_id: str, body: AddAlertsRequest, db: DBSession, user:
raise
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.post("/{case_id}/observables", response_model=CaseResponse, summary="Update observable graph")
@@ -700,7 +704,8 @@ async def update_observables(case_id: str, body: UpdateObservablesRequest, db: D
return _row_to_case(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.post("/{case_id}/comments", response_model=CommentResponse, status_code=201, summary="Add comment")
@@ -748,7 +753,8 @@ async def add_comment(case_id: str, body: AddCommentRequest, db: DBSession, user
)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/{case_id}/comments", response_model=list[CommentResponse], summary="List case comments")
@@ -1000,7 +1006,8 @@ async def create_task(
return _row_to_task(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.patch("/{case_id}/tasks/{task_id}", response_model=TaskResponse, summary="Update task")
@@ -1056,7 +1063,8 @@ async def update_task(
raise
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in cases endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
# ─────────────────────────────────────────────────────────────────────────────
diff --git a/services/api/app/api/v1/endpoints/compliance.py b/services/api/app/api/v1/endpoints/compliance.py
index 0d3cbde3c..f20e4de70 100644
--- a/services/api/app/api/v1/endpoints/compliance.py
+++ b/services/api/app/api/v1/endpoints/compliance.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import hashlib
import json
+import logging
import uuid
from datetime import UTC, datetime
from typing import Any, Literal
@@ -29,6 +30,8 @@ from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
+logger = logging.getLogger(__name__)
+
router = APIRouter(prefix="/compliance", tags=["compliance"])
# ────────────────────────────────────────────────────────────────────────────
@@ -272,7 +275,8 @@ async def collect_evidence(body: CollectEvidenceRequest, db: DBSession, user: Au
return _row_to_evidence(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in compliance endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/evidence", response_model=list[EvidenceResponse], summary="List evidence items")
@@ -308,7 +312,8 @@ async def list_evidence(
rows = (await db.execute(q)).fetchall()
return [_row_to_evidence(r) for r in rows]
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in compliance endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/evidence/{evidence_id}", response_model=EvidenceResponse, summary="Get evidence item")
@@ -337,7 +342,8 @@ async def review_evidence(evidence_id: uuid.UUID, body: ReviewEvidenceRequest, d
raise
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in compliance endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/report", response_model=list[CompliancePosture], summary="Generate compliance posture report")
@@ -367,7 +373,8 @@ async def compliance_report(
try:
rows = (await db.execute(q)).fetchall()
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in compliance endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
# Aggregate by framework
by_fw: dict[str, Any] = {}
diff --git a/services/api/app/api/v1/endpoints/easm.py b/services/api/app/api/v1/endpoints/easm.py
index c8f31279b..60bd0f5f0 100644
--- a/services/api/app/api/v1/endpoints/easm.py
+++ b/services/api/app/api/v1/endpoints/easm.py
@@ -59,6 +59,7 @@ async def trigger_easm_scan(
body: ScanRequest,
background_tasks: BackgroundTasks,
db: AsyncSession = Depends(get_db),
+ current_user: CurrentUser = Depends(get_current_user),
) -> dict[str, Any]:
"""
Trigger an EASM discovery scan for a tenant (Tier 3.6).
@@ -71,6 +72,12 @@ async def trigger_easm_scan(
if not s.AISOC_FEATURE_EASM:
raise HTTPException(status_code=403, detail="EASM feature is disabled")
+ if body.tenant_id != current_user.tenant_id:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Cannot trigger EASM scan for a different tenant",
+ )
+
tenant = await db.get(Tenant, body.tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
@@ -103,9 +110,16 @@ async def list_external_assets(
"""List externally discovered assets for a tenant.
``tenant_id`` defaults to the authenticated user's tenant, so the analyst
- console can hit ``/easm/assets`` without explicit tenant scoping.
+ console can hit ``/easm/assets`` without explicit tenant scoping. A user
+ can never request another tenant's assets — supplying a foreign
+ ``tenant_id`` returns 403.
"""
- effective_tenant = tenant_id or current_user.tenant_id
+ if tenant_id is not None and tenant_id != current_user.tenant_id:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Cannot list EASM assets for a different tenant",
+ )
+ effective_tenant = current_user.tenant_id
stmt = select(ExternalAsset).where(ExternalAsset.tenant_id == effective_tenant).order_by(ExternalAsset.last_seen.desc()).limit(limit)
if asset_type:
stmt = stmt.where(ExternalAsset.asset_type == asset_type)
@@ -133,8 +147,17 @@ async def list_external_asset_drift(
db: AsyncSession = Depends(get_db),
current_user: CurrentUser = Depends(get_current_user),
) -> list[dict[str, Any]]:
- """List drift events (new ports, certs, sub-domains, etc.)."""
- effective_tenant = tenant_id or current_user.tenant_id
+ """List drift events (new ports, certs, sub-domains, etc.).
+
+ A user can never request another tenant's drift events — supplying a
+ foreign ``tenant_id`` returns 403.
+ """
+ if tenant_id is not None and tenant_id != current_user.tenant_id:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Cannot list EASM drift for a different tenant",
+ )
+ effective_tenant = current_user.tenant_id
stmt = (
select(ExternalAssetDrift)
.where(ExternalAssetDrift.tenant_id == effective_tenant)
diff --git a/services/api/app/api/v1/endpoints/hunts.py b/services/api/app/api/v1/endpoints/hunts.py
index b18cc4390..8be19aef3 100644
--- a/services/api/app/api/v1/endpoints/hunts.py
+++ b/services/api/app/api/v1/endpoints/hunts.py
@@ -25,6 +25,7 @@ cross-tenant data leakage during the rollout window.
from __future__ import annotations
import json
+import logging
import os
import uuid
from datetime import UTC, datetime
@@ -37,6 +38,8 @@ from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
+logger = logging.getLogger(__name__)
+
router = APIRouter(prefix="/hunts", tags=["hunts"])
# ────────────────────────────────────────────────────────────────────────────
@@ -232,7 +235,8 @@ async def list_hunts(
rows = (await db.execute(q)).fetchall()
return [_row_to_hunt(r) for r in rows]
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in hunts endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.post("", response_model=HuntResponse, status_code=status.HTTP_201_CREATED, summary="Create hunt hypothesis")
@@ -273,7 +277,8 @@ async def create_hunt(body: CreateHuntRequest, db: DBSession, user: AuthUser) ->
return _row_to_hunt(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in hunts endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/{hunt_id}", response_model=HuntResponse, summary="Get hunt")
@@ -344,7 +349,8 @@ async def update_hunt(hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession
raise
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in hunts endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.post("/{hunt_id}/run", response_model=HuntRunResponse, status_code=status.HTTP_200_OK, summary="Execute hunt query")
@@ -430,7 +436,8 @@ async def run_hunt(hunt_id: uuid.UUID, body: RunHuntRequest, db: DBSession, user
)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in hunts endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/{hunt_id}/runs", response_model=list[HuntRunResponse], summary="List hunt runs")
@@ -506,4 +513,5 @@ async def add_findings(hunt_id: uuid.UUID, body: AddFindingsRequest, db: DBSessi
raise
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in hunts endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
diff --git a/services/api/app/api/v1/endpoints/inbox_itsm.py b/services/api/app/api/v1/endpoints/inbox_itsm.py
index ec18e0c3c..f29f0e3a8 100644
--- a/services/api/app/api/v1/endpoints/inbox_itsm.py
+++ b/services/api/app/api/v1/endpoints/inbox_itsm.py
@@ -406,7 +406,7 @@ async def _fetch_token_and_connector(
await db.execute(
text(
"""
- SELECT id, tenant_id, connector_type, enabled
+ SELECT id, tenant_id, connector_type, is_enabled
FROM connectors
WHERE id = :id
"""
@@ -434,7 +434,7 @@ async def _fetch_token_and_connector(
detail="Token and connector belong to different tenants",
)
- if not connector_row.enabled:
+ if not connector_row.is_enabled:
# A disabled connector should not be receiving traffic. Prefer 409
# over 200 here so the vendor's webhook delivery dashboard surfaces
# the issue instead of silently consuming the events.
diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.py
index 9f03fdbe9..3afb32815 100644
--- a/services/api/app/api/v1/endpoints/knowledge_base.py
+++ b/services/api/app/api/v1/endpoints/knowledge_base.py
@@ -15,6 +15,7 @@ Endpoints
from __future__ import annotations
+import logging
import os
import uuid
from datetime import UTC, datetime
@@ -27,6 +28,8 @@ from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
+logger = logging.getLogger(__name__)
+
router = APIRouter(prefix="/kb", tags=["knowledge_base"])
# ────────────────────────────────────────────────────────────────────────────
@@ -176,7 +179,8 @@ async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBD
rows.append(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in knowledge_base endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
await db.commit()
return [_row_to_doc(r) for r in rows]
@@ -189,7 +193,8 @@ async def list_documents(db: DBSession, user: AuthUser) -> list[KBDocResponse]:
).fetchall()
return [_row_to_doc(r) for r in rows]
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in knowledge_base endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/documents/{doc_id}", response_model=KBDocResponse, summary="Get KB document")
@@ -229,7 +234,8 @@ async def query_kb(body: QueryRequest, db: DBSession, user: AuthUser) -> QueryRe
try:
db_rows = (await db.execute(sql)).fetchall()
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in knowledge_base endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
chunks = [
KBChunk(
diff --git a/services/api/app/api/v1/endpoints/marketplace.py b/services/api/app/api/v1/endpoints/marketplace.py
index cb85339c4..074e9c569 100644
--- a/services/api/app/api/v1/endpoints/marketplace.py
+++ b/services/api/app/api/v1/endpoints/marketplace.py
@@ -115,24 +115,61 @@ def _install_record(
def _resolve_item_path(item: dict[str, Any]) -> Path:
+ """Resolve a marketplace item's on-disk path safely.
+
+ The ``rel`` value comes from ``marketplace/index.json``, which is
+ generated by ``scripts/build_marketplace.py`` and *should* only ever
+ contain relative paths inside ``detections/``, ``playbooks/``, or
+ ``plugins/``. We still validate defensively so a tampered or
+ misgenerated index can't be used to read arbitrary files via
+ ``../../etc/passwd`` style entries.
+ """
rel = item.get("path")
- if not rel:
+ if not rel or not isinstance(rel, str):
raise HTTPException(
status_code=500,
detail=f"Marketplace item {item.get('id')} has no path field",
)
- target = (_REPO_ROOT / rel).resolve()
- if not target.exists():
- # Containerised deployments may have a different layout.
- alt = Path("/app") / rel
- if alt.exists():
- target = alt
- else:
- raise HTTPException(
- status_code=404,
- detail=f"Marketplace item file missing on disk: {rel}",
- )
- return target
+
+ rel_path = Path(rel)
+ if rel_path.is_absolute() or any(part == ".." for part in rel_path.parts):
+ # Either an absolute path or one with parent-directory traversal —
+ # neither is ever legitimate for an index entry.
+ raise HTTPException(
+ status_code=400,
+ detail="Invalid marketplace item path",
+ )
+
+ # Items must live under one of these trees. Anything else is rejected,
+ # even if it resolves to a real file on disk.
+ _ALLOWED_SUBDIRS = ("detections", "playbooks", "plugins")
+ if rel_path.parts and rel_path.parts[0] not in _ALLOWED_SUBDIRS:
+ raise HTTPException(
+ status_code=400,
+ detail="Marketplace items must live under detections/, playbooks/, or plugins/",
+ )
+
+ def _is_within(child: Path, parent: Path) -> bool:
+ try:
+ child.relative_to(parent)
+ except ValueError:
+ return False
+ return True
+
+ candidate_roots = [_REPO_ROOT, Path("/app")]
+ for root in candidate_roots:
+ resolved_root = root.resolve()
+ target = (root / rel_path).resolve()
+ if not _is_within(target, resolved_root):
+ # Symlink games or odd resolution — refuse to serve.
+ continue
+ if target.exists():
+ return target
+
+ raise HTTPException(
+ status_code=404,
+ detail=f"Marketplace item file missing on disk: {rel}",
+ )
def _hash_file(path: Path) -> str:
diff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.py
index 251e401e7..fccbb64d4 100644
--- a/services/api/app/api/v1/endpoints/phishing.py
+++ b/services/api/app/api/v1/endpoints/phishing.py
@@ -15,6 +15,7 @@ Endpoints
from __future__ import annotations
import json
+import logging
import os
import uuid
from datetime import UTC, datetime
@@ -28,6 +29,8 @@ from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
from app.core.airgap import AirgapViolation, enforce_airgap_for_url
+logger = logging.getLogger(__name__)
+
router = APIRouter(prefix="/phishing", tags=["phishing"])
# ────────────────────────────────────────────────────────────────────────────
@@ -221,7 +224,8 @@ async def submit(body: SubmitRequest, db: DBSession, user: AuthUser) -> Submissi
return _row_to_submission(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in phishing endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/submissions", response_model=list[SubmissionResponse], summary="List phishing submissions")
@@ -244,7 +248,8 @@ async def list_submissions(
rows = (await db.execute(q)).fetchall()
return [_row_to_submission(r) for r in rows]
except Exception as exc:
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in phishing endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
@router.get("/{submission_id}", response_model=SubmissionResponse, summary="Get submission")
@@ -288,4 +293,5 @@ async def retriage(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> S
return _row_to_submission(row)
except Exception as exc:
await db.rollback()
- raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
+ logger.exception("Database error in phishing endpoint")
+ raise HTTPException(status_code=503, detail="Database error") from exc
diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.py
index a421576b3..355f64609 100644
--- a/services/api/app/auth/oidc.py
+++ b/services/api/app/auth/oidc.py
@@ -41,12 +41,19 @@ router = APIRouter(prefix="/auth/oidc", tags=["auth-oidc"])
# ─── JWT helpers ──────────────────────────────────────────────────────────────
-_JWT_SECRET = os.getenv("JWT_SECRET", "changeme-insecure-default")
+_JWT_SECRET = os.getenv("JWT_SECRET", "")
_JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
_JWT_EXPIRE_MINUTES = int(os.getenv("JWT_EXPIRE_MINUTES", "480"))
def _issue_jwt(claims: dict[str, Any]) -> str:
+ # Refuse to sign OIDC session tokens with a missing or well-known-default
+ # secret. See the matching guard in ``services/api/app/auth/saml.py`` for
+ # the rationale: a literal "changeme-insecure-default" baked into source
+ # is not a credential, and silently using it forfeits the entire SSO
+ # trust model.
+ if not _JWT_SECRET or _JWT_SECRET == "changeme-insecure-default":
+ raise RuntimeError("JWT_SECRET is not configured. Set the env var to a long random string before issuing OIDC session tokens.")
payload = {
**claims,
"iat": datetime.now(UTC),
diff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.py
index 4e08ee660..b3eeef41c 100644
--- a/services/api/app/auth/saml.py
+++ b/services/api/app/auth/saml.py
@@ -60,12 +60,20 @@ router = APIRouter(prefix="/auth/saml", tags=["auth-saml"])
# ─── JWT helpers ──────────────────────────────────────────────────────────────
-_JWT_SECRET = os.getenv("JWT_SECRET", "changeme-insecure-default")
+_JWT_SECRET = os.getenv("JWT_SECRET", "")
_JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
_JWT_EXPIRE_MINUTES = int(os.getenv("JWT_EXPIRE_MINUTES", "480"))
def _issue_jwt(claims: dict[str, Any]) -> str:
+ # Refuse to mint a token signed with a missing or well-known-default
+ # secret. Previously this defaulted to ``"changeme-insecure-default"``,
+ # so a misconfigured deployment would happily sign session tokens with
+ # a value that's literally checked into source. We now fail closed and
+ # let the caller surface a 503/500 — operators must wire ``JWT_SECRET``
+ # explicitly (e.g. via Fly/k8s secrets).
+ if not _JWT_SECRET or _JWT_SECRET == "changeme-insecure-default":
+ raise RuntimeError("JWT_SECRET is not configured. Set the env var to a long random string before issuing SAML session tokens.")
payload = {
**claims,
"iat": datetime.now(UTC),
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 6682b8340..8474ecf69 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -343,6 +343,14 @@ class Settings(BaseSettings):
REALTIME_BASE_URL: str = "http://realtime:8086"
REALTIME_INTERNAL_TOKEN: str = ""
+ # SAML/OIDC session token signing secret. Consumed by ``app/auth/saml.py``
+ # and ``app/auth/oidc.py`` to mint AiSOC session JWTs after an external
+ # identity provider returns a successful authn response. We surface this
+ # as a real Settings field (not just ``os.getenv``) so that
+ # ``warn_if_insecure_defaults`` can be exercised deterministically in
+ # tests by passing ``JWT_SECRET=""`` instead of mutating the environment.
+ JWT_SECRET: str = ""
+
# Relying party identity for WebAuthn / Passkey ceremonies. RP_ID must
# match the eTLD+1 of the PWA origin (no scheme, no port). RP_NAME is
# what the OS prompt shows the user.
@@ -633,6 +641,23 @@ def warn_if_insecure_defaults(s: Settings | None = None) -> list[str]:
if not is_dev_env(s.ENVIRONMENT) and not s.AISOC_CREDENTIAL_KEY:
msgs.append("AISOC_CREDENTIAL_KEY is empty in a non-development environment — connector credentials cannot be encrypted at rest.")
+ # JWT signing secret used by the SAML/OIDC session-issuance paths in
+ # ``app/auth/saml.py`` and ``app/auth/oidc.py``. Those modules now refuse
+ # to sign tokens with an empty or well-known placeholder, but we still
+ # want a noisy boot-time warning so the operator sees the misconfig
+ # *before* the first SSO callback 500s.
+ if not is_dev_env(s.ENVIRONMENT) and (not s.JWT_SECRET or s.JWT_SECRET == "changeme-insecure-default"):
+ msgs.append(
+ "JWT_SECRET is empty or set to the well-known placeholder — SAML/OIDC "
+ "session token issuance will fail closed until you wire a real secret."
+ )
+
+ # Internal token used by the agents service to authenticate to the
+ # realtime service. We no longer ship a "changeme" default in code, but
+ # warn here so operators don't quietly run with no inter-service auth.
+ if not is_dev_env(s.ENVIRONMENT) and not s.REALTIME_INTERNAL_TOKEN:
+ msgs.append("REALTIME_INTERNAL_TOKEN is empty in a non-development environment — agent → realtime events are unauthenticated.")
+
# Air-gap sanity check: if an operator flipped on AISOC_AIRGAPPED but
# the LLM is still pointed at a public endpoint (api.openai.com, etc.)
# surface that as an insecure-default rather than silently 503-ing
diff --git a/services/api/app/graphql/query.py b/services/api/app/graphql/query.py
index d2da1cd8c..dac761146 100644
--- a/services/api/app/graphql/query.py
+++ b/services/api/app/graphql/query.py
@@ -46,6 +46,19 @@ _AGENTS_URL = os.getenv("AGENTS_SERVICE_URL") or os.getenv("AGENTS_API_URL", "ht
# ─── helpers ──────────────────────────────────────────────────────────────────
+def _escape_like(value: str) -> str:
+ """Escape SQL LIKE/ILIKE wildcard metacharacters in a user-supplied
+ search string.
+
+ Without this, a user can pass ``%`` or ``_`` and turn an ``ILIKE``
+ intended as substring search into a wildcard scan (mild data-exposure
+ risk and a DoS surface on large tables). We escape ``%``, ``_`` and the
+ escape character ``\\`` itself, and rely on the resolver to pass
+ ``escape="\\"`` to the SQLAlchemy ``ilike`` call.
+ """
+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
def _db(info: Info) -> AsyncSession:
"""Pull the async session injected by the Strawberry FastAPI integration."""
return info.context["db"]
@@ -202,7 +215,8 @@ class Query:
if status:
q = q.where(Alert.status == status)
if search:
- q = q.where(Alert.title.ilike(f"%{search}%"))
+ safe = _escape_like(search)
+ q = q.where(Alert.title.ilike(f"%{safe}%", escape="\\"))
total_result = await db.execute(select(func.count()).select_from(q.subquery()))
total = total_result.scalar_one()
@@ -249,7 +263,8 @@ class Query:
if priority:
q = q.where(Case.priority == priority)
if search:
- q = q.where(Case.title.ilike(f"%{search}%"))
+ safe = _escape_like(search)
+ q = q.where(Case.title.ilike(f"%{safe}%", escape="\\"))
total_result = await db.execute(select(func.count()).select_from(q.subquery()))
total = total_result.scalar_one()
diff --git a/services/api/app/main.py b/services/api/app/main.py
index d03953a7b..73853f445 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -246,6 +246,29 @@ async def api_version_middleware(request: Request, call_next) -> Response:
return response
+def _metrics_endpoint_label(request: Request) -> str:
+ """Pick a low-cardinality label for the request's route.
+
+ Using ``request.url.path`` directly is dangerous: any unmatched path
+ (think ``/api/v1/cases/<uuid>``, ``/static/<sha>``, or attacker-supplied
+ junk like ``/.git/config``) becomes its own Prometheus time series.
+ Over time this blows up the metrics backend and turns the ``/metrics``
+ endpoint into an outage vector.
+
+ FastAPI/Starlette resolves the matched route into ``request.scope["route"]``
+ once routing has run. We use ``route.path`` (the parameterized template,
+ e.g. ``/api/v1/cases/{case_id}``) when available, and fall back to a
+ single ``__unmatched__`` bucket for 404s. This caps cardinality at
+ "number of declared routes" instead of "number of distinct URLs ever
+ requested".
+ """
+ route = request.scope.get("route") if request.scope else None
+ template = getattr(route, "path", None)
+ if isinstance(template, str) and template:
+ return template
+ return "__unmatched__"
+
+
@app.middleware("http")
async def metrics_middleware(request: Request, call_next) -> Response:
"""Collect Prometheus metrics for each request."""
@@ -253,7 +276,7 @@ async def metrics_middleware(request: Request, call_next) -> Response:
response = await call_next(request)
duration = time.time() - start_time
- endpoint = request.url.path
+ endpoint = _metrics_endpoint_label(request)
REQUEST_COUNT.labels(request.method, endpoint, response.status_code).inc()
REQUEST_LATENCY.labels(request.method, endpoint).observe(duration)
diff --git a/services/api/tests/test_inbox_itsm_endpoint.py b/services/api/tests/test_inbox_itsm_endpoint.py
index 7a6324eb7..266efa748 100644
--- a/services/api/tests/test_inbox_itsm_endpoint.py
+++ b/services/api/tests/test_inbox_itsm_endpoint.py
@@ -354,7 +354,7 @@ async def test_fetch_token_and_connector_happy_path() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
db = _mock_db(token_row, connector_row)
tok, conn = await _fetch_token_and_connector(db, tenant_token="tok-xyz", connector_instance_id=connector_id)
@@ -431,7 +431,7 @@ async def test_fetch_token_and_connector_cross_tenant_raises_403() -> None:
id=uuid.uuid4(),
tenant_id=uuid.uuid4(), # tenant B — different
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
db = _mock_db(token_row, connector_row)
with pytest.raises(HTTPException) as exc:
@@ -460,7 +460,7 @@ async def test_fetch_token_and_connector_disabled_connector_raises_409() -> None
id=uuid.uuid4(),
tenant_id=tenant_id,
connector_type="jira",
- enabled=False,
+ is_enabled=False,
)
db = _mock_db(token_row, connector_row)
with pytest.raises(HTTPException) as exc:
@@ -483,7 +483,7 @@ async def test_fetch_token_and_connector_unsupported_vendor_raises_422() -> None
id=uuid.uuid4(),
tenant_id=tenant_id,
connector_type="splunk",
- enabled=True,
+ is_enabled=True,
)
db = _mock_db(token_row, connector_row)
with pytest.raises(HTTPException) as exc:
@@ -726,7 +726,7 @@ async def test_endpoint_invalid_json_raises_400() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
db = _build_db_for_endpoint(token_row=token_row, connector_row=connector_row, ref_row=None)
request = _build_request(b"this is not json")
@@ -759,7 +759,7 @@ async def test_endpoint_non_object_json_raises_400() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
db = _build_db_for_endpoint(token_row=token_row, connector_row=connector_row, ref_row=None)
request = _build_request(b"[1,2,3]")
@@ -791,7 +791,7 @@ async def test_endpoint_missing_external_id_returns_200_with_note() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
db = _build_db_for_endpoint(token_row=token_row, connector_row=connector_row, ref_row=None)
request = _build_request(json.dumps({"webhookEvent": "ping"}).encode())
@@ -828,7 +828,7 @@ async def test_endpoint_unlinked_external_id_returns_200_with_note() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
# ref_row=None means the JOIN found no AiSOC link.
db = _build_db_for_endpoint(token_row=token_row, connector_row=connector_row, ref_row=None)
@@ -882,7 +882,7 @@ async def test_endpoint_idempotent_when_case_already_in_target_status() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
ref_row = SimpleNamespace(
id=uuid.uuid4(),
@@ -933,7 +933,7 @@ async def test_endpoint_unmapped_status_bumps_last_synced_only() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
ref_row = SimpleNamespace(
id=uuid.uuid4(),
@@ -985,7 +985,7 @@ async def test_endpoint_real_status_change_writes_and_returns_changed() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
ref_row = SimpleNamespace(
id=uuid.uuid4(),
@@ -1036,7 +1036,7 @@ async def test_endpoint_servicenow_dispatches_to_servicenow_parser() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="servicenow",
- enabled=True,
+ is_enabled=True,
)
ref_row = SimpleNamespace(
id=uuid.uuid4(),
@@ -1085,7 +1085,7 @@ async def test_endpoint_hmac_required_but_missing_returns_401() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
db = _build_db_for_endpoint(token_row=token_row, connector_row=connector_row, ref_row=None)
request = _build_request(b"{}")
@@ -1118,7 +1118,7 @@ async def test_endpoint_hmac_valid_passes_through() -> None:
id=connector_id,
tenant_id=tenant_id,
connector_type="jira",
- enabled=True,
+ is_enabled=True,
)
ref_row = SimpleNamespace(
id=uuid.uuid4(),
diff --git a/services/api/tests/test_security_defaults.py b/services/api/tests/test_security_defaults.py
index 4614f05aa..83155abc4 100644
--- a/services/api/tests/test_security_defaults.py
+++ b/services/api/tests/test_security_defaults.py
@@ -32,6 +32,13 @@ def _make_settings(**overrides) -> Settings:
"PLUGIN_TRUST_MODE": "strict",
# Pre-generated Fernet key. Real deployments mount this via Fly secret.
"AISOC_CREDENTIAL_KEY": "Z7t9fM3pZ8U_bN5oVxQYr1w2kLsHd4aJiTvE6cNxYpA=",
+ # SAML/OIDC session signing secret. Empty/placeholder values now warn
+ # in prod (issue #130, finding #10), so the "clean prod" baseline
+ # has to set a real value.
+ "JWT_SECRET": "b" * 64,
+ # Bearer token the agents service uses to push events into realtime.
+ # Empty in prod means the channel is unauthenticated, which warns.
+ "REALTIME_INTERNAL_TOKEN": "c" * 64,
}
base.update(overrides)
# ``_env_file=None`` skips .env discovery so test runs are deterministic
@@ -101,6 +108,40 @@ def test_empty_credential_key_in_dev_does_not_warn():
assert not any("AISOC_CREDENTIAL_KEY" in m for m in msgs)
+def test_empty_jwt_secret_in_prod_warns():
+ """SAML/OIDC session tokens must be signed with a real secret in prod."""
+ s = _make_settings(JWT_SECRET="")
+ msgs = warn_if_insecure_defaults(s)
+ assert any("JWT_SECRET" in m for m in msgs)
+
+
+def test_placeholder_jwt_secret_in_prod_warns():
+ """The "changeme" sentinel is treated as empty — same warning fires."""
+ s = _make_settings(JWT_SECRET="changeme-insecure-default")
+ msgs = warn_if_insecure_defaults(s)
+ assert any("JWT_SECRET" in m for m in msgs)
+
+
+def test_empty_jwt_secret_in_dev_does_not_warn():
+ """Dev environments are noisy; we don't nag there."""
+ s = _make_settings(ENVIRONMENT="development", JWT_SECRET="")
+ msgs = warn_if_insecure_defaults(s)
+ assert not any("JWT_SECRET" in m for m in msgs)
+
+
+def test_empty_realtime_token_in_prod_warns():
+ """Agents → realtime channel is unauthenticated when the token is unset."""
+ s = _make_settings(REALTIME_INTERNAL_TOKEN="")
+ msgs = warn_if_insecure_defaults(s)
+ assert any("REALTIME_INTERNAL_TOKEN" in m for m in msgs)
+
+
+def test_empty_realtime_token_in_dev_does_not_warn():
+ s = _make_settings(ENVIRONMENT="development", REALTIME_INTERNAL_TOKEN="")
+ msgs = warn_if_insecure_defaults(s)
+ assert not any("REALTIME_INTERNAL_TOKEN" in m for m in msgs)
+
+
# ─── /metrics auth gate ────────────────────────────────────────────────────
diff --git a/services/honeytokens/app/core/config.py b/services/honeytokens/app/core/config.py
index 17f569236..e0df3f3db 100644
--- a/services/honeytokens/app/core/config.py
+++ b/services/honeytokens/app/core/config.py
@@ -7,9 +7,14 @@ class Settings(BaseSettings):
# Database
database_url: str = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"
- # Webhook alerting
+ # Webhook alerting. ``alert_webhook_secret`` previously defaulted to the
+ # literal string ``"changeme"`` — anyone running this service with the
+ # defaults would sign every outbound honeytoken alert with a public secret,
+ # so a downstream verifier couldn't distinguish a real trigger from a
+ # forged one. We now default to empty and require operators to wire a
+ # real HMAC secret before alerts will be signed.
alert_webhook_url: str = ""
- alert_webhook_secret: str = "changeme"
+ alert_webhook_secret: str = ""
# Token defaults
token_ttl_days: int = 365
diff --git a/services/honeytokens/app/services/alerting.py b/services/honeytokens/app/services/alerting.py
index 5d22edc15..8c0b46dc9 100644
--- a/services/honeytokens/app/services/alerting.py
+++ b/services/honeytokens/app/services/alerting.py
@@ -39,6 +39,17 @@ async def send_alert(
LOG.info("No alert_webhook_url configured; skipping outbound alert.")
return False
+ # Require an explicit HMAC secret. Previously this defaulted to "changeme"
+ # in ``app/core/config.py``, which meant alerts were signed with a public
+ # value — a downstream verifier couldn't distinguish a real trigger from
+ # one a third party forged using the same well-known string.
+ if not settings.alert_webhook_secret:
+ LOG.error(
+ "alert_webhook_url is configured but alert_webhook_secret is empty; "
+ "refusing to send unsigned/forge-able alerts. Set HONEYTOKEN_ALERT_WEBHOOK_SECRET."
+ )
+ return False
+
payload_dict = {
"event": "honeytoken.triggered",
"honeytoken_id": str(honeytoken_id),