Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Require a child tenant's consent before a parent can act on it (#787)
Beenu Arorac073c8ebc647
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 725374e19..a3050db65 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- **Any authenticated user could disable detection rules inside any other+ tenant.** `_ensure_mssp_parent`, the guard on the MSSP write surface, had+ `pass` for a body. Four routes took a caller-supplied child tenant id and+ wrote it onto a row without checking whose child it was.++ The consequential one was `POST /api/v1/mssp/overrides`. An override with+ `action: "exclude"` is read back by `resolve_effective_rules`, filtered on+ `child_tenant_id == <the reader's tenant>`, and the rule is popped out of the+ set `POST /api/v1/rules/hunt` runs. So naming another tenant's id silently+ deleted a named detection from their hunts, and the victim's only symptom was+ a hunt that stopped matching. Reproduced against the previous commit: a+ tenant's effective ruleset went from one critical cloud rule to zero on an+ override written by an unrelated tenant.++ Closing those four routes alone would not have been enough, because+ `POST /api/v1/mssp/children/{id}/onboard` let anyone *become* the parent+ first — its only check was a `409` when the target already had a parent, so+ every standalone tenant on a deployment was adoptable by any authenticated+ user. Adoption now requires the child to have invited that specific parent by+ setting `settings.mssp_parent_invite` through `PATCH /api/v1/tenants/me/settings`,+ which only ever writes the caller's own row and is gated on `settings:write`.+ The invite is single-use. The child-scoped routes answer `404` rather than+ `403` for a tenant that is not yours, so they cannot enumerate tenant UUIDs.+### Fixed- **Scheduled hunts ran against credentials that could not exist, so every onediff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 2f1ef06ea..7b90777d9 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 100 rows+The last row is the one worth reading first. It is the honest index: 101 rows`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.mdindex 55d9a63b8..8508277da 100644--- a/apps/docs/docs/operations/security.md+++ b/apps/docs/docs/operations/security.md@@ -116,6 +116,21 @@ If `app.current_tenant_id` is not set (e.g. an internal job that needs to operatThe `users` table is excluded from RLS deliberately — it would create a chicken-and-egg problem during authentication. Tenant filtering on `users` is enforced at the application layer through `get_current_user()`.+### MSSP parent/child links require the child's consent++A managed provider can hold other tenants as children (`tenants.parent_tenant_id`), which grants the parent real authority over them: rule packs, per-rule overrides, notes and delegations are all keyed on the child's tenant id, and an override with `action: "exclude"` removes a detection rule from the ruleset that child's hunts run against.++Because that authority is real, the link cannot be created unilaterally. `POST /api/v1/mssp/children/{child_id}/onboard` requires the child to have invited that specific parent:++1. An admin of the tenant being adopted calls `PATCH /api/v1/tenants/me/settings` (gated on `settings:write`, and it only ever writes the caller's own row) with `settings.mssp_parent_invite` set to the parent's tenant UUID.+2. The parent calls the onboard endpoint. The invite is consumed on success, so it is single-use and a stale value cannot re-adopt a tenant that later left.++Without a matching invite the endpoint answers `403` and nothing is written. The four child-scoped write routes (`/mssp/overrides`, `/mssp/notes`, `/mssp/delegations`, `/mssp/rule-packs/{id}/assign`) independently verify that the named child really is the caller's, and answer `404` — never `403` — when it is not, so they cannot be used to discover which tenant UUIDs exist.++:::note What this replaced+The guard on these routes was a function named `_ensure_mssp_parent` whose body was `pass`, and onboarding's only check was a `409` when the target already had a parent. Every standalone tenant on a deployment was therefore adoptable by any authenticated user, after which that user could disable named detection rules inside it. See the `[Unreleased]` section of the changelog.+:::+## Audit loggingEvery state-changing API action is appended to an immutable audit log. The schema lives in [`004_audit_log.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/004_audit_log.sql) (chain columns added in [`043_audit_log_hash_chain.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/043_audit_log_hash_chain.sql)), the model in `services/api/app/models/audit.py`, and the helper that emits events in [`services/api/app/services/audit.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit.py).diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex d0140686e..03f050d24 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -27,6 +27,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Plugin SDK Python/TS/Go | README L79, L193 | `ci.yml :: sdk-*` | PARTIAL (build/test gated; OpenAPI breaking-change now gated via `openapi-breaking.yml`, so a spec change that would break the generated SDKs is caught; per-language generated-client contract-drift is 11b) | Phase 11b || Prompt-injection resistance | (implied by agent claims) | `ci.yml :: python-test` (agents) runs `test_prompt_sanitizer.py`, `test_prompt_envelope.py` and `tests/adversarial/` — a 32-payload corpus grouped by attacker goal, enforcing a recall floor **and** a false-positive ceiling on real security content that reads adversarially. Action-trigger and exfiltration payloads are individually required rather than averaged, because an injected containment turns the SOC into a denial-of-service tool pointed at its own estate | GATED | obfuscation is an arms race and is recorded rather than individually required; two payloads are currently xfail and counted in the recall rate || Cross-tenant isolation (Postgres) | (implied by multi-tenant) | `cross-tenant-rbac.yml` (nightly, 3 endpoints) + `ci.yml` | PARTIAL (Postgres only, compiled-SQL not live DB) | Phase 1.3 |+| An MSSP parent holds only tenants that invited it | operations/security.md (MSSP parent/child links) | `ci.yml` api job (`test_mssp_cross_tenant_authz.py` — the four child-scoped write routes refuse a tenant that is not the caller's child and persist nothing; unknown and unowned are indistinguishable so the routes cannot enumerate tenant UUIDs; onboarding refuses without an invite, refuses an invite addressed to another parent, consumes the invite on success, and refuses self-adoption) | GATED | the guard is unit-level against the route functions; the nightly live-DB `cross-tenant-rbac.yml` sweep does not yet cover the MSSP routes || Cross-tenant isolation (Qdrant/Neo4j/Redis/ClickHouse/Kafka) | (implied by multi-tenant) | `isolation.yml` (offline: read paths construct a tenant scope) + `isolation-live.yml` (live A-vs-B replay: Neo4j property filter, Redis keyspace namespacing, ClickHouse via production `lake_sql.rewrite_for_tenant`, Kafka per-tenant envelope filter) | GATED | - || SAST | README badge (CodeQL) | `codeql.yml` | GATED | - || Dependency CVE scanning | (implied by security) | `security-audit.yml` | GATED | - |@@ -120,7 +121,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 100+- GATED: 101- PARTIAL: 9- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 19500fbc3..f80357b53 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -8716,7 +8716,34 @@ paths:tags:- msspsummary: Onboard Child Tenant- description: Link an existing tenant as a child of the current MSSP tenant.+ description: 'Link an existing tenant as a child, if that tenant invited the+ caller.+++ Adoption previously required nothing but an authenticated session and a++ tenant UUID: the only check was a 409 when the target already had a++ parent, so **every standalone tenant on the deployment was adoptable by++ any user**, and adoption is what makes the child-scoped write routes below++ accept you. That is the root of the escalation ``_require_own_child``++ describes — closing those routes alone would not have helped, because an++ attacker could simply adopt the victim first.+++ Consent is now required and comes from the child''s own side: an admin of++ the tenant being adopted sets ``settings["mssp_parent_invite"]`` to the++ parent''s UUID through ``PATCH /api/v1/tenants/me/settings``. The invite is++ single-use — it is cleared here — so a stale value cannot re-adopt a++ tenant that later left.'operationId: onboard_child_tenant_api_v1_mssp_children__child_id__onboard_postsecurity:- HTTPBearer: []diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.pyindex ed9ff73a3..003441214 100644--- a/services/api/app/api/v1/endpoints/mssp.py+++ b/services/api/app/api/v1/endpoints/mssp.py@@ -2,6 +2,7 @@from __future__ import annotations+import loggingimport uuidfrom datetime import UTC, datetime@@ -16,6 +17,8 @@ from app.db.database import get_dbfrom app.models.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNotefrom app.models.tenant import Tenant, User+logger = logging.getLogger(__name__)+router = APIRouter(prefix="/mssp", tags=["mssp"])@@ -98,12 +101,52 @@ async def onboard_child_tenant(db: AsyncSession = Depends(get_db),current_user: User = Depends(get_current_user),) -> dict[str, str]:- """Link an existing tenant as a child of the current MSSP tenant."""+ """Link an existing tenant as a child, if that tenant invited the caller.++ Adoption previously required nothing but an authenticated session and a+ tenant UUID: the only check was a 409 when the target already had a+ parent, so **every standalone tenant on the deployment was adoptable by+ any user**, and adoption is what makes the child-scoped write routes below+ accept you. That is the root of the escalation ``_require_own_child``+ describes — closing those routes alone would not have helped, because an+ attacker could simply adopt the victim first.++ Consent is now required and comes from the child's own side: an admin of+ the tenant being adopted sets ``settings["mssp_parent_invite"]`` to the+ parent's UUID through ``PATCH /api/v1/tenants/me/settings``. The invite is+ single-use — it is cleared here — so a stale value cannot re-adopt a+ tenant that later left.+ """child = await db.get(Tenant, child_id)if not child:- raise HTTPException(status_code=404, detail="Tenant not found")- if child.parent_tenant_id and child.parent_tenant_id != current_user.tenant_id:- raise HTTPException(status_code=409, detail="Tenant already has a parent")+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found")+ if child.id == current_user.tenant_id:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="A tenant cannot be its own parent")+ if child.parent_tenant_id == current_user.tenant_id:+ # Already ours — idempotent, and it must not consume a fresh invite.+ return {"status": "ok", "child_id": str(child_id)}+ if child.parent_tenant_id:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Tenant already has a parent")++ child_settings = dict(child.settings or {})+ invited = str(child_settings.get(_MSSP_INVITE_SETTING) or "")+ if invited != str(current_user.tenant_id):+ # Deliberately does not say whether an invite exists for someone else.+ logger.warning(+ "mssp.onboard.refused_without_invite parent=%s child=%s",+ str(current_user.tenant_id).replace("\r", "").replace("\n", " ")[:64],+ str(child_id).replace("\r", "").replace("\n", " ")[:64],+ )+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=(+ "That tenant has not invited you to manage it. An admin of the tenant must set "+ f"settings.{_MSSP_INVITE_SETTING} to your tenant id first."+ ),+ )++ child_settings.pop(_MSSP_INVITE_SETTING, None)+ child.settings = child_settings # type: ignore[assignment]child.parent_tenant_id = current_user.tenant_id # type: ignore[assignment]child.mssp_role = "child" # type: ignore[assignment]parent = await db.get(Tenant, current_user.tenant_id)@@ -138,6 +181,7 @@ async def create_note(db: AsyncSession = Depends(get_db),current_user: User = Depends(get_current_user),) -> MSSPTenantNote:+ await _require_own_child(db, current_user, body.child_id)note = MSSPTenantNote(parent_id=current_user.tenant_id,child_id=body.child_id,@@ -177,6 +221,7 @@ async def create_delegation(db: AsyncSession = Depends(get_db),current_user: User = Depends(get_current_user),) -> MSSPDelegation:+ await _require_own_child(db, current_user, body.child_tenant_id)delegation = MSSPDelegation(parent_tenant_id=current_user.tenant_id,child_tenant_id=body.child_tenant_id,@@ -351,9 +396,44 @@ class EffectiveRuleCountOut(BaseModel):excluded: int-def _ensure_mssp_parent(current_user: User) -> None:- """Lightweight guard — a parent tenant is one that has (or can have) children."""- pass+#: Key a child tenant's own admin sets in ``tenants.settings`` to consent to+#: being managed, holding the UUID of the parent they are inviting.+#:+#: Consent lives in the child's settings rather than in a new table because+#: ``PATCH /api/v1/tenants/me/settings`` already writes only the caller's own+#: row and is gated on ``settings:write``. That makes the invite unforgeable by+#: construction: the only principal who can name a parent is an admin of the+#: tenant being adopted.+_MSSP_INVITE_SETTING = "mssp_parent_invite"+++async def _require_own_child(+ db: AsyncSession,+ current_user: User,+ child_id: uuid.UUID,+) -> Tenant:+ """Return ``child_id`` only if it is a child of the caller's tenant.++ Raises 404 — not 403 — for both "no such tenant" and "not yours", so the+ endpoint cannot be used to enumerate which tenant UUIDs exist.++ This replaces ``_ensure_mssp_parent``, whose body was ``pass``. Four write+ routes took a caller-supplied ``child_tenant_id`` and wrote it straight+ onto a row. The one that mattered was ``create_rule_override``: an override+ with ``action="exclude"`` is read back by+ :func:`app.services.mssp_rule_resolver.resolve_effective_rules`, filtered on+ ``child_tenant_id == <the victim's tenant>``, and pops the rule out of the+ ruleset that `POST /rules/hunt` runs. Any authenticated user of any tenant+ could therefore disable a named detection rule inside any other tenant, and+ the victim's only symptom was a hunt that stopped matching.+ """+ child = await db.get(Tenant, child_id)+ if child is None or child.parent_tenant_id != current_user.tenant_id:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="Child tenant not found",+ )+ return child@router.get("/rule-packs", response_model=list[RulePackOut])@@ -362,7 +442,6 @@ async def list_rule_packs(current_user: User = Depends(get_current_user),) -> list[MSSPRulePack]:"""List all rule packs owned by the current parent tenant."""- _ensure_mssp_parent(current_user)result = await db.execute(select(MSSPRulePack).where(MSSPRulePack.parent_tenant_id == current_user.tenant_id).order_by(MSSPRulePack.created_at.desc()))@@ -376,7 +455,6 @@ async def create_rule_pack(current_user: User = Depends(get_current_user),) -> MSSPRulePack:"""Create a new rule pack (parent tenant only)."""- _ensure_mssp_parent(current_user)pack = MSSPRulePack(parent_tenant_id=current_user.tenant_id,name=body.name,@@ -486,6 +564,9 @@ async def assign_pack_to_child(pack = await db.get(MSSPRulePack, pack_id)if not pack or pack.parent_tenant_id != current_user.tenant_id:raise HTTPException(status_code=404, detail="Rule pack not found")+ # Pack ownership was checked; the assignment target was not, so a pack the+ # caller legitimately owns could be pushed into a tenant they do not.+ await _require_own_child(db, current_user, body.child_tenant_id)assignment = MSSPRulePackAssignment(pack_id=pack_id,@@ -505,9 +586,12 @@ async def create_rule_override(db: AsyncSession = Depends(get_db),current_user: User = Depends(get_current_user),) -> MSSPRuleOverride:- _ensure_mssp_parent(current_user)if body.action not in ("exclude", "customize"):raise HTTPException(status_code=422, detail="action must be 'exclude' or 'customize'")+ # The severe one. An "exclude" override is read back by the effective-rule+ # resolver keyed on the *child's* tenant id and removes the rule from the+ # ruleset `POST /rules/hunt` runs for them.+ await _require_own_child(db, current_user, body.child_tenant_id)override = MSSPRuleOverride(parent_tenant_id=current_user.tenant_id,child_tenant_id=body.child_tenant_id,diff --git a/services/api/tests/test_mssp_cross_tenant_authz.py b/services/api/tests/test_mssp_cross_tenant_authz.pynew file mode 100644index 000000000..2db5e1f3a--- /dev/null+++ b/services/api/tests/test_mssp_cross_tenant_authz.py@@ -0,0 +1,306 @@+"""Cross-tenant authorization on the MSSP surface.++The hole these tests close+~~~~~~~~~~~~~~~~~~~~~~~~~~++``_ensure_mssp_parent`` had ``pass`` for a body, and four MSSP write routes+took a caller-supplied child tenant id and wrote it onto a row without ever+checking whose child it was.++The one that mattered is ``create_rule_override``. An override with+``action="exclude"`` is read back by+``app.services.mssp_rule_resolver.resolve_effective_rules``, filtered on+``MSSPRuleOverride.child_tenant_id == <the reader's tenant>``, and the rule is+popped out of the set that ``POST /rules/hunt`` runs. So any authenticated+user of any tenant could name any other tenant and silently delete a detection+rule from that tenant's hunts. The victim's only symptom is a hunt that stops+matching.++Closing those four routes alone would not have been enough, because+``onboard_child_tenant`` let anyone *become* the parent first: its only check+was a 409 when the target already had a parent, so every standalone tenant on+the deployment was adoptable by any authenticated user. Adoption now requires+the child to have invited that specific parent from its own settings.++Every test here fails against the previous implementation. The guard tests+fail because the routes returned 201 and wrote the row; the adoption tests+fail because onboarding returned 200 and reparented the tenant.+"""++from __future__ import annotations++import uuid+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+from app.api.v1.endpoints import mssp+from app.api.v1.endpoints.mssp import (+ _MSSP_INVITE_SETTING,+ _require_own_child,+ assign_pack_to_child,+ create_delegation,+ create_note,+ create_rule_override,+ onboard_child_tenant,+)+from fastapi import HTTPException++PARENT = uuid.uuid4()+OTHER_PARENT = uuid.uuid4()+++def _tenant(tid: uuid.UUID, *, parent: uuid.UUID | None = None, settings: dict[str, Any] | None = None) -> Any:+ t = MagicMock()+ t.id = tid+ t.parent_tenant_id = parent+ t.settings = settings+ t.mssp_role = "child" if parent else "standalone"+ return t+++def _user(tenant_id: uuid.UUID = PARENT) -> Any:+ u = MagicMock()+ u.id = uuid.uuid4()+ u.tenant_id = tenant_id+ return u+++def _db(get_returns: dict[uuid.UUID, Any] | None = None) -> Any:+ """AsyncSession double. ``db.get(Model, pk)`` resolves from a pk map."""+ table = get_returns or {}++ async def _get(_model: Any, pk: Any) -> Any:+ return table.get(pk)++ db = MagicMock()+ db.get = AsyncMock(side_effect=_get)+ db.add = MagicMock()+ db.commit = AsyncMock()+ db.refresh = AsyncMock()+ return db+++class TestRequireOwnChild:+ async def test_accepts_a_real_child(self) -> None:+ child_id = uuid.uuid4()+ child = _tenant(child_id, parent=PARENT)+ got = await _require_own_child(_db({child_id: child}), _user(), child_id)+ assert got is child++ async def test_rejects_a_tenant_owned_by_someone_else(self) -> None:+ child_id = uuid.uuid4()+ db = _db({child_id: _tenant(child_id, parent=OTHER_PARENT)})+ with pytest.raises(HTTPException) as exc:+ await _require_own_child(db, _user(), child_id)+ assert exc.value.status_code == 404++ async def test_rejects_a_standalone_tenant(self) -> None:+ child_id = uuid.uuid4()+ db = _db({child_id: _tenant(child_id, parent=None)})+ with pytest.raises(HTTPException) as exc:+ await _require_own_child(db, _user(), child_id)+ assert exc.value.status_code == 404++ async def test_unknown_and_unowned_are_indistinguishable(self) -> None:+ """Both answer 404 with the same detail, so the route cannot be used to+ enumerate which tenant UUIDs exist on the deployment."""+ unknown = uuid.uuid4()+ foreign_id = uuid.uuid4()+ foreign_db = _db({foreign_id: _tenant(foreign_id, parent=OTHER_PARENT)})++ with pytest.raises(HTTPException) as unknown_exc:+ await _require_own_child(_db({}), _user(), unknown)+ with pytest.raises(HTTPException) as foreign_exc:+ await _require_own_child(foreign_db, _user(), foreign_id)++ assert unknown_exc.value.status_code == foreign_exc.value.status_code == 404+ assert unknown_exc.value.detail == foreign_exc.value.detail+++class TestWriteRoutesRefuseForeignTenants:+ """Each of these returned 201 and persisted the row before the fix."""++ async def test_rule_override_refuses_a_tenant_that_is_not_your_child(self) -> None:+ victim = uuid.uuid4()+ db = _db({victim: _tenant(victim, parent=OTHER_PARENT)})+ body = MagicMock(+ child_tenant_id=victim, rule_id=uuid.uuid4(), action="exclude", note=None, severity_override=None, parameter_overrides=None+ )++ with pytest.raises(HTTPException) as exc:+ await create_rule_override(body=body, db=db, current_user=_user())++ assert exc.value.status_code == 404+ db.add.assert_not_called()+ db.commit.assert_not_awaited()++ async def test_rule_override_validates_action_before_touching_the_db(self) -> None:+ """A bad action is a 422 and must not become a 404 about the tenant."""+ body = MagicMock(child_tenant_id=uuid.uuid4(), rule_id=uuid.uuid4(), action="delete-everything")+ db = _db({})++ with pytest.raises(HTTPException) as exc:+ await create_rule_override(body=body, db=db, current_user=_user())++ assert exc.value.status_code == 422++ async def test_note_refuses_a_foreign_tenant(self) -> None:+ victim = uuid.uuid4()+ db = _db({victim: _tenant(victim, parent=OTHER_PARENT)})+ body = MagicMock(child_id=victim, body="recon notes")++ with pytest.raises(HTTPException) as exc:+ await create_note(body=body, db=db, current_user=_user())++ assert exc.value.status_code == 404+ db.add.assert_not_called()++ async def test_delegation_refuses_a_foreign_tenant(self) -> None:+ """Otherwise a user could mint themselves a role over any tenant."""+ victim = uuid.uuid4()+ db = _db({victim: _tenant(victim, parent=OTHER_PARENT)})+ body = MagicMock(child_tenant_id=victim, granted_role="admin", expires_at=None)++ with pytest.raises(HTTPException) as exc:+ await create_delegation(body=body, db=db, current_user=_user())++ assert exc.value.status_code == 404+ db.add.assert_not_called()++ async def test_pack_assignment_refuses_a_foreign_tenant(self) -> None:+ """Pack ownership was already checked; the assignment target was not,+ so an owned pack could be pushed into an unowned tenant."""+ victim = uuid.uuid4()+ pack_id = uuid.uuid4()+ pack = MagicMock(id=pack_id, parent_tenant_id=PARENT)+ db = _db({pack_id: pack, victim: _tenant(victim, parent=OTHER_PARENT)})+ body = MagicMock(child_tenant_id=victim, enabled=True, parameter_overrides=None)++ with pytest.raises(HTTPException) as exc:+ await assign_pack_to_child(pack_id=pack_id, body=body, db=db, current_user=_user())++ assert exc.value.status_code == 404+ db.add.assert_not_called()++ async def test_pack_assignment_still_works_for_a_real_child(self) -> None:+ child_id = uuid.uuid4()+ pack_id = uuid.uuid4()+ db = _db({pack_id: MagicMock(id=pack_id, parent_tenant_id=PARENT), child_id: _tenant(child_id, parent=PARENT)})+ body = MagicMock(child_tenant_id=child_id, enabled=True, parameter_overrides=None)++ await assign_pack_to_child(pack_id=pack_id, body=body, db=db, current_user=_user())++ db.add.assert_called_once()+ db.commit.assert_awaited_once()+++class TestOnboardingRequiresConsent:+ async def test_refuses_an_uninvited_tenant(self) -> None:+ """The escalation root: every standalone tenant used to be adoptable."""+ victim = uuid.uuid4()+ target = _tenant(victim, parent=None, settings={})+ db = _db({victim: target})++ with pytest.raises(HTTPException) as exc:+ await onboard_child_tenant(child_id=victim, db=db, current_user=_user())++ assert exc.value.status_code == 403+ assert target.parent_tenant_id is None+ db.commit.assert_not_awaited()++ async def test_refuses_when_no_settings_at_all(self) -> None:+ victim = uuid.uuid4()+ db = _db({victim: _tenant(victim, parent=None, settings=None)})++ with pytest.raises(HTTPException) as exc:+ await onboard_child_tenant(child_id=victim, db=db, current_user=_user())++ assert exc.value.status_code == 403++ async def test_refuses_an_invite_addressed_to_a_different_parent(self) -> None:+ victim = uuid.uuid4()+ target = _tenant(victim, parent=None, settings={_MSSP_INVITE_SETTING: str(OTHER_PARENT)})+ db = _db({victim: target})++ with pytest.raises(HTTPException) as exc:+ await onboard_child_tenant(child_id=victim, db=db, current_user=_user())++ assert exc.value.status_code == 403+ assert target.parent_tenant_id is None++ async def test_accepts_an_invite_naming_the_caller(self) -> None:+ child_id = uuid.uuid4()+ child = _tenant(child_id, parent=None, settings={_MSSP_INVITE_SETTING: str(PARENT), "keep": "me"})+ parent_row = _tenant(PARENT)+ db = _db({child_id: child, PARENT: parent_row})++ result = await onboard_child_tenant(child_id=child_id, db=db, current_user=_user())++ assert result["status"] == "ok"+ assert child.parent_tenant_id == PARENT+ assert child.mssp_role == "child"+ assert parent_row.mssp_role == "parent"+ db.commit.assert_awaited_once()++ async def test_invite_is_single_use(self) -> None:+ """A stale invite must not silently re-adopt a tenant that later left."""+ child_id = uuid.uuid4()+ child = _tenant(child_id, parent=None, settings={_MSSP_INVITE_SETTING: str(PARENT), "keep": "me"})+ db = _db({child_id: child, PARENT: _tenant(PARENT)})++ await onboard_child_tenant(child_id=child_id, db=db, current_user=_user())++ assert _MSSP_INVITE_SETTING not in child.settings+ # Unrelated settings survive — the route must not clobber the object.+ assert child.settings["keep"] == "me"++ async def test_a_tenant_cannot_adopt_itself(self) -> None:+ db = _db({PARENT: _tenant(PARENT)})++ with pytest.raises(HTTPException) as exc:+ await onboard_child_tenant(child_id=PARENT, db=db, current_user=_user())++ assert exc.value.status_code == 422++ async def test_already_owned_child_is_idempotent_and_consumes_no_invite(self) -> None:+ child_id = uuid.uuid4()+ child = _tenant(child_id, parent=PARENT, settings={_MSSP_INVITE_SETTING: str(PARENT)})+ db = _db({child_id: child})++ result = await onboard_child_tenant(child_id=child_id, db=db, current_user=_user())++ assert result["status"] == "ok"+ assert child.settings[_MSSP_INVITE_SETTING] == str(PARENT)+ db.commit.assert_not_awaited()++ async def test_tenant_owned_by_another_parent_still_conflicts(self) -> None:+ child_id = uuid.uuid4()+ db = _db({child_id: _tenant(child_id, parent=OTHER_PARENT, settings={_MSSP_INVITE_SETTING: str(PARENT)})})++ with pytest.raises(HTTPException) as exc:+ await onboard_child_tenant(child_id=child_id, db=db, current_user=_user())++ assert exc.value.status_code == 409++ async def test_unknown_tenant_is_404(self) -> None:+ with pytest.raises(HTTPException) as exc:+ await onboard_child_tenant(child_id=uuid.uuid4(), db=_db({}), current_user=_user())+ assert exc.value.status_code == 404++ async def test_refusal_is_logged_without_newline_injection(self, caplog: pytest.LogCaptureFixture) -> None:+ victim = uuid.uuid4()+ db = _db({victim: _tenant(victim, parent=None, settings={})})++ with caplog.at_level("WARNING", logger=mssp.__name__):+ with pytest.raises(HTTPException):+ await onboard_child_tenant(child_id=victim, db=db, current_user=_user())++ assert any("mssp.onboard.refused_without_invite" in r.message for r in caplog.records)+++class TestNoOpGuardIsGone:+ def test_ensure_mssp_parent_no_longer_exists(self) -> None:+ """A function named `_ensure_mssp_parent` whose body is `pass` reads as+ an authorization check in every call site and enforces nothing."""+ assert not hasattr(mssp, "_ensure_mssp_parent")