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.

Give the MSSP console a parent organisation to be scoped by, and delete the invented tenants (#796)

Beenu Arora6c078a6341ea
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 83be86500..0baab23b2 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -325,6 +325,24 @@ jobs:
[ "${FILES}" = "${ROWS}" ] \
|| { echo "::error::tracked migrations (${ROWS}) != migration files (${FILES})"; exit 1; }
+ # The MSSP portfolio surface reads across tenants on purpose, so
+ # "does it stay inside its portfolio" cannot be answered by a mocked
+ # session. This is the only job with a real database and the full
+ # migration chain already applied, which makes it the honest home for
+ # the replay: it seeds two organisations plus an unmanaged tenant and
+ # asserts an aggregate as one operator never returns the others.
+ #
+ # MSSP_ISOLATION_REQUIRED turns an unreachable database into a failure
+ # rather than a skip. A gate that quietly declines to run looks
+ # identical to one that passed, which is how the public scoreboard sat
+ # ten weeks stale; here it would mean shipping a cross-tenant surface
+ # with nobody having checked it stays inside its portfolio.
+ - name: Cross-tenant MSSP portfolio isolation (live Postgres)
+ working-directory: services/api
+ env:
+ MSSP_ISOLATION_REQUIRED: '1'
+ run: pip install --quiet pytest pytest-asyncio && python -m pytest tests/test_mssp_portfolio_isolation.py -v --tb=short
+
# The UEBA package layout (app/ dir) isn't wheel-buildable; alembic's
# env.py only needs `app.models.ueba` importable, so run in-place with
# PYTHONPATH instead of pip-installing the service.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f19a75f46..cb166ce1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### BREAKING
+
+- **Three MSSP response schemas describing fabricated data are removed:
+ `MSSPKpiOverview`, `ManagedTenantRow`, `CrossTenantIncident`.** They were
+ the shape of five hardcoded companies with invented alert counts, not the
+ shape of anything the platform measured. `/mssp/overview`,
+ `/mssp/tenants` and `/mssp/incidents` keep their paths and now return
+ `PortfolioSummaryOut`, `PortfolioTenantOut` and `PortfolioAlertOut`,
+ computed from real rows.
+
+ What moved, and why it could not be preserved:
+
+ - `health_score` / `avg_health_score` are **gone**, not nulled. It was an
+ undefined composite with no formula anywhere in the tree; keeping the
+ field would promise a measurement that does not exist. (`MetricsOut` on
+ the separate `/mssp/metrics` route still carries a `health_score` and is
+ unchanged by this release.)
+ - `avg_mttr_minutes` → `mttr_minutes`, measured from cases a tenant
+ actually closed in the trailing 30 days, and **null** when it closed
+ none. The old value was the literal `23.4`. Present on both the per-tenant
+ row and the portfolio summary, where it averages only over tenants that
+ closed something rather than counting a null as a zero.
+ - `sla_breach_count` and `sla_breaches` → `sla_breached_cases`, counted
+ from `cases.sla_breached`.
+ - `connectors_online` / `connectors_degraded` / `connector_status` →
+ `total` / `healthy` / `stale` / `error`, derived from each connector's
+ `health_status` and `last_sync`. Nested under a `connectors` object on
+ the per-tenant row; flat `connectors_*` fields on the summary.
+ - `tenant_id` is now a real tenant UUID rather than a string like
+ `"t-acme"`.
+ - `assignee` is gone from the incident rows. It named invented analysts;
+ an alert's real owner is `case_id`, which is now returned instead.
+ - New: `synthetic_alerts`, so seeded demo rows are counted apart from a
+ tenant's real posture instead of inflating it.
+
+ The routes also return `403` to a caller who belongs to no operator
+ organisation, where they previously returned an empty list to anyone
+ authenticated.
+
+ Nothing in `apps/web` consumes these three routes; it calls
+ `/mssp/children`, which is unchanged.
+
### Security
- **`/api/v1/identity-timeline` read every tenant's alerts.** Both routes bound
@@ -532,6 +574,62 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
every pivot navigated to the graph and dropped the entity, leaving the
analyst to find the node by eye. Both the typed form (`host:WIN-DC01`) and
the bare form `HuntView` emits are accepted, matching on node id then label.
+- **A real operator organisation above tenants, so the MSSP console can be
+ backed by data instead of gated behind demo mode.** `/mssp/overview`,
+ `/mssp/tenants` and `/mssp/incidents` returned five hardcoded companies —
+ "Acme Corp, health 92.4, 12 open alerts", "Wayne Enterprises", invented
+ incidents with invented assignees — because the cross-tenant aggregation
+ query behind them was never written. Gating the sample behind demo mode
+ removed the lie but left the feature unbuilt: outside demo mode the
+ console showed zeros forever. Making it real was a schema change, not an
+ ungating.
+
+ Migration `058` adds `organizations`, `organization_members`,
+ `organization_tenants` and `organization_member_tenants`, and backfills
+ from `tenants.parent_tenant_id`, which keeps working. Three constraints
+ hold the boundary in the database rather than in whichever code path
+ writes a row: `organization_tenants` is unique on `tenant_id` so two
+ providers cannot claim one customer; `organization_member_tenants` has
+ composite foreign keys onto both the membership and the portfolio, so a
+ grant cannot name an unmanaged tenant and releasing a tenant revokes every
+ grant over it; and `organizations.home_tenant_id` cascades, so erasing a
+ provider's own tenant removes the organisation while leaving its customers
+ standing as unclaimed tenants.
+
+ Roles carry two separate axes. `owner`/`admin` reach the whole portfolio;
+ `operator`/`viewer` reach only tenants granted to them, and **nothing**
+ when they have no grants — "no scope" degrading into "all scopes" is the
+ shape every cross-tenant leak in this codebase has had.
+
+ Every cross-tenant read resolves its tenant list through
+ `resolve_portfolio_scope` and nowhere else, then passes it to
+ `require_scope`, which raises rather than letting an aggregate run
+ unfiltered; the list is bound as a query parameter. A `?tenant_id=` filter
+ is intersected with the portfolio, so naming an outside tenant narrows to
+ nothing instead of reaching out. An AST gate fails the build if a new
+ cross-tenant function is added that never calls `require_scope`, and
+ `test_mssp_portfolio_isolation.py` replays two organisations plus an
+ unmanaged tenant against live Postgres in `integration.yml`.
+
+ The sample rows are deleted rather than gated. `health_score` is gone
+ because it was an undefined composite; `mttr_minutes` is measured from
+ cases a tenant actually closed and is null when it closed none; seeded
+ rows are counted separately as `synthetic_alerts` and excluded from the
+ headline figures.
+
+- **Per-tenant limit headroom, so a cap cannot throttle a customer
+ silently.** A tenant that hits a ceiling raises no error anyone sees —
+ alerts keep arriving and stop being triaged, which reads to an evaluator
+ as "the AI doesn't work". `app/services/entitlements.py` measures
+ `connectors`, `seats`, `alerts_per_day` and `triages_per_month` from real
+ rows, reports `ok` / `warning` / `exhausted` per tenant across a
+ portfolio, and logs exhaustion at `warning`. AiSOC ships uncapped: a key
+ with no configured ceiling reports `unlimited` rather than a default
+ nobody set. Ceilings come from `tenants.limits` (per tenant, wins in
+ either direction) or the new `AISOC_DEFAULT_TENANT_LIMITS` setting —
+ declared as a real field, because an undeclared setting is dropped by
+ `extra="ignore"` and the operator who exports it gets no explanation.
+
- **The Splunk warehouse driver executes.** It previously raised
`HuntNotConfigured("provider scaffolded but live SPL execution not yet
diff --git a/apps/docs/docs/concepts/multi-tenancy.md b/apps/docs/docs/concepts/multi-tenancy.md
new file mode 100644
index 000000000..acd78bd92
--- /dev/null
+++ b/apps/docs/docs/concepts/multi-tenancy.md
@@ -0,0 +1,152 @@
+---
+title: Multi-tenancy and managed portfolios
+sidebar_label: Multi-tenancy
+---
+
+# Multi-tenancy and managed portfolios
+
+AiSOC separates two things that are easy to conflate: the **tenant**, which
+is a security boundary around one estate's data, and the **organisation**,
+which is the operator that manages some number of them. A managed service
+provider is an organisation. A single company running its own SOC is also an
+organisation, with a portfolio of one.
+
+## Why the operator is not a tenant
+
+An earlier model added `tenants.parent_tenant_id` — the provider was itself
+a tenant, and its customers were child rows. That is enough to draw a tree
+and not enough to run a managed service:
+
+- It conflates the operator with a boundary. Every consumer of
+ `current_user.tenant_id` on an MSSP route asks "who is the operator" and
+ "whose data is this" with one value, and those have to be different
+ questions or a cross-tenant surface has nothing to enforce.
+- There is no per-analyst scoping. Every user of the parent tenant reaches
+ every child. Providers assign analysts to accounts; the column cannot say
+ so.
+- `ON DELETE SET NULL` meant deleting the parent silently detached the whole
+ portfolio, leaving no record it had existed.
+
+`parent_tenant_id` still works and still backs `GET /api/v1/mssp/children`,
+so existing deployments are unaffected. Migration `058` adds the
+organisation model above it and backfills from it.
+
+## The schema
+
+| Table | Holds |
+| --- | --- |
+| `organizations` | The operator. `home_tenant_id` is the tenant its own staff sign in to. |
+| `organization_members` | Who belongs to it, and with what authority. |
+| `organization_tenants` | The managed portfolio. |
+| `organization_member_tenants` | Which portfolio tenants one member may reach. |
+
+Three constraints do the work that would otherwise live in application code,
+and therefore hold even if that code is wrong:
+
+- `organization_tenants` is unique on `tenant_id`, so two providers cannot
+ both claim one customer and "whose portfolio is this in" has one answer.
+- `organization_member_tenants` carries composite foreign keys onto both
+ `organization_members` and `organization_tenants`. A grant cannot name a
+ tenant the organisation does not manage, and releasing a tenant from the
+ portfolio revokes every grant over it in the same statement.
+- `organizations.home_tenant_id` cascades. If the provider's own tenant is
+ erased under a deletion request, the organisation goes with it — and the
+ customers it managed survive as unclaimed tenants, because offboarding a
+ provider is not an instruction to erase its customers.
+
+## Roles
+
+Two axes, kept separate because they answer different questions.
+
+| Role | Reaches | May act |
+| --- | --- | --- |
+| `owner` | The whole portfolio | Yes, and may administer the organisation |
+| `admin` | The whole portfolio | Yes, and may administer the organisation |
+| `operator` | Only tenants granted to them | Yes |
+| `viewer` | Only tenants granted to them | No |
+
+An `operator` or `viewer` with no grants reaches **nothing**. That is the
+case the design is shaped around: "no scope" must never degrade into "all
+scopes", or every new analyst starts with the entire book of business.
+
+## Cross-tenant surfaces
+
+| Endpoint | Returns |
+| --- | --- |
+| `GET /api/v1/mssp/portfolio` | Per-tenant posture plus derived totals |
+| `GET /api/v1/mssp/portfolio/alerts` | Open alerts across the portfolio |
+| `GET /api/v1/mssp/overview` | Portfolio totals only |
+| `GET /api/v1/mssp/tenants` | Per-tenant posture only |
+| `GET /api/v1/mssp/incidents` | Open alerts across the portfolio |
+
+Each resolves its tenant list through `resolve_portfolio_scope` and nowhere
+else, then passes it to `require_scope`, which raises rather than letting an
+aggregate run with no filter. The tenant list is bound as a query parameter,
+never formatted into SQL. A `?tenant_id=` filter is intersected with the
+portfolio, so naming a tenant outside it narrows the result to nothing
+instead of reaching outside.
+
+A caller who belongs to no organisation gets `403`. A member whose portfolio
+is genuinely empty gets zeros and an empty list, plus `scoped_tenants` and
+`portfolio_wide` in the payload so the console can say *why* it is empty —
+"you have no tenant grants" and "your organisation manages no tenants" are
+different problems with different fixes.
+
+### What these endpoints do not return
+
+They previously returned five hardcoded companies — Acme Corp, Globex
+Industries, Wayne Enterprises — with invented alert counts and a
+`health_score` nobody could reproduce. Every figure is now counted from that
+tenant's own rows, and two consequences are worth stating plainly:
+
+- **`health_score` is gone.** It was an undefined composite. There is no
+ honest way to keep the field and no honest way to compute it.
+- **`mttr_minutes` is null when a tenant has closed no cases.** It is
+ measured from cases that tenant actually closed in the trailing 30 days.
+ Reporting `0.0` would put the account that has done nothing at the top of
+ the league table.
+- **Seeded demo rows are counted separately** as `synthetic_alerts` and
+ excluded from the headline figures, so a demo install reads "0 real, 15
+ synthetic" rather than reporting fixtures as a customer's posture.
+
+## Limits and headroom
+
+A provider's most expensive failure is a quiet one. A tenant that hits a cap
+does not raise an error anyone sees: alerts keep arriving and stop being
+triaged, and the customer reports it as "the AI doesn't work".
+
+Every tenant row carries per-key headroom, and the portfolio summary counts
+how many tenants are in `warning` or `exhausted`. Exhaustion is logged at
+`warning` with the tenant and key.
+
+AiSOC ships **uncapped**. A key with no configured ceiling reports
+`"state": "unlimited"` and `"limit": null` — not a default ceiling, because
+drawing a headroom bar against a number nobody set would put a fabricated
+figure on every tenant row. Set ceilings either way:
+
+- `tenants.limits` (JSONB, per tenant) overrides everything, in either
+ direction. `"unlimited"` and `-1` both mean no limit.
+- `AISOC_DEFAULT_TENANT_LIMITS` (JSON object) sets a deployment-wide
+ default, e.g. `{"connectors": 25, "seats": 50}`.
+
+Measured keys are `connectors`, `seats`, `alerts_per_day` and
+`triages_per_month`. Each is a count over real rows; a key that cannot be
+counted honestly is not offered.
+
+## Isolation
+
+Cross-tenant reads are the one place in the product where per-tenant
+filtering is deliberately relaxed, so they carry their own gates:
+
+- `services/api/tests/test_org_scope.py` runs on every PR. An empty scope
+ refuses; a `?tenant_id=` filter can only narrow; and an AST check fails
+ the build if a new cross-tenant function is added that never calls
+ `require_scope`.
+- `services/api/tests/test_mssp_portfolio_isolation.py` runs against live
+ Postgres in `integration.yml`. It seeds two organisations plus an
+ unmanaged tenant, asserts the outsiders' data really exists so a scoped
+ read cannot pass vacuously, then asserts an aggregate as one operator
+ never returns the others.
+
+See [Tenant isolation](../operations/security.md) for the per-store rules
+that apply to ordinary single-tenant reads.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 7f741b582..b389d4b7b 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -20,6 +20,7 @@ const sidebars: SidebarsConfig = {
label: "Core Concepts",
items: [
"concepts/capabilities",
+ "concepts/multi-tenancy",
"concepts/cases",
"concepts/playbooks",
"concepts/detections",
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 0cd183ca5..1d2e04621 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -9433,19 +9433,127 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
- /api/v1/mssp/overview:
+ /api/v1/mssp/portfolio:
get:
tags:
- mssp
- summary: Mssp Overview
- description: 'Cross-tenant KPI summary for the MSSP parent dashboard.
+ summary: Get Portfolio
+ description: 'Managed portfolio: per-tenant posture plus derived totals.
- Not yet implemented against real data. Returns zeros outside demo mode
+ Every figure is counted from that tenant''s own rows. A portfolio with no
- rather than the sample figures, because a dashboard reading 23.4 minutes
-
- MTTR that nobody measured is worse than one reading nothing.'
+ tenants returns zeros and an empty list.'
+ operationId: get_portfolio_api_v1_mssp_portfolio_get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: tenant_id
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: array
+ items:
+ type: string
+ format: uuid
+ - type: 'null'
+ description: Restrict to these tenants; ignored if outside the portfolio.
+ title: Tenant Id
+ description: Restrict to these tenants; ignored if outside the portfolio.
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PortfolioOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/mssp/portfolio/alerts:
+ get:
+ tags:
+ - mssp
+ summary: List Portfolio Alerts
+ description: Open alerts across the portfolio, newest first.
+ operationId: list_portfolio_alerts_api_v1_mssp_portfolio_alerts_get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: severity
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ description: critical | high | medium | low | info
+ title: Severity
+ description: critical | high | medium | low | info
+ - name: status
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Status
+ - name: include_synthetic
+ in: query
+ required: false
+ schema:
+ type: boolean
+ description: Include seeded demo rows, labelled as such.
+ default: false
+ title: Include Synthetic
+ description: Include seeded demo rows, labelled as such.
+ - name: limit
+ in: query
+ required: false
+ schema:
+ type: integer
+ maximum: 500
+ minimum: 1
+ default: 50
+ title: Limit
+ - name: tenant_id
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: array
+ items:
+ type: string
+ format: uuid
+ - type: 'null'
+ title: Tenant Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/PortfolioAlertOut'
+ title: Response List Portfolio Alerts Api V1 Mssp Portfolio Alerts
+ Get
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/mssp/overview:
+ get:
+ tags:
+ - mssp
+ summary: Mssp Overview
+ description: Portfolio totals for the operator dashboard.
operationId: mssp_overview_api_v1_mssp_overview_get
responses:
'200':
@@ -9453,7 +9561,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/MSSPKpiOverview'
+ $ref: '#/components/schemas/PortfolioSummaryOut'
security:
- HTTPBearer: []
/api/v1/mssp/tenants:
@@ -9461,12 +9569,7 @@ paths:
tags:
- mssp
summary: List Managed Tenants
- description: 'List managed tenants with health scores for the parent dashboard.
-
-
- Empty outside demo mode. `GET /api/v1/mssp/children` is the route backed
-
- by real rows.'
+ description: Managed tenants with their measured posture.
operationId: list_managed_tenants_api_v1_mssp_tenants_get
responses:
'200':
@@ -9475,7 +9578,7 @@ paths:
application/json:
schema:
items:
- $ref: '#/components/schemas/ManagedTenantRow'
+ $ref: '#/components/schemas/PortfolioTenantOut'
type: array
title: Response List Managed Tenants Api V1 Mssp Tenants Get
security:
@@ -9485,8 +9588,7 @@ paths:
tags:
- mssp
summary: List Cross Tenant Incidents
- description: Critical incidents across all managed tenants. Empty outside demo
- mode.
+ description: Open alerts across the portfolio.
operationId: list_cross_tenant_incidents_api_v1_mssp_incidents_get
security:
- HTTPBearer: []
@@ -9498,9 +9600,18 @@ paths:
anyOf:
- type: string
- type: 'null'
- description: 'Filter: high | medium | low'
+ description: critical | high | medium | low | info
title: Severity
- description: 'Filter: high | medium | low'
+ description: critical | high | medium | low | info
+ - name: limit
+ in: query
+ required: false
+ schema:
+ type: integer
+ maximum: 500
+ minimum: 1
+ default: 50
+ title: Limit
responses:
'200':
description: Successful Response
@@ -9509,7 +9620,7 @@ paths:
schema:
type: array
items:
- $ref: '#/components/schemas/CrossTenantIncident'
+ $ref: '#/components/schemas/PortfolioAlertOut'
title: Response List Cross Tenant Incidents Api V1 Mssp Incidents
Get
'422':
@@ -9518,6 +9629,225 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/mssp/organizations:
+ post:
+ tags:
+ - mssp
+ summary: Create Organization
+ description: 'Create an operator organisation around the caller''s own tenant.
+
+
+ The creator becomes its owner. Available to any authenticated user
+
+ because there is no organisation to be a member of yet — the
+
+ home tenant is taken from the caller''s session rather than the body, so
+
+ nobody can found an organisation on top of somebody else''s tenant.'
+ operationId: create_organization_api_v1_mssp_organizations_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OrganizationCreate'
+ required: true
+ responses:
+ '201':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OrganizationOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/mssp/organizations/current:
+ get:
+ tags:
+ - mssp
+ summary: Get Current Organization
+ operationId: get_current_organization_api_v1_mssp_organizations_current_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OrganizationOut'
+ security:
+ - HTTPBearer: []
+ /api/v1/mssp/organizations/current/tenants:
+ post:
+ tags:
+ - mssp
+ summary: Add Tenants To Portfolio
+ description: 'Bring tenants under management.
+
+
+ A tenant already managed by another organisation is rejected rather than
+
+ reassigned: `organization_tenants` carries a unique constraint on
+
+ `tenant_id` precisely so a customer cannot end up in two portfolios, and
+
+ silently moving one would be a cross-tenant transfer performed by
+
+ whoever asked last.'
+ operationId: add_tenants_to_portfolio_api_v1_mssp_organizations_current_tenants_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TenantGrant'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ additionalProperties: true
+ type: object
+ title: Response Add Tenants To Portfolio Api V1 Mssp Organizations
+ Current Tenants Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/mssp/organizations/current/tenants/{tenant_id}:
+ delete:
+ tags:
+ - mssp
+ summary: Remove Tenant From Portfolio
+ description: 'Release a tenant from management.
+
+
+ Deletes the portfolio link only. The tenant and all of its data survive
+
+ as a standalone tenant — offboarding a customer from a provider is not
+
+ the same request as erasing them, and conflating the two would make this
+
+ button destructive in a way its label does not say.'
+ operationId: remove_tenant_from_portfolio_api_v1_mssp_organizations_current_tenants__tenant_id__delete
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: tenant_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Tenant Id
+ responses:
+ '204':
+ description: Successful Response
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/mssp/organizations/current/members:
+ get:
+ tags:
+ - mssp
+ summary: List Members
+ operationId: list_members_api_v1_mssp_organizations_current_members_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ items:
+ $ref: '#/components/schemas/MemberOut'
+ type: array
+ title: Response List Members Api V1 Mssp Organizations Current Members
+ Get
+ security:
+ - HTTPBearer: []
+ put:
+ tags:
+ - mssp
+ summary: Upsert Member
+ operationId: upsert_member_api_v1_mssp_organizations_current_members_put
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MemberUpsert'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MemberOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/mssp/organizations/current/members/{user_id}/tenants:
+ put:
+ tags:
+ - mssp
+ summary: Set Member Tenant Grants
+ description: 'Replace which portfolio tenants one member may reach.
+
+
+ Tenants outside the portfolio are refused here *and* would be refused by
+
+ the database: `organization_member_tenants` has a composite foreign key
+
+ onto `organization_tenants`, so a grant cannot name a tenant the
+
+ organisation does not manage even if this check were removed.'
+ operationId: set_member_tenant_grants_api_v1_mssp_organizations_current_members__user_id__tenants_put
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: user_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: User Id
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TenantGrant'
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MemberOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/insider-threat/profiles:
get:
tags:
@@ -17137,6 +17467,27 @@ components:
- medianConfidence
- lowConfidence
title: ConfidenceSummary
+ ConnectorHealthOut:
+ properties:
+ total:
+ type: integer
+ title: Total
+ healthy:
+ type: integer
+ title: Healthy
+ stale:
+ type: integer
+ title: Stale
+ error:
+ type: integer
+ title: Error
+ type: object
+ required:
+ - total
+ - healthy
+ - stale
+ - error
+ title: ConnectorHealthOut
ConnectorHealthSummary:
properties:
total:
@@ -18160,40 +18511,6 @@ components:
required:
- items
title: CredentialsListResponse
- CrossTenantIncident:
- properties:
- incident_id:
- type: string
- title: Incident Id
- tenant_name:
- type: string
- title: Tenant Name
- title:
- type: string
- title: Title
- severity:
- type: string
- title: Severity
- status:
- type: string
- title: Status
- created_at:
- type: string
- title: Created At
- assignee:
- anyOf:
- - type: string
- - type: 'null'
- title: Assignee
- type: object
- required:
- - incident_id
- - tenant_name
- - title
- - severity
- - status
- - created_at
- title: CrossTenantIncident
CspmScanRequest:
properties:
resources:
@@ -21429,6 +21746,46 @@ components:
the first event to land. Keeping the shape minimal avoids paying
the full ``ConnectorResponse`` cost on every poll tick.'
+ LimitHeadroomOut:
+ properties:
+ key:
+ type: string
+ title: Key
+ label:
+ type: string
+ title: Label
+ used:
+ type: integer
+ title: Used
+ limit:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Limit
+ remaining:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Remaining
+ pct_used:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Pct Used
+ state:
+ type: string
+ title: State
+ description: unlimited | ok | warning | exhausted
+ type: object
+ required:
+ - key
+ - label
+ - used
+ - limit
+ - remaining
+ - pct_used
+ - state
+ title: LimitHeadroomOut
ListResponse:
properties:
rules:
@@ -21581,83 +21938,9 @@ components:
title: Password
type: object
required:
- - email
- - password
- title: LoginRequest
- MSSPKpiOverview:
- properties:
- total_tenants:
- type: integer
- title: Total Tenants
- total_open_alerts:
- type: integer
- title: Total Open Alerts
- total_critical_incidents:
- type: integer
- title: Total Critical Incidents
- avg_health_score:
- type: number
- title: Avg Health Score
- avg_mttr_minutes:
- type: number
- title: Avg Mttr Minutes
- sla_breach_count:
- type: integer
- title: Sla Breach Count
- connectors_online:
- type: integer
- title: Connectors Online
- connectors_degraded:
- type: integer
- title: Connectors Degraded
- type: object
- required:
- - total_tenants
- - total_open_alerts
- - total_critical_incidents
- - avg_health_score
- - avg_mttr_minutes
- - sla_breach_count
- - connectors_online
- - connectors_degraded
- title: MSSPKpiOverview
- ManagedTenantRow:
- properties:
- tenant_id:
- type: string
- title: Tenant Id
- name:
- type: string
- title: Name
- health_score:
- type: number
- title: Health Score
- open_alerts:
- type: integer
- title: Open Alerts
- critical_alerts:
- type: integer
- title: Critical Alerts
- sla_breaches:
- type: integer
- title: Sla Breaches
- connector_status:
- type: string
- title: Connector Status
- last_event_at:
- type: string
- title: Last Event At
- type: object
- required:
- - tenant_id
- - name
- - health_score
- - open_alerts
- - critical_alerts
- - sla_breaches
- - connector_status
- - last_event_at
- title: ManagedTenantRow
+ - email
+ - password
+ title: LoginRequest
MarketplaceItemSummary:
properties:
id:
@@ -21797,6 +22080,45 @@ components:
- changed_at
- created_at
title: MaturityOut
+ MemberOut:
+ properties:
+ user_id:
+ type: string
+ format: uuid
+ title: User Id
+ email:
+ type: string
+ title: Email
+ org_role:
+ type: string
+ title: Org Role
+ granted_tenants:
+ items:
+ type: string
+ format: uuid
+ type: array
+ title: Granted Tenants
+ type: object
+ required:
+ - user_id
+ - email
+ - org_role
+ - granted_tenants
+ title: MemberOut
+ MemberUpsert:
+ properties:
+ user_id:
+ type: string
+ format: uuid
+ title: User Id
+ org_role:
+ type: string
+ title: Org Role
+ default: viewer
+ type: object
+ required:
+ - user_id
+ title: MemberUpsert
MetricsOut:
properties:
tenant_id:
@@ -22898,6 +23220,62 @@ components:
required:
- status
title: OnCallUpdateRequest
+ OrganizationCreate:
+ properties:
+ slug:
+ type: string
+ maxLength: 64
+ minLength: 2
+ pattern: ^[a-z0-9][a-z0-9-]*$
+ title: Slug
+ name:
+ type: string
+ maxLength: 255
+ minLength: 1
+ title: Name
+ kind:
+ type: string
+ pattern: ^(mssp|enterprise)$
+ title: Kind
+ default: mssp
+ type: object
+ required:
+ - slug
+ - name
+ title: OrganizationCreate
+ OrganizationOut:
+ properties:
+ id:
+ type: string
+ format: uuid
+ title: Id
+ slug:
+ type: string
+ title: Slug
+ name:
+ type: string
+ title: Name
+ kind:
+ type: string
+ title: Kind
+ home_tenant_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Home Tenant Id
+ is_active:
+ type: boolean
+ title: Is Active
+ type: object
+ required:
+ - id
+ - slug
+ - name
+ - kind
+ - home_tenant_id
+ - is_active
+ title: OrganizationOut
OverrideEntryModel:
properties:
key:
@@ -23336,6 +23714,278 @@ components:
- loaded_at
- error
title: PluginOut
+ PortfolioAlertOut:
+ properties:
+ alert_id:
+ type: string
+ format: uuid
+ title: Alert Id
+ tenant_id:
+ type: string
+ format: uuid
+ title: Tenant Id
+ tenant_name:
+ type: string
+ title: Tenant Name
+ title:
+ type: string
+ title: Title
+ severity:
+ type: string
+ title: Severity
+ status:
+ type: string
+ title: Status
+ category:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Category
+ created_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Created At
+ event_time:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Event Time
+ case_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Case Id
+ is_synthetic:
+ type: boolean
+ title: Is Synthetic
+ type: object
+ required:
+ - alert_id
+ - tenant_id
+ - tenant_name
+ - title
+ - severity
+ - status
+ - category
+ - created_at
+ - event_time
+ - case_id
+ - is_synthetic
+ title: PortfolioAlertOut
+ PortfolioOut:
+ properties:
+ org_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Org Id
+ org_slug:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Org Slug
+ org_name:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Org Name
+ org_role:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Org Role
+ portfolio_wide:
+ type: boolean
+ title: Portfolio Wide
+ description: True when the caller's role reaches the whole portfolio rather
+ than a set of explicit tenant grants.
+ scoped_tenants:
+ type: integer
+ title: Scoped Tenants
+ summary:
+ $ref: '#/components/schemas/PortfolioSummaryOut'
+ tenants:
+ items:
+ $ref: '#/components/schemas/PortfolioTenantOut'
+ type: array
+ title: Tenants
+ type: object
+ required:
+ - org_id
+ - org_slug
+ - org_name
+ - org_role
+ - portfolio_wide
+ - scoped_tenants
+ - summary
+ - tenants
+ title: PortfolioOut
+ PortfolioSummaryOut:
+ properties:
+ tenants:
+ type: integer
+ title: Tenants
+ tenants_active:
+ type: integer
+ title: Tenants Active
+ open_alerts:
+ type: integer
+ title: Open Alerts
+ critical_alerts:
+ type: integer
+ title: Critical Alerts
+ high_alerts:
+ type: integer
+ title: High Alerts
+ untriaged_alerts:
+ type: integer
+ title: Untriaged Alerts
+ synthetic_alerts:
+ type: integer
+ title: Synthetic Alerts
+ open_cases:
+ type: integer
+ title: Open Cases
+ sla_breached_cases:
+ type: integer
+ title: Sla Breached Cases
+ mttr_minutes:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Mttr Minutes
+ description: Mean of the per-tenant figures, over tenants that closed something.
+ Null when the portfolio closed nothing.
+ connectors_total:
+ type: integer
+ title: Connectors Total
+ connectors_healthy:
+ type: integer
+ title: Connectors Healthy
+ connectors_stale:
+ type: integer
+ title: Connectors Stale
+ connectors_error:
+ type: integer
+ title: Connectors Error
+ tenants_with_exhausted_limits:
+ type: integer
+ title: Tenants With Exhausted Limits
+ tenants_with_limit_warnings:
+ type: integer
+ title: Tenants With Limit Warnings
+ tenants_without_connectors:
+ type: integer
+ title: Tenants Without Connectors
+ type: object
+ required:
+ - tenants
+ - tenants_active
+ - open_alerts
+ - critical_alerts
+ - high_alerts
+ - untriaged_alerts
+ - synthetic_alerts
+ - open_cases
+ - sla_breached_cases
+ - mttr_minutes
+ - connectors_total
+ - connectors_healthy
+ - connectors_stale
+ - connectors_error
+ - tenants_with_exhausted_limits
+ - tenants_with_limit_warnings
+ - tenants_without_connectors
+ title: PortfolioSummaryOut
+ PortfolioTenantOut:
+ properties:
+ tenant_id:
+ type: string
+ format: uuid
+ title: Tenant Id
+ name:
+ type: string
+ title: Name
+ slug:
+ type: string
+ title: Slug
+ relationship:
+ type: string
+ title: Relationship
+ is_active:
+ type: boolean
+ title: Is Active
+ open_alerts:
+ type: integer
+ title: Open Alerts
+ critical_alerts:
+ type: integer
+ title: Critical Alerts
+ high_alerts:
+ type: integer
+ title: High Alerts
+ untriaged_alerts:
+ type: integer
+ title: Untriaged Alerts
+ synthetic_alerts:
+ type: integer
+ title: Synthetic Alerts
+ description: Seeded demo rows, counted apart from the figures above.
+ open_cases:
+ type: integer
+ title: Open Cases
+ sla_breached_cases:
+ type: integer
+ title: Sla Breached Cases
+ mttr_minutes:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Mttr Minutes
+ description: Mean minutes to close, over cases this tenant closed in the
+ trailing 30 days. Null when it closed none.
+ connectors:
+ $ref: '#/components/schemas/ConnectorHealthOut'
+ last_event_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Last Event At
+ limits:
+ items:
+ $ref: '#/components/schemas/LimitHeadroomOut'
+ type: array
+ title: Limits
+ limits_exhausted:
+ type: integer
+ title: Limits Exhausted
+ limits_warning:
+ type: integer
+ title: Limits Warning
+ type: object
+ required:
+ - tenant_id
+ - name
+ - slug
+ - relationship
+ - is_active
+ - open_alerts
+ - critical_alerts
+ - high_alerts
+ - untriaged_alerts
+ - synthetic_alerts
+ - open_cases
+ - sla_breached_cases
+ - mttr_minutes
+ - connectors
+ - last_event_at
+ - limits
+ - limits_exhausted
+ - limits_warning
+ title: PortfolioTenantOut
PostureSummary:
properties:
total:
@@ -26475,6 +27125,18 @@ components:
the only thing standing between "preview the erase" and "erase", and this
endpoint has no undo.'
+ TenantGrant:
+ properties:
+ tenant_ids:
+ items:
+ type: string
+ format: uuid
+ type: array
+ title: Tenant Ids
+ type: object
+ required:
+ - tenant_ids
+ title: TenantGrant
TenantHeaderResponse:
properties:
id:
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index 003441214..eb83c824d 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -1,4 +1,19 @@
-"""MSSP parent-tenant console endpoints."""
+"""MSSP console endpoints.
+
+Two generations of model live here side by side, deliberately.
+
+`/mssp/children`, `/mssp/notes`, `/mssp/delegations` and the rule-pack routes
+read `tenants.parent_tenant_id` (migration 012), which makes the managing
+provider a tenant. Existing deployments have data in those tables, so they
+keep working unchanged — with the consent and ownership checks that sit
+alongside them.
+
+Everything under `/mssp/portfolio` and `/mssp/organizations` reads the
+organisation model (migration 058), where the operator is its own object
+with members, per-member roles, and per-member tenant grants. Cross-tenant
+reads resolve their tenant list through
+`app.services.org_scope.resolve_portfolio_scope` and nothing else.
+"""
from __future__ import annotations
@@ -7,15 +22,23 @@ import uuid
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, Query, status
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
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.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNote
+from app.models.organization import (
+ ORG_ROLES,
+ Organization,
+ OrganizationMember,
+ OrganizationMemberTenant,
+ OrganizationTenant,
+)
from app.models.tenant import Tenant, User
+from app.services import mssp_portfolio
+from app.services.org_scope import PortfolioScope, narrow, resolve_portfolio_scope
logger = logging.getLogger(__name__)
@@ -703,225 +726,563 @@ async def count_effective_rules_for_child(
# ---------------------------------------------------------------------------
-# Cross-tenant dashboard rollups (mock data for UI)
+# Cross-tenant portfolio surfaces (organisation model, migration 058)
# ---------------------------------------------------------------------------
+#
+# These three routes used to return five hardcoded companies — "Acme Corp,
+# health 92.4, 12 open alerts", "Wayne Enterprises", a list of invented
+# incidents with invented assignees — to any authenticated caller. The
+# aggregation query behind them was never written. A later change stopped
+# short of deleting the sample and instead gated it behind demo mode, which
+# removed the lie but left the feature unimplemented: outside demo mode the
+# MSSP console showed zeros forever.
+#
+# They are now computed from real rows in `app.services.mssp_portfolio`. The
+# sample is gone from the file rather than gated, because a fabricated
+# portfolio has no honest use — an operator evaluating the product needs to
+# see their own empty portfolio, not somebody else's fictional one.
-class MSSPKpiOverview(BaseModel):
- total_tenants: int
- total_open_alerts: int
- total_critical_incidents: int
- avg_health_score: float
- avg_mttr_minutes: float
- sla_breach_count: int
- connectors_online: int
- connectors_degraded: int
+async def _scope(
+ db: AsyncSession = Depends(get_db),
+ current_user: User = Depends(get_current_user),
+) -> PortfolioScope:
+ """Resolve the caller's managed portfolio, or refuse the surface.
+
+ 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)
+ if not scope.is_member:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Not a member of an operator organisation",
+ )
+ return scope
- model_config = ConfigDict(from_attributes=True)
+
+async def _admin_scope(scope: PortfolioScope = Depends(_scope)) -> PortfolioScope:
+ if not scope.can_administer:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Organisation owner or admin role required",
+ )
+ return scope
-class ManagedTenantRow(BaseModel):
- tenant_id: str
+class LimitHeadroomOut(BaseModel):
+ key: str
+ label: str
+ used: int
+ # `None` means uncapped. AiSOC ships with no limits, and a tenant that
+ # has none reports `unlimited` rather than a ceiling nobody configured.
+ limit: int | None
+ remaining: int | None
+ pct_used: float | None
+ state: str = Field(description="unlimited | ok | warning | exhausted")
+
+
+class ConnectorHealthOut(BaseModel):
+ total: int
+ healthy: int
+ stale: int
+ error: int
+
+
+class PortfolioTenantOut(BaseModel):
+ tenant_id: uuid.UUID
name: str
- health_score: float
+ slug: str
+ relationship: str
+ is_active: bool
open_alerts: int
critical_alerts: int
- sla_breaches: int
- connector_status: str
- last_event_at: str
+ high_alerts: int
+ untriaged_alerts: int
+ synthetic_alerts: int = Field(description="Seeded demo rows, counted apart from the figures above.")
+ open_cases: int
+ sla_breached_cases: int
+ mttr_minutes: float | None = Field(
+ description="Mean minutes to close, over cases this tenant closed in the trailing 30 days. Null when it closed none."
+ )
+ connectors: ConnectorHealthOut
+ last_event_at: str | None
+ limits: list[LimitHeadroomOut]
+ limits_exhausted: int
+ limits_warning: int
- model_config = ConfigDict(from_attributes=True)
+
+class PortfolioSummaryOut(BaseModel):
+ tenants: int
+ tenants_active: int
+ open_alerts: int
+ critical_alerts: int
+ high_alerts: int
+ untriaged_alerts: int
+ synthetic_alerts: int
+ open_cases: int
+ sla_breached_cases: int
+ mttr_minutes: float | None = Field(
+ description="Mean of the per-tenant figures, over tenants that closed something. Null when the portfolio closed nothing."
+ )
+ connectors_total: int
+ connectors_healthy: int
+ connectors_stale: int
+ connectors_error: int
+ tenants_with_exhausted_limits: int
+ tenants_with_limit_warnings: int
+ tenants_without_connectors: int
+
+
+class PortfolioOut(BaseModel):
+ org_id: uuid.UUID | None
+ org_slug: str | None
+ org_name: str | None
+ org_role: str | None
+ portfolio_wide: bool = Field(
+ description="True when the caller's role reaches the whole portfolio rather than a set of explicit tenant grants."
+ )
+ # Present so an empty console can explain itself. "You have no tenant
+ # grants" and "your organisation manages no tenants" are different
+ # problems with different fixes, and a bare zero distinguishes neither.
+ scoped_tenants: int
+ summary: PortfolioSummaryOut
+ tenants: list[PortfolioTenantOut]
-class CrossTenantIncident(BaseModel):
- incident_id: str
+class PortfolioAlertOut(BaseModel):
+ alert_id: uuid.UUID
+ tenant_id: uuid.UUID
tenant_name: str
title: str
severity: str
status: str
- created_at: str
- assignee: str | None = None
+ category: str | None
+ created_at: str | None
+ event_time: str | None
+ case_id: uuid.UUID | None
+ is_synthetic: bool
- model_config = ConfigDict(from_attributes=True)
[email protected]("/portfolio", response_model=PortfolioOut)
+async def get_portfolio(
+ tenant_id: list[uuid.UUID] | None = Query(None, description="Restrict to these tenants; ignored if outside the portfolio."),
+ scope: PortfolioScope = Depends(_scope),
+ db: AsyncSession = Depends(get_db),
+) -> PortfolioOut:
+ """Managed portfolio: per-tenant posture plus derived totals.
-_MSSP_TENANTS_MOCK = [
- ManagedTenantRow(
- tenant_id="t-acme",
- name="Acme Corp",
- health_score=92.4,
- open_alerts=12,
- critical_alerts=1,
- sla_breaches=0,
- connector_status="healthy",
- last_event_at="2026-05-07T20:31:00Z",
- ),
- ManagedTenantRow(
- tenant_id="t-globex",
- name="Globex Industries",
- health_score=78.1,
- open_alerts=34,
- critical_alerts=3,
- sla_breaches=2,
- connector_status="degraded",
- last_event_at="2026-05-07T20:28:00Z",
- ),
- ManagedTenantRow(
- tenant_id="t-initech",
- name="Initech LLC",
- health_score=95.7,
- open_alerts=5,
- critical_alerts=0,
- sla_breaches=0,
- connector_status="healthy",
- last_event_at="2026-05-07T20:30:00Z",
- ),
- ManagedTenantRow(
- tenant_id="t-wayne",
- name="Wayne Enterprises",
- health_score=64.3,
- open_alerts=58,
- critical_alerts=7,
- sla_breaches=4,
- connector_status="degraded",
- last_event_at="2026-05-07T20:25:00Z",
- ),
- ManagedTenantRow(
- tenant_id="t-stark",
- name="Stark Solutions",
- health_score=88.9,
- open_alerts=9,
- critical_alerts=1,
- sla_breaches=0,
- connector_status="healthy",
- last_event_at="2026-05-07T20:29:00Z",
- ),
-]
-
-_MSSP_INCIDENTS_MOCK = [
- CrossTenantIncident(
- incident_id="INC-4201",
- tenant_name="Wayne Enterprises",
- title="Ransomware lateral movement detected",
- severity="high",
- status="investigating",
- created_at="2026-05-07T19:45:00Z",
- assignee="Jordan Lee",
- ),
- CrossTenantIncident(
- incident_id="INC-4198",
- tenant_name="Globex Industries",
- title="Suspicious OAuth token abuse in Azure AD",
- severity="high",
- status="investigating",
- created_at="2026-05-07T18:12:00Z",
- assignee="Morgan Chen",
- ),
- CrossTenantIncident(
- incident_id="INC-4195",
- tenant_name="Wayne Enterprises",
- title="Data exfiltration via DNS tunneling",
- severity="high",
- status="contained",
- created_at="2026-05-07T16:30:00Z",
- assignee="Alex Rivera",
- ),
- CrossTenantIncident(
- incident_id="INC-4192",
- tenant_name="Acme Corp",
- title="Brute-force against VPN gateway",
- severity="medium",
- status="resolved",
- created_at="2026-05-07T14:20:00Z",
- assignee="Taylor Kim",
- ),
- CrossTenantIncident(
- incident_id="INC-4189",
- tenant_name="Globex Industries",
- title="Compromised service account in GCP",
- severity="high",
- status="investigating",
- created_at="2026-05-07T12:55:00Z",
- assignee=None,
- ),
-]
-
-
-# The three rollup routes below have no implementation behind them — the
-# cross-tenant aggregation query was never written. They returned the
-# hardcoded rows above to *authenticated* callers with no demo check and no
-# marker, so "Acme Corp, health 92.4, 12 open alerts" was indistinguishable
-# from a measurement. Fabricated security posture presented as real is the one
-# thing this project will not ship.
-#
-# They now serve that sample only in demo mode, and return empty outside it.
-# An empty rollup is the truthful answer: nothing has been aggregated.
+ Every figure is counted from that tenant's own rows. A portfolio with no
+ tenants returns zeros and an empty list.
+ """
+ effective = narrow(scope, tenant_id) if tenant_id else scope
+
+ if effective.is_empty:
+ return PortfolioOut(
+ org_id=scope.org_id,
+ org_slug=scope.org_slug,
+ org_name=scope.org_name,
+ org_role=scope.org_role,
+ portfolio_wide=scope.portfolio_wide,
+ scoped_tenants=0,
+ summary=PortfolioSummaryOut(**mssp_portfolio.EMPTY_SUMMARY),
+ tenants=[],
+ )
+
+ rollups = await mssp_portfolio.tenant_rollups(db, effective)
+ return PortfolioOut(
+ org_id=scope.org_id,
+ org_slug=scope.org_slug,
+ org_name=scope.org_name,
+ org_role=scope.org_role,
+ portfolio_wide=scope.portfolio_wide,
+ scoped_tenants=len(effective.tenant_ids),
+ summary=PortfolioSummaryOut(**mssp_portfolio.summarise(rollups)),
+ tenants=[PortfolioTenantOut(**r.as_dict()) for r in rollups],
+ )
+
+
[email protected]("/portfolio/alerts", response_model=list[PortfolioAlertOut])
+async def list_portfolio_alerts(
+ severity: str | None = Query(None, description="critical | high | medium | low | info"),
+ alert_status: str | None = Query(None, alias="status"),
+ include_synthetic: bool = Query(False, description="Include seeded demo rows, labelled as such."),
+ limit: int = Query(50, ge=1, le=500),
+ tenant_id: list[uuid.UUID] | None = Query(None),
+ scope: PortfolioScope = Depends(_scope),
+ db: AsyncSession = Depends(get_db),
+) -> list[PortfolioAlertOut]:
+ """Open alerts across the portfolio, newest first."""
+ effective = narrow(scope, tenant_id) if tenant_id else scope
+ if effective.is_empty:
+ return []
+
+ rows = await mssp_portfolio.portfolio_alerts(
+ db,
+ effective,
+ severity=severity,
+ status=alert_status,
+ include_synthetic=include_synthetic,
+ limit=limit,
+ )
+ return [PortfolioAlertOut(**row) for row in rows]
-def _mssp_sample_allowed() -> bool:
- return bool(settings.AISOC_DEMO_MODE)
+# The original three paths, kept so existing callers keep working, now
+# reading the same real rows as `/portfolio`. Their payloads changed with
+# their honesty: `health_score` is gone because it was an undefined
+# composite nobody could reproduce, and `avg_mttr_minutes` is now measured
+# from cases the tenant actually closed and is null when it closed none.
[email protected]("/overview", response_model=MSSPKpiOverview)
[email protected]("/overview", response_model=PortfolioSummaryOut)
async def mssp_overview(
+ scope: PortfolioScope = Depends(_scope),
+ db: AsyncSession = Depends(get_db),
+) -> PortfolioSummaryOut:
+ """Portfolio totals for the operator dashboard."""
+ if scope.is_empty:
+ return PortfolioSummaryOut(**mssp_portfolio.EMPTY_SUMMARY)
+ rollups = await mssp_portfolio.tenant_rollups(db, scope)
+ return PortfolioSummaryOut(**mssp_portfolio.summarise(rollups))
+
+
[email protected]("/tenants", response_model=list[PortfolioTenantOut])
+async def list_managed_tenants(
+ scope: PortfolioScope = Depends(_scope),
+ db: AsyncSession = Depends(get_db),
+) -> list[PortfolioTenantOut]:
+ """Managed tenants with their measured posture."""
+ if scope.is_empty:
+ return []
+ rollups = await mssp_portfolio.tenant_rollups(db, scope)
+ return [PortfolioTenantOut(**r.as_dict()) for r in rollups]
+
+
[email protected]("/incidents", response_model=list[PortfolioAlertOut])
+async def list_cross_tenant_incidents(
+ severity: str | None = Query(None, description="critical | high | medium | low | info"),
+ limit: int = Query(50, ge=1, le=500),
+ scope: PortfolioScope = Depends(_scope),
+ db: AsyncSession = Depends(get_db),
+) -> list[PortfolioAlertOut]:
+ """Open alerts across the portfolio."""
+ if scope.is_empty:
+ return []
+ rows = await mssp_portfolio.portfolio_alerts(db, scope, severity=severity, limit=limit)
+ return [PortfolioAlertOut(**row) for row in rows]
+
+
+# ---------------------------------------------------------------------------
+# Organisation administration
+# ---------------------------------------------------------------------------
+
+
+class OrganizationOut(BaseModel):
+ id: uuid.UUID
+ slug: str
+ name: str
+ kind: str
+ home_tenant_id: uuid.UUID | None
+ is_active: bool
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class OrganizationCreate(BaseModel):
+ slug: str = Field(min_length=2, max_length=64, pattern=r"^[a-z0-9][a-z0-9-]*$")
+ name: str = Field(min_length=1, max_length=255)
+ kind: str = Field(default="mssp", pattern="^(mssp|enterprise)$")
+
+
+class MemberOut(BaseModel):
+ user_id: uuid.UUID
+ email: str
+ org_role: str
+ granted_tenants: list[uuid.UUID]
+
+
+class MemberUpsert(BaseModel):
+ user_id: uuid.UUID
+ org_role: str = Field(default="viewer")
+
+
+class TenantGrant(BaseModel):
+ tenant_ids: list[uuid.UUID]
+
+
[email protected]("/organizations", response_model=OrganizationOut, status_code=status.HTTP_201_CREATED)
+async def create_organization(
+ body: OrganizationCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
-) -> MSSPKpiOverview:
- """Cross-tenant KPI summary for the MSSP parent dashboard.
+) -> Organization:
+ """Create an operator organisation around the caller's own tenant.
- Not yet implemented against real data. Returns zeros outside demo mode
- rather than the sample figures, because a dashboard reading 23.4 minutes
- MTTR that nobody measured is worse than one reading nothing.
+ The creator becomes its owner. Available to any authenticated user
+ because there is no organisation to be a member of yet — the
+ home tenant is taken from the caller's session rather than the body, so
+ nobody can found an organisation on top of somebody else's tenant.
"""
- if not _mssp_sample_allowed():
- return MSSPKpiOverview(
- total_tenants=0,
- total_open_alerts=0,
- total_critical_incidents=0,
- avg_health_score=0.0,
- avg_mttr_minutes=0.0,
- sla_breach_count=0,
- connectors_online=0,
- connectors_degraded=0,
- )
- tenants = _MSSP_TENANTS_MOCK
- return MSSPKpiOverview(
- total_tenants=len(tenants),
- total_open_alerts=sum(t.open_alerts for t in tenants),
- total_critical_incidents=sum(t.critical_alerts for t in tenants),
- avg_health_score=round(sum(t.health_score for t in tenants) / len(tenants), 1),
- avg_mttr_minutes=23.4,
- sla_breach_count=sum(t.sla_breaches for t in tenants),
- connectors_online=3,
- connectors_degraded=2,
+ existing = (await db.execute(select(Organization).where(Organization.slug == body.slug))).scalar_one_or_none()
+ if existing is not None:
+ raise HTTPException(status_code=409, detail="Organisation slug already taken")
+
+ already_home = (
+ await db.execute(select(Organization).where(Organization.home_tenant_id == current_user.tenant_id))
+ ).scalar_one_or_none()
+ if already_home is not None:
+ raise HTTPException(status_code=409, detail="This tenant already hosts an organisation")
+
+ org = Organization(
+ slug=body.slug,
+ name=body.name,
+ kind=body.kind,
+ home_tenant_id=current_user.tenant_id,
)
+ db.add(org)
+ await db.flush()
+ db.add(OrganizationMember(org_id=org.id, user_id=current_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"))
+ await db.commit()
+ await db.refresh(org)
+ return org
[email protected]("/tenants", response_model=list[ManagedTenantRow])
-async def list_managed_tenants(
[email protected]("/organizations/current", response_model=OrganizationOut)
+async def get_current_organization(
+ scope: PortfolioScope = Depends(_scope),
+ db: AsyncSession = Depends(get_db),
+) -> Organization:
+ org = await db.get(Organization, scope.org_id)
+ if org is None: # pragma: no cover - scope resolution just read this row
+ raise HTTPException(status_code=404, detail="Organisation not found")
+ return org
+
+
[email protected]("/organizations/current/tenants", status_code=status.HTTP_200_OK)
+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),
-) -> list[ManagedTenantRow]:
- """List managed tenants with health scores for the parent dashboard.
+) -> dict[str, object]:
+ """Bring tenants under management.
+
+ A tenant already managed by another organisation is rejected rather than
+ reassigned: `organization_tenants` carries a unique constraint on
+ `tenant_id` precisely so a customer cannot end up in two portfolios, and
+ silently moving one would be a cross-tenant transfer performed by
+ whoever asked last.
+ """
+ added: list[str] = []
+ rejected: dict[str, str] = {}
+
+ for tenant_id in body.tenant_ids:
+ tenant = await db.get(Tenant, tenant_id)
+ if tenant is None:
+ rejected[str(tenant_id)] = "tenant not found"
+ continue
+ claim = (await db.execute(select(OrganizationTenant).where(OrganizationTenant.tenant_id == tenant_id))).scalar_one_or_none()
+ if claim is not None:
+ rejected[str(tenant_id)] = "already in this portfolio" if claim.org_id == scope.org_id else "managed by another organisation"
+ continue
+ db.add(
+ OrganizationTenant(
+ org_id=scope.org_id,
+ tenant_id=tenant_id,
+ relationship="managed",
+ onboarded_by=current_user.id,
+ )
+ )
+ added.append(str(tenant_id))
- Empty outside demo mode. `GET /api/v1/mssp/children` is the route backed
- by real rows.
+ await db.commit()
+ return {"added": added, "rejected": rejected}
+
+
[email protected]("/organizations/current/tenants/{tenant_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
+async def remove_tenant_from_portfolio(
+ tenant_id: uuid.UUID,
+ scope: PortfolioScope = Depends(_admin_scope),
+ db: AsyncSession = Depends(get_db),
+) -> None:
+ """Release a tenant from management.
+
+ Deletes the portfolio link only. The tenant and all of its data survive
+ as a standalone tenant — offboarding a customer from a provider is not
+ the same request as erasing them, and conflating the two would make this
+ button destructive in a way its label does not say.
"""
- if not _mssp_sample_allowed():
- return []
- return _MSSP_TENANTS_MOCK
+ link = (
+ await db.execute(
+ select(OrganizationTenant).where(
+ OrganizationTenant.org_id == scope.org_id,
+ OrganizationTenant.tenant_id == tenant_id,
+ )
+ )
+ ).scalar_one_or_none()
+ if link is None:
+ raise HTTPException(status_code=404, detail="Tenant is not in this portfolio")
+ # Per-member grants over this tenant go with it, by foreign key cascade.
+ await db.delete(link)
+ await db.commit()
[email protected]("/incidents", response_model=list[CrossTenantIncident])
-async def list_cross_tenant_incidents(
- severity: str | None = Query(None, description="Filter: high | medium | low"),
[email protected]("/organizations/current/members", response_model=list[MemberOut])
+async def list_members(
+ scope: PortfolioScope = Depends(_admin_scope),
+ db: AsyncSession = Depends(get_db),
+) -> list[MemberOut]:
+ rows = (
+ await db.execute(
+ select(OrganizationMember, User)
+ .join(User, User.id == OrganizationMember.user_id)
+ .where(OrganizationMember.org_id == scope.org_id)
+ .order_by(User.email)
+ )
+ ).all()
+
+ grants: dict[uuid.UUID, list[uuid.UUID]] = {}
+ for user_id, tenant_id in (
+ await db.execute(
+ select(OrganizationMemberTenant.user_id, OrganizationMemberTenant.tenant_id).where(
+ OrganizationMemberTenant.org_id == scope.org_id
+ )
+ )
+ ).all():
+ grants.setdefault(uuid.UUID(str(user_id)), []).append(uuid.UUID(str(tenant_id)))
+
+ return [
+ MemberOut(
+ user_id=uuid.UUID(str(member.user_id)),
+ email=str(user.email),
+ org_role=str(member.org_role),
+ granted_tenants=sorted(grants.get(uuid.UUID(str(member.user_id)), [])),
+ )
+ for member, user in rows
+ ]
+
+
[email protected]("/organizations/current/members", response_model=MemberOut)
+async def upsert_member(
+ body: MemberUpsert,
+ scope: PortfolioScope = Depends(_admin_scope),
+ db: AsyncSession = Depends(get_db),
+) -> MemberOut:
+ if body.org_role not in ORG_ROLES:
+ raise HTTPException(status_code=422, detail=f"org_role must be one of {', '.join(ORG_ROLES)}")
+
+ user = await db.get(User, body.user_id)
+ if user is None:
+ raise HTTPException(status_code=404, detail="User not found")
+
+ member = (
+ await db.execute(
+ select(OrganizationMember).where(
+ OrganizationMember.org_id == scope.org_id,
+ OrganizationMember.user_id == body.user_id,
+ )
+ )
+ ).scalar_one_or_none()
+
+ if member is None:
+ member = OrganizationMember(org_id=scope.org_id, user_id=body.user_id, org_role=body.org_role)
+ db.add(member)
+ else:
+ member.org_role = body.org_role
+ await db.commit()
+
+ return MemberOut(
+ user_id=uuid.UUID(str(body.user_id)),
+ email=str(user.email),
+ org_role=body.org_role,
+ granted_tenants=[],
+ )
+
+
[email protected]("/organizations/current/members/{user_id}/tenants", response_model=MemberOut)
+async def set_member_tenant_grants(
+ user_id: uuid.UUID,
+ body: TenantGrant,
+ scope: PortfolioScope = Depends(_admin_scope),
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
-) -> list[CrossTenantIncident]:
- """Critical incidents across all managed tenants. Empty outside demo mode."""
- if not _mssp_sample_allowed():
- return []
- incidents = _MSSP_INCIDENTS_MOCK
- if severity:
- incidents = [i for i in incidents if i.severity == severity]
- return incidents
+) -> MemberOut:
+ """Replace which portfolio tenants one member may reach.
+
+ Tenants outside the portfolio are refused here *and* would be refused by
+ the database: `organization_member_tenants` has a composite foreign key
+ onto `organization_tenants`, so a grant cannot name a tenant the
+ organisation does not manage even if this check were removed.
+ """
+ member = (
+ await db.execute(
+ select(OrganizationMember).where(
+ OrganizationMember.org_id == scope.org_id,
+ OrganizationMember.user_id == user_id,
+ )
+ )
+ ).scalar_one_or_none()
+ if member is None:
+ raise HTTPException(status_code=404, detail="Not a member of this organisation")
+
+ portfolio = {
+ uuid.UUID(str(t))
+ for t in (await db.execute(select(OrganizationTenant.tenant_id).where(OrganizationTenant.org_id == scope.org_id))).scalars()
+ }
+ requested = {uuid.UUID(str(t)) for t in body.tenant_ids}
+ outside = requested - portfolio
+ if outside:
+ raise HTTPException(
+ status_code=422,
+ detail=f"not in this portfolio: {', '.join(sorted(str(t) for t in outside))}",
+ )
+
+ existing = (
+ await db.execute(
+ select(OrganizationMemberTenant).where(
+ OrganizationMemberTenant.org_id == scope.org_id,
+ OrganizationMemberTenant.user_id == user_id,
+ )
+ )
+ ).scalars()
+ for row in existing:
+ if uuid.UUID(str(row.tenant_id)) not in requested:
+ await db.delete(row)
+
+ held = {
+ uuid.UUID(str(t))
+ for t in (
+ await db.execute(
+ select(OrganizationMemberTenant.tenant_id).where(
+ OrganizationMemberTenant.org_id == scope.org_id,
+ OrganizationMemberTenant.user_id == user_id,
+ )
+ )
+ ).scalars()
+ }
+ for tenant_id in requested - held:
+ db.add(
+ OrganizationMemberTenant(
+ org_id=scope.org_id,
+ user_id=user_id,
+ tenant_id=tenant_id,
+ granted_by=current_user.id,
+ )
+ )
+
+ await db.commit()
+
+ user = await db.get(User, user_id)
+ return MemberOut(
+ user_id=user_id,
+ email=str(user.email) if user else "",
+ org_role=str(member.org_role),
+ granted_tenants=sorted(requested),
+ )
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 15248cebf..edb7ede2d 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -386,6 +386,18 @@ class Settings(BaseSettings):
MAX_TENANTS: int = 1000
DEFAULT_TENANT_PLAN: str = "starter"
+ # Deployment-wide per-tenant ceilings, e.g.
+ # `{"connectors": 25, "seats": 50}`. Empty by default: AiSOC ships
+ # uncapped, and `app/services/entitlements.py` reports `unlimited`
+ # rather than drawing headroom against a ceiling nobody set. A
+ # tenant's own `tenants.limits` JSONB overrides anything here, in
+ # either direction.
+ #
+ # Declared as a real field rather than read with `getattr`: an
+ # undeclared setting is silently dropped by `extra="ignore"`, so an
+ # operator who exports it gets no limits and no explanation.
+ AISOC_DEFAULT_TENANT_LIMITS: dict = {}
+
# Plugin system
AISOC_PLUGINS_DIR: str = "/opt/aisoc/plugins"
diff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.py
index de8ee2d5d..0ceb41094 100644
--- a/services/api/app/models/__init__.py
+++ b/services/api/app/models/__init__.py
@@ -28,6 +28,12 @@ from app.models.mssp import (
MSSPTenantNote,
)
from app.models.oauth import OAuthAppCredential, OAuthState
+from app.models.organization import (
+ Organization,
+ OrganizationMember,
+ OrganizationMemberTenant,
+ OrganizationTenant,
+)
from app.models.posture import PostureDriftEvent, PostureFinding, PostureScanRun
from app.models.published_replay import PublishedReplay
from app.models.remediation import RemediationGateLog, RemediationMaturity, RemediationWhitelist
@@ -76,6 +82,10 @@ __all__ = [
"MSSPTenantMetrics",
"MSSPTenantNote",
"OAuthAppCredential",
+ "Organization",
+ "OrganizationMember",
+ "OrganizationMemberTenant",
+ "OrganizationTenant",
"OAuthState",
"TenantInboxToken",
"TenantLlmCredential",
diff --git a/services/api/app/models/organization.py b/services/api/app/models/organization.py
new file mode 100644
index 000000000..04e3ce80d
--- /dev/null
+++ b/services/api/app/models/organization.py
@@ -0,0 +1,133 @@
+"""Operator organisations: the parent concept above tenants (migration 058).
+
+`tenants.parent_tenant_id` (migration 012) makes the managing provider a
+tenant, which is enough to draw a tree and not enough to run a managed
+service. These four tables separate the operator from the boundary:
+
+- :class:`Organization` is the provider itself.
+- :class:`OrganizationMember` says who belongs to it, with what authority.
+- :class:`OrganizationTenant` is the managed portfolio.
+- :class:`OrganizationMemberTenant` scopes an individual principal to a
+ subset of that portfolio.
+
+The composite foreign keys on the last table are load-bearing and are
+declared here as well as in the migration so a test running against SQLite
+gets the same rejection Postgres gives: a grant can only name a tenant the
+organisation actually manages.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import (
+ Boolean,
+ DateTime,
+ ForeignKey,
+ ForeignKeyConstraint,
+ PrimaryKeyConstraint,
+ Text,
+ UniqueConstraint,
+)
+from sqlalchemy.dialects.postgresql import JSONB, UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+# Authority to act on a scoped tenant. `viewer` reads; the rest may act.
+ORG_ROLES: tuple[str, ...] = ("owner", "admin", "operator", "viewer")
+
+# Roles whose reach is the whole portfolio. Everyone else reaches only what
+# `organization_member_tenants` grants them — and nothing when that is empty.
+PORTFOLIO_WIDE_ROLES: frozenset[str] = frozenset({"owner", "admin"})
+
+# Roles permitted to perform actions rather than only read.
+ACTING_ROLES: frozenset[str] = frozenset({"owner", "admin", "operator"})
+
+# Roles permitted to change the organisation itself: membership, portfolio,
+# per-member grants.
+ADMINISTERING_ROLES: frozenset[str] = frozenset({"owner", "admin"})
+
+
+class Organization(Base):
+ __tablename__ = "organizations"
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ slug: Mapped[str] = mapped_column(Text, nullable=False, unique=True, index=True)
+ name: Mapped[str] = mapped_column(Text, nullable=False)
+ kind: Mapped[str] = mapped_column(Text, nullable=False, default="mssp")
+ # The tenant the operator's own staff sign in to. Cascades on delete: an
+ # erased home tenant takes the organisation with it, and leaves the
+ # managed customers standing as unclaimed tenants.
+ home_tenant_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=True, index=True)
+ is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
+ settings: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(UTC),
+ onupdate=lambda: datetime.now(UTC),
+ )
+
+
+class OrganizationMember(Base):
+ __tablename__ = "organization_members"
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ org_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
+ user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
+ org_role: Mapped[str] = mapped_column(Text, nullable=False, default="viewer")
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(UTC),
+ onupdate=lambda: datetime.now(UTC),
+ )
+
+ __table_args__ = (UniqueConstraint("org_id", "user_id", name="organization_members_org_id_user_id_key"),)
+
+
+class OrganizationTenant(Base):
+ __tablename__ = "organization_tenants"
+
+ org_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("organizations.id", ondelete="CASCADE"), primary_key=True)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), primary_key=True, index=True)
+ relationship: Mapped[str] = mapped_column(Text, nullable=False, default="managed")
+ onboarded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+ onboarded_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
+
+ # One managing organisation per tenant, so "whose portfolio is this in"
+ # has exactly one answer and two providers cannot both claim a customer.
+ __table_args__ = (UniqueConstraint("tenant_id", name="organization_tenants_tenant_id_key"),)
+
+
+class OrganizationMemberTenant(Base):
+ """Which managed tenants one principal may reach.
+
+ Enforced by the database rather than by the code path that writes it: the
+ composite keys mean a grant cannot name a tenant outside the portfolio,
+ and a tenant leaving the portfolio takes its grants with it.
+ """
+
+ __tablename__ = "organization_member_tenants"
+
+ org_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
+ granted_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
+ granted_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+
+ __table_args__ = (
+ PrimaryKeyConstraint("org_id", "user_id", "tenant_id"),
+ ForeignKeyConstraint(
+ ["org_id", "user_id"],
+ ["organization_members.org_id", "organization_members.user_id"],
+ ondelete="CASCADE",
+ ),
+ ForeignKeyConstraint(
+ ["org_id", "tenant_id"],
+ ["organization_tenants.org_id", "organization_tenants.tenant_id"],
+ ondelete="CASCADE",
+ ),
+ )
diff --git a/services/api/app/services/entitlements.py b/services/api/app/services/entitlements.py
new file mode 100644
index 000000000..3b25f090d
--- /dev/null
+++ b/services/api/app/services/entitlements.py
@@ -0,0 +1,236 @@
+"""Per-tenant limits, and how much room is left under them.
+
+A managed provider's most expensive failure is a quiet one. A tenant that
+hits a cap does not raise an error anyone sees: alerts keep arriving and
+simply stop being triaged, and the customer reports it as "the AI doesn't
+work". Somebody then spends a day debugging a model that was never invoked.
+So the point of this module is not enforcement — it is making exhaustion
+*visible*, per tenant, across a whole portfolio, before anyone phones in.
+
+Two rules govern the numbers it produces.
+
+**Limits are only those an operator configured.** AiSOC ships uncapped. A
+tenant with nothing in `tenants.limits` and no deployment default reports
+``unlimited``, not a made-up ceiling — a headroom bar drawn against an
+invented cap is a fabricated metric, and inventing one here would put a
+fabrication on every tenant row in the portfolio view.
+
+**Usage is measured, never estimated.** Every key below maps to a real
+count over real rows. A key that cannot be counted honestly does not appear.
+
+`tenants.limits` is a JSONB per-tenant override that wins over the
+deployment default. The string ``"unlimited"`` and the integer ``-1`` both
+mean no limit, matching what operators already write there.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any, Final
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import settings
+
+logger = logging.getLogger("aisoc.entitlements")
+
+# Values that mean "no ceiling", in the forms operators actually write.
+_UNLIMITED: Final[frozenset[object]] = frozenset({-1, "-1", "unlimited", "none", ""})
+
+# Fraction of a limit at which a tenant is called `warning` rather than `ok`.
+WARN_AT: Final[float] = 0.8
+
+
+@dataclass(frozen=True)
+class LimitKey:
+ """A measurable entitlement.
+
+ ``usage_sql`` counts current usage for one tenant and must bind the
+ tenant as a parameter — never format it into the string.
+ """
+
+ name: str
+ label: str
+ description: str
+ usage_sql: str
+
+
+LIMIT_KEYS: Final[tuple[LimitKey, ...]] = (
+ LimitKey(
+ "connectors",
+ "Connectors",
+ "Enabled data sources.",
+ "SELECT count(*) FROM connectors WHERE tenant_id = :tenant_id AND is_enabled",
+ ),
+ LimitKey(
+ "seats",
+ "Seats",
+ "Active user accounts.",
+ "SELECT count(*) FROM users WHERE tenant_id = :tenant_id AND is_active",
+ ),
+ LimitKey(
+ "alerts_per_day",
+ "Alerts / day",
+ "Alerts created in the trailing 24 hours.",
+ "SELECT count(*) FROM alerts WHERE tenant_id = :tenant_id AND created_at >= :since",
+ ),
+ LimitKey(
+ # Counted as alerts that carry AI output, because that is the row a
+ # triage actually writes. There is no usage-metering table in this
+ # build, and inventing a number for one would be worse than counting
+ # the evidence that a triage happened.
+ "triages_per_month",
+ "AI triages / month",
+ "Alerts with AI triage output this calendar month.",
+ (
+ "SELECT count(*) FROM alerts "
+ "WHERE tenant_id = :tenant_id AND created_at >= :month_start "
+ "AND (ai_summary IS NOT NULL OR ai_score IS NOT NULL)"
+ ),
+ ),
+)
+
+LIMIT_KEYS_BY_NAME: Final[dict[str, LimitKey]] = {k.name: k for k in LIMIT_KEYS}
+
+
+@dataclass(frozen=True)
+class Headroom:
+ """How much of one limit a tenant has left.
+
+ ``limit is None`` means uncapped; ``remaining`` and ``pct_used`` are then
+ ``None`` too rather than a sentinel that a chart would plot.
+ """
+
+ key: str
+ label: str
+ used: int
+ limit: int | None
+ state: str # unlimited | ok | warning | exhausted
+
+ @property
+ def remaining(self) -> int | None:
+ if self.limit is None:
+ return None
+ return max(self.limit - self.used, 0)
+
+ @property
+ def pct_used(self) -> float | None:
+ if self.limit is None or self.limit <= 0:
+ return None
+ return round(min(self.used / self.limit, 1.0) * 100, 1)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "key": self.key,
+ "label": self.label,
+ "used": self.used,
+ "limit": self.limit,
+ "remaining": self.remaining,
+ "pct_used": self.pct_used,
+ "state": self.state,
+ }
+
+
+def _coerce_limit(raw: object) -> int | None:
+ """Normalise one configured value to an int ceiling, or ``None``."""
+ if raw is None:
+ return None
+ if isinstance(raw, bool):
+ return None
+ if isinstance(raw, str):
+ stripped = raw.strip().lower()
+ if stripped in _UNLIMITED:
+ return None
+ try:
+ raw = int(stripped)
+ except ValueError:
+ return None
+ if isinstance(raw, int | float):
+ value = int(raw)
+ return None if value < 0 else value
+ return None
+
+
+def _deployment_defaults() -> dict[str, object]:
+ """Deployment-wide caps, if the operator set any.
+
+ Empty by default: an open-source install has no plan and no ceiling
+ until someone chooses one.
+ """
+ configured = getattr(settings, "AISOC_DEFAULT_TENANT_LIMITS", None) or {}
+ return configured if isinstance(configured, dict) else {}
+
+
+def limit_for(tenant_limits: dict | None, key: str) -> int | None:
+ """The effective ceiling for ``key``, or ``None`` when uncapped.
+
+ The per-tenant override in `tenants.limits` wins over the deployment
+ default, including when it raises the ceiling — that is the mechanism for
+ sizing one customer differently without editing a shared config.
+ """
+ overrides = tenant_limits if isinstance(tenant_limits, dict) else {}
+ if key in overrides:
+ return _coerce_limit(overrides[key])
+ defaults = _deployment_defaults()
+ if key in defaults:
+ return _coerce_limit(defaults[key])
+ return None
+
+
+def classify(used: int, limit: int | None) -> str:
+ if limit is None:
+ return "unlimited"
+ if limit <= 0:
+ # A configured ceiling of zero is a real state: the feature is off.
+ return "exhausted"
+ if used >= limit:
+ return "exhausted"
+ if used >= limit * WARN_AT:
+ return "warning"
+ return "ok"
+
+
+async def measure_usage(db: AsyncSession, tenant_id: uuid.UUID) -> dict[str, int]:
+ """Count current usage of every limit key for one tenant."""
+ now = datetime.now(UTC)
+ params = {
+ "tenant_id": str(tenant_id),
+ "since": now - timedelta(hours=24),
+ "month_start": now.replace(day=1, hour=0, minute=0, second=0, microsecond=0),
+ }
+ usage: dict[str, int] = {}
+ for key in LIMIT_KEYS:
+ bound = {name: value for name, value in params.items() if f":{name}" in key.usage_sql}
+ result = await db.execute(text(key.usage_sql), bound)
+ usage[key.name] = int(result.scalar_one() or 0)
+ return usage
+
+
+async def headroom_for_tenant(
+ db: AsyncSession,
+ tenant_id: uuid.UUID,
+ tenant_limits: dict | None,
+) -> list[Headroom]:
+ """Per-key headroom for one tenant, with exhaustion logged loudly."""
+ usage = await measure_usage(db, tenant_id)
+ rows: list[Headroom] = []
+ for key in LIMIT_KEYS:
+ used = usage.get(key.name, 0)
+ limit = limit_for(tenant_limits, key.name)
+ state = classify(used, limit)
+ if state == "exhausted":
+ # A cap silently stopping work is the failure this module exists
+ # to prevent, so it is never quieter than a warning.
+ logger.warning(
+ "entitlements.limit_exhausted tenant=%s key=%s used=%d limit=%s",
+ tenant_id,
+ key.name,
+ used,
+ limit,
+ )
+ rows.append(Headroom(key=key.name, label=key.label, used=used, limit=limit, state=state))
+ return rows
diff --git a/services/api/app/services/mssp_portfolio.py b/services/api/app/services/mssp_portfolio.py
new file mode 100644
index 000000000..4a7036e33
--- /dev/null
+++ b/services/api/app/services/mssp_portfolio.py
@@ -0,0 +1,386 @@
+"""Cross-tenant aggregates over a managed portfolio.
+
+Every function here reads more than one tenant's data on purpose, which
+makes this the most dangerous module in the tenancy surface: it is the one
+place where "filter by the caller's tenant" is deliberately not the rule.
+Three properties keep it honest, and they are structural rather than
+conventional because a convention is what the previous cross-tenant leaks
+were relying on.
+
+**The scope is a parameter, not a default.** No function reads the request,
+the session, or the current user. Each takes a resolved
+:class:`~app.services.org_scope.PortfolioScope` and passes it through
+:func:`~app.services.org_scope.require_scope`, which raises on an empty
+portfolio. An aggregate therefore cannot run with no filter — the failure
+mode is an exception, not a table scan.
+
+**The tenant list is bound, never interpolated.** `tenant_id = ANY(:ids)`
+with the ids as a parameter. This mirrors the ClickHouse lesson: the moment
+a scoping predicate is built by string formatting, its correctness depends
+on whoever edits the string next.
+
+**Nothing is invented.** These endpoints previously returned five
+hardcoded companies — "Acme Corp, health 92.4, 12 open alerts" — to any
+authenticated caller. Where a figure cannot be measured from real rows it
+is absent or zero here, and an empty portfolio returns empty results rather
+than a sample.
+"""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.services.entitlements import Headroom, headroom_for_tenant
+from app.services.org_scope import PortfolioScope, require_scope
+
+# A connector that has not synced in this long is stale. Chosen against the
+# platform's own defaults: the connector scheduler polls every five minutes,
+# so an hour is twelve missed cycles — comfortably past a transient blip and
+# well short of a working day.
+STALE_AFTER = timedelta(hours=1)
+
+# Window for the resolution-time average. Long enough that a tenant closing
+# a handful of cases a week still has a number, short enough that it tracks
+# how the account is being run now rather than a year ago.
+MTTR_WINDOW = timedelta(days=30)
+
+
+@dataclass(frozen=True)
+class TenantRollup:
+ """One managed tenant's posture, every field counted from real rows."""
+
+ tenant_id: uuid.UUID
+ name: str
+ slug: str
+ relationship: str
+ is_active: bool
+ open_alerts: int
+ critical_alerts: int
+ high_alerts: int
+ untriaged_alerts: int
+ # Seeded demo rows, counted apart from everything above so a demo
+ # install reads "0 real, 15 synthetic" rather than reporting fifteen
+ # alerts an operator would go looking for.
+ synthetic_alerts: int
+ open_cases: int
+ sla_breached_cases: int
+ # Mean time to resolve, from cases this tenant actually closed in the
+ # trailing window. `None` when they closed none — a tenant with no
+ # closed cases has no MTTR, and reporting 0.0 would put them top of the
+ # league table for having done nothing.
+ mttr_minutes: float | None
+ connectors_total: int
+ connectors_healthy: int
+ connectors_stale: int
+ connectors_error: int
+ last_event_at: datetime | None
+ limits: list[Headroom]
+
+ @property
+ def limits_exhausted(self) -> int:
+ return sum(1 for limit in self.limits if limit.state == "exhausted")
+
+ @property
+ def limits_warning(self) -> int:
+ return sum(1 for limit in self.limits if limit.state == "warning")
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "tenant_id": str(self.tenant_id),
+ "name": self.name,
+ "slug": self.slug,
+ "relationship": self.relationship,
+ "is_active": self.is_active,
+ "open_alerts": self.open_alerts,
+ "critical_alerts": self.critical_alerts,
+ "high_alerts": self.high_alerts,
+ "untriaged_alerts": self.untriaged_alerts,
+ "synthetic_alerts": self.synthetic_alerts,
+ "open_cases": self.open_cases,
+ "sla_breached_cases": self.sla_breached_cases,
+ "mttr_minutes": self.mttr_minutes,
+ "connectors": {
+ "total": self.connectors_total,
+ "healthy": self.connectors_healthy,
+ "stale": self.connectors_stale,
+ "error": self.connectors_error,
+ },
+ "last_event_at": self.last_event_at.isoformat() if self.last_event_at else None,
+ "limits": [limit.as_dict() for limit in self.limits],
+ "limits_exhausted": self.limits_exhausted,
+ "limits_warning": self.limits_warning,
+ }
+
+
+# Statuses that mean "still needs someone". Kept in one place so the
+# portfolio backlog and a single tenant's queue cannot drift apart.
+_OPEN_ALERT_STATUSES = ("new", "open", "investigating", "triaged", "in_progress")
+_OPEN_CASE_STATUSES = ("open", "investigating", "in_progress", "containment", "eradication", "recovery")
+
+
+async def tenant_rollups(db: AsyncSession, scope: PortfolioScope) -> list[TenantRollup]:
+ """Per-tenant posture for every tenant in ``scope``.
+
+ Returns a row for each scoped tenant even when that tenant has no data
+ at all — a managed customer with zero alerts is a real state an operator
+ needs to see, and dropping the row would read as "not onboarded".
+ """
+ tenant_ids = require_scope(scope)
+ ids = [str(t) for t in tenant_ids]
+ stale_before = datetime.now(UTC) - STALE_AFTER
+
+ rows = (
+ await db.execute(
+ text(
+ """
+ SELECT
+ t.id,
+ t.name,
+ t.slug,
+ t.is_active,
+ t.limits,
+ COALESCE(ot.relationship, 'managed') AS relationship,
+ COALESCE(a.open_alerts, 0) AS open_alerts,
+ COALESCE(a.critical_alerts, 0) AS critical_alerts,
+ COALESCE(a.high_alerts, 0) AS high_alerts,
+ COALESCE(a.untriaged_alerts, 0) AS untriaged_alerts,
+ COALESCE(a.synthetic_alerts, 0) AS synthetic_alerts,
+ a.last_event_at AS last_event_at,
+ COALESCE(c.open_cases, 0) AS open_cases,
+ COALESCE(c.sla_breached_cases, 0) AS sla_breached_cases,
+ r.mttr_minutes AS mttr_minutes,
+ COALESCE(k.total, 0) AS connectors_total,
+ COALESCE(k.healthy, 0) AS connectors_healthy,
+ COALESCE(k.stale, 0) AS connectors_stale,
+ COALESCE(k.errored, 0) AS connectors_error
+ FROM tenants t
+ LEFT JOIN organization_tenants ot ON ot.tenant_id = t.id
+ LEFT JOIN (
+ SELECT
+ tenant_id,
+ count(*) FILTER (WHERE status = ANY(:open_statuses)
+ AND NOT COALESCE(is_synthetic, FALSE)) AS open_alerts,
+ count(*) FILTER (WHERE severity = 'critical'
+ AND status = ANY(:open_statuses)
+ AND NOT COALESCE(is_synthetic, FALSE)) AS critical_alerts,
+ count(*) FILTER (WHERE severity = 'high'
+ AND status = ANY(:open_statuses)
+ AND NOT COALESCE(is_synthetic, FALSE)) AS high_alerts,
+ count(*) FILTER (WHERE ai_summary IS NULL AND ai_score IS NULL
+ AND status = ANY(:open_statuses)
+ AND NOT COALESCE(is_synthetic, FALSE)) AS untriaged_alerts,
+ count(*) FILTER (WHERE COALESCE(is_synthetic, FALSE)) AS synthetic_alerts,
+ max(event_time) FILTER (WHERE NOT COALESCE(is_synthetic, FALSE)) AS last_event_at
+ FROM alerts
+ WHERE tenant_id = ANY(:tenant_ids)
+ GROUP BY tenant_id
+ ) a ON a.tenant_id = t.id
+ LEFT JOIN (
+ SELECT
+ tenant_id,
+ count(*) AS open_cases,
+ count(*) FILTER (WHERE COALESCE(sla_breached, FALSE)) AS sla_breached_cases
+ FROM cases
+ WHERE tenant_id = ANY(:tenant_ids) AND status = ANY(:open_case_statuses)
+ GROUP BY tenant_id
+ ) c ON c.tenant_id = t.id
+ LEFT JOIN (
+ SELECT
+ tenant_id,
+ round(
+ (avg(EXTRACT(EPOCH FROM (closed_at - created_at))) / 60.0)::numeric,
+ 1
+ )::float8 AS mttr_minutes
+ FROM cases
+ WHERE tenant_id = ANY(:tenant_ids)
+ AND closed_at IS NOT NULL
+ AND closed_at >= :mttr_since
+ AND closed_at >= created_at
+ GROUP BY tenant_id
+ ) r ON r.tenant_id = t.id
+ LEFT JOIN (
+ SELECT
+ tenant_id,
+ count(*) AS total,
+ count(*) FILTER (WHERE health_status = 'healthy'
+ AND last_sync IS NOT NULL
+ AND last_sync >= :stale_before) AS healthy,
+ count(*) FILTER (WHERE health_status <> 'unhealthy'
+ AND (last_sync IS NULL
+ OR last_sync < :stale_before)) AS stale,
+ count(*) FILTER (WHERE health_status = 'unhealthy') AS errored
+ FROM connectors
+ WHERE tenant_id = ANY(:tenant_ids) AND is_enabled
+ GROUP BY tenant_id
+ ) k ON k.tenant_id = t.id
+ WHERE t.id = ANY(:tenant_ids)
+ ORDER BY t.name
+ """
+ ),
+ {
+ "tenant_ids": ids,
+ "open_statuses": list(_OPEN_ALERT_STATUSES),
+ "open_case_statuses": list(_OPEN_CASE_STATUSES),
+ "stale_before": stale_before,
+ "mttr_since": datetime.now(UTC) - MTTR_WINDOW,
+ },
+ )
+ ).mappings()
+
+ rollups: list[TenantRollup] = []
+ for row in rows:
+ tenant_id = uuid.UUID(str(row["id"]))
+ rollups.append(
+ TenantRollup(
+ tenant_id=tenant_id,
+ name=str(row["name"]),
+ slug=str(row["slug"]),
+ relationship=str(row["relationship"]),
+ is_active=bool(row["is_active"]),
+ open_alerts=int(row["open_alerts"]),
+ critical_alerts=int(row["critical_alerts"]),
+ high_alerts=int(row["high_alerts"]),
+ untriaged_alerts=int(row["untriaged_alerts"]),
+ synthetic_alerts=int(row["synthetic_alerts"]),
+ open_cases=int(row["open_cases"]),
+ sla_breached_cases=int(row["sla_breached_cases"]),
+ mttr_minutes=float(row["mttr_minutes"]) if row["mttr_minutes"] is not None else None,
+ connectors_total=int(row["connectors_total"]),
+ connectors_healthy=int(row["connectors_healthy"]),
+ connectors_stale=int(row["connectors_stale"]),
+ connectors_error=int(row["connectors_error"]),
+ last_event_at=row["last_event_at"],
+ limits=await headroom_for_tenant(db, tenant_id, row["limits"]),
+ )
+ )
+ return rollups
+
+
+def _mean(values: list[float]) -> float | None:
+ return round(sum(values) / len(values), 1) if values else None
+
+
+def summarise(rollups: list[TenantRollup]) -> dict[str, Any]:
+ """Portfolio totals derived from the per-tenant rows above.
+
+ Derived rather than separately queried so the summary and the table can
+ never disagree — a dashboard whose header contradicts its own rows is
+ how people stop trusting both.
+ """
+ return {
+ "tenants": len(rollups),
+ "tenants_active": sum(1 for r in rollups if r.is_active),
+ "open_alerts": sum(r.open_alerts for r in rollups),
+ "critical_alerts": sum(r.critical_alerts for r in rollups),
+ "high_alerts": sum(r.high_alerts for r in rollups),
+ "untriaged_alerts": sum(r.untriaged_alerts for r in rollups),
+ "synthetic_alerts": sum(r.synthetic_alerts for r in rollups),
+ "open_cases": sum(r.open_cases for r in rollups),
+ "sla_breached_cases": sum(r.sla_breached_cases for r in rollups),
+ # Averaged only over tenants that closed something. `None` when the
+ # whole portfolio has closed nothing, rather than a confident 0.0.
+ "mttr_minutes": _mean([r.mttr_minutes for r in rollups if r.mttr_minutes is not None]),
+ "connectors_total": sum(r.connectors_total for r in rollups),
+ "connectors_healthy": sum(r.connectors_healthy for r in rollups),
+ "connectors_stale": sum(r.connectors_stale for r in rollups),
+ "connectors_error": sum(r.connectors_error for r in rollups),
+ "tenants_with_exhausted_limits": sum(1 for r in rollups if r.limits_exhausted),
+ "tenants_with_limit_warnings": sum(1 for r in rollups if r.limits_warning),
+ "tenants_without_connectors": sum(1 for r in rollups if r.connectors_total == 0),
+ }
+
+
+EMPTY_SUMMARY: dict[str, Any] = {
+ "tenants": 0,
+ "tenants_active": 0,
+ "open_alerts": 0,
+ "critical_alerts": 0,
+ "high_alerts": 0,
+ "untriaged_alerts": 0,
+ "synthetic_alerts": 0,
+ "open_cases": 0,
+ "sla_breached_cases": 0,
+ "mttr_minutes": None,
+ "connectors_total": 0,
+ "connectors_healthy": 0,
+ "connectors_stale": 0,
+ "connectors_error": 0,
+ "tenants_with_exhausted_limits": 0,
+ "tenants_with_limit_warnings": 0,
+ "tenants_without_connectors": 0,
+}
+
+
+async def portfolio_alerts(
+ db: AsyncSession,
+ scope: PortfolioScope,
+ *,
+ severity: str | None = None,
+ status: str | None = None,
+ include_synthetic: bool = False,
+ limit: int = 50,
+) -> list[dict[str, Any]]:
+ """Open alerts across the portfolio, newest first.
+
+ Replaces a list of five invented incidents attributed to invented
+ companies. Every row here is an `alerts` row belonging to a tenant in
+ ``scope``, carrying the real tenant name so an operator can tell whose
+ estate they are looking at.
+ """
+ tenant_ids = require_scope(scope)
+ clauses = ["a.tenant_id = ANY(:tenant_ids)"]
+ params: dict[str, Any] = {
+ "tenant_ids": [str(t) for t in tenant_ids],
+ "limit": max(1, min(int(limit), 500)),
+ }
+
+ if severity:
+ clauses.append("a.severity = :severity")
+ params["severity"] = severity
+ if status:
+ clauses.append("a.status = :status")
+ params["status"] = status
+ else:
+ clauses.append("a.status = ANY(:open_statuses)")
+ params["open_statuses"] = list(_OPEN_ALERT_STATUSES)
+ if not include_synthetic:
+ clauses.append("NOT COALESCE(a.is_synthetic, FALSE)")
+
+ rows = (
+ await db.execute(
+ text(
+ "SELECT a.id, a.tenant_id, t.name AS tenant_name, a.title, a.severity, a.status, "
+ " a.category, a.created_at, a.event_time, a.case_id, "
+ " COALESCE(a.is_synthetic, FALSE) AS is_synthetic "
+ "FROM alerts a JOIN tenants t ON t.id = a.tenant_id "
+ f"WHERE {' AND '.join(clauses)} "
+ "ORDER BY a.created_at DESC LIMIT :limit"
+ ),
+ params,
+ )
+ ).mappings()
+
+ return [
+ {
+ "alert_id": str(row["id"]),
+ "tenant_id": str(row["tenant_id"]),
+ "tenant_name": str(row["tenant_name"]),
+ "title": str(row["title"]),
+ "severity": str(row["severity"]),
+ "status": str(row["status"]),
+ "category": row["category"],
+ "created_at": row["created_at"].isoformat() if row["created_at"] else None,
+ "event_time": row["event_time"].isoformat() if row["event_time"] else None,
+ "case_id": str(row["case_id"]) if row["case_id"] else None,
+ # Carried through rather than hidden: a caller that opts into
+ # seeded rows must be able to tell them apart.
+ "is_synthetic": bool(row["is_synthetic"]),
+ }
+ for row in rows
+ ]
diff --git a/services/api/app/services/org_scope.py b/services/api/app/services/org_scope.py
new file mode 100644
index 000000000..f600760d6
--- /dev/null
+++ b/services/api/app/services/org_scope.py
@@ -0,0 +1,208 @@
+"""Resolve which tenants an operator principal may read across.
+
+Every cross-tenant surface in the MSSP API takes its tenant list from here
+and from nowhere else. That is the whole design: there is one place that
+decides "which tenants", it is small enough to read in a sitting, and the
+aggregate layer physically cannot run a query without its answer.
+
+The rule that matters is the empty one. A member with no grants resolves to
+an **empty** portfolio, never an unfiltered one. Every cross-tenant leak this
+codebase has had took the same shape — a scope that was absent rather than
+narrow, and a query that treated absent as "no filter". `get_entity_neighbors`
+accepted a `tenant_id` and never bound it. `_events_of_interest` handed
+API-authored SQL to a rewriter meant for untrusted SQL and checked nothing,
+so every fresh tenant saw the same global funnel. `rewrite_for_tenant` itself
+returned unscoped SQL and reported success when its parser moved a dict key.
+So:
+
+- resolution returns a frozenset, and an empty frozenset is a real answer;
+- :class:`PortfolioScope.tenant_ids` is the only input the aggregates accept;
+- the aggregates raise on an empty set rather than running unfiltered SQL.
+
+Two axes, kept separate because they answer different questions:
+
+ breadth owner/admin reach the whole portfolio. operator/viewer reach
+ only what `organization_member_tenants` grants them.
+ authority owner/admin/operator may act. viewer is read-only.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.organization import (
+ ACTING_ROLES,
+ ADMINISTERING_ROLES,
+ PORTFOLIO_WIDE_ROLES,
+ Organization,
+ OrganizationMember,
+ OrganizationMemberTenant,
+ OrganizationTenant,
+)
+from app.models.tenant import User
+
+logger = logging.getLogger("aisoc.org_scope")
+
+
+class PortfolioScopeError(RuntimeError):
+ """A cross-tenant query was attempted without a resolved portfolio.
+
+ Raised by :func:`require_scope`. This is a programming error, not a user
+ error: it means an aggregate was about to run with no tenant filter.
+ """
+
+
+@dataclass(frozen=True)
+class PortfolioScope:
+ """The tenants one principal may read across, and what they may do.
+
+ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream is
+ permitted to widen it, and no code path may substitute "all tenants" for
+ an empty one.
+ """
+
+ org_id: uuid.UUID | None = None
+ org_slug: str | None = None
+ org_name: str | None = None
+ org_role: str | None = None
+ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)
+ # True when the member's reach is the entire portfolio rather than a set
+ # of explicit grants. Surfaced so the console can say *why* a portfolio
+ # looks small instead of leaving an operator guessing.
+ portfolio_wide: bool = False
+
+ @property
+ def is_member(self) -> bool:
+ return self.org_id is not None
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.tenant_ids
+
+ @property
+ def can_act(self) -> bool:
+ return self.org_role in ACTING_ROLES
+
+ @property
+ def can_administer(self) -> bool:
+ return self.org_role in ADMINISTERING_ROLES
+
+ def covers(self, tenant_id: uuid.UUID) -> bool:
+ return tenant_id in self.tenant_ids
+
+ def ordered_ids(self) -> list[uuid.UUID]:
+ """Deterministic ordering, so queries and their tests are stable."""
+ return sorted(self.tenant_ids)
+
+
+EMPTY_SCOPE = PortfolioScope()
+
+
+async def resolve_portfolio_scope(db: AsyncSession, user: User) -> PortfolioScope:
+ """Resolve ``user``'s managed portfolio.
+
+ 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.
+ """
+ membership = (
+ await db.execute(
+ select(OrganizationMember, Organization)
+ .join(Organization, Organization.id == OrganizationMember.org_id)
+ .where(
+ OrganizationMember.user_id == user.id,
+ Organization.is_active.is_(True),
+ )
+ .order_by(Organization.created_at)
+ )
+ ).first()
+
+ if membership is None:
+ logger.debug("org_scope.not_a_member user=%s", user.id)
+ return EMPTY_SCOPE
+
+ member, org = membership
+ role = str(member.org_role)
+
+ portfolio_rows = (await db.execute(select(OrganizationTenant.tenant_id).where(OrganizationTenant.org_id == org.id))).scalars()
+ portfolio = {uuid.UUID(str(t)) for t in portfolio_rows}
+
+ if role in PORTFOLIO_WIDE_ROLES:
+ tenant_ids = portfolio
+ portfolio_wide = True
+ else:
+ granted_rows = (
+ await db.execute(
+ select(OrganizationMemberTenant.tenant_id).where(
+ OrganizationMemberTenant.org_id == org.id,
+ OrganizationMemberTenant.user_id == user.id,
+ )
+ )
+ ).scalars()
+ # Intersected with the portfolio even though the composite foreign
+ # key already guarantees containment. Belt and braces: this is the
+ # set that becomes a SQL predicate, and a stale grant surviving a
+ # schema change must narrow the result, never widen it.
+ tenant_ids = {uuid.UUID(str(t)) for t in granted_rows} & portfolio
+ portfolio_wide = False
+
+ if not tenant_ids:
+ # Logged at warning, with ids, because "the console is empty" is
+ # otherwise indistinguishable from "the platform is broken" — the
+ # 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,
+ org.id,
+ role,
+ len(portfolio),
+ )
+
+ return PortfolioScope(
+ org_id=uuid.UUID(str(org.id)),
+ org_slug=str(org.slug),
+ org_name=str(org.name),
+ org_role=role,
+ tenant_ids=frozenset(tenant_ids),
+ portfolio_wide=portfolio_wide,
+ )
+
+
+def require_scope(scope: PortfolioScope) -> list[uuid.UUID]:
+ """Return the tenant list for a query, or refuse to build one.
+
+ The aggregates call this instead of reading ``scope.tenant_ids``
+ directly, so "I forgot to check for empty" produces an exception at the
+ point of the mistake rather than a `WHERE tenant_id = ANY('{}')` that a
+ later refactor could drop.
+ """
+ if scope.is_empty:
+ raise PortfolioScopeError("refusing to build a cross-tenant query with an empty portfolio scope")
+ return scope.ordered_ids()
+
+
+def narrow(scope: PortfolioScope, tenant_ids: Sequence[uuid.UUID]) -> PortfolioScope:
+ """Restrict a scope to a caller-supplied subset.
+
+ Used by endpoints that accept a `tenant_id` filter. Intersection only —
+ naming a tenant outside the portfolio narrows the result to nothing
+ rather than reaching outside it, so a filter parameter can never become
+ a selector for someone else's data.
+ """
+ requested = {uuid.UUID(str(t)) for t in tenant_ids}
+ return PortfolioScope(
+ org_id=scope.org_id,
+ org_slug=scope.org_slug,
+ org_name=scope.org_name,
+ org_role=scope.org_role,
+ tenant_ids=frozenset(requested & scope.tenant_ids),
+ portfolio_wide=False,
+ )
diff --git a/services/api/app/services/tenant_deletion.py b/services/api/app/services/tenant_deletion.py
index 3596710d5..630ddf331 100644
--- a/services/api/app/services/tenant_deletion.py
+++ b/services/api/app/services/tenant_deletion.py
@@ -127,6 +127,30 @@ async def discover_tenant_tables(db: AsyncSession) -> list[str]:
return [r[0] for r in rows.fetchall()]
+async def _count_dependent_organizations(db: AsyncSession, tenant_id: uuid.UUID) -> int:
+ """Organisations this tenant *hosts*, which go with it.
+
+ Discovery finds tables by a column literally named ``tenant_id``, and
+ ``organizations.home_tenant_id`` is not one — so the row is removed by
+ the foreign-key cascade but never appears in the report. A deletion
+ report that undercounts is the same class of problem as one that
+ overstates completeness: the operator signing off on an erasure needs to
+ know an operator organisation was part of it.
+
+ Only the organisation row and its membership go. The tenants it managed
+ are other people's customers; they survive as unclaimed tenants, and
+ ``organization_tenants`` loses its links by cascade.
+ """
+ return int(
+ (
+ await db.execute(
+ text("SELECT count(*) FROM organizations WHERE home_tenant_id = :t"),
+ {"t": str(tenant_id)},
+ )
+ ).scalar_one()
+ )
+
+
async def purge_postgres(db: AsyncSession, tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:
result = StoreResult(store="postgres")
try:
@@ -159,6 +183,15 @@ async def purge_postgres(db: AsyncSession, tenant_id: uuid.UUID, *, dry_run: boo
{"t": str(tenant_id)},
)
+ hosted_orgs = await _count_dependent_organizations(db, tenant_id)
+ if hosted_orgs:
+ result.detail["organizations"] = hosted_orgs
+ result.rows += hosted_orgs
+ if not dry_run:
+ # Explicit rather than left to the cascade, so the delete and
+ # the number we just reported are the same operation.
+ await db.execute(text("DELETE FROM organizations WHERE home_tenant_id = :t"), {"t": str(tenant_id)})
+
tenant_rows = (await db.execute(text("SELECT count(*) FROM tenants WHERE id = :t"), {"t": str(tenant_id)})).scalar_one()
if tenant_rows:
result.detail[_TENANTS_TABLE] = int(tenant_rows)
diff --git a/services/api/migrations/058_mssp_organizations.sql b/services/api/migrations/058_mssp_organizations.sql
new file mode 100644
index 000000000..5e8eef105
--- /dev/null
+++ b/services/api/migrations/058_mssp_organizations.sql
@@ -0,0 +1,159 @@
+-- Migration 058: a real operator organisation above tenants
+--
+-- Migration 012 added `tenants.parent_tenant_id`, which makes the managing
+-- provider *a tenant*. That is enough to draw a tree and not enough to run a
+-- managed service, for three reasons:
+--
+-- 1. It conflates the operator with a security boundary. Every consumer of
+-- `current_user.tenant_id` on an /mssp route is simultaneously asking
+-- "who is the operator" and "whose data is this", and those must be
+-- different questions or a cross-tenant surface has no boundary to
+-- enforce.
+-- 2. There is no per-principal scoping. `parent_tenant_id` grants every
+-- user of the parent tenant the same reach over every child. A managed
+-- provider assigns analysts to accounts; it cannot express that here.
+-- 3. `ON DELETE SET NULL` means deleting the parent silently detaches the
+-- entire portfolio with no record that it ever existed.
+--
+-- So the parent concept moves up a level, onto its own object, and the
+-- relationship becomes explicit membership rather than an inherited column.
+--
+-- `tenants.parent_tenant_id` is kept and backfilled from, not dropped: it is
+-- what `GET /api/v1/mssp/children` and `mssp_rule_resolver` read today, and
+-- existing deployments have data in it.
+
+BEGIN;
+
+-- 1. The operator ------------------------------------------------------------
+--
+-- `home_tenant_id` is the tenant the operator's own staff log in to. It
+-- cascades: if that tenant is erased under a deletion request, the operator
+-- object goes with it. The managed tenants do *not* — they are separate
+-- customers and simply become unclaimed. Getting this backwards is how an
+-- offboarding turns into someone else's outage.
+CREATE TABLE IF NOT EXISTS organizations (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ slug TEXT NOT NULL UNIQUE,
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL DEFAULT 'mssp'
+ CHECK (kind IN ('mssp', 'enterprise')),
+ home_tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
+ is_active BOOLEAN NOT NULL DEFAULT TRUE,
+ settings JSONB NOT NULL DEFAULT '{}',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS idx_organizations_home_tenant
+ ON organizations (home_tenant_id) WHERE home_tenant_id IS NOT NULL;
+
+-- 2. Who belongs to the operator, and with what authority ---------------------
+--
+-- Two axes, deliberately separated, because they answer different questions:
+--
+-- breadth owner/admin reach the whole portfolio; operator/viewer reach
+-- only tenants granted to them in organization_member_tenants,
+-- and reach nothing at all when they have no grants.
+-- authority owner/admin/operator may act; viewer is read-only.
+--
+-- The empty case is the important one. A member with no grants gets an empty
+-- portfolio, never an unfiltered one — "no scope" must not degrade into "all
+-- scopes", which is the shape every cross-tenant leak in this codebase has
+-- had.
+CREATE TABLE IF NOT EXISTS organization_members (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ org_role TEXT NOT NULL DEFAULT 'viewer'
+ CHECK (org_role IN ('owner', 'admin', 'operator', 'viewer')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (org_id, user_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_org_members_user ON organization_members (user_id);
+
+-- 3. The managed portfolio ----------------------------------------------------
+--
+-- `UNIQUE (tenant_id)` is a boundary, not a convenience: it makes it
+-- impossible for two operators to both claim the same customer, so "which
+-- portfolio does this tenant belong to" has exactly one answer.
+CREATE TABLE IF NOT EXISTS organization_tenants (
+ org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ relationship TEXT NOT NULL DEFAULT 'managed'
+ CHECK (relationship IN ('managed', 'own')),
+ onboarded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ onboarded_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ PRIMARY KEY (org_id, tenant_id),
+ UNIQUE (tenant_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_org_tenants_tenant ON organization_tenants (tenant_id);
+
+-- 4. Which managed tenants a given principal may act on -----------------------
+--
+-- The composite foreign keys are the point. Granting a member a tenant the
+-- organisation does not manage is rejected by Postgres, not by whichever
+-- application code path happened to write the row — and a tenant leaving the
+-- portfolio takes every grant over it along, so a revoked customer cannot
+-- leave a live grant behind.
+CREATE TABLE IF NOT EXISTS organization_member_tenants (
+ org_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ tenant_id UUID NOT NULL,
+ granted_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ granted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (org_id, user_id, tenant_id),
+ FOREIGN KEY (org_id, user_id)
+ REFERENCES organization_members (org_id, user_id) ON DELETE CASCADE,
+ FOREIGN KEY (org_id, tenant_id)
+ REFERENCES organization_tenants (org_id, tenant_id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_org_member_tenants_user
+ ON organization_member_tenants (org_id, user_id);
+
+-- 5. Backfill from the tenant-tree model --------------------------------------
+--
+-- Every tenant that already names a parent becomes a managed tenant of an
+-- organisation derived from that parent. Idempotent, so re-running the
+-- migration chain is safe.
+INSERT INTO organizations (slug, name, kind, home_tenant_id)
+SELECT
+ 'org-' || p.slug,
+ p.name,
+ 'mssp',
+ p.id
+FROM tenants p
+WHERE EXISTS (SELECT 1 FROM tenants c WHERE c.parent_tenant_id = p.id)
+ON CONFLICT (slug) DO NOTHING;
+
+-- The operator's own tenant joins its portfolio as `own`, so a provider that
+-- also runs its own estate sees it in the same rollup.
+INSERT INTO organization_tenants (org_id, tenant_id, relationship)
+SELECT o.id, o.home_tenant_id, 'own'
+FROM organizations o
+WHERE o.home_tenant_id IS NOT NULL
+ON CONFLICT DO NOTHING;
+
+INSERT INTO organization_tenants (org_id, tenant_id, relationship)
+SELECT o.id, c.id, 'managed'
+FROM organizations o
+JOIN tenants c ON c.parent_tenant_id = o.home_tenant_id
+ON CONFLICT DO NOTHING;
+
+-- Users of the operator's own tenant become members. A tenant admin becomes
+-- an org owner; everyone else becomes an operator, which can act but only on
+-- tenants explicitly granted to them — so the backfill cannot widen anyone's
+-- reach beyond what an administrator later chooses to grant.
+INSERT INTO organization_members (org_id, user_id, org_role)
+SELECT
+ o.id,
+ u.id,
+ CASE WHEN u.role IN ('admin', 'tenant_admin', 'owner') THEN 'owner' ELSE 'operator' END
+FROM organizations o
+JOIN users u ON u.tenant_id = o.home_tenant_id
+ON CONFLICT (org_id, user_id) DO NOTHING;
+
+COMMIT;
diff --git a/services/api/tests/test_mssp_portfolio_contract.py b/services/api/tests/test_mssp_portfolio_contract.py
new file mode 100644
index 000000000..8fa3fec14
--- /dev/null
+++ b/services/api/tests/test_mssp_portfolio_contract.py
@@ -0,0 +1,99 @@
+"""Every figure the portfolio computes has to survive serialisation.
+
+`test_mssp_portfolio_isolation.py` proves the aggregation is right, but it
+asserts on `TenantRollup` — the dataclass, one layer below the response model.
+A field that is computed, tested, and absent from the `BaseModel` is dropped by
+Pydantic without a word, and the service-layer test still passes. That is how
+`mttr_minutes` reached review: measured by real SQL over `cases.closed_at`,
+carried by `as_dict()`, present in `EMPTY_SUMMARY`, described in the route
+comment and the CHANGELOG — and declared on neither `PortfolioTenantOut` nor
+`PortfolioSummaryOut`, so no caller could ever read it.
+
+These tests sit at the drop point: dict in, response model out, assert the
+value is still there. No database, so they run in the ordinary API job rather
+than only where a live Postgres is available.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+from app.api.v1.endpoints.mssp import PortfolioSummaryOut, PortfolioTenantOut
+from app.services.entitlements import Headroom
+from app.services.mssp_portfolio import EMPTY_SUMMARY, TenantRollup, summarise
+
+
+def _rollup(*, name: str = "Portfolio A", mttr: float | None = 42.5) -> TenantRollup:
+ return TenantRollup(
+ tenant_id=uuid.uuid4(),
+ name=name,
+ slug=name.lower().replace(" ", "-"),
+ relationship="owner",
+ is_active=True,
+ open_alerts=3,
+ critical_alerts=1,
+ high_alerts=1,
+ untriaged_alerts=2,
+ synthetic_alerts=0,
+ open_cases=2,
+ sla_breached_cases=1,
+ mttr_minutes=mttr,
+ connectors_total=2,
+ connectors_healthy=1,
+ connectors_stale=1,
+ connectors_error=0,
+ last_event_at=None,
+ limits=[Headroom(key="connectors", label="Connectors", used=2, limit=5, state="ok")],
+ )
+
+
+def test_a_tenant_row_carries_its_measured_mttr_to_the_wire() -> None:
+ row = PortfolioTenantOut(**_rollup(mttr=42.5).as_dict())
+ assert row.mttr_minutes == 42.5
+ assert "mttr_minutes" in row.model_dump()
+
+
+def test_a_tenant_that_closed_nothing_serialises_null_not_zero() -> None:
+ """Null and 0.0 are opposite claims: "no data" and "instant resolution"."""
+ row = PortfolioTenantOut(**_rollup(mttr=None).as_dict())
+ assert row.mttr_minutes is None
+ assert row.model_dump()["mttr_minutes"] is None
+
+
+def test_the_summary_carries_its_mttr_to_the_wire() -> None:
+ summary = PortfolioSummaryOut(**summarise([_rollup(mttr=20.0), _rollup(name="Portfolio B", mttr=40.0)]))
+ assert summary.mttr_minutes == 30.0
+
+
+def test_the_summary_mttr_skips_tenants_that_closed_nothing() -> None:
+ """Averaging a null as zero would drag the portfolio figure toward a
+ number nobody measured."""
+ summary = PortfolioSummaryOut(**summarise([_rollup(mttr=20.0), _rollup(name="Portfolio B", mttr=None)]))
+ assert summary.mttr_minutes == 20.0
+
+
+def test_an_empty_portfolio_reports_no_mttr_rather_than_zero() -> None:
+ summary = PortfolioSummaryOut(**EMPTY_SUMMARY)
+ assert summary.mttr_minutes is None
+ assert summary.tenants == 0
+
+
+def test_every_key_the_service_emits_is_declared_on_the_response_model() -> None:
+ """The general form of the bug, so the next dropped field fails here.
+
+ Pydantic ignores unknown keys, so a service that starts emitting a new
+ measurement gains a silent no-op rather than a new field. Compared in the
+ direction that actually drifts: service → model.
+ """
+ emitted = set(_rollup().as_dict())
+ declared = set(PortfolioTenantOut.model_fields)
+ assert emitted - declared == set(), f"computed but never reaches a caller: {sorted(emitted - declared)}"
+
+ emitted_summary = set(summarise([_rollup()]))
+ declared_summary = set(PortfolioSummaryOut.model_fields)
+ assert emitted_summary - declared_summary == set(), f"computed but never reaches a caller: {sorted(emitted_summary - declared_summary)}"
+
+
+def test_the_empty_summary_and_the_computed_summary_agree_on_shape() -> None:
+ """Otherwise an empty portfolio 500s on a key the populated path added."""
+ assert set(EMPTY_SUMMARY) == set(summarise([_rollup()]))
diff --git a/services/api/tests/test_mssp_portfolio_isolation.py b/services/api/tests/test_mssp_portfolio_isolation.py
new file mode 100644
index 000000000..275342fcf
--- /dev/null
+++ b/services/api/tests/test_mssp_portfolio_isolation.py
@@ -0,0 +1,537 @@
+"""Live-Postgres proof that a portfolio aggregate cannot see outside itself.
+
+The MSSP surface deliberately reads more than one tenant's rows, which makes
+it the one place in the product where "filter by the caller's tenant" is not
+the rule. That is worth a gate that runs against a real database rather than
+a mocked session, for the reason the cross-store suite exists at all: an
+isolation contract that is only unit-tested against a mock is a claim, not a
+gate.
+
+Shape of every test here, borrowed from `tests/isolation/test_live_stores.py`
+because it is what makes such a test meaningful:
+
+1. Seed a managed portfolio *and* data belonging to tenants outside it.
+2. Assert the outside data really exists, so a scoped read returning
+ nothing cannot pass vacuously on an empty database.
+3. Assert the scoped read returns the portfolio and never the outsiders.
+
+Two of these also stand as regression tests against what this surface used
+to do. `/mssp/tenants` returned five hardcoded companies — Acme Corp, Globex
+Industries, Wayne Enterprises — with invented alert counts and health
+scores. `test_every_returned_tenant_exists_in_the_database` fails against
+that code, because none of those names is a row.
+
+Skips when no database answers, so a local `pytest` run stays green — but
+**cannot** skip where it is supposed to run. `integration.yml` sets
+`MSSP_ISOLATION_REQUIRED=1`, and an unreachable database is then a failure
+rather than a skip. A gate that quietly declines to run is the shape that
+left the public scoreboard ten weeks stale while its page promised weekly
+rows; checking the DSN *string* is not the same as checking that a database
+is there, and `ci.yml` sets a placeholder DSN with no server behind it.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+
+import pytest
+import pytest_asyncio
+from app.services.entitlements import limit_for
+from app.services.mssp_portfolio import portfolio_alerts, summarise, tenant_rollups
+from app.services.org_scope import (
+ PortfolioScope,
+ PortfolioScopeError,
+ narrow,
+ resolve_portfolio_scope,
+)
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+DSN = os.environ.get("DATABASE_URL", "")
+# Set in `integration.yml`, where a real Postgres with the full migration
+# chain is guaranteed. When it is set, an unreachable database fails the
+# build instead of skipping past the isolation proof.
+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")
+
+pytestmark = [
+ pytest.mark.skipif(
+ "postgres" not in DSN and not REQUIRED,
+ reason="needs a live Postgres with the migration chain applied (integration.yml)",
+ ),
+ pytest.mark.asyncio,
+]
+
+# Fixed ids so a failure names something greppable.
+ORG_P = uuid.UUID("0a000000-0000-0000-0000-000000000001")
+ORG_Q = uuid.UUID("0a000000-0000-0000-0000-000000000002")
+TENANT_A = uuid.UUID("0b000000-0000-0000-0000-00000000000a")
+TENANT_B = uuid.UUID("0b000000-0000-0000-0000-00000000000b")
+# Managed by a *different* organisation — the interesting outsider, because
+# it is in the organisation tables and must still be invisible to P.
+TENANT_C = uuid.UUID("0c000000-0000-0000-0000-00000000000c")
+# Managed by nobody.
+TENANT_D = uuid.UUID("0d000000-0000-0000-0000-00000000000d")
+
+OWNER_P = uuid.UUID("0e000000-0000-0000-0000-000000000001")
+OPERATOR_P = uuid.UUID("0e000000-0000-0000-0000-000000000002")
+NEWCOMER_P = uuid.UUID("0e000000-0000-0000-0000-000000000003")
+STRANGER = uuid.UUID("0e000000-0000-0000-0000-000000000009")
+
+_ALL_TENANTS = (TENANT_A, TENANT_B, TENANT_C, TENANT_D)
+_ALL_USERS = (OWNER_P, OPERATOR_P, NEWCOMER_P, STRANGER)
+
+
+@pytest_asyncio.fixture
+async def db():
+ engine = create_async_engine(DSN)
+ try:
+ async with engine.connect() as probe:
+ await probe.execute(text("SELECT 1"))
+ except Exception as exc:
+ await engine.dispose()
+ if REQUIRED:
+ pytest.fail(
+ "MSSP_ISOLATION_REQUIRED is set but no database answered at DATABASE_URL — "
+ f"the cross-tenant isolation proof did not run: {type(exc).__name__}: {exc}"
+ )
+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")
+
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ await _seed(session)
+ try:
+ yield session
+ finally:
+ await _teardown(session)
+ await engine.dispose()
+
+
+async def _teardown(session) -> None:
+ await session.rollback()
+ for table in ("alerts", "cases", "connectors"):
+ await session.execute(
+ text(f"DELETE FROM {table} WHERE tenant_id = ANY(:ids)"),
+ {"ids": [str(t) for t in _ALL_TENANTS]},
+ )
+ await session.execute(
+ text("DELETE FROM organizations WHERE id = ANY(:ids)"),
+ {"ids": [str(ORG_P), str(ORG_Q)]},
+ )
+ await session.execute(text("DELETE FROM users WHERE id = ANY(:ids)"), {"ids": [str(u) for u in _ALL_USERS]})
+ await session.execute(
+ text("DELETE FROM tenants WHERE id = ANY(:ids)"),
+ {"ids": [str(t) for t in _ALL_TENANTS]},
+ )
+ await session.commit()
+
+
+async def _seed(session) -> None:
+ await _teardown(session)
+
+ await session.execute(
+ text(
+ "INSERT INTO tenants (id, name, slug, limits) VALUES "
+ "(:a, 'Portfolio A', 'iso-portfolio-a', '{\"connectors\": 1}'::jsonb), "
+ "(:b, 'Portfolio B', 'iso-portfolio-b', '{}'::jsonb), "
+ "(:c, 'Rival Customer', 'iso-rival-customer', '{}'::jsonb), "
+ "(:d, 'Unmanaged', 'iso-unmanaged', '{}'::jsonb)"
+ ),
+ {"a": str(TENANT_A), "b": str(TENANT_B), "c": str(TENANT_C), "d": str(TENANT_D)},
+ )
+ await session.execute(
+ text(
+ "INSERT INTO users (id, tenant_id, email, username, hashed_password, role) VALUES "
+ "(:owner, :a, '[email protected]', 'owner', 'x', 'admin'), "
+ "(:operator, :a, '[email protected]', 'operator', 'x', 'soc_analyst'), "
+ "(:newcomer, :a, '[email protected]', 'newcomer', 'x', 'soc_analyst'), "
+ "(:stranger, :d, '[email protected]', 'stranger', 'x', 'soc_analyst')"
+ ),
+ {
+ "owner": str(OWNER_P),
+ "operator": str(OPERATOR_P),
+ "newcomer": str(NEWCOMER_P),
+ "stranger": str(STRANGER),
+ "a": str(TENANT_A),
+ "d": str(TENANT_D),
+ },
+ )
+ await session.execute(
+ text(
+ # Provider P's own staff sign in to tenant A, so A is both its
+ # home tenant and part of its portfolio — the shape a provider
+ # that also runs its own estate actually has.
+ "INSERT INTO organizations (id, slug, name, home_tenant_id) VALUES "
+ "(:p, 'iso-provider-p', 'Provider P', :a), (:q, 'iso-provider-q', 'Provider Q', NULL)"
+ ),
+ {"p": str(ORG_P), "q": str(ORG_Q), "a": str(TENANT_A)},
+ )
+ await session.execute(
+ text("INSERT INTO organization_tenants (org_id, tenant_id) VALUES " "(:p, :a), (:p, :b), (:q, :c)"),
+ {"p": str(ORG_P), "q": str(ORG_Q), "a": str(TENANT_A), "b": str(TENANT_B), "c": str(TENANT_C)},
+ )
+ await session.execute(
+ text(
+ "INSERT INTO organization_members (org_id, user_id, org_role) VALUES "
+ "(:p, :owner, 'owner'), (:p, :operator, 'operator'), (:p, :newcomer, 'operator')"
+ ),
+ {"p": str(ORG_P), "owner": str(OWNER_P), "operator": str(OPERATOR_P), "newcomer": str(NEWCOMER_P)},
+ )
+ # The operator is granted one of the two managed tenants. The newcomer is
+ # granted nothing.
+ await session.execute(
+ text("INSERT INTO organization_member_tenants (org_id, user_id, tenant_id) VALUES (:p, :operator, :a)"),
+ {"p": str(ORG_P), "operator": str(OPERATOR_P), "a": str(TENANT_A)},
+ )
+
+ await session.execute(
+ text(
+ "INSERT INTO alerts (tenant_id, title, severity, status, is_synthetic) VALUES "
+ "(:a, 'A real critical', 'critical', 'new', false), "
+ "(:b, 'B real medium', 'medium', 'new', false), "
+ "(:b, 'B SEEDED DEMO ROW', 'critical', 'new', true), "
+ "(:c, 'RIVAL CUSTOMER SECRET', 'critical', 'new', false), "
+ "(:d, 'UNMANAGED SECRET', 'critical', 'new', false)"
+ ),
+ {"a": str(TENANT_A), "b": str(TENANT_B), "c": str(TENANT_C), "d": str(TENANT_D)},
+ )
+ await session.execute(
+ text(
+ "INSERT INTO connectors (tenant_id, name, connector_type, is_enabled, last_sync, health_status) VALUES "
+ "(:a, 'a-okta', 'okta', true, now(), 'healthy'), "
+ "(:c, 'c-okta', 'okta', true, now(), 'healthy'), "
+ "(:d, 'd-okta', 'okta', true, now(), 'healthy')"
+ ),
+ {"a": str(TENANT_A), "c": str(TENANT_C), "d": str(TENANT_D)},
+ )
+ await session.commit()
+
+
+def _owner_scope() -> PortfolioScope:
+ return PortfolioScope(
+ org_id=ORG_P,
+ org_slug="iso-provider-p",
+ org_role="owner",
+ tenant_ids=frozenset({TENANT_A, TENANT_B}),
+ portfolio_wide=True,
+ )
+
+
+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
+# ---------------------------------------------------------------------------
+
+
+async def test_outsider_data_is_really_present(db) -> None:
+ """Without this, every assertion below could pass on an empty database."""
+ total = (
+ await db.execute(
+ text("SELECT count(*) FROM alerts WHERE tenant_id = ANY(:ids)"),
+ {"ids": [str(t) for t in _ALL_TENANTS]},
+ )
+ ).scalar_one()
+ assert total == 5, total
+
+ outsiders = (
+ await db.execute(
+ text("SELECT count(*) FROM alerts WHERE tenant_id = ANY(:ids)"),
+ {"ids": [str(TENANT_C), str(TENANT_D)]},
+ )
+ ).scalar_one()
+ assert outsiders == 2, outsiders
+
+
+# ---------------------------------------------------------------------------
+# The isolation property
+# ---------------------------------------------------------------------------
+
+
+async def test_rollups_never_include_a_tenant_outside_the_portfolio(db) -> None:
+ rollups = await tenant_rollups(db, _owner_scope())
+
+ assert {r.name for r in rollups} == {"Portfolio A", "Portfolio B"}
+ assert all(r.tenant_id in {TENANT_A, TENANT_B} for r in rollups)
+ assert "Rival Customer" not in {r.name for r in rollups}, "another organisation's tenant leaked into the rollup"
+ assert "Unmanaged" not in {r.name for r in rollups}
+
+
+async def test_portfolio_alerts_never_include_an_outsider(db) -> None:
+ titles = [a["title"] for a in await portfolio_alerts(db, _owner_scope())]
+
+ assert "A real critical" in titles
+ assert "B real medium" in titles
+ assert not any("SECRET" in t for t in titles), f"outsider alert leaked: {titles}"
+
+
+async def test_connector_health_counts_only_portfolio_connectors(db) -> None:
+ """C and D each own an enabled connector; the portfolio owns one."""
+ summary = summarise(await tenant_rollups(db, _owner_scope()))
+ assert summary["connectors_total"] == 1, summary
+
+
+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))
+
+ assert scope.is_member
+ assert scope.portfolio_wide is False
+ assert scope.tenant_ids == frozenset({TENANT_A})
+
+ rollups = await tenant_rollups(db, scope)
+ assert {r.name for r in rollups} == {"Portfolio A"}
+
+
+async def test_a_member_with_no_grants_resolves_to_empty_not_everything(db) -> None:
+ """The failure mode this whole design is shaped around.
+
+ An operator who has been added to the organisation but assigned no
+ 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))
+
+ assert scope.is_member, "should still be recognised as a member"
+ assert scope.tenant_ids == frozenset()
+
+ with pytest.raises(PortfolioScopeError):
+ await tenant_rollups(db, scope)
+
+
+async def test_a_non_member_resolves_to_no_organisation_at_all(db) -> None:
+ scope = await resolve_portfolio_scope(db, await _user(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))
+
+ assert owner.org_id == ORG_P
+ assert TENANT_C not in owner.tenant_ids, "Provider Q's customer is in Provider P's scope"
+
+
+async def test_a_tenant_filter_cannot_select_a_tenant_outside_the_portfolio(db) -> None:
+ """`?tenant_id=` narrows; it must never widen."""
+ narrowed = narrow(_owner_scope(), [TENANT_C, TENANT_D])
+ assert narrowed.tenant_ids == frozenset()
+
+ with pytest.raises(PortfolioScopeError):
+ await tenant_rollups(db, narrowed)
+
+
+# ---------------------------------------------------------------------------
+# Regressions against the invented-tenant surface these routes used to serve
+# ---------------------------------------------------------------------------
+
+
+async def test_every_returned_tenant_exists_in_the_database(db) -> None:
+ """Fails against the pre-fix `/mssp/tenants`.
+
+ That route returned Acme Corp, Globex Industries, Initech LLC, Wayne
+ Enterprises and Stark Solutions with invented alert counts and health
+ scores. None of them was a row in `tenants`, which is precisely what
+ this asserts.
+ """
+ rollups = await tenant_rollups(db, _owner_scope())
+ assert rollups, "fixture should produce rows"
+
+ known = {uuid.UUID(str(r[0])) for r in (await db.execute(text("SELECT id FROM tenants"))).all()}
+ for rollup in rollups:
+ assert rollup.tenant_id in known, f"{rollup.name} is not a tenant in this database"
+
+
+async def test_figures_are_counted_not_asserted(db) -> None:
+ """Every headline number must move when the underlying rows move."""
+ before = summarise(await tenant_rollups(db, _owner_scope()))
+
+ await db.execute(
+ text(
+ "INSERT INTO alerts (tenant_id, title, severity, status, is_synthetic) "
+ "VALUES (:a, 'A second critical', 'critical', 'new', false)"
+ ),
+ {"a": str(TENANT_A)},
+ )
+ await db.commit()
+
+ after = summarise(await tenant_rollups(db, _owner_scope()))
+ assert after["critical_alerts"] == before["critical_alerts"] + 1
+ assert after["open_alerts"] == before["open_alerts"] + 1
+
+
+async def test_seeded_rows_are_counted_apart_from_real_ones(db) -> None:
+ """A demo install must not report its fixtures as the customer's posture."""
+ rollups = {r.name: r for r in await tenant_rollups(db, _owner_scope())}
+ tenant_b = rollups["Portfolio B"]
+
+ assert tenant_b.synthetic_alerts == 1
+ assert tenant_b.critical_alerts == 0, "a seeded critical was counted as real"
+
+ default_titles = [a["title"] for a in await portfolio_alerts(db, _owner_scope())]
+ assert "B SEEDED DEMO ROW" not in default_titles
+
+ opted_in = await portfolio_alerts(db, _owner_scope(), include_synthetic=True)
+ seeded = [a for a in opted_in if a["title"] == "B SEEDED DEMO ROW"]
+ assert seeded and seeded[0]["is_synthetic"] is True, "opting in must label what it returns"
+
+
+async def test_headroom_is_measured_and_uncapped_stays_uncapped(db) -> None:
+ rollups = {r.name: r for r in await tenant_rollups(db, _owner_scope())}
+ limits = {h.key: h for h in rollups["Portfolio A"].limits}
+
+ # Tenant A has one enabled connector and a configured ceiling of one.
+ assert limits["connectors"].used == 1
+ assert limits["connectors"].limit == 1
+ assert limits["connectors"].state == "exhausted"
+
+ # Tenant A configured nothing else, and this build ships no plan caps.
+ assert limits["seats"].limit is None
+ assert limits["seats"].state == "unlimited"
+ assert limits["seats"].used == 3, "seats must be counted, not guessed"
+
+ # Tenant B configured nothing at all.
+ b_limits = {h.key: h for h in rollups["Portfolio B"].limits}
+ assert all(h.limit is None for h in b_limits.values())
+ assert limit_for({}, "connectors") is None
+
+
+async def test_mttr_is_null_rather_than_zero_when_nothing_closed(db) -> None:
+ """A tenant that has closed no cases has no resolution time.
+
+ Reporting 0.0 would put the account that has done nothing at the top of
+ the league table.
+ """
+ rollups = {r.name: r for r in await tenant_rollups(db, _owner_scope())}
+ assert rollups["Portfolio A"].mttr_minutes is None
+
+ await db.execute(
+ text(
+ "INSERT INTO cases (tenant_id, case_number, title, status, created_at, closed_at) "
+ "VALUES (:a, :num, 'closed case', 'closed', now() - interval '30 minutes', now())"
+ ),
+ {"a": str(TENANT_A), "num": f"ISO-{uuid.uuid4().hex[:8]}"},
+ )
+ await db.commit()
+
+ rollups = {r.name: r for r in await tenant_rollups(db, _owner_scope())}
+ assert rollups["Portfolio A"].mttr_minutes == pytest.approx(30.0, abs=1.0)
+
+
+# ---------------------------------------------------------------------------
+# The database refuses what the application would also refuse
+# ---------------------------------------------------------------------------
+
+
+async def test_a_grant_cannot_name_a_tenant_outside_the_portfolio(db) -> None:
+ """Enforced by the composite foreign key, not by the writing code path.
+
+ If the API check were deleted tomorrow, this would still fail.
+ """
+ with pytest.raises(Exception) as excinfo:
+ await db.execute(
+ text("INSERT INTO organization_member_tenants (org_id, user_id, tenant_id) VALUES (:p, :u, :c)"),
+ {"p": str(ORG_P), "u": str(OPERATOR_P), "c": str(TENANT_C)},
+ )
+ await db.commit()
+ assert "foreign key" in str(excinfo.value).lower()
+ await db.rollback()
+
+
+async def test_two_organisations_cannot_both_claim_one_tenant(db) -> None:
+ with pytest.raises(Exception) as excinfo:
+ await db.execute(
+ text("INSERT INTO organization_tenants (org_id, tenant_id) VALUES (:q, :a)"),
+ {"q": str(ORG_Q), "a": str(TENANT_A)},
+ )
+ await db.commit()
+ assert "unique" in str(excinfo.value).lower() or "duplicate" in str(excinfo.value).lower()
+ await db.rollback()
+
+
+async def test_releasing_a_tenant_revokes_every_grant_over_it(db) -> None:
+ """Offboarding a customer must not leave a live grant behind."""
+ before = (
+ await db.execute(
+ text("SELECT count(*) FROM organization_member_tenants WHERE tenant_id = :a"),
+ {"a": str(TENANT_A)},
+ )
+ ).scalar_one()
+ assert before == 1
+
+ await db.execute(
+ text("DELETE FROM organization_tenants WHERE org_id = :p AND tenant_id = :a"),
+ {"p": str(ORG_P), "a": str(TENANT_A)},
+ )
+ await db.commit()
+
+ after = (
+ await db.execute(
+ text("SELECT count(*) FROM organization_member_tenants WHERE tenant_id = :a"),
+ {"a": str(TENANT_A)},
+ )
+ ).scalar_one()
+ assert after == 0
+
+ # 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))
+ assert scope.tenant_ids == frozenset()
+
+
+async def test_releasing_a_tenant_does_not_delete_the_tenant(db) -> None:
+ """Offboarding from a provider is not a deletion request."""
+ await db.execute(
+ text("DELETE FROM organization_tenants WHERE org_id = :p AND tenant_id = :b"),
+ {"p": str(ORG_P), "b": str(TENANT_B)},
+ )
+ await db.commit()
+
+ still_there = (await db.execute(text("SELECT count(*) FROM tenants WHERE id = :b"), {"b": str(TENANT_B)})).scalar_one()
+ assert still_there == 1
+
+ alerts_kept = (await db.execute(text("SELECT count(*) FROM alerts WHERE tenant_id = :b"), {"b": str(TENANT_B)})).scalar_one()
+ assert alerts_kept == 2
+
+
+# ---------------------------------------------------------------------------
+# Offboarding: the organisation participates, and the report says so
+# ---------------------------------------------------------------------------
+
+
+async def test_deleting_the_home_tenant_reports_and_removes_the_organisation(db) -> None:
+ """`discover_tenant_tables` looks for a column named `tenant_id`.
+
+ `organizations.home_tenant_id` is not one, so the row would be removed
+ by the foreign-key cascade and never appear in the report. An erasure
+ sign-off that undercounts is the same class of problem as one that
+ overstates completeness.
+ """
+ from app.services.tenant_deletion import purge_postgres
+
+ # The Postgres store directly: the satellite stores are not running in
+ # this job, and `delete_tenant` correctly rolls the whole erasure back
+ # when any of them fails, which would hide what we are asserting.
+ preview = await purge_postgres(db, TENANT_A, dry_run=True)
+ assert preview.ok, preview.error
+ assert preview.detail.get("organizations") == 1, preview.detail
+
+ applied = await purge_postgres(db, TENANT_A, dry_run=False)
+ assert applied.ok, applied.error
+ await db.commit()
+
+ orgs_left = (await db.execute(text("SELECT count(*) FROM organizations WHERE id = :p"), {"p": str(ORG_P)})).scalar_one()
+ assert orgs_left == 0
+
+ # The customers the provider managed are not the provider's to erase.
+ survivors = (
+ await db.execute(
+ text("SELECT count(*) FROM tenants WHERE id = ANY(:ids)"),
+ {"ids": [str(TENANT_B), str(TENANT_C)]},
+ )
+ ).scalar_one()
+ assert survivors == 2
diff --git a/services/api/tests/test_org_scope.py b/services/api/tests/test_org_scope.py
new file mode 100644
index 000000000..587f7ebf2
--- /dev/null
+++ b/services/api/tests/test_org_scope.py
@@ -0,0 +1,224 @@
+"""Scope resolution and limit arithmetic, without a database.
+
+The live-Postgres proof that a portfolio aggregate cannot see outside its
+portfolio is in `test_mssp_portfolio_isolation.py`. This file covers the
+decisions that happen before any SQL runs, and the one structural property
+that keeps the aggregate layer honest as it grows: a cross-tenant query
+function must route its tenant list through `require_scope`, so adding a new
+aggregate without scoping fails here rather than in production.
+"""
+
+from __future__ import annotations
+
+import ast
+import uuid
+from pathlib import Path
+
+import pytest
+from app.services import entitlements, mssp_portfolio
+from app.services.org_scope import (
+ EMPTY_SCOPE,
+ PortfolioScope,
+ PortfolioScopeError,
+ narrow,
+ require_scope,
+)
+
+A = uuid.UUID("11111111-1111-1111-1111-11111111000a")
+B = uuid.UUID("11111111-1111-1111-1111-11111111000b")
+OUTSIDE = uuid.UUID("99999999-9999-9999-9999-999999990000")
+
+ORG = uuid.UUID("22222222-2222-2222-2222-222222222222")
+
+
+def _scope(role: str = "admin", tenants: set[uuid.UUID] | None = None) -> PortfolioScope:
+ return PortfolioScope(
+ org_id=ORG,
+ org_slug="provider",
+ org_name="Provider",
+ org_role=role,
+ tenant_ids=frozenset(tenants if tenants is not None else {A, B}),
+ portfolio_wide=role in {"owner", "admin"},
+ )
+
+
+# ---------------------------------------------------------------------------
+# An absent scope must never behave like an unrestricted one
+# ---------------------------------------------------------------------------
+
+
+def test_require_scope_refuses_an_empty_portfolio() -> None:
+ """The single most important assertion in the tenancy surface.
+
+ Every cross-tenant leak in this codebase has had the same shape: a scope
+ that was absent rather than narrow, and a query that read absent as "no
+ filter". `require_scope` makes that combination raise.
+ """
+ with pytest.raises(PortfolioScopeError):
+ require_scope(EMPTY_SCOPE)
+
+ with pytest.raises(PortfolioScopeError):
+ require_scope(_scope(tenants=set()))
+
+
+def test_require_scope_returns_a_deterministic_list() -> None:
+ assert require_scope(_scope()) == sorted({A, B})
+
+
+def test_non_member_is_not_silently_treated_as_an_operator() -> None:
+ assert EMPTY_SCOPE.is_member is False
+ assert EMPTY_SCOPE.can_act is False
+ assert EMPTY_SCOPE.can_administer is False
+ assert EMPTY_SCOPE.tenant_ids == frozenset()
+
+
+# ---------------------------------------------------------------------------
+# A filter parameter must not become a selector for someone else's data
+# ---------------------------------------------------------------------------
+
+
+def test_narrow_cannot_reach_outside_the_portfolio() -> None:
+ narrowed = narrow(_scope(), [OUTSIDE])
+ assert narrowed.tenant_ids == frozenset()
+ assert not narrowed.covers(OUTSIDE)
+
+
+def test_narrow_keeps_only_the_intersection() -> None:
+ narrowed = narrow(_scope(), [A, OUTSIDE])
+ assert narrowed.tenant_ids == frozenset({A})
+
+
+def test_narrow_preserves_identity_but_not_breadth() -> None:
+ narrowed = narrow(_scope("owner"), [A])
+ assert narrowed.org_id == ORG
+ assert narrowed.org_role == "owner"
+ # No longer the whole portfolio, and the payload should not claim it is.
+ assert narrowed.portfolio_wide is False
+
+
+# ---------------------------------------------------------------------------
+# Authority
+# ---------------------------------------------------------------------------
+
+
+ ("role", "can_act", "can_administer"),
+ [
+ ("owner", True, True),
+ ("admin", True, True),
+ ("operator", True, False),
+ ("viewer", False, False),
+ ],
+)
+def test_role_authority(role: str, can_act: bool, can_administer: bool) -> None:
+ scope = _scope(role)
+ assert scope.can_act is can_act
+ assert scope.can_administer is can_administer
+
+
+# ---------------------------------------------------------------------------
+# The structural gate: a new aggregate cannot forget to scope itself
+# ---------------------------------------------------------------------------
+
+
+def test_every_cross_tenant_query_routes_through_require_scope() -> None:
+ """Any function here taking a `scope` must call `require_scope(scope)`.
+
+ Reviewing for a missing `WHERE tenant_id` is exactly the check humans
+ are worst at and that this codebase has failed several times. Reading
+ `scope.tenant_ids` directly is not enough: it would produce
+ `ANY('{}')` on an empty portfolio, which a later refactor could drop
+ without anybody noticing the day it stopped filtering.
+ """
+ source = Path(mssp_portfolio.__file__).read_text(encoding="utf-8")
+ tree = ast.parse(source)
+
+ unscoped: list[str] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.AsyncFunctionDef | ast.FunctionDef):
+ continue
+ takes_scope = any(arg.arg == "scope" for arg in [*node.args.args, *node.args.kwonlyargs])
+ if not takes_scope:
+ continue
+ calls = {child.func.id for child in ast.walk(node) if isinstance(child, ast.Call) and isinstance(child.func, ast.Name)}
+ if "require_scope" not in calls:
+ unscoped.append(node.name)
+
+ assert not unscoped, f"cross-tenant function(s) that never call require_scope: {unscoped}"
+
+
+def test_empty_summary_matches_the_computed_summary_shape() -> None:
+ """A portfolio with no tenants must answer in the same shape as one with.
+
+ Otherwise the empty case needs its own branch in every consumer, and the
+ branch nobody exercises is the one that renders a blank card instead of
+ a zero.
+ """
+ assert set(mssp_portfolio.EMPTY_SUMMARY) == set(mssp_portfolio.summarise([]))
+
+
+# ---------------------------------------------------------------------------
+# Limits: uncapped must read as uncapped, not as zero
+# ---------------------------------------------------------------------------
+
+
[email protected]("raw", [-1, "-1", "unlimited", "UNLIMITED", "none", "", None, "not-a-number"])
+def test_values_meaning_no_ceiling(raw: object) -> None:
+ assert entitlements.limit_for({"connectors": raw}, "connectors") is None
+
+
+def test_per_tenant_override_wins_over_the_deployment_default(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(entitlements, "_deployment_defaults", lambda: {"connectors": 5})
+ assert entitlements.limit_for({}, "connectors") == 5
+ # Raising as well as lowering: sizing one customer differently is the
+ # whole reason the override exists.
+ assert entitlements.limit_for({"connectors": 50}, "connectors") == 50
+ assert entitlements.limit_for({"connectors": "unlimited"}, "connectors") is None
+
+
+def test_unconfigured_key_is_uncapped_not_invented() -> None:
+ """No plan, no ceiling.
+
+ An open-source install has no billing tier, so drawing a headroom bar
+ against an invented cap would put a fabricated number on every tenant
+ row in the portfolio view.
+ """
+ assert entitlements.limit_for({}, "connectors") is None
+ assert entitlements.limit_for(None, "seats") is None
+
+
+ ("used", "limit", "expected"),
+ [
+ (0, None, "unlimited"),
+ (10_000, None, "unlimited"),
+ (0, 10, "ok"),
+ (7, 10, "ok"),
+ (8, 10, "warning"),
+ (10, 10, "exhausted"),
+ (11, 10, "exhausted"),
+ (0, 0, "exhausted"),
+ ],
+)
+def test_limit_states(used: int, limit: int | None, expected: str) -> None:
+ assert entitlements.classify(used, limit) == expected
+
+
+def test_uncapped_headroom_reports_none_not_a_plottable_zero() -> None:
+ row = entitlements.Headroom(key="seats", label="Seats", used=3, limit=None, state="unlimited")
+ assert row.remaining is None
+ assert row.pct_used is None
+ assert row.as_dict()["limit"] is None
+
+
+def test_exhausted_headroom_never_reports_negative_remaining() -> None:
+ row = entitlements.Headroom(key="seats", label="Seats", used=12, limit=10, state="exhausted")
+ assert row.remaining == 0
+ assert row.pct_used == 100.0
+
+
+def test_every_usage_query_binds_the_tenant() -> None:
+ """Usage counts are per tenant; the tenant is bound, never formatted in."""
+ for key in entitlements.LIMIT_KEYS:
+ assert ":tenant_id" in key.usage_sql, key.name
+ assert "tenant_id = :tenant_id" in key.usage_sql, key.name
diff --git a/tests/isolation/README.md b/tests/isolation/README.md
index b66639f72..db00de636 100644
--- a/tests/isolation/README.md
+++ b/tests/isolation/README.md
@@ -32,6 +32,26 @@ See `stores.py::STORES`. Each store is one of:
- `container_gated` — live-container A-vs-B replay in `isolation-live.yml`
(Neo4j, Redis, ClickHouse, Kafka).
+## Deliberate cross-tenant reads
+
+The MSSP portfolio surface reads several tenants at once by design, which
+makes it the one place where "filter by the caller's tenant" is not the rule
+and therefore the one place a bypass would look like a feature. It is scoped
+in one place — `services/api/app/services/org_scope.py` — and the aggregates
+in `mssp_portfolio.py` take that scope as a parameter and pass it through
+`require_scope`, which raises on an empty portfolio rather than running SQL
+with no filter. Two gates:
+
+- `services/api/tests/test_org_scope.py` (every PR) — an empty scope refuses,
+ a `?tenant_id=` filter can only narrow, and an AST check fails the build if
+ a new cross-tenant function is added that never calls `require_scope`.
+- `services/api/tests/test_mssp_portfolio_isolation.py` (live Postgres, in
+ `integration.yml`) — seeds two organisations plus an unmanaged tenant and
+ asserts an aggregate run as one operator never returns the others, that an
+ operator with no grants resolves to empty rather than to everything, and
+ that the database itself rejects a grant naming a tenant outside the
+ portfolio.
+
## The parser that enforces ClickHouse isolation is itself a dependency
ClickHouse scoping is produced by `sqlglot` walking a parse tree, so the
diff --git a/tests/isolation/stores.py b/tests/isolation/stores.py
index 95de232aa..6d88248fd 100644
--- a/tests/isolation/stores.py
+++ b/tests/isolation/stores.py
@@ -21,7 +21,9 @@ STORES: tuple[StoreCoverage, ...] = (
StoreCoverage(
"postgres",
"rls",
- "migrations/002_rls.sql + query-layer WHERE tenant_id; services/api/tests/test_*_tenant_isolation.py",
+ "migrations/002_rls.sql + query-layer WHERE tenant_id; services/api/tests/test_*_tenant_isolation.py; "
+ "deliberate cross-tenant reads (MSSP portfolio) resolve their tenant list through org_scope and are "
+ "replayed against live Postgres by test_mssp_portfolio_isolation.py (integration.yml)",
),
StoreCoverage(
"qdrant",