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: four things that worked in tests and not on a running deployment (#806)

Beenu Arora9544b0e536f0
diff --git a/README.md b/README.md
index bc8ce9b06..7aaf9a460 100644
--- a/README.md
+++ b/README.md
@@ -59,7 +59,7 @@ of the public API. Every stage reports PASS or FAIL:
[PASS] alert is retrievable by id from the API
```
-Open **http://localhost:3000** (API docs at **http://localhost:8000/docs**).
+Open **http://localhost:3000** (API docs at **http://localhost:8000/api/docs**).
Something wrong? `make doctor` checks every dependency and tells you what to
run next. Requires Docker with ~6 GB of RAM.
diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile
index f38528cf2..284b24e08 100644
--- a/apps/web/Dockerfile
+++ b/apps/web/Dockerfile
@@ -58,12 +58,21 @@ ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL}
# - NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL/_PASSWORD: credentials DemoAutoLogin uses on
# first paint so visitors land already authenticated and can roam
#
-# Defaults match the canonical hosted demo so a no-arg `docker build` of the web
-# image (e.g. CI's publish-images.yml) ships a demo-ready bundle. Production
-# customers override NEXT_PUBLIC_DEMO_MODE="" at build time to suppress all
-# demo affordances. The api/agents/realtime images are unaffected — demo gating
-# in those services is runtime via AISOC_DEMO_MODE, not build-time.
-ARG NEXT_PUBLIC_DEMO_MODE="true"
+# `NEXT_PUBLIC_DEMO_MODE` defaults to **off**, so a no-arg `docker build`
+# produces a self-host bundle rather than a demo one. It used to default to
+# "true", which meant a self-hoster's console announced "Demo data resets
+# daily at 00:00 UTC. All write actions are disabled." over their own real
+# ingested alerts, disabled every write control, and offered them a
+# "Self-host AiSOC" link inside their own self-hosted install. Next inlines
+# `NEXT_PUBLIC_*` at build time, so there is no runtime escape from a bundle
+# built this way — the operator has to rebuild the image.
+#
+# Every path that genuinely wants the demo sets the flag explicitly
+# (`publish-images.yml`, `release.yml`, `infra/fly/web/fly.toml`,
+# `infra/compose/docker-compose.demo.yml`), so the safe default costs those
+# nothing. The api/agents/realtime images are unaffected — demo gating in
+# those services is runtime via AISOC_DEMO_MODE, not build-time.
+ARG NEXT_PUBLIC_DEMO_MODE=""
ARG NEXT_PUBLIC_DEMO_DEEPLINK="/cases/INC-RT-001?tab=ledger"
ARG NEXT_PUBLIC_DEMO_BANNER="Demo data resets daily at 00:00 UTC. All write actions are disabled."
ARG NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL="[email protected]"
diff --git a/apps/web/src/lib/api.alert-rail-entities.test.ts b/apps/web/src/lib/api.alert-rail-entities.test.ts
new file mode 100644
index 000000000..56b2735eb
--- /dev/null
+++ b/apps/web/src/lib/api.alert-rail-entities.test.ts
@@ -0,0 +1,135 @@
+/**
+ * `alertsApi.get` — Investigation Rail related-entity contract.
+ *
+ * `RelatedEntity` in `services/api/app/services/alert_rail.py` serialises as
+ * `{group, kind, value, label, pivot}`. The client mapper read `e.type` and
+ * `e.pivot_path`, neither of which the API has ever sent, and fed `e.kind`
+ * ("host") into its own `kind`, which is the rail *column* ("principal").
+ *
+ * All three were wrong in the same direction, so the failure was silent:
+ * `pivotPath` resolved to `null` and no chip was ever a link; `type` was
+ * empty; and `ENTITY_KIND_CONFIG[kind]` missed on every row, so
+ * `RelatedEntitiesSection` rendered its header and count with no chips
+ * underneath. Observed against a live core stack: an alert whose API payload
+ * carried a host and a user rendered "RELATED ENTITIES (4)" with an empty
+ * body and zero anchors in the DOM.
+ *
+ * The consequence worth pinning is that the `/graph?entity=…` route
+ * correction and its URL encoding — both unit-tested on the server — could
+ * not be reached from the console at all. `InvestigationRail.test.tsx`
+ * constructs the client-side type directly, so it never crossed this
+ * boundary.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { alertsApi } from './api';
+
+/** Exactly what `GET /api/v1/alerts/{id}` returned on a live stack. */
+const API_PAYLOAD = {
+ id: '28f0699a-423b-4111-8111-1e59c15fa35f',
+ title: 'SuspiciousPowerShell',
+ severity: 'medium',
+ status: 'new',
+ created_at: '2026-09-23T23:20:12Z',
+ related_entities: [
+ { group: 'principal', kind: 'host', value: 'Finance & Legal #2', label: null, pivot: '/graph?entity=host%3AFinance%20%26%20Legal%20%232' },
+ { group: 'principal', kind: 'user', value: 'CORP\\svc backup', label: null, pivot: '/graph?entity=user%3ACORP%5Csvc%20backup' },
+ { group: 'workflow', kind: 'rule', value: 'CrowdStrike Falcon', label: null, pivot: null },
+ ],
+};
+
+function jsonResponse(body: unknown) {
+ return {
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ headers: new Headers({ 'content-type': 'application/json' }),
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ } as unknown as Response;
+}
+
+let fetchMock: ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+ fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('alertsApi.get related entities', () => {
+ it('carries the pivot the API sends, so a chip can be a link', async () => {
+ fetchMock.mockResolvedValue(jsonResponse(API_PAYLOAD));
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+ const host = alert.relatedEntities?.find((e) => e.type === 'host');
+
+ // Against the pre-fix client this is `null` for every entity.
+ expect(host?.pivotPath).toBe('/graph?entity=host%3AFinance%20%26%20Legal%20%232');
+ });
+
+ it('preserves the encoding, so an ampersand does not truncate the pivot', async () => {
+ fetchMock.mockResolvedValue(jsonResponse(API_PAYLOAD));
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+ const host = alert.relatedEntities?.find((e) => e.type === 'host');
+
+ expect(host?.pivotPath).toContain('%26');
+ expect(host?.pivotPath).toContain('%232');
+ expect(decodeURIComponent(host!.pivotPath!.split('entity=')[1])).toBe('host:Finance & Legal #2');
+ });
+
+ it('maps the rail column onto `kind` so the grouped render finds its bucket', async () => {
+ fetchMock.mockResolvedValue(jsonResponse(API_PAYLOAD));
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+
+ // `RelatedEntitiesSection` keys `ENTITY_KIND_CONFIG` off `kind`, whose
+ // valid values are the rail columns. Pre-fix this was 'host'/'user', which
+ // matched no bucket, so the chips were dropped from the output entirely.
+ expect(alert.relatedEntities?.map((e) => e.kind)).toEqual(['principal', 'principal', 'workflow']);
+ });
+
+ it('maps the concrete entity type onto `type` so the chip has a label', async () => {
+ fetchMock.mockResolvedValue(jsonResponse(API_PAYLOAD));
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+
+ expect(alert.relatedEntities?.map((e) => e.type)).toEqual(['host', 'user', 'rule']);
+ expect(alert.relatedEntities?.every((e) => e.type !== '')).toBe(true);
+ });
+
+ it('leaves an informational entity without a pivot', async () => {
+ fetchMock.mockResolvedValue(jsonResponse(API_PAYLOAD));
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+
+ expect(alert.relatedEntities?.find((e) => e.type === 'rule')?.pivotPath).toBeNull();
+ });
+
+ it('still reads the older `pivot_path` spelling', async () => {
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ ...API_PAYLOAD,
+ related_entities: [{ kind: 'principal', type: 'host', value: 'web-01', pivot_path: '/graph?entity=host%3Aweb-01' }],
+ }),
+ );
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+
+ expect(alert.relatedEntities?.[0].pivotPath).toBe('/graph?entity=host%3Aweb-01');
+ expect(alert.relatedEntities?.[0].type).toBe('host');
+ });
+
+ it('does not throw when the API sends no entities', async () => {
+ fetchMock.mockResolvedValue(jsonResponse({ ...API_PAYLOAD, related_entities: [] }));
+
+ const alert = await alertsApi.get(API_PAYLOAD.id);
+
+ expect(alert.relatedEntities).toEqual([]);
+ });
+});
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 8f68aa31e..3dd4483de 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -752,14 +752,30 @@ function normalizeAlert(raw: unknown): Alert {
: undefined;
// ── Investigation Rail envelope (W6) ────────────────────────────────────
+ // `alert_rail.RelatedEntity` serialises as `{group, kind, value, label,
+ // pivot}`. This mapper read `e.type` and `e.pivot_path`, which the API has
+ // never sent, and passed `e.kind` ("host") into the client's `kind`, which
+ // is the rail *column* ("principal"). All three were wrong in the same
+ // direction: `pivotPath` was always null so no chip was ever a link, `type`
+ // was always empty, and `ENTITY_KIND_CONFIG[kind]` missed on every row — so
+ // the section rendered its header with a count and no chips beneath it. The
+ // `/graph?entity=…` route fix and its URL encoding were therefore
+ // unreachable from the console on every deployment.
+ //
+ // `group`/`kind` are read first and the old spellings kept as fallbacks, so
+ // a console pointed at an older API still renders.
const relatedRaw = r.related_entities ?? r.relatedEntities;
const relatedEntities = Array.isArray(relatedRaw)
? (relatedRaw as Array<Record<string, unknown>>).map((e) => ({
- kind: (e.kind ?? 'principal') as RelatedEntity['kind'],
- type: String(e.type ?? ''),
+ kind: (e.group ?? e.kind ?? 'principal') as RelatedEntity['kind'],
+ // `type` prefers its own spelling so a legacy `{kind: 'principal',
+ // type: 'host'}` payload still reports the concrete type, and falls
+ // back to `kind` for the current `{group, kind}` shape.
+ type: String(e.type ?? e.kind ?? ''),
value: String(e.value ?? ''),
label: (e.label as string | null | undefined) ?? null,
pivotPath:
+ (e.pivot as string | null | undefined) ??
(e.pivot_path as string | null | undefined) ??
(e.pivotPath as string | null | undefined) ??
null,
diff --git a/services/api/app/api/v1/endpoints/assets.py b/services/api/app/api/v1/endpoints/assets.py
index adb7c61d7..f89fbdccc 100644
--- a/services/api/app/api/v1/endpoints/assets.py
+++ b/services/api/app/api/v1/endpoints/assets.py
@@ -10,10 +10,10 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.asset import Asset, AssetVulnerability
-from app.models.tenant import User
router = APIRouter(prefix="/assets", tags=["assets"])
@@ -104,7 +104,7 @@ async def list_assets(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[Asset]:
q = select(Asset).where(Asset.tenant_id == current_user.tenant_id)
if asset_type:
@@ -120,7 +120,7 @@ async def list_assets(
async def create_asset(
body: AssetCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> Asset:
data = body.model_dump()
asset = Asset(
@@ -141,7 +141,7 @@ async def list_vulnerabilities(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[AssetVulnerability]:
q = select(AssetVulnerability).where(AssetVulnerability.tenant_id == current_user.tenant_id)
if severity:
@@ -157,7 +157,7 @@ async def list_vulnerabilities(
async def get_asset(
asset_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> Asset:
asset = await db.get(Asset, asset_id)
if not asset or asset.tenant_id != current_user.tenant_id:
@@ -170,7 +170,7 @@ async def update_asset(
asset_id: uuid.UUID,
body: AssetUpdate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> Asset:
asset = await db.get(Asset, asset_id)
if not asset or asset.tenant_id != current_user.tenant_id:
@@ -189,7 +189,7 @@ async def update_asset(
async def delete_asset(
asset_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
asset = await db.get(Asset, asset_id)
if not asset or asset.tenant_id != current_user.tenant_id:
@@ -207,7 +207,7 @@ async def delete_asset(
async def create_vulnerability(
body: VulnerabilityCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> AssetVulnerability:
# ensure asset belongs to this tenant
asset = await db.get(Asset, body.asset_id)
@@ -229,7 +229,7 @@ async def create_vulnerability(
async def list_asset_vulnerabilities(
asset_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[AssetVulnerability]:
asset = await db.get(Asset, asset_id)
if not asset or asset.tenant_id != current_user.tenant_id:
diff --git a/services/api/app/api/v1/endpoints/effective_permissions.py b/services/api/app/api/v1/endpoints/effective_permissions.py
index 6b90f48fe..828739917 100644
--- a/services/api/app/api/v1/endpoints/effective_permissions.py
+++ b/services/api/app/api/v1/endpoints/effective_permissions.py
@@ -50,11 +50,11 @@ from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, s
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.core.config import settings
from app.db.database import get_db
from app.models.connector import Connector
-from app.models.tenant import User
from app.security.credential_vault import get_vault
from app.services.effective_permissions.base import ResolverError
from app.services.effective_permissions.posture_loader import (
@@ -118,7 +118,7 @@ async def _maybe_live_snapshot(db: AsyncSession, tenant_id: Any, provider: str,
summary="List supported effective-permissions providers",
)
async def list_providers(
- _user: User = Depends(get_current_user),
+ _user: CurrentUser = Depends(get_current_user),
) -> dict[str, Any]:
"""Return ``{"providers": [{"name", "coverage"}, ...]}``.
@@ -149,7 +149,7 @@ async def get_effective_permissions(
"Optional base64-encoded JSON snapshot for dry-run resolution. " "Only honoured when AISOC_ALLOW_INLINE_SNAPSHOT=1 is set."
),
),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Resolve and return the effective-permissions envelope.
diff --git a/services/api/app/api/v1/endpoints/identity_graph.py b/services/api/app/api/v1/endpoints/identity_graph.py
index 531303538..8a0480798 100644
--- a/services/api/app/api/v1/endpoints/identity_graph.py
+++ b/services/api/app/api/v1/endpoints/identity_graph.py
@@ -11,10 +11,10 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.identity_graph import AlertIdentityLink, IdentityEdge, IdentityNode
-from app.models.tenant import User
router = APIRouter(prefix="/identity-graph", tags=["identity-graph"])
@@ -91,7 +91,7 @@ async def list_nodes(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[IdentityNode]:
q = select(IdentityNode).where(IdentityNode.tenant_id == current_user.tenant_id)
if node_type:
@@ -109,7 +109,7 @@ async def list_nodes(
async def create_node(
body: NodeCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> IdentityNode:
node = IdentityNode(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(node)
@@ -122,7 +122,7 @@ async def create_node(
async def get_node(
node_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> IdentityNode:
node = await db.get(IdentityNode, node_id)
if not node or node.tenant_id != current_user.tenant_id:
@@ -134,7 +134,7 @@ async def get_node(
async def get_node_edges(
node_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[IdentityEdge]:
node = await db.get(IdentityNode, node_id)
if not node or node.tenant_id != current_user.tenant_id:
@@ -159,7 +159,7 @@ async def list_edges(
limit: int = Query(100, le=1000),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[IdentityEdge]:
q = select(IdentityEdge).where(IdentityEdge.tenant_id == current_user.tenant_id)
if edge_type:
@@ -173,7 +173,7 @@ async def list_edges(
async def create_edge(
body: EdgeCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> IdentityEdge:
edge = IdentityEdge(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(edge)
@@ -191,7 +191,7 @@ async def create_edge(
async def link_alert_to_identity(
body: AlertLinkCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> AlertIdentityLink:
link = AlertIdentityLink(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(link)
@@ -204,7 +204,7 @@ async def link_alert_to_identity(
async def get_alert_identity_links(
alert_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[AlertIdentityLink]:
result = await db.execute(
select(AlertIdentityLink).where(
diff --git a/services/api/app/api/v1/endpoints/insider_threat.py b/services/api/app/api/v1/endpoints/insider_threat.py
index 9c473e14f..871ac8dd8 100644
--- a/services/api/app/api/v1/endpoints/insider_threat.py
+++ b/services/api/app/api/v1/endpoints/insider_threat.py
@@ -11,10 +11,10 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfile
-from app.models.tenant import User
router = APIRouter(prefix="/insider-threat", tags=["insider-threat"])
@@ -100,7 +100,7 @@ async def list_profiles(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[UserRiskProfile]:
q = select(UserRiskProfile).where(UserRiskProfile.tenant_id == current_user.tenant_id)
if risk_tier:
@@ -116,7 +116,7 @@ async def list_profiles(
async def get_profile(
profile_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> UserRiskProfile:
profile = await db.get(UserRiskProfile, profile_id)
if not profile or profile.tenant_id != current_user.tenant_id:
@@ -129,7 +129,7 @@ async def update_watchlist(
profile_id: uuid.UUID,
body: WatchlistUpdate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> UserRiskProfile:
profile = await db.get(UserRiskProfile, profile_id)
if not profile or profile.tenant_id != current_user.tenant_id:
@@ -138,7 +138,7 @@ async def update_watchlist(
profile.watchlist_reason = body.watchlist_reason # type: ignore[assignment]
if body.is_watchlisted:
profile.watchlisted_at = datetime.now(UTC) # type: ignore[assignment]
- profile.watchlisted_by = current_user.id # type: ignore[assignment]
+ profile.watchlisted_by = current_user.user_id # type: ignore[assignment]
await db.commit()
await db.refresh(profile)
return profile
@@ -156,7 +156,7 @@ async def list_indicators(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[InsiderIndicator]:
q = select(InsiderIndicator).where(InsiderIndicator.tenant_id == current_user.tenant_id)
if severity:
@@ -172,7 +172,7 @@ async def list_indicators(
async def create_indicator(
body: IndicatorCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> InsiderIndicator:
profile = await db.get(UserRiskProfile, body.profile_id)
if not profile or profile.tenant_id != current_user.tenant_id:
@@ -191,12 +191,12 @@ async def create_indicator(
async def acknowledge_indicator(
indicator_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> InsiderIndicator:
indicator = await db.get(InsiderIndicator, indicator_id)
if not indicator or indicator.tenant_id != current_user.tenant_id:
raise HTTPException(status_code=404, detail="Indicator not found")
- indicator.acknowledged_by = current_user.id # type: ignore[assignment]
+ indicator.acknowledged_by = current_user.user_id # type: ignore[assignment]
indicator.acknowledged_at = datetime.now(UTC) # type: ignore[assignment]
await db.commit()
await db.refresh(indicator)
@@ -211,7 +211,7 @@ async def acknowledge_indicator(
@router.get("/peer-groups", response_model=list[PeerGroupOut])
async def list_peer_groups(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[InsiderPeerGroup]:
result = await db.execute(
select(InsiderPeerGroup).where(InsiderPeerGroup.tenant_id == current_user.tenant_id).order_by(InsiderPeerGroup.name)
@@ -223,7 +223,7 @@ async def list_peer_groups(
async def create_peer_group(
body: PeerGroupCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> InsiderPeerGroup:
group = InsiderPeerGroup(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(group)
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index eb83c824d..74857f18f 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -26,6 +26,7 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNote
@@ -111,7 +112,7 @@ class MetricsOut(BaseModel):
@router.get("/children", response_model=list[ChildTenantOut])
async def list_child_tenants(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[Tenant]:
"""Return all child tenants of the current parent tenant."""
result = await db.execute(select(Tenant).where(Tenant.parent_tenant_id == current_user.tenant_id))
@@ -122,7 +123,7 @@ async def list_child_tenants(
async def onboard_child_tenant(
child_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> dict[str, str]:
"""Link an existing tenant as a child, if that tenant invited the caller.
@@ -188,7 +189,7 @@ async def onboard_child_tenant(
async def list_notes(
child_id: uuid.UUID | None = Query(None),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[MSSPTenantNote]:
q = select(MSSPTenantNote).where(MSSPTenantNote.parent_id == current_user.tenant_id)
if child_id:
@@ -202,14 +203,14 @@ async def list_notes(
async def create_note(
body: TenantNoteCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPTenantNote:
await _require_own_child(db, current_user, body.child_id)
note = MSSPTenantNote(
parent_id=current_user.tenant_id,
child_id=body.child_id,
body=body.body,
- author_id=current_user.id,
+ author_id=current_user.user_id,
)
db.add(note)
await db.commit()
@@ -225,7 +226,7 @@ async def create_note(
@router.get("/delegations", response_model=list[DelegationOut])
async def list_delegations(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[MSSPDelegation]:
result = await db.execute(
select(MSSPDelegation)
@@ -242,14 +243,14 @@ async def list_delegations(
async def create_delegation(
body: DelegationCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPDelegation:
await _require_own_child(db, current_user, body.child_tenant_id)
delegation = MSSPDelegation(
parent_tenant_id=current_user.tenant_id,
child_tenant_id=body.child_tenant_id,
granted_role=body.granted_role,
- granted_by_user=current_user.id,
+ granted_by_user=current_user.user_id,
expires_at=body.expires_at,
)
db.add(delegation)
@@ -262,7 +263,7 @@ async def create_delegation(
async def revoke_delegation(
delegation_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
delegation = await db.get(MSSPDelegation, delegation_id)
if not delegation or delegation.parent_tenant_id != current_user.tenant_id:
@@ -279,7 +280,7 @@ async def revoke_delegation(
@router.get("/metrics", response_model=list[MetricsOut])
async def list_metrics(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[MSSPTenantMetrics]:
"""Return the latest metrics snapshot for every child tenant."""
# Get child tenant ids
@@ -432,7 +433,7 @@ _MSSP_INVITE_SETTING = "mssp_parent_invite"
async def _require_own_child(
db: AsyncSession,
- current_user: User,
+ current_user: CurrentUser,
child_id: uuid.UUID,
) -> Tenant:
"""Return ``child_id`` only if it is a child of the caller's tenant.
@@ -462,7 +463,7 @@ async def _require_own_child(
@router.get("/rule-packs", response_model=list[RulePackOut])
async def list_rule_packs(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[MSSPRulePack]:
"""List all rule packs owned by the current parent tenant."""
result = await db.execute(
@@ -475,7 +476,7 @@ async def list_rule_packs(
async def create_rule_pack(
body: RulePackCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPRulePack:
"""Create a new rule pack (parent tenant only)."""
pack = MSSPRulePack(
@@ -484,7 +485,7 @@ async def create_rule_pack(
description=body.description,
category=body.category,
is_default=body.is_default,
- created_by_user=current_user.id,
+ created_by_user=current_user.user_id,
)
db.add(pack)
await db.commit()
@@ -496,7 +497,7 @@ async def create_rule_pack(
async def get_rule_pack(
pack_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPRulePack:
pack = await db.get(MSSPRulePack, pack_id)
if not pack or pack.parent_tenant_id != current_user.tenant_id:
@@ -509,7 +510,7 @@ async def update_rule_pack(
pack_id: uuid.UUID,
body: RulePackUpdate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPRulePack:
pack = await db.get(MSSPRulePack, pack_id)
if not pack or pack.parent_tenant_id != current_user.tenant_id:
@@ -531,7 +532,7 @@ async def update_rule_pack(
async def delete_rule_pack(
pack_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
pack = await db.get(MSSPRulePack, pack_id)
if not pack or pack.parent_tenant_id != current_user.tenant_id:
@@ -545,7 +546,7 @@ async def add_rule_to_pack(
pack_id: uuid.UUID,
body: RulePackRuleAdd,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> dict[str, str]:
pack = await db.get(MSSPRulePack, pack_id)
if not pack or pack.parent_tenant_id != current_user.tenant_id:
@@ -566,7 +567,7 @@ async def remove_rule_from_pack(
pack_id: uuid.UUID,
rule_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
pack = await db.get(MSSPRulePack, pack_id)
if not pack or pack.parent_tenant_id != current_user.tenant_id:
@@ -582,7 +583,7 @@ async def assign_pack_to_child(
pack_id: uuid.UUID,
body: PackAssignmentCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPRulePackAssignment:
pack = await db.get(MSSPRulePack, pack_id)
if not pack or pack.parent_tenant_id != current_user.tenant_id:
@@ -607,7 +608,7 @@ async def assign_pack_to_child(
async def create_rule_override(
body: RuleOverrideCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MSSPRuleOverride:
if body.action not in ("exclude", "customize"):
raise HTTPException(status_code=422, detail="action must be 'exclude' or 'customize'")
@@ -623,7 +624,7 @@ async def create_rule_override(
note=body.note,
severity_override=body.severity_override,
parameter_overrides=body.parameter_overrides,
- created_by_user=current_user.id,
+ created_by_user=current_user.user_id,
)
db.add(override)
await db.commit()
@@ -635,7 +636,7 @@ async def create_rule_override(
async def list_overrides(
child_id: uuid.UUID | None = Query(None),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[MSSPRuleOverride]:
q = select(MSSPRuleOverride).where(
MSSPRuleOverride.child_tenant_id.in_(select(Tenant.id).where(Tenant.parent_tenant_id == current_user.tenant_id))
@@ -650,7 +651,7 @@ async def list_overrides(
async def delete_override(
override_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
override = await db.get(MSSPRuleOverride, override_id)
if not override:
@@ -671,7 +672,7 @@ async def delete_override(
async def list_effective_rules_for_child(
child_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
category: str | None = Query(None),
rule_language: str | None = Query(None),
) -> list[EffectiveRuleOut]:
@@ -714,7 +715,7 @@ async def list_effective_rules_for_child(
async def count_effective_rules_for_child(
child_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> EffectiveRuleCountOut:
"""Return source-breakdown counts for a child tenant's effective ruleset."""
child = await db.get(Tenant, child_id)
@@ -745,17 +746,21 @@ async def count_effective_rules_for_child(
async def _scope(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> PortfolioScope:
"""Resolve the caller's managed portfolio, or refuse the surface.
+ Annotated with the type `get_current_user` actually returns. The rest of
+ this module still says `User`, which is why nothing caught the id being
+ read off the wrong attribute here.
+
A principal who belongs to no organisation gets 403 rather than an empty
list: an empty list would read as "you manage nothing", when the truth
is that cross-tenant reads are not theirs to make. A member whose
portfolio is genuinely empty does get empty results, and the payload
says so explicitly.
"""
- scope = await resolve_portfolio_scope(db, current_user)
+ scope = await resolve_portfolio_scope(db, current_user.user_id)
if not scope.is_member:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
@@ -1018,7 +1023,7 @@ class TenantGrant(BaseModel):
async def create_organization(
body: OrganizationCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> Organization:
"""Create an operator organisation around the caller's own tenant.
@@ -1045,7 +1050,7 @@ async def create_organization(
)
db.add(org)
await db.flush()
- db.add(OrganizationMember(org_id=org.id, user_id=current_user.id, org_role="owner"))
+ db.add(OrganizationMember(org_id=org.id, user_id=current_user.user_id, org_role="owner"))
# The operator's own tenant joins its own portfolio, so a provider that
# also runs an estate sees it in the same rollup as its customers.
db.add(OrganizationTenant(org_id=org.id, tenant_id=current_user.tenant_id, relationship="own"))
@@ -1070,7 +1075,7 @@ async def add_tenants_to_portfolio(
body: TenantGrant,
scope: PortfolioScope = Depends(_admin_scope),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> dict[str, object]:
"""Bring tenants under management.
@@ -1097,7 +1102,7 @@ async def add_tenants_to_portfolio(
org_id=scope.org_id,
tenant_id=tenant_id,
relationship="managed",
- onboarded_by=current_user.id,
+ onboarded_by=current_user.user_id,
)
)
added.append(str(tenant_id))
@@ -1212,7 +1217,7 @@ async def set_member_tenant_grants(
body: TenantGrant,
scope: PortfolioScope = Depends(_admin_scope),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> MemberOut:
"""Replace which portfolio tenants one member may reach.
@@ -1273,7 +1278,7 @@ async def set_member_tenant_grants(
org_id=scope.org_id,
user_id=user_id,
tenant_id=tenant_id,
- granted_by=current_user.id,
+ granted_by=current_user.user_id,
)
)
diff --git a/services/api/app/api/v1/endpoints/posture.py b/services/api/app/api/v1/endpoints/posture.py
index c619ae8c2..5b3758c99 100644
--- a/services/api/app/api/v1/endpoints/posture.py
+++ b/services/api/app/api/v1/endpoints/posture.py
@@ -11,10 +11,10 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.posture import PostureFinding, PostureScanRun
-from app.models.tenant import User
from app.services.compliance_mapping import evidence_for_cspm_finding
from app.services.cspm import scan_resources, summarize
from app.services.destinations import (
@@ -105,7 +105,7 @@ async def list_findings(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[PostureFinding]:
q = select(PostureFinding).where(PostureFinding.tenant_id == current_user.tenant_id)
if cloud_provider:
@@ -125,7 +125,7 @@ async def list_findings(
async def ingest_finding(
body: FindingCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> PostureFinding:
finding = PostureFinding(**body.model_dump(), tenant_id=current_user.tenant_id)
db.add(finding)
@@ -138,7 +138,7 @@ async def ingest_finding(
async def get_finding(
finding_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> PostureFinding:
f = await db.get(PostureFinding, finding_id)
if not f or f.tenant_id != current_user.tenant_id:
@@ -151,14 +151,14 @@ async def suppress_finding(
finding_id: uuid.UUID,
body: SuppressRequest,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> PostureFinding:
f = await db.get(PostureFinding, finding_id)
if not f or f.tenant_id != current_user.tenant_id:
raise HTTPException(status_code=404, detail="Finding not found")
f.status = "suppressed" # type: ignore[assignment]
f.suppressed_at = datetime.now(UTC) # type: ignore[assignment]
- f.suppressed_by = current_user.id # type: ignore[assignment]
+ f.suppressed_by = current_user.user_id # type: ignore[assignment]
f.suppress_reason = body.reason # type: ignore[assignment]
await db.commit()
await db.refresh(f)
@@ -169,7 +169,7 @@ async def suppress_finding(
async def resolve_finding(
finding_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> PostureFinding:
f = await db.get(PostureFinding, finding_id)
if not f or f.tenant_id != current_user.tenant_id:
@@ -185,7 +185,7 @@ async def resolve_finding(
async def get_summary(
cloud_provider: str | None = Query(None),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> PostureSummary:
q = select(PostureFinding).where(PostureFinding.tenant_id == current_user.tenant_id)
if cloud_provider:
@@ -215,7 +215,7 @@ async def list_scans(
limit: int = Query(20, le=100),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[PostureScanRun]:
result = await db.execute(
select(PostureScanRun)
@@ -246,7 +246,7 @@ class CspmScanResponse(BaseModel):
@router.post("/scan", response_model=CspmScanResponse)
async def cspm_scan(
body: CspmScanRequest,
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> CspmScanResponse:
"""Agentless CSPM MVP (W6.2): evaluate a cloud-resource snapshot against the
misconfiguration checks, returning findings + a severity summary + the
@@ -269,7 +269,7 @@ class DestinationPreviewRequest(BaseModel):
@router.post("/destinations/preview")
async def destination_preview(
body: DestinationPreviewRequest,
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> dict[str, Any]:
"""Preview the exact payload a destination would send (W6.3) — no send."""
if body.kind == "opsgenie":
diff --git a/services/api/app/api/v1/endpoints/remediation.py b/services/api/app/api/v1/endpoints/remediation.py
index 179462c24..a112487d6 100644
--- a/services/api/app/api/v1/endpoints/remediation.py
+++ b/services/api/app/api/v1/endpoints/remediation.py
@@ -11,10 +11,10 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.remediation import RemediationGateLog, RemediationMaturity, RemediationWhitelist
-from app.models.tenant import User
router = APIRouter(prefix="/remediation", tags=["remediation"])
@@ -79,7 +79,7 @@ class WhitelistOut(WhitelistCreate):
@router.get("/config", response_model=MaturityOut)
async def get_maturity_config(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> RemediationMaturity:
result = await db.execute(select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id))
config = result.scalar_one_or_none()
@@ -98,7 +98,7 @@ async def get_maturity_config(
async def update_maturity_config(
body: MaturityConfig,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> RemediationMaturity:
result = await db.execute(select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id))
config = result.scalar_one_or_none()
@@ -108,7 +108,7 @@ async def update_maturity_config(
config.maturity_tier = body.maturity_tier # type: ignore[assignment]
config.action_overrides = body.action_overrides # type: ignore[assignment]
- config.changed_by = current_user.id # type: ignore[assignment]
+ config.changed_by = current_user.user_id # type: ignore[assignment]
config.changed_at = datetime.now(UTC) # type: ignore[assignment]
await db.commit()
await db.refresh(config)
@@ -126,7 +126,7 @@ async def list_gate_log(
limit: int = Query(50, le=500),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[RemediationGateLog]:
q = select(RemediationGateLog).where(RemediationGateLog.tenant_id == current_user.tenant_id)
if decision:
@@ -144,7 +144,7 @@ async def list_gate_log(
@router.get("/whitelist", response_model=list[WhitelistOut])
async def list_whitelist(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[RemediationWhitelist]:
result = await db.execute(select(RemediationWhitelist).where(RemediationWhitelist.tenant_id == current_user.tenant_id))
return list(result.scalars().all())
@@ -154,12 +154,12 @@ async def list_whitelist(
async def add_to_whitelist(
body: WhitelistCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> RemediationWhitelist:
entry = RemediationWhitelist(
**body.model_dump(),
tenant_id=current_user.tenant_id,
- approved_by=current_user.id,
+ approved_by=current_user.user_id,
)
db.add(entry)
await db.commit()
@@ -171,7 +171,7 @@ async def add_to_whitelist(
async def remove_from_whitelist(
entry_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
entry = await db.get(RemediationWhitelist, entry_id)
if not entry or entry.tenant_id != current_user.tenant_id:
diff --git a/services/api/app/api/v1/endpoints/replay.py b/services/api/app/api/v1/endpoints/replay.py
index ed4cda9a9..8da12fbfe 100644
--- a/services/api/app/api/v1/endpoints/replay.py
+++ b/services/api/app/api/v1/endpoints/replay.py
@@ -200,7 +200,7 @@ async def publish_replay(
case_id=run.case_id,
title=title,
snapshot=result.snapshot,
- published_by=current_user.id,
+ published_by=current_user.user_id,
)
db.add(row)
await db.commit()
diff --git a/services/api/app/api/v1/endpoints/reports.py b/services/api/app/api/v1/endpoints/reports.py
index 48e65b930..40939c0e7 100644
--- a/services/api/app/api/v1/endpoints/reports.py
+++ b/services/api/app/api/v1/endpoints/reports.py
@@ -15,10 +15,10 @@ from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.report import ReportArtefact, ReportTemplate
-from app.models.tenant import User
from app.services.digest_html import render_digest_html
from app.services.digest_pdf import WeasyPrintUnavailableError, render_digest_pdf
from app.services.executive_digest import ExecutiveDigest, build_weekly_digest
@@ -89,7 +89,7 @@ class GenerateRequest(BaseModel):
@router.get("/templates", response_model=list[TemplateOut])
async def list_templates(
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[ReportTemplate]:
result = await db.execute(
select(ReportTemplate).where(ReportTemplate.tenant_id == current_user.tenant_id).order_by(ReportTemplate.name)
@@ -101,12 +101,12 @@ async def list_templates(
async def create_template(
body: TemplateCreate,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> ReportTemplate:
template = ReportTemplate(
**body.model_dump(),
tenant_id=current_user.tenant_id,
- created_by=current_user.id,
+ created_by=current_user.user_id,
)
db.add(template)
await db.commit()
@@ -118,7 +118,7 @@ async def create_template(
async def get_template(
template_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> ReportTemplate:
tmpl = await db.get(ReportTemplate, template_id)
if not tmpl or tmpl.tenant_id != current_user.tenant_id:
@@ -130,7 +130,7 @@ async def get_template(
async def delete_template(
template_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> None:
tmpl = await db.get(ReportTemplate, template_id)
if not tmpl or tmpl.tenant_id != current_user.tenant_id:
@@ -151,7 +151,7 @@ async def list_artefacts(
limit: int = Query(20, le=100),
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> list[ReportArtefact]:
q = select(ReportArtefact).where(ReportArtefact.tenant_id == current_user.tenant_id)
if report_type:
@@ -167,7 +167,7 @@ async def list_artefacts(
async def generate_report(
body: GenerateRequest,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> ReportArtefact:
"""Enqueue a report generation job. Returns the artefact record immediately with status='pending'."""
artefact = ReportArtefact(
@@ -179,7 +179,7 @@ async def generate_report(
output_format=body.output_format,
delivered_to=body.recipients,
status="pending",
- generated_by=str(current_user.id),
+ generated_by=str(current_user.user_id),
)
db.add(artefact)
await db.commit()
@@ -191,7 +191,7 @@ async def generate_report(
async def get_artefact(
artefact_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> ReportArtefact:
art = await db.get(ReportArtefact, artefact_id)
if not art or art.tenant_id != current_user.tenant_id:
@@ -218,7 +218,7 @@ async def weekly_digest(
period_start: datetime | None = Query(None, description="ISO timestamp; defaults to now-7d"),
period_end: datetime | None = Query(None, description="ISO timestamp; defaults to now"),
db: AsyncSession = Depends(get_db),
- current_user: User = Depends(get_current_user),
+ current_user: CurrentUser = Depends(get_current_user),
) -> ExecutiveDigest | HTMLResponse | Response:
"""Build a deterministic weekly digest for the caller's tenant.
diff --git a/services/api/app/api/v1/endpoints/sla.py b/services/api/app/api/v1/endpoints/sla.py
index ed3300332..9319aed44 100644
--- a/services/api/app/api/v1/endpoints/sla.py
+++ b/services/api/app/api/v1/endpoints/sla.py
@@ -208,7 +208,7 @@ async def record_sla_event(
severity=body.severity,
event_type=body.event_type,
occurred_at=body.occurred_at or datetime.utcnow(),
- actor_id=current_user.id,
+ actor_id=current_user.user_id,
# ORM attr is `metadata_` (DB column is still `metadata`) — `metadata`
# itself is reserved on Declarative `Base`.
metadata_=body.metadata,
diff --git a/services/api/app/models/alert.py b/services/api/app/models/alert.py
index e93bfaf60..7a15b5458 100644
--- a/services/api/app/models/alert.py
+++ b/services/api/app/models/alert.py
@@ -73,6 +73,14 @@ class Alert(Base):
affected_users: Mapped[list] = mapped_column(JSONB, default=list)
affected_assets: Mapped[list] = mapped_column(JSONB, default=list)
+ # `[{"type": "host", "value": "…"}, …]`, written by the fusion alert sink.
+ # The four columns above are only ever populated by the demo seed: the
+ # production sink's INSERT does not list them, so the Investigation Rail
+ # showed entity pivots on seeded alerts and none at all on real ones. The
+ # column has existed since migration 001 and was simply never mapped here,
+ # so nothing above the database could read what the pipeline produced.
+ entities: Mapped[list] = mapped_column(JSONB, default=list)
+
# Relations
case_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True, index=True)
parent_alert_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
diff --git a/services/api/app/models/saved_view.py b/services/api/app/models/saved_view.py
index b932eab08..01beb3d6a 100644
--- a/services/api/app/models/saved_view.py
+++ b/services/api/app/models/saved_view.py
@@ -17,7 +17,7 @@ validation for a per-user preference store.
Tenant isolation is enforced via Row-Level Security in
``services/api/migrations/037_saved_views.sql``. User isolation is
enforced in the API layer (every query is scoped
-``WHERE user_id = current_user.id``).
+``WHERE user_id = current_user.user_id``).
"""
from __future__ import annotations
diff --git a/services/api/app/services/alert_rail.py b/services/api/app/services/alert_rail.py
index 30dacfdff..fe28c89af 100644
--- a/services/api/app/services/alert_rail.py
+++ b/services/api/app/services/alert_rail.py
@@ -35,7 +35,7 @@ from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime
-from typing import Any
+from typing import Any, Final
from urllib.parse import quote
from pydantic import BaseModel, Field
@@ -200,6 +200,64 @@ def _graph_pivot(kind: str, value: str) -> str:
return f"/graph?entity={quote(f'{kind}:{value}', safe='')}"
+# Entity kinds the rail files under "network" rather than "principal".
+_NETWORK_KINDS: Final[frozenset[str]] = frozenset({"ip", "domain", "url"})
+
+# `type` values the fusion sink emits, mapped to the rail's kinds. Anything
+# outside this map is ignored rather than guessed at: an unrecognised kind
+# would build a `/graph?entity=<kind>:…` link the graph cannot resolve, which
+# is the class of defect the pivot-route test exists to prevent.
+_PIPELINE_ENTITY_KINDS: Final[dict[str, str]] = {
+ "host": "host",
+ "hostname": "host",
+ "device": "host",
+ "user": "user",
+ "username": "user",
+ "account": "user",
+ "asset": "asset",
+ "ip": "ip",
+ "ip_address": "ip",
+ "src_ip": "ip",
+ "domain": "domain",
+ "url": "url",
+}
+
+
+def _pipeline_entities(alert: Alert) -> list[tuple[str, str]]:
+ """Entities the fusion sink recorded, as ``(kind, value)`` pairs.
+
+ `services/fusion` writes `alerts.entities` as
+ ``[{"type": "host", "value": "WIN-01"}, …]`` and does **not** write
+ `affected_hosts` / `affected_users` / `affected_ips` — its INSERT does not
+ list those columns. Only `seed_demo.py` populates them. So every entity
+ pivot in the rail rendered for demo data and for nothing the real pipeline
+ produced, on every deployment.
+
+ Order is preserved and the caller's bucket dedups against the
+ denormalised columns, so a row that happens to carry both spellings
+ yields one chip rather than two.
+ """
+ raw = getattr(alert, "entities", None)
+ if not isinstance(raw, list):
+ return []
+ out: list[tuple[str, str]] = []
+ seen: set[tuple[str, str]] = set()
+ for item in raw:
+ if not isinstance(item, dict):
+ continue
+ declared = _norm_str(item.get("type")) or ""
+ kind = _PIPELINE_ENTITY_KINDS.get(declared.lower())
+ value = _norm_str(item.get("value"))
+ if not kind or not value:
+ continue
+ key = (kind, value.lower())
+ if key in seen:
+ continue
+ seen.add(key)
+ out.append((kind, value))
+ return out
+
+
def build_related_entities(alert: Alert) -> list[RelatedEntity]:
"""Produce the rail's Related Entities list from an ``Alert`` row.
@@ -214,8 +272,16 @@ def build_related_entities(alert: Alert) -> list[RelatedEntity]:
# ── Principal ───────────────────────────────────────────────────────
# Hosts and users an analyst would isolate / disable. We promote
- # the denormalised columns first, then mine the raw event blob
- # for fields the connector didn't curate into a top-level column.
+ # the denormalised columns first, then the `entities` blob the fusion
+ # sink writes, then mine the raw event for fields the connector didn't
+ # curate into a top-level column.
+ for kind, value in _pipeline_entities(alert):
+ bucket.add(
+ group="network" if kind in _NETWORK_KINDS else "principal",
+ kind=kind,
+ value=value,
+ pivot=_graph_pivot(kind, value),
+ )
for host in _dedup_strs(alert.affected_hosts or ()):
bucket.add(
group="principal",
diff --git a/services/api/app/services/audit.py b/services/api/app/services/audit.py
index 134208b89..2304372cf 100644
--- a/services/api/app/services/audit.py
+++ b/services/api/app/services/audit.py
@@ -7,7 +7,7 @@ Usage::
await emit_audit(
db=db,
tenant_id=current_user.tenant_id,
- actor_id=current_user.id,
+ actor_id=current_user.user_id,
actor_email=current_user.email,
action="cases:create",
resource="case",
diff --git a/services/api/app/services/org_scope.py b/services/api/app/services/org_scope.py
index f600760d6..b1abad662 100644
--- a/services/api/app/services/org_scope.py
+++ b/services/api/app/services/org_scope.py
@@ -45,7 +45,6 @@ from app.models.organization import (
OrganizationMemberTenant,
OrganizationTenant,
)
-from app.models.tenant import User
logger = logging.getLogger("aisoc.org_scope")
@@ -104,21 +103,30 @@ class PortfolioScope:
EMPTY_SCOPE = PortfolioScope()
-async def resolve_portfolio_scope(db: AsyncSession, user: User) -> PortfolioScope:
- """Resolve ``user``'s managed portfolio.
+async def resolve_portfolio_scope(db: AsyncSession, user_id: uuid.UUID) -> PortfolioScope:
+ """Resolve the portfolio managed by the principal ``user_id``.
Returns :data:`EMPTY_SCOPE` for a principal who belongs to no
organisation. Returns a member scope with an empty ``tenant_ids`` for a
member who has been granted nothing — which is a different situation
(they are an operator, they just cannot see anything yet) and the API
distinguishes the two.
+
+ Takes the id rather than a principal object on purpose. This function
+ previously accepted ``user: User`` and read ``user.id``, while its only
+ production caller passes the authenticated ``CurrentUser``, which carries
+ its identifier as ``user_id`` and has no ``id`` at all — so every
+ ``/mssp/portfolio`` request raised ``AttributeError`` and returned 500,
+ including the non-member case the route means to answer with 403. The
+ service tests passed throughout because they handed it an ORM ``User``,
+ which does have ``.id``. An identifier cannot be the wrong shape.
"""
membership = (
await db.execute(
select(OrganizationMember, Organization)
.join(Organization, Organization.id == OrganizationMember.org_id)
.where(
- OrganizationMember.user_id == user.id,
+ OrganizationMember.user_id == user_id,
Organization.is_active.is_(True),
)
.order_by(Organization.created_at)
@@ -126,7 +134,7 @@ async def resolve_portfolio_scope(db: AsyncSession, user: User) -> PortfolioScop
).first()
if membership is None:
- logger.debug("org_scope.not_a_member user=%s", user.id)
+ logger.debug("org_scope.not_a_member user=%s", user_id)
return EMPTY_SCOPE
member, org = membership
@@ -143,7 +151,7 @@ async def resolve_portfolio_scope(db: AsyncSession, user: User) -> PortfolioScop
await db.execute(
select(OrganizationMemberTenant.tenant_id).where(
OrganizationMemberTenant.org_id == org.id,
- OrganizationMemberTenant.user_id == user.id,
+ OrganizationMemberTenant.user_id == user_id,
)
)
).scalars()
@@ -160,7 +168,7 @@ async def resolve_portfolio_scope(db: AsyncSession, user: User) -> PortfolioScop
# exact confusion a `debug`-level skip caused for tenant resolution.
logger.warning(
"org_scope.empty_portfolio user=%s org=%s role=%s portfolio_size=%d",
- user.id,
+ user_id,
org.id,
role,
len(portfolio),
diff --git a/services/api/tests/services/test_alert_rail_pipeline_entities.py b/services/api/tests/services/test_alert_rail_pipeline_entities.py
new file mode 100644
index 000000000..e4eccad05
--- /dev/null
+++ b/services/api/tests/services/test_alert_rail_pipeline_entities.py
@@ -0,0 +1,122 @@
+"""The rail has to read the column the pipeline actually writes.
+
+`services/fusion/app/services/alert_sink.py` records extracted entities in
+`alerts.entities` as ``[{"type": "host", "value": "…"}, …]``. Its INSERT does
+not list `affected_hosts`, `affected_users`, `affected_ips` or
+`affected_assets` — the only writer of those four is
+`services/api/app/scripts/seed_demo.py`.
+
+`build_related_entities` sourced its pivots exclusively from those four
+columns, and `Alert` did not map `entities` at all, so the Investigation Rail
+rendered entity chips for seeded demo alerts and **none** for any alert the
+real ingest → fusion pipeline produced. Verified against a live core stack:
+an event pushed through `/v1/ingest/batch` landed with
+``entities = [{"type": "host", "value": "Finance & Legal #2"}, {"type":
+"user", "value": "CORP\\svc backup"}]`` and an empty `affected_hosts`, and the
+alert's rail returned zero pivotable entities.
+
+That made the pivot-route and URL-encoding fixes unreachable in production
+while their own unit tests passed — the same shape as every other defect in
+this audit: the mechanism worked, nothing called it on the path that mattered.
+So these tests assert on the fusion spelling specifically, and one of them
+uses the ampersand-and-hash hostname that motivated the encoding fix.
+"""
+
+from __future__ import annotations
+
+from app.models.alert import Alert
+from app.services.alert_rail import build_related_entities
+
+
+def _alert(**kw) -> Alert:
+ """An `Alert` shaped like a row the fusion sink just wrote."""
+ defaults = {
+ "entities": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "affected_ips": [],
+ "affected_assets": [],
+ "raw_event": {},
+ "enrichment_data": {},
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "connector_type": "acme_waf",
+ }
+ defaults.update(kw)
+ return Alert(**defaults)
+
+
+def _by_kind(alert: Alert) -> dict[str, list[str]]:
+ out: dict[str, list[str]] = {}
+ for e in build_related_entities(alert):
+ if e.pivot:
+ out.setdefault(e.kind, []).append(e.pivot)
+ return out
+
+
+def test_the_alert_model_maps_the_column_fusion_writes() -> None:
+ """Pins the premise: unmapped, the rail cannot see pipeline entities."""
+ assert hasattr(Alert, "entities")
+
+
+def test_pipeline_entities_become_pivotable_chips() -> None:
+ pivots = _by_kind(_alert(entities=[{"type": "host", "value": "WIN-DC01"}, {"type": "user", "value": "svc_backup"}]))
+ assert pivots["host"] == ["/graph?entity=host%3AWIN-DC01"]
+ assert pivots["user"] == ["/graph?entity=user%3Asvc_backup"]
+
+
+def test_a_host_needing_encoding_survives_the_pivot() -> None:
+ """The value observed on a live stack. Unencoded, `Finance & Legal #2`
+ truncates at the ampersand and pivots to a different node while looking
+ like it worked."""
+ pivots = _by_kind(_alert(entities=[{"type": "host", "value": "Finance & Legal #2"}]))
+ assert pivots["host"] == ["/graph?entity=host%3AFinance%20%26%20Legal%20%232"]
+
+
+def test_a_backslashed_account_survives_the_pivot() -> None:
+ pivots = _by_kind(_alert(entities=[{"type": "user", "value": "CORP\\svc backup"}]))
+ assert pivots["user"] == ["/graph?entity=user%3ACORP%5Csvc%20backup"]
+
+
+def test_network_entities_are_grouped_as_network() -> None:
+ groups = {e.kind: e.group for e in build_related_entities(_alert(entities=[{"type": "ip", "value": "10.0.0.7"}]))}
+ assert groups["ip"] == "network"
+
+
+def test_vendor_spellings_are_normalised() -> None:
+ pivots = _by_kind(
+ _alert(
+ entities=[
+ {"type": "hostname", "value": "web-01"},
+ {"type": "username", "value": "alice"},
+ {"type": "ip_address", "value": "10.0.0.9"},
+ ]
+ )
+ )
+ assert pivots["host"] == ["/graph?entity=host%3Aweb-01"]
+ assert pivots["user"] == ["/graph?entity=user%3Aalice"]
+ assert pivots["ip"] == ["/graph?entity=ip%3A10.0.0.9"]
+
+
+def test_an_unrecognised_kind_is_dropped_not_guessed() -> None:
+ """A `/graph?entity=<kind>:…` link the graph cannot resolve is worse than
+ no chip: it looks like a working pivot and lands nowhere."""
+ assert not _by_kind(_alert(entities=[{"type": "mutex", "value": "Global\\x"}]))
+
+
+def test_a_row_carrying_both_spellings_yields_one_chip() -> None:
+ pivots = _by_kind(_alert(entities=[{"type": "host", "value": "WIN-DC01"}], affected_hosts=["win-dc01"]))
+ assert pivots["host"] == ["/graph?entity=host%3AWIN-DC01"]
+
+
+def test_malformed_entity_rows_do_not_raise() -> None:
+ alert = _alert(entities=[None, "host", {"value": "no-type"}, {"type": "host"}, {"type": "host", "value": " "}])
+ assert not _by_kind(alert)
+
+
+def test_demo_seeded_columns_still_work() -> None:
+ """The seed writes the four columns; that path must not regress."""
+ pivots = _by_kind(_alert(affected_hosts=["WIN-FIN-01"], affected_users=["bob"], affected_ips=["10.1.1.1"]))
+ assert pivots["host"] == ["/graph?entity=host%3AWIN-FIN-01"]
+ assert pivots["user"] == ["/graph?entity=user%3Abob"]
+ assert pivots["ip"] == ["/graph?entity=ip%3A10.1.1.1"]
diff --git a/services/api/tests/test_authenticated_principal_attrs.py b/services/api/tests/test_authenticated_principal_attrs.py
new file mode 100644
index 000000000..9873a8cb7
--- /dev/null
+++ b/services/api/tests/test_authenticated_principal_attrs.py
@@ -0,0 +1,117 @@
+"""No route may read an attribute the authenticated principal does not have.
+
+`get_current_user` returns :class:`app.api.v1.deps.CurrentUser`, whose
+identifier is ``user_id``. Sixteen handlers across seven modules read
+``current_user.id`` instead, so every mutating route that stamps "who did
+this" answered ``500 Internal Server Error``: creating a report template,
+creating an operator organisation, granting a tenant, watchlisting a profile,
+acknowledging an indicator, publishing a replay, suppressing a finding. The
+MSSP portfolio surface was unreachable in both directions — the aggregate
+500'd, and so did the only route that can create the organisation it
+aggregates over.
+
+Two things let that ship:
+
+* **The annotation lied.** Thirty-plus handlers declared
+ ``current_user: User`` while the dependency returns ``CurrentUser``, so a
+ type checker was told the attribute existed.
+* **The tests used the other type.** `resolve_portfolio_scope` was exercised
+ with an ORM ``User`` fetched from the test database, which really does have
+ ``.id``. A passing test on the wrong object is indistinguishable from a
+ working feature.
+
+A gate is cheaper than remembering. This one reads the endpoint sources and
+fails on any attribute access against a name bound to the authenticated
+principal that ``CurrentUser`` does not define, which catches the next
+instance whether or not it is annotated honestly.
+"""
+
+from __future__ import annotations
+
+import ast
+import pathlib
+
+from app.api.v1.deps import CurrentUser
+
+ENDPOINTS = pathlib.Path(__file__).resolve().parents[1] / "app" / "api" / "v1" / "endpoints"
+
+# Names the codebase binds to the resolved principal.
+PRINCIPAL_NAMES = {"current_user", "_user", "user", "principal"}
+
+# The dependency callables that produce a `CurrentUser`.
+PRINCIPAL_DEPS = {"get_current_user", "require_permission", "AuthUser"}
+
+
+def _principal_attributes() -> set[str]:
+ """Everything a `CurrentUser` actually exposes, read off the class."""
+ probe = CurrentUser(
+ user_id=__import__("uuid").uuid4(),
+ tenant_id=__import__("uuid").uuid4(),
+ role="admin",
+ )
+ return {a for a in dir(probe) if not a.startswith("__")}
+
+
+def _principal_locals(fn: ast.AST) -> set[str]:
+ """Parameter names in ``fn`` bound to the authenticated principal."""
+ bound: set[str] = set()
+ args = getattr(fn, "args", None)
+ if args is None:
+ return bound
+ every = list(args.args) + list(args.kwonlyargs)
+ defaults = list(args.defaults) + [d for d in args.kw_defaults if d is not None]
+ rendered_defaults = " ".join(ast.unparse(d) for d in defaults)
+ for arg in every:
+ if arg.arg not in PRINCIPAL_NAMES:
+ continue
+ annotation = ast.unparse(arg.annotation) if arg.annotation else ""
+ blob = f"{annotation} {rendered_defaults}"
+ if any(dep in blob for dep in PRINCIPAL_DEPS):
+ bound.add(arg.arg)
+ return bound
+
+
+def test_no_handler_reads_an_attribute_the_principal_lacks() -> None:
+ allowed = _principal_attributes()
+ assert "user_id" in allowed and "id" not in allowed, "premise changed; revisit this gate"
+
+ offenders: list[str] = []
+ for path in sorted(ENDPOINTS.glob("*.py")):
+ tree = ast.parse(path.read_text(), filename=str(path))
+ for fn in ast.walk(tree):
+ if not isinstance(fn, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+ bound = _principal_locals(fn)
+ if not bound:
+ continue
+ for node in ast.walk(fn):
+ if (
+ isinstance(node, ast.Attribute)
+ and isinstance(node.value, ast.Name)
+ and node.value.id in bound
+ and node.attr not in allowed
+ ):
+ offenders.append(f"{path.name}:{node.lineno} {node.value.id}.{node.attr}")
+
+ assert not offenders, "authenticated principal has no such attribute:\n " + "\n ".join(offenders)
+
+
+def test_the_gate_would_catch_the_defect_it_was_written_for() -> None:
+ """A gate that cannot fail is decorative. Feed it the original shape."""
+ source = (
+ "async def create_template(\n"
+ " current_user: CurrentUser = Depends(get_current_user),\n"
+ "):\n"
+ " return ReportTemplate(created_by=current_user.id)\n"
+ )
+ tree = ast.parse(source)
+ fn = tree.body[0]
+ bound = _principal_locals(fn)
+ assert bound == {"current_user"}
+ bad = [
+ n.attr
+ for n in ast.walk(fn)
+ if isinstance(n, ast.Attribute) and isinstance(n.value, ast.Name) and n.value.id in bound and n.attr not in _principal_attributes()
+ ]
+ assert bad == ["id"]
diff --git a/services/api/tests/test_mssp_portfolio_isolation.py b/services/api/tests/test_mssp_portfolio_isolation.py
index 275342fcf..e0b665db0 100644
--- a/services/api/tests/test_mssp_portfolio_isolation.py
+++ b/services/api/tests/test_mssp_portfolio_isolation.py
@@ -217,12 +217,6 @@ def _owner_scope() -> PortfolioScope:
)
-async def _user(session, user_id: uuid.UUID):
- from app.models.tenant import User
-
- return await session.get(User, user_id)
-
-
# ---------------------------------------------------------------------------
# Step 2 of the shape: the outsiders really exist
# ---------------------------------------------------------------------------
@@ -276,7 +270,7 @@ async def test_connector_health_counts_only_portfolio_connectors(db) -> None:
async def test_an_operator_sees_only_the_tenants_granted_to_them(db) -> None:
- scope = await resolve_portfolio_scope(db, await _user(db, OPERATOR_P))
+ scope = await resolve_portfolio_scope(db, OPERATOR_P)
assert scope.is_member
assert scope.portfolio_wide is False
@@ -293,7 +287,7 @@ async def test_a_member_with_no_grants_resolves_to_empty_not_everything(db) -> N
accounts must see nothing. If "no grants" ever degraded into "no
filter", every new hire would get the entire book of business.
"""
- scope = await resolve_portfolio_scope(db, await _user(db, NEWCOMER_P))
+ scope = await resolve_portfolio_scope(db, NEWCOMER_P)
assert scope.is_member, "should still be recognised as a member"
assert scope.tenant_ids == frozenset()
@@ -303,14 +297,14 @@ async def test_a_member_with_no_grants_resolves_to_empty_not_everything(db) -> N
async def test_a_non_member_resolves_to_no_organisation_at_all(db) -> None:
- scope = await resolve_portfolio_scope(db, await _user(db, STRANGER))
+ scope = await resolve_portfolio_scope(db, STRANGER)
assert scope.is_member is False
assert scope.tenant_ids == frozenset()
async def test_an_owner_of_one_organisation_cannot_reach_another(db) -> None:
- owner = await resolve_portfolio_scope(db, await _user(db, OWNER_P))
+ owner = await resolve_portfolio_scope(db, OWNER_P)
assert owner.org_id == ORG_P
assert TENANT_C not in owner.tenant_ids, "Provider Q's customer is in Provider P's scope"
@@ -479,7 +473,7 @@ async def test_releasing_a_tenant_revokes_every_grant_over_it(db) -> None:
# And the operator's resolved scope collapses to empty rather than
# silently keeping the account they no longer manage.
- scope = await resolve_portfolio_scope(db, await _user(db, OPERATOR_P))
+ scope = await resolve_portfolio_scope(db, OPERATOR_P)
assert scope.tenant_ids == frozenset()
diff --git a/services/api/tests/test_mssp_scope_principal.py b/services/api/tests/test_mssp_scope_principal.py
new file mode 100644
index 000000000..5b8220460
--- /dev/null
+++ b/services/api/tests/test_mssp_scope_principal.py
@@ -0,0 +1,97 @@
+"""The portfolio scope resolver has to accept the principal the route hands it.
+
+`test_mssp_portfolio_isolation.py` proves the aggregation is tenant-scoped and
+`test_mssp_portfolio_contract.py` proves every figure survives serialisation.
+Neither could see the defect that made the whole surface unreachable, because
+both call `resolve_portfolio_scope` with an ORM `User` fetched from the test
+database, and the one production caller passes the authenticated
+`CurrentUser`. `CurrentUser` carries its identifier as `user_id` and has no
+`id` at all, so `GET /mssp/portfolio` raised `AttributeError` and returned 500
+to every caller — including the non-member, whom the route means to answer
+with a deliberate 403. The route was annotated `current_user: User`, so type
+checking believed the attribute was there.
+
+The lesson is the one the audit keeps relearning: a passing test on the wrong
+object is indistinguishable from a working feature. So this test drives the
+real dependency with the real principal type, and needs no database to do it
+— the non-member path returns before any row is read.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints.mssp import _scope
+from app.services.org_scope import resolve_portfolio_scope
+from fastapi import HTTPException
+
+
+class _NoRows:
+ """The single result shape `resolve_portfolio_scope` reads on this path."""
+
+ def first(self):
+ return None
+
+ def scalars(self):
+ return []
+
+
+class _StubSession:
+ """Answers `execute` with "no membership" and records that it was asked.
+
+ A stub rather than a mock because the assertion is about the *principal*
+ reaching the query at all. If the id is read off the wrong attribute the
+ call never gets here, which is exactly the failure being pinned.
+ """
+
+ def __init__(self) -> None:
+ self.executed = 0
+
+ async def execute(self, *_args, **_kwargs):
+ self.executed += 1
+ return _NoRows()
+
+
+def _principal() -> CurrentUser:
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=uuid.uuid4(),
+ role="admin",
+ )
+
+
+def test_the_authenticated_principal_exposes_no_id_attribute() -> None:
+ """Pins the premise. If `CurrentUser` ever grows an `id`, the call sites
+ below stop being load-bearing and this test says so rather than passing
+ for a reason that no longer holds."""
+ assert not hasattr(_principal(), "id")
+ assert isinstance(_principal().user_id, uuid.UUID)
+
+
+async def test_resolving_a_scope_accepts_the_principals_identifier() -> None:
+ """The resolver takes an id, so it cannot be handed the wrong shape."""
+ db = _StubSession()
+ scope = await resolve_portfolio_scope(db, _principal().user_id)
+ assert db.executed == 1, "the membership query never ran"
+ assert not scope.is_member
+ assert scope.is_empty
+
+
+async def test_a_non_member_is_refused_with_403_not_a_500() -> None:
+ """The observed defect, stated as an assertion.
+
+ Before the fix this raised `AttributeError` out of the dependency and
+ FastAPI turned it into `500 Internal Server Error`, so an operator who
+ manages nothing could not tell "this surface is not yours" from "this
+ product is broken".
+ """
+ with pytest.raises(HTTPException) as caught:
+ await _scope(db=_StubSession(), current_user=_principal())
+
+ assert caught.value.status_code == 403
+ assert "organisation" in str(caught.value.detail).lower()
diff --git a/services/api/tests/test_readme_api_docs_url.py b/services/api/tests/test_readme_api_docs_url.py
new file mode 100644
index 000000000..5d42d209a
--- /dev/null
+++ b/services/api/tests/test_readme_api_docs_url.py
@@ -0,0 +1,36 @@
+"""The README's API-docs URL has to be the one the app serves.
+
+The quick start told a new user to open `http://localhost:8000/docs`. FastAPI
+is mounted with `docs_url="/api/docs"`, so that URL returned
+`{"detail":"Not Found"}` on a freshly-started stack — the second link in the
+quick start, 404 on arrival.
+
+Pinned as a test rather than fixed once because the two live in different
+files and neither mentions the other.
+"""
+
+from __future__ import annotations
+
+import pathlib
+import re
+
+from app.core.config import settings
+from app.main import create_application
+
+README = pathlib.Path(__file__).resolve().parents[3] / "README.md"
+
+
+def test_the_readme_points_at_the_url_the_app_mounts() -> None:
+ app = create_application()
+ assert not settings.is_production, "this test asserts the dev-mode mount"
+ docs_url = app.docs_url
+ assert docs_url, "docs are unmounted; the README should not advertise them"
+
+ text = README.read_text()
+ advertised = set(re.findall(r"http://localhost:8000(/[\w/.-]*)", text))
+ assert advertised, "README no longer advertises an API docs URL"
+
+ for path in advertised:
+ assert path in {docs_url, app.openapi_url, app.redoc_url, "/health"}, (
+ f"README advertises http://localhost:8000{path}, which the app does not serve " f"(docs are at {docs_url})"
+ )