Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(gateway): make workspace ownership an owner-only decision (CHOO-2722)
Petr Bauchaf22ad1fdd53
diff --git a/core/switch_core/authz.py b/core/switch_core/authz.pyindex f21eb4947..da6a15087 100644--- a/core/switch_core/authz.py+++ b/core/switch_core/authz.py@@ -68,6 +68,19 @@ def administers_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:return is_operator or tenant_role in TENANT_ADMIN_ROLES+def owns_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:+ """Whether a caller may dispose of the tenant they hold `tenant_role` in.++ Narrower than `administers_tenant` on purpose. An `admin` runs a workspace;+ an `owner` decides who else gets to. The two collapse into one bit for+ everything inside a workspace — rooms, agents, references — but not for the+ ownership set itself: if an admin may grant `owner`, demote an owner, or+ remove one, then an admin may take the workspace, and each of those steps+ passes a last-owner guard on its own. Gate those three on this.+ """+ return is_operator or tenant_role == "owner"++@runtime_checkableclass Authorizable(Protocol):"""Structural interface for any entity `can` arbitrates over.diff --git a/core/switch_core/db/stores/invitation_store.py b/core/switch_core/db/stores/invitation_store.pyindex ac433bad8..0e6b73d1e 100644--- a/core/switch_core/db/stores/invitation_store.py+++ b/core/switch_core/db/stores/invitation_store.py@@ -164,15 +164,3 @@ class InvitationStore:invitation.revoked_at = datetime.now(UTC)await session.flush()return invitation-- async def consume(- self, session: AsyncSession, invitation: Invitation- ) -> Invitation:- """Record one use of `invitation`.-- Called only after every validity check (expiry, revocation, email,- remaining uses) has already passed; it does not repeat any of them.- """- invitation.uses_remaining -= 1- await session.flush()- return invitationdiff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 4071c2dc4..51b0d2283 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -6,7 +6,7 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.authz import administers_tenant+from switch_core.authz import administers_tenant, owns_tenantfrom switch_core.db.models import (OidcIdentity,TenantMember,@@ -384,3 +384,23 @@ class UserStore:)role = await self.tenant_role(session, tenant_id, user.id)return administers_tenant(is_operator=user.role == "admin", tenant_role=role)++ async def owns(self, session: AsyncSession, user: User) -> bool:+ """Whether `user` may decide who owns the tenant bound to `session`'s+ context — the operator bypass, or an `owner` membership in it.++ The same composition as `administers`, over `authz.owns_tenant`; see+ there for why the two are separate bits rather than one.++ Raises:+ RuntimeError: no tenant is bound, for the same reason+ `administers` raises.+ """+ tenant_id = current_tenant_id()+ if tenant_id is None:+ raise RuntimeError(+ "owns requires a bound tenant; whether someone owns a "+ "workspace is only answerable about a particular one"+ )+ role = await self.tenant_role(session, tenant_id, user.id)+ return owns_tenant(is_operator=user.role == "admin", tenant_role=role)diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 8d9d4ad52..2aff989b4 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -182,7 +182,7 @@ async def get_authenticated_caller() -> AuthenticatedCaller:"""Like `get_authenticated_user_id`, but with the caller's own email too.- Backs `POST /invitations/{token}/accept` (`gateway/tenants.py`), which has+ Backs `POST /invitations/accept` (`gateway/tenants.py`), which hasto check an email-bound invitation against the caller's *current* addressbefore any tenant is bound — the same "no tenant chosen yet" shape as`get_authenticated_user_id`, plus one more column of the same global,@@ -461,6 +461,20 @@ async def get_tenant_is_admin(return await user_store.administers(session, user)+async def get_tenant_is_owner(+ session: Annotated[AsyncSession, Depends(get_session)],+ user: Annotated[User, Depends(get_current_user)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+) -> bool:+ """Whether `user` may decide who owns the tenant this request is bound to.++ Strictly narrower than ``get_tenant_is_admin`` — see+ ``authz.owns_tenant``. A route that changes the ownership set needs both:+ ``require_tenant_admin`` to get in, this to make the call.+ """+ return await user_store.owns(session, user)++async def require_tenant_admin(user: Annotated[User, Depends(get_current_user)],is_admin: Annotated[bool, Depends(get_tenant_is_admin)],diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex a9a81fc21..bc67cfe2e 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -682,10 +682,20 @@ class InvitationCreateRequest(BaseModel):# None mints a shareable link; set, the invitation is addressed to one# email and accepting it with any other is refused.email: str | None = None- expires_in_hours: int = Field(default=168, gt=0)+ # Bounded above as well as below: `timedelta` raises `OverflowError` past+ # roughly 2.4e9 hours, so an unbounded value turns a bad request into a 500.+ # A year is well beyond any legitimate invitation's life.+ expires_in_hours: int = Field(default=168, gt=0, le=8760)uses_remaining: int = Field(default=1, ge=1)+class InvitationAcceptRequest(BaseModel):+ # In the body rather than the path: a URL travels through proxy logs,+ # browser history and `Referer` headers, and this one is a bearer+ # credential.+ token: str++class InvitationDetail(BaseModel):id: strrole: strdiff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex fbc36c2cd..45f84901c 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -1,6 +1,7 @@from __future__ import annotationsimport hashlib+import loggingimport refrom datetime import UTC, datetime, timedeltafrom typing import Annotated@@ -16,13 +17,17 @@ from switch_core.db.models import Invitation, Tenant, TenantMember, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.invitation_store import InvitationStore+from switch_core.db.stores.invitation_store import (+ InvitationNotUsableError,+ InvitationStore,+)from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (AuthenticatedCaller,get_authenticated_caller,get_authenticated_user_id,get_current_user,+ get_tenant_is_owner,is_tenant_member,list_tenant_memberships,require_tenant_admin,@@ -43,6 +48,7 @@ from switch_core.gateway.dependencies import (get_user_store,)from switch_core.gateway.schemas import (+ InvitationAcceptRequest,InvitationCreateRequest,InvitationCreateResponse,InvitationDetail,@@ -54,6 +60,8 @@ from switch_core.gateway.schemas import ()from switch_core.tenant_context import current_tenant_id+logger = logging.getLogger(__name__)+router = APIRouter()TENANT_MEMBER_ROLES = ("owner", "admin", "member")@@ -119,6 +127,23 @@ def _member_detail(user: User, membership: TenantMember) -> MemberDetail:)+def _require_owner(is_owner: bool, action: str) -> None:+ """Raise 403 unless the caller owns the bound tenant.++ The three actions this guards — granting `owner`, changing an owner's+ role, removing an owner — are the ones that move a workspace's ownership+ set, and none of them is reachable by a last-owner guard: an admin who+ promotes themselves first leaves two owners standing at every subsequent+ step, so each individual request looks safe while the sequence takes the+ workspace. `require_tenant_admin` still gates getting this far; this is+ the narrower bit on top (`authz.owns_tenant`).+ """+ if not is_owner:+ raise HTTPException(+ status_code=403, detail=f"Only a workspace owner may {action}"+ )++def _require_invitation_usable(invitation: Invitation, caller_email: str) -> None:"""Raise 403 unless `invitation` may still be accepted by `caller_email`.@@ -126,10 +151,17 @@ def _require_invitation_usable(invitation: Invitation, caller_email: str) -> Nonexpiry, remaining uses and an addressed email are four separate ways aninvitation stops working, none of them optional(`docs/old/multi-tenancy-phase2-tenants.md`, §5).++ This is for the message, not for the decision. Three of the four gates are+ re-checked inside `InvitationStore.consume`'s own `UPDATE`, which is what+ actually settles a race between two acceptances; read here, they can only+ say why an invitation that is already unusable is unusable, in words the+ invitee can act on. The fourth — the addressed email — is the one gate+ only this function applies, because the store has no idea who is asking."""if invitation.revoked_at is not None:raise HTTPException(status_code=403, detail="This invitation has been revoked")- if invitation.expires_at < datetime.now(UTC): # type: ignore[operator]+ if invitation.expires_at < datetime.now(UTC):raise HTTPException(status_code=403, detail="This invitation has expired")if invitation.uses_remaining <= 0:raise HTTPException(@@ -183,6 +215,16 @@ async def create_tenant(admin client every other tenant does. The membership row is not part ofthat call (it provisions the tenant, not any particular person's place init), so it is written here, in its own session bound to the new tenant.++ Two transactions, therefore, and the gap between them is real: the tenant+ is committed before the membership is attempted, so a failure in the+ second leaves a workspace nobody belongs to and a slug nobody can reuse.+ It is not folded into one because the tenant row has to be committed+ before `ensure_system_client` can provision against it, and that call is+ inside the seam. What the gap gets instead is a log line naming the+ workspace and the person who should have owned it, because the alternative+ — a 500 with the orphan unrecorded — is the silent degradation this+ codebase refuses. An operator repairs it by inserting the membership."""slug = _derive_slug(req.name)try:@@ -192,11 +234,22 @@ async def create_tenant(status_code=409, detail=f"Slug already taken: {slug}") from exc- async with tenant_session(session_factory, tenant.id) as session:- await user_store.add_membership(- session, tenant_id=tenant.id, user_id=user_id, role="owner"+ try:+ async with tenant_session(session_factory, tenant.id) as session:+ await user_store.add_membership(+ session, tenant_id=tenant.id, user_id=user_id, role="owner"+ )+ await session.commit()+ except Exception:+ logger.error(+ "Workspace %s (slug %s) was created but its owner membership for "+ "user %s was not written: it now has no members and its slug is "+ "taken. Insert the membership to repair it.",+ tenant.id,+ slug,+ user_id,)- await session.commit()+ raisereturn TenantMembershipResponse(id=tenant.id, slug=tenant.slug, name=tenant.name, role="owner"@@ -248,11 +301,19 @@ async def create_invitation(session: Annotated[AsyncSession, Depends(get_session)],invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],user: Annotated[User, Depends(require_tenant_admin)],+ is_owner: Annotated[bool, Depends(get_tenant_is_owner)],) -> InvitationCreateResponse:- """Mint an invitation to the bound tenant. `owner`/`admin` only."""+ """Mint an invitation to the bound tenant. `owner`/`admin` only.++ An `owner` invitation is owner-only: minting one is granting ownership+ with a step of indirection, so it answers to the same gate the direct+ grant does (`_require_owner`).+ """_require_bound_tenant(tenant_id)if req.role not in TENANT_MEMBER_ROLES:raise HTTPException(status_code=400, detail=f"Invalid role: {req.role}")+ if req.role == "owner":+ _require_owner(is_owner, "invite another owner")expires_at = datetime.now(UTC) + timedelta(hours=req.expires_in_hours)invitation, token = await invitation_store.create(@@ -298,9 +359,9 @@ async def revoke_invitation(return _invitation_detail(invitation)[email protected]("/invitations/{token}/accept")[email protected]("/invitations/accept")async def accept_invitation(- token: str,+ req: InvitationAcceptRequest,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session_factory: Annotated[async_sessionmaker[AsyncSession], Depends(get_session_factory)@@ -320,8 +381,19 @@ async def accept_invitation(own work inside a fresh `tenant_session` bound to exactly that tenant,rather than touching the request's session at all(`docs/old/multi-tenancy-phase2-tenants.md`, §5).++ The token arrives in the body, not the path: it is a bearer credential,+ and a path segment is written to proxy and access logs, kept in browser+ history, and sent onward in `Referer`.++ A use is spent only when a membership is actually granted. Accepting an+ invitation you already hold is a no-op that returns your existing role —+ a double-clicked shared link must not cost the invite a slot — and the+ `consume` that does spend one is a conditional `UPDATE` that arbitrates+ between simultaneous acceptances, so a single-use link grants exactly one+ membership however many people race for it."""- token_hash = hashlib.sha256(token.encode()).hexdigest()+ token_hash = hashlib.sha256(req.token.encode()).hexdigest()tenant_id = await tenant_of_invitation_token(session_factory, token_hash)if tenant_id is None:raise HTTPException(status_code=404, detail="Invitation not found")@@ -333,12 +405,19 @@ async def accept_invitation(_require_invitation_usable(invitation, caller.email)existing_role = await user_store.tenant_role(session, tenant_id, caller.id)- role = existing_role if existing_role is not None else invitation.roleif existing_role is None:+ try:+ await invitation_store.consume(session, invitation.id)+ except InvitationNotUsableError as exc:+ raise HTTPException(+ status_code=403, detail="This invitation has already been used"+ ) from exc+ role = invitation.roleawait user_store.add_membership(session, tenant_id=tenant_id, user_id=caller.id, role=role)- await invitation_store.consume(session, invitation)+ else:+ role = existing_roletenant = await session.get(Tenant, tenant_id)assert tenant is not None@@ -374,11 +453,18 @@ async def update_member_role(session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],_admin: Annotated[User, Depends(require_tenant_admin)],+ is_owner: Annotated[bool, Depends(get_tenant_is_owner)],) -> MemberDetail:"""Change a member's role. `owner`/`admin` only.- Refuses to demote the last `owner`: with no workspace deletion in this- phase, there is no legitimate route to a workspace with none.+ Both ends of the ownership set are owner-only: an admin may promote a+ member to admin, but not to `owner`, and may not touch an existing+ owner's role at all. See `_require_owner` for what an admin who could do+ either would be able to do in three requests.++ Refuses to demote the last `owner` on top of that: with no workspace+ deletion in this phase, there is no legitimate route to a workspace with+ none."""_require_bound_tenant(tenant_id)if req.role not in TENANT_MEMBER_ROLES:@@ -388,7 +474,11 @@ async def update_member_role(if membership is None:raise HTTPException(status_code=404, detail="Not a member of this tenant")+ if req.role == "owner" and membership.role != "owner":+ _require_owner(is_owner, "grant ownership")+if membership.role == "owner" and req.role != "owner":+ _require_owner(is_owner, "change an owner's role")if await user_store.count_owners(session) <= 1:raise HTTPException(status_code=409, detail="Cannot demote the last owner")@@ -410,10 +500,12 @@ async def remove_member(api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],_admin: Annotated[User, Depends(require_tenant_admin)],+ is_owner: Annotated[bool, Depends(get_tenant_is_owner)],) -> dict[str, bool]:"""Remove a member from the bound tenant. `owner`/`admin` only.- Refuses to remove the last `owner`, same as demoting one.+ Removing an *owner* is owner-only, the same as demoting one and for the+ same reason (`_require_owner`), and refuses on the last owner besides.Removal also revokes what the member's own credentials in this tenant letthem do here, in the same transaction as the membership row going away —@@ -431,16 +523,21 @@ async def remove_member(another — but deleting an agent is not, and a member removal is routineenough, including by mistake, that it must not be the thing that makes anirreversible call about shared infrastructure. An admin who hits this- reassigns or deletes those agents deliberately, with the agent in front of- them, then removes the member.+ deletes those agents deliberately, with the agent in front of them, then+ removes the member. The 409 says exactly that and nothing more: there is+ no route that reassigns an agent's owner in this phase, so offering+ reassignment as the way out would send an admin looking for a button that+ does not exist."""_require_bound_tenant(tenant_id)membership = await session.get(TenantMember, (tenant_id, user_id))if membership is None:raise HTTPException(status_code=404, detail="Not a member of this tenant")- if membership.role == "owner" and await user_store.count_owners(session) <= 1:- raise HTTPException(status_code=409, detail="Cannot remove the last owner")+ if membership.role == "owner":+ _require_owner(is_owner, "remove an owner")+ if await user_store.count_owners(session) <= 1:+ raise HTTPException(status_code=409, detail="Cannot remove the last owner")owned_agents = await agent_store.get_by_owner(session, user_id)if owned_agents:@@ -449,7 +546,7 @@ async def remove_member(status_code=409,detail=("Cannot remove: this member owns agents in this tenant — "- f"reassign or delete them first: {names}"+ f"delete them first: {names}"),)diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.pyindex 31895eb62..d362550c4 100644--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py@@ -31,6 +31,7 @@ from fastapi import APIRouterimport switch_core.gateway as gateway_packagefrom switch_core.gateway.auth import (+ get_authenticated_caller,get_authenticated_user_id,get_current_user,require_admin,@@ -50,15 +51,39 @@ _ROUTES_WITH_NO_TENANT_BOUND = {("POST", "/tenants/{tenant_id}/switch"),}-# The only routes that may authenticate a caller without resolving a tenant at-# all. `get_authenticated_user_id` verifies the cookie and stops there, so it-# is a reachable way past the membership check `get_current_user` performs —-# every case of `_resolve_tenant_id`, including the two 403s. These two need-# it because a caller with several memberships and no selection cannot reach-# `get_current_user` by construction; nothing else has that excuse.-_ROUTES_AUTHENTICATED_WITHOUT_RESOLVING_A_TENANT = {+# Every route that does not resolve a tenant, for any reason. `get_current_user`+# is the only dependency that performs the membership check in+# `_resolve_tenant_id`, so a route without it authorizes against no workspace —+# whether it skipped the check deliberately (`get_authenticated_user_id`,+# `get_authenticated_caller`) or simply has no caller yet (login, the OIDC+# handshake).+#+# The predicate is the absence of `get_current_user` rather than the presence of+# any particular alternative, because the alternatives keep arriving: keying on+# `get_system_session` missed the routes that take `get_session_factory` and open+# their own, and keying on `get_authenticated_user_id` missed+# `get_authenticated_caller`. This way the next door is a failing test rather+# than a route nobody counted. `_ROUTES_WITH_NO_TENANT_BOUND` is a strict subset.+_ROUTES_THAT_NEVER_BIND_A_TENANT = {+ # No caller yet: the sign-in surface and what it hands back.+ ("GET", "/auth/config"),+ ("GET", "/auth/oidc/login"),+ ("GET", "/auth/oidc/callback"),+ ("POST", "/auth/login"),+ ("POST", "/auth/logout"),+ # A deployment-wide constant — the agent types this build knows about.+ # Nothing tenant-specific to scope it to.+ ("GET", "/known-types"),+ # A caller with several memberships and no selection cannot reach+ # `get_current_user` by construction, and these are the routes such a+ # caller needs: list the workspaces, make one, pick one.("GET", "/tenants"),+ ("POST", "/tenants"),("POST", "/tenants/{tenant_id}/switch"),+ # Accepting an invitation binds the tenant the *token* names, which is+ # neither the one on the caller's session nor one they belong to yet. It+ # opens its own `tenant_session` around that id — see `accept_invitation`.+ ("POST", "/invitations/accept"),}@@ -139,16 +164,38 @@ def test_the_routes_with_no_tenant_bound_are_exactly_these_three() -> None:} == _ROUTES_WITH_NO_TENANT_BOUND-def test_the_routes_skipping_tenant_resolution_are_exactly_these_two() -> None:- """`get_authenticated_user_id` is the newest way past the tenant check, and- the one with the least around it: no membership read, no scoped session,- nothing a policy would refuse. Pinned by the same reasoning- `test_tenant_exemption_allowlist` gives for the `SECURITY DEFINER`- lookups — what matters is that it is reachable, not that today's two- callers happen to be the right ones."""+def test_the_routes_that_never_bind_a_tenant_are_exactly_these() -> None:+ """Pinned by the same reasoning `test_tenant_exemption_allowlist` gives for+ the `SECURITY DEFINER` lookups — what matters is that skipping the tenant+ check is *reachable*, not that today's callers happen to be the right ones.+ A route that lands here has no workspace to authorize against and has to+ say, in its own docstring, what it does instead."""assert {- route.key for route in ROUTES if get_authenticated_user_id in route.calls- } == _ROUTES_AUTHENTICATED_WITHOUT_RESOLVING_A_TENANT+ route.key for route in ROUTES if get_current_user not in route.calls+ } == _ROUTES_THAT_NEVER_BIND_A_TENANT+++def test_the_routes_with_no_tenant_bound_do_not_bind_a_tenant() -> None:+ """The two exemptions agree: anything allowed to open an unscoped session+ is, necessarily, a route that resolves no tenant."""+ assert _ROUTES_WITH_NO_TENANT_BOUND <= _ROUTES_THAT_NEVER_BIND_A_TENANT+++def test_skipping_tenant_resolution_is_only_reached_by_a_known_dependency() -> None:+ """`get_authenticated_user_id` and `get_authenticated_caller` verify the+ cookie and stop there — no membership read, no scoped session, nothing a+ policy would refuse. They are the only authenticated way into the set+ above; a route that invents a third is caught here rather than inheriting+ the exemption quietly."""+ assert not [+ str(route)+ for route in ROUTES+ if (+ get_authenticated_user_id in route.calls+ or get_authenticated_caller in route.calls+ )+ and route.key not in _ROUTES_THAT_NEVER_BIND_A_TENANT+ ]def test_no_route_both_resolves_a_tenant_and_skips_resolving_one() -> None:diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex 7b646042e..f023dd4d2 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -328,6 +328,131 @@ class TestInvitationAuthorisation:assert body["uses_remaining"] == 3assert "token" in body and body["token"]+ async def test_an_absurd_expiry_is_refused_rather_than_crashing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`timedelta` raises `OverflowError` well before `int` runs out, so an+ expiry bounded only from below turns a bad request into a 500. The+ bound belongs on the schema, where it is a 422 with a field name."""+ await _make_tenant(session_factory, TENANT_A)+ user_id = await _make_member(+ session_factory, name="time-lord", tenant_id=TENANT_A, role="owner"+ )+ token = _token(user_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ response = await client.post(+ f"/tenants/{TENANT_A}/invitations",+ json={"role": "member", "expires_in_hours": 1000000000},+ )++ assert response.status_code == 422, response.text+++class TestOwnershipIsOwnerOnly:+ """Who owns a workspace is decided by its owners, not by its admins.++ An `admin` runs the workspace; only an `owner` moves the ownership set.+ The distinction exists because a last-owner guard cannot see a sequence:+ each request below is individually safe — two owners stand at every+ step — and together they hand the workspace to someone the founder never+ promoted.+ """++ async def test_an_admin_cannot_take_the_workspace_from_its_owner(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ await _make_tenant(session_factory, TENANT_A)+ founder_id = await _make_member(+ session_factory, name="founder-owner", tenant_id=TENANT_A, role="owner"+ )+ admin_id = await _make_member(+ session_factory, name="ambitious-admin", tenant_id=TENANT_A, role="admin"+ )+ token = _token(admin_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ promote_self = await client.patch(+ f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "owner"}+ )+ demote_founder = await client.patch(+ f"/tenants/{TENANT_A}/members/{founder_id}", json={"role": "member"}+ )+ remove_founder = await client.delete(+ f"/tenants/{TENANT_A}/members/{founder_id}"+ )++ assert promote_self.status_code == 403, promote_self.text+ assert demote_founder.status_code == 403, demote_founder.text+ assert remove_founder.status_code == 403, remove_founder.text++ async with session_factory() as session:+ founder = await session.get(TenantMember, (TENANT_A, founder_id))+ admin = await session.get(TenantMember, (TENANT_A, admin_id))+ assert founder is not None and founder.role == "owner"+ assert admin is not None and admin.role == "admin"++ async def test_an_admin_cannot_mint_an_owner_invitation(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Otherwise the escalation above is the same three steps with a link+ in the middle: invite an accomplice as owner, then let them do it."""+ await _make_tenant(session_factory, TENANT_A)+ await _make_member(+ session_factory, name="quiet-owner", tenant_id=TENANT_A, role="owner"+ )+ admin_id = await _make_member(+ session_factory, name="inviting-admin", tenant_id=TENANT_A, role="admin"+ )+ token = _token(admin_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ refused = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}+ )+ allowed = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "admin"}+ )++ assert refused.status_code == 403, refused.text+ assert allowed.status_code == 201, allowed.text++ async with tenant_session(session_factory, TENANT_A) as scoped:+ roles = [i.role for i in await InvitationStore().list_for_tenant(scoped)]+ assert roles == ["admin"]++ async def test_an_owner_can_do_all_of_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The guard is narrower authority, not a locked door: everything the+ admin was refused above succeeds for an owner."""+ await _make_tenant(session_factory, TENANT_A)+ owner_id = await _make_member(+ session_factory, name="real-owner", tenant_id=TENANT_A, role="owner"+ )+ member_id = await _make_member(+ session_factory, name="promoted", tenant_id=TENANT_A, role="member"+ )+ token = _token(owner_id, "[email protected]", TENANT_A)++ async with _client(_app(session_factory), token) as client:+ promote = await client.patch(+ f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "owner"}+ )+ demote = await client.patch(+ f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "member"}+ )+ invite = await client.post(+ f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}+ )+ remove = await client.delete(f"/tenants/{TENANT_A}/members/{member_id}")++ assert promote.status_code == 200, promote.text+ assert promote.json()["role"] == "owner"+ assert demote.status_code == 200, demote.text+ assert invite.status_code == 201, invite.text+ assert remove.status_code == 200, remove.text+class TestInvitationLifecycle:async def _mint(@@ -373,7 +498,7 @@ class TestInvitationLifecycle:caller_token = _token(invitee_id, "[email protected]", TENANT_B)async with _client(_app(session_factory), caller_token) as client:- response = await client.post(f"/invitations/{token}/accept")+ response = await client.post("/invitations/accept", json={"token": token})assert response.status_code == 200, response.textbody = response.json()@@ -385,6 +510,43 @@ class TestInvitationLifecycle:assert membership is not Noneassert membership.role == "admin"+ async def test_re_accepting_an_invitation_you_already_hold_costs_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A shared link is double-clicked, or reloaded, or opened on a phone+ as well. The second acceptance grants nothing new, so it must spend+ nothing either — otherwise one careless refresh burns a seat that was+ meant for somebody else, and the invitation dies with nobody's+ membership to show for it.+ """+ await _make_tenant(session_factory, TENANT_A)+ admin_id = await _make_member(+ session_factory, name="link-sharer", tenant_id=TENANT_A, role="owner"+ )+ invitation_id, token = await self._mint(+ session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=2+ )+ await _make_tenant(session_factory, TENANT_B)+ invitee_id = await _make_member(+ session_factory, name="double-clicker", tenant_id=TENANT_B, role="member"+ )++ app = _app(session_factory)+ async with _client(+ app, _token(invitee_id, "[email protected]", TENANT_B)+ ) as client:+ first = await client.post("/invitations/accept", json={"token": token})+ second = await client.post("/invitations/accept", json={"token": token})++ assert first.status_code == 200, first.text+ assert second.status_code == 200, second.text+ assert second.json()["role"] == first.json()["role"]++ async with tenant_session(session_factory, TENANT_A) as session:+ invitation = await session.get(Invitation, invitation_id)+ assert invitation is not None+ assert invitation.uses_remaining == 1+async def test_accepting_twice_fails_the_second_time(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -407,13 +569,13 @@ class TestInvitationLifecycle:async with _client(app, _token(first_invitee, "[email protected]", TENANT_B)) as client:- first = await client.post(f"/invitations/{token}/accept")+ first = await client.post("/invitations/accept", json={"token": token})assert first.status_code == 200, first.textasync with _client(app, _token(second_invitee, "[email protected]", TENANT_B)) as client:- second = await client.post(f"/invitations/{token}/accept")+ second = await client.post("/invitations/accept", json={"token": token})assert second.status_code == 403assert "used" in second.json()["detail"].lower()@@ -444,7 +606,7 @@ class TestInvitationLifecycle:_app(session_factory),_token(invitee_id, "[email protected]", TENANT_B),) as client:- response = await client.post(f"/invitations/{token}/accept")+ response = await client.post("/invitations/accept", json={"token": token})assert response.status_code == 403assert "revoked" in response.json()["detail"].lower()@@ -480,7 +642,7 @@ class TestInvitationLifecycle:_app(session_factory),_token(invitee_id, "[email protected]", TENANT_B),) as client:- response = await client.post(f"/invitations/{token}/accept")+ response = await client.post("/invitations/accept", json={"token": token})assert response.status_code == 403assert "expired" in response.json()["detail"].lower()@@ -511,7 +673,7 @@ class TestInvitationLifecycle:_app(session_factory),_token(wrong_person, "[email protected]", TENANT_B),) as client:- response = await client.post(f"/invitations/{token}/accept")+ response = await client.post("/invitations/accept", json={"token": token})assert response.status_code == 403assert "email" in response.json()["detail"].lower()@@ -542,7 +704,7 @@ class TestInvitationLifecycle:_app(session_factory),_token(right_person, "[email protected]", TENANT_B),) as client:- response = await client.post(f"/invitations/{token}/accept")+ response = await client.post("/invitations/accept", json={"token": token})assert response.status_code == 200, response.textdiff --git a/core/tests/switch_core/test_authz.py b/core/tests/switch_core/test_authz.pyindex ecf8d1182..4e2214287 100644--- a/core/tests/switch_core/test_authz.py+++ b/core/tests/switch_core/test_authz.py@@ -9,6 +9,7 @@ from switch_core.authz import (administers_tenant,can,can_manage,+ owns_tenant,require,require_manage,validate_visibility_pair,@@ -127,6 +128,29 @@ class TestAdministersTenant:assert not administers_tenant(is_operator=False, tenant_role=None)+class TestOwnsTenant:+ """`owns_tenant` is the narrower bit: who may move the ownership set,+ which is not everyone who may administer the workspace."""++ def test_operator_owns_regardless_of_tenant_role(self) -> None:+ assert owns_tenant(is_operator=True, tenant_role=None)+ assert owns_tenant(is_operator=True, tenant_role="member")++ def test_owner_membership_owns(self) -> None:+ assert owns_tenant(is_operator=False, tenant_role="owner")++ def test_admin_membership_administers_but_does_not_own(self) -> None:+ """The whole point of there being two functions: an admin who also+ owned could take the workspace from its owner one safe-looking+ request at a time."""+ assert administers_tenant(is_operator=False, tenant_role="admin")+ assert not owns_tenant(is_operator=False, tenant_role="admin")++ def test_plain_member_and_no_membership_do_not_own(self) -> None:+ assert not owns_tenant(is_operator=False, tenant_role="member")+ assert not owns_tenant(is_operator=False, tenant_role=None)++class TestValidateVisibilityPair:@pytest.mark.parametrize("read,write",diff --git a/docs/old/multi-tenancy-phase2-tenants.md b/docs/old/multi-tenancy-phase2-tenants.mdindex 931048675..6928ea199 100644--- a/docs/old/multi-tenancy-phase2-tenants.md+++ b/docs/old/multi-tenancy-phase2-tenants.md@@ -188,7 +188,9 @@ this phase must prove it has removed.- `POST /tenants/{id}/switch` — verify membership, re-mint the cookie.- `POST /tenants/{id}/invitations`, `GET`, `DELETE …/{token_id}` — mint, list,revoke. `owner` and `admin` only.-- `POST /invitations/{token}/accept` — accept.+- `POST /invitations/accept` — accept. The token goes in the body, not the+ path: a URL segment ends up in proxy logs, browser history and `Referer`,+ and this one is a bearer credential.- `GET /tenants/{id}/members`, `PATCH …/{user_id}`, `DELETE …/{user_id}` —list, change a role, remove. The original design omitted these and thenassumed the role-change route existed.@@ -197,6 +199,14 @@ this phase must prove it has removed.is refused; deletion of a workspace is not in this phase, so there is nolegitimate path to an ownerless one.+**Who owns a workspace is decided by its owners, not by its admins.** Granting+`owner`, changing an owner's role, removing an owner, and minting an `owner`+invitation are all owner-only, over and above the `owner`/`admin` gate on the+route. The last-owner rule above cannot substitute for this, because it cannot+see a sequence: an admin who promotes themselves first leaves two owners+standing at every subsequent step, so each individual request passes while the+three together take the workspace.+**Invitations are a table, and a link that grants membership is a credential.**`id`, `tenant_id`, `role`, `email` (null for a link), `expires_at`,`uses_remaining`, `revoked_at`, `created_by`, and a hash of the token rather