Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

[CHOO-3906] Organization admins administer every workspace of their organization

Petr Bauchd6066cad39a3
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.py
index 816eb06e0..47def6dc8 100644
--- a/core/switch_core/accounts/deletion.py
+++ b/core/switch_core/accounts/deletion.py
@@ -14,6 +14,8 @@ ahead would strand something nobody else could reach:
- the server's own administrator account, which the server recreates on every
start anyway;
- a workspace with other people in it whose only owner is this person;
+- an organization with other people in it whose only `org_admin` is this
+ person;
- a cloud machine, whose teardown is driven from its row;
- an active messaging app installed in a workspace nobody else is in, which
would keep receiving messages for no one.
@@ -34,6 +36,7 @@ from typing import TYPE_CHECKING, Literal, Protocol
from sqlalchemy import delete, func, or_, select, update
+from switch_core.authz import ORGANIZATION_ADMIN_ROLE
from switch_core.bridges.resource.service import ReferenceTypeInUseError
from switch_core.connections.broker import ServiceError
from switch_core.db.audit import AuditAction, record_audit_event
@@ -49,6 +52,8 @@ from switch_core.db.models import (
MessagingInstall,
MessagingInstallState,
OidcIdentity,
+ Organization,
+ OrganizationMember,
Package,
Reference,
ReferenceType,
@@ -198,11 +203,17 @@ class AccountDeletion:
async def _workspace_refusal(self, user: User, workspace: Workspace) -> str | None:
async with tenant_session(self.session_factory, workspace.id) as session:
+ organization_refusal = await self._organization_refusal(
+ session, user, workspace.id
+ )
+ if organization_refusal is not None:
+ return organization_refusal
members = await self.users.list_tenant_members(session)
alone = all(member.id == user.id for member, _ in members)
if (
not alone
- and workspace.role == "owner"
+ and await self.users.tenant_role(session, workspace.id, user.id)
+ == "owner"
and await self.users.count_owners(session) <= 1
):
return (
@@ -223,6 +234,34 @@ class AccountDeletion:
)
return None
+ async def _organization_refusal(
+ self, session: AsyncSession, user: User, tenant_id: str
+ ) -> str | None:
+ """Refuse the last `org_admin` of the organization `tenant_id` belongs
+ to while anyone else is in it: nobody would be left to run it.
+ Asked on a session bound to `tenant_id`, which the organization's
+ policy derives the organization from."""
+ if (
+ await self.users.organization_role(session, tenant_id, user.id)
+ != ORGANIZATION_ADMIN_ROLE
+ ):
+ return None
+ others = (
+ await session.execute(
+ select(OrganizationMember.role).where(
+ OrganizationMember.user_id != user.id
+ )
+ )
+ ).scalars()
+ roles = set(others)
+ if not roles or ORGANIZATION_ADMIN_ROLE in roles:
+ return None
+ organization = await session.scalar(select(Organization.name))
+ return (
+ f"You're the only organization admin of {organization}, which has "
+ "other members. Make one of them an organization admin first."
+ )
+
async def delete(
self, session: AsyncSession, user: User, workspaces: list[Workspace]
) -> None:
diff --git a/core/switch_core/authz.py b/core/switch_core/authz.py
index da6a15087..1efe2919d 100644
--- a/core/switch_core/authz.py
+++ b/core/switch_core/authz.py
@@ -14,7 +14,9 @@ Model:
request" — the deployment operator bypass (`User.role == "admin"`, global,
never granted by anything self-service) OR an `owner`/`admin` membership
row for this user in the bound tenant (`tenant_members.role`, granted per
- tenant, e.g. by creating it). `administers_tenant` below computes it; a
+ tenant, e.g. by creating it) OR `org_admin` of the organization the bound
+ tenant belongs to (`organization_members.role`), which administers every
+ workspace in it. `administers_tenant` below computes it; a
caller with a database session should use that rather than re-deriving it.
- Owned entities carry a nullable owner plus independent `read_visibility`
and `write_visibility` ("public" | "private").
@@ -56,19 +58,38 @@ class Principal:
TENANT_ADMIN_ROLES = ("owner", "admin")
-def administers_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:
- """Whether a caller may administer the tenant they hold `tenant_role` in.
+ORGANIZATION_ADMIN_ROLE = "org_admin"
+
+# The workspace role an organization's `org_admin` is reported as holding in
+# each of its workspaces, membership row or not: everything `owns_tenant`
+# allows an `owner`, it allows them.
+ORGANIZATION_ADMIN_TENANT_ROLE = "owner"
+
+
+def administers_tenant(
+ *, is_operator: bool, tenant_role: str | None, organization_role: str | None
+) -> bool:
+ """Whether a caller may administer the tenant they hold `tenant_role` in,
+ and `organization_role` in the organization it belongs to.
True for a deployment operator (the global bypass), regardless of
- membership — an operator administers every tenant. Otherwise true only if
- the membership role itself is `owner` or `admin`; a plain `member`, or no
- membership row at all, is false. This is the one function that should ever
- turn a role into an admin bit — see `Principal.is_admin`.
+ membership — an operator administers every tenant. True for the
+ organization's `org_admin`, with or without a membership row in the tenant.
+ Otherwise true only if the membership role itself is `owner` or `admin`; a
+ plain `member`, or no membership row at all, is false. This is the one
+ function that should ever turn a role into an admin bit — see
+ `Principal.is_admin`.
"""
- return is_operator or tenant_role in TENANT_ADMIN_ROLES
+ return (
+ is_operator
+ or organization_role == ORGANIZATION_ADMIN_ROLE
+ or tenant_role in TENANT_ADMIN_ROLES
+ )
-def owns_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:
+def owns_tenant(
+ *, is_operator: bool, tenant_role: str | None, organization_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;
@@ -77,8 +98,16 @@ def owns_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:
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.
+
+ The organization's `org_admin` owns every workspace in it: the
+ organization decides who runs its workspaces, and a workspace owner
+ cannot take one away from it.
"""
- return is_operator or tenant_role == "owner"
+ return (
+ is_operator
+ or organization_role == ORGANIZATION_ADMIN_ROLE
+ or tenant_role == "owner"
+ )
@runtime_checkable
diff --git a/core/switch_core/bridges/agent/operations/my_context.py b/core/switch_core/bridges/agent/operations/my_context.py
index 996748cfd..2e14d55c4 100644
--- a/core/switch_core/bridges/agent/operations/my_context.py
+++ b/core/switch_core/bridges/agent/operations/my_context.py
@@ -126,7 +126,9 @@ async def get_my_context() -> dict[str, Any]:
if owner is None:
raise PermissionError(f"Agent {caller.name}'s owner no longer exists.")
tenant = await session.get(Tenant, tenant_id)
- role = await protocol.user_store.tenant_role(session, tenant_id, owner.id)
+ role = await protocol.user_store.effective_tenant_role(
+ session, tenant_id, owner.id
+ )
members = await session.scalar(select(func.count()).select_from(TenantMember))
agents = await protocol.agent_store.get_by_owner(session, owner.id)
usernames_by_bridge: dict[str, list[str]] = {}
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 55ce86376..7f21eaba0 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -397,8 +397,13 @@ class ChatService:
self, session: AsyncSession, tenant_id: str, user: User
) -> bool:
"""Whether the user manages every room in the tenant (`can_manage`)."""
- role = await self._user_store.tenant_role(session, tenant_id, user.id)
- return administers_tenant(is_operator=user.role == "admin", tenant_role=role)
+ return administers_tenant(
+ is_operator=user.role == "admin",
+ tenant_role=await self._user_store.tenant_role(session, tenant_id, user.id),
+ organization_role=await self._user_store.organization_role(
+ session, tenant_id, user.id
+ ),
+ )
async def head_seqs(
self, session: AsyncSession, room_ids: list[str]
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index 4d7327298..e170e7b2b 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -9,7 +9,12 @@ from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.authz import administers_tenant, owns_tenant
+from switch_core.authz import (
+ ORGANIZATION_ADMIN_ROLE,
+ ORGANIZATION_ADMIN_TENANT_ROLE,
+ administers_tenant,
+ owns_tenant,
+)
from switch_core.db.models import (
OidcIdentity,
OrganizationMember,
@@ -497,6 +502,39 @@ class UserStore:
membership = await session.get(TenantMember, (tenant_id, user_id))
return membership.role if membership is not None else None
+ async def organization_role(
+ self, session: AsyncSession, tenant_id: str, user_id: str
+ ) -> str | None:
+ """`user_id`'s role in the organization `tenant_id` belongs to, or
+ None if they are not its member.
+
+ Asked of a workspace-bound session, whose organization the policy on
+ `organization_members` derives from the workspace. A workspace from
+ before organizations has none until the revision that makes
+ `tenants.organization_id` `NOT NULL`; nobody holds a role in it, and
+ the policy would refuse the read, so it is not made.
+ """
+ tenant = await session.get(Tenant, tenant_id)
+ if tenant is None or tenant.organization_id is None:
+ return None
+ member = await session.get(
+ OrganizationMember, (tenant.organization_id, user_id)
+ )
+ return member.role if member is not None else None
+
+ async def effective_tenant_role(
+ self, session: AsyncSession, tenant_id: str, user_id: str
+ ) -> str | None:
+ """The role `user_id` acts with in `tenant_id`: their membership role,
+ or `ORGANIZATION_ADMIN_TENANT_ROLE` when they are the organization's
+ `org_admin`, membership row or not. None when they hold neither."""
+ if (
+ await self.organization_role(session, tenant_id, user_id)
+ == ORGANIZATION_ADMIN_ROLE
+ ):
+ return ORGANIZATION_ADMIN_TENANT_ROLE
+ return await self.tenant_role(session, tenant_id, user_id)
+
async def list_tenant_members(
self, session: AsyncSession
) -> list[tuple[User, TenantMember]]:
@@ -527,7 +565,8 @@ class UserStore:
async def administers(self, session: AsyncSession, user: User) -> bool:
"""Whether `user` may administer the tenant bound to `session`'s
- context — the operator bypass, or an owner/admin membership in it.
+ context — the operator bypass, an owner/admin membership in it, or
+ `org_admin` of its organization.
See `authz.administers_tenant`, which this composes with a read of the
one membership row that can answer "in *this* tenant".
@@ -547,12 +586,16 @@ class UserStore:
"administer a workspace is only answerable about a particular "
"one"
)
- role = await self.tenant_role(session, tenant_id, user.id)
- return administers_tenant(is_operator=user.role == "admin", tenant_role=role)
+ return administers_tenant(
+ is_operator=user.role == "admin",
+ tenant_role=await self.tenant_role(session, tenant_id, user.id),
+ organization_role=await self.organization_role(session, tenant_id, user.id),
+ )
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.
+ context — the operator bypass, an `owner` membership in it, or
+ `org_admin` of its organization.
The same composition as `administers`, over `authz.owns_tenant`; see
there for why the two are separate bits rather than one.
@@ -567,5 +610,8 @@ class UserStore:
"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)
+ return owns_tenant(
+ is_operator=user.role == "admin",
+ tenant_role=await self.tenant_role(session, tenant_id, user.id),
+ organization_role=await self.organization_role(session, tenant_id, user.id),
+ )
diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.py
index ec332fc6a..bad3a7f5c 100644
--- a/core/switch_core/db/tenant_lookup.py
+++ b/core/switch_core/db/tenant_lookup.py
@@ -1,4 +1,4 @@
-"""The whole exemption from row-level security, written out as thirteen functions.
+"""The whole exemption from row-level security, written out as fourteen functions.
Row-level security is enforced by `require_tenant_id()` (`db/rls_ddl.py`),
which raises when no tenant is bound. That is the property everything else
@@ -159,6 +159,14 @@ those are, so each row is read with its own tenant bound. It discloses which
workspaces a machine, and so its owner, belongs to: what `tenants_of_user`
already discloses about the same person.
+**`tenants_administered_through_organization` is the fourteenth**, and the
+same question as `tenants_of_user` asked of the organization above the
+workspace. An organization's `org_admin` administers every workspace in it,
+and may bind one without holding a membership row there, so resolving a
+request's workspace has to read which workspaces those are before any is
+bound. It discloses which workspaces a person administers through an
+organization; the gateway asks it only about the signed-in caller.
+
Why not the obvious alternatives is argued in
`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the short
version is that returning rows instead of tenant ids would put a second copy
@@ -251,7 +259,7 @@ class TenantLookup:
return f"{self.name}({', '.join('text' for _ in self.arguments)})"
-# The thirteen of them. Ordered as the three shapes above: enumeration, then
+# The fourteen of them. Ordered as the three shapes above: enumeration, then
# credential resolution, then deriving a tenant from an identifier in hand.
TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
TenantLookup(
@@ -277,6 +285,22 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
"object, and it is scoped, so a session cannot read its own way in."
),
),
+ TenantLookup(
+ name="tenants_administered_through_organization",
+ arguments=("user_id",),
+ query=(
+ "SELECT tenants.id FROM tenants "
+ "JOIN organization_members "
+ "ON organization_members.organization_id = tenants.organization_id "
+ "WHERE organization_members.user_id = p_user_id "
+ "AND organization_members.role = 'org_admin' ORDER BY tenants.id"
+ ),
+ purpose=(
+ "Which tenants a gateway login administers as its organization's "
+ "`org_admin`, holding a membership row there or not. Read before "
+ "a tenant is bound, for the same reason as `tenants_of_user`."
+ ),
+ ),
TenantLookup(
name="tenant_of_api_key",
arguments=("key_hash",),
@@ -472,18 +496,22 @@ def attach_tenant_lookups(metadata: MetaData) -> None:
# ── Calling them ──────────────────────────────────────────────────────────────
# One `text()` per lookup, written out rather than assembled from `lookup.name`
-# at call time: the thirteen names are fixed and known here, so there is nothing
+# at call time: the fourteen names are fixed and known here, so there is nothing
# for a call site to build. Each bind is named after the lookup's own argument,
# which is what lets `_call` zip them positionally against the dataclass and
# fail loudly on a mismatch rather than binding the workspace to the platform.
# The assertion below is what keeps this dict from quietly falling behind
-# `TENANT_LOOKUPS`: a fourteenth lookup with no entry here fails at import, not
+# `TENANT_LOOKUPS`: a fifteenth lookup with no entry here fails at import, not
# with a `KeyError` on whatever request reaches it first.
_LOOKUP_STATEMENTS: dict[str, TextClause] = {
"all_tenant_ids": text("SELECT tenant_id FROM all_tenant_ids() AS tenant_id"),
"tenants_of_user": text(
"SELECT tenant_id FROM tenants_of_user(:user_id) AS tenant_id"
),
+ "tenants_administered_through_organization": text(
+ "SELECT tenant_id FROM "
+ "tenants_administered_through_organization(:user_id) AS tenant_id"
+ ),
"tenant_of_api_key": text(
"SELECT tenant_id FROM tenant_of_api_key(:key_hash) AS tenant_id"
),
@@ -578,6 +606,16 @@ async def tenants_of_user(
)
+async def tenants_administered_through_organization(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str
+) -> list[str]:
+ return await _call(
+ session_factory,
+ TENANT_LOOKUPS_BY_NAME["tenants_administered_through_organization"],
+ user_id,
+ )
+
+
async def tenant_of_api_key(
session_factory: async_sessionmaker[AsyncSession], key_hash: str
) -> str | None:
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index ac15568fe..7f10c3018 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -22,6 +22,7 @@ from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
from switch_core.db.tenant_lookup import (
tenant_of_invitation,
+ tenants_administered_through_organization,
tenants_inviting_email,
tenants_of_user,
tenants_open_to_domain,
@@ -349,17 +350,28 @@ async def tenants_open_to(
return await tenants_open_to_domain(session_factory, domain)
-async def is_tenant_member(
+async def tenants_bindable_by(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str
+) -> list[str]:
+ """Every tenant `user_id` may bind: those they are a member of, and those
+ they administer as their organization's `org_admin`. Sorted, each once."""
+ return sorted(
+ set(await tenants_of_user(session_factory, user_id))
+ | set(await tenants_administered_through_organization(session_factory, user_id))
+ )
+
+
+async def may_bind_tenant(
session_factory: async_sessionmaker[AsyncSession], user_id: str, tenant_id: str
) -> bool:
- """Whether `user_id` has a membership in `tenant_id`.
+ """Whether `user_id` may bind `tenant_id` (`tenants_bindable_by`).
Backs `POST /tenants/{id}/switch`: the claim it goes on to mint never
authorises by itself (`_resolve_tenant_id` re-checks it on every request
regardless), but switching still must not let someone select a tenant
- they do not belong to.
+ they may not bind.
"""
- return tenant_id in await tenants_of_user(session_factory, user_id)
+ return tenant_id in await tenants_bindable_by(session_factory, user_id)
async def _describe_memberships(
@@ -387,22 +399,29 @@ async def _describe_memberships(
for tenant_id in tenant_ids:
async with tenant_session(session_factory, tenant_id) as session:
tenant = await session.get(Tenant, tenant_id)
- role = await user_store.tenant_role(session, tenant_id, user_id)
+ role = await user_store.effective_tenant_role(session, tenant_id, user_id)
+ organization_role = await user_store.organization_role(
+ session, tenant_id, user_id
+ )
if tenant is None or role is None:
- # tenants_of_user just said this tenant has a membership row for
- # this user; either read failing to confirm it a moment later is
- # a genuine race (removed between the two calls), not a bug to
- # paper over by including a tenant we can no longer describe.
+ # tenants_bindable_by just said this user may bind this tenant;
+ # either read failing to confirm it a moment later is a genuine
+ # race (removed between the two calls), not a bug to paper over by
+ # including a tenant we can no longer describe.
logger.warning(
- "tenants_of_user named tenant %s for user %s, but it or the "
- "membership row was gone by the time it was read",
+ "tenants_bindable_by named tenant %s for user %s, but it or the "
+ "role there was gone by the time it was read",
tenant_id,
user_id,
)
continue
memberships.append(
TenantMembershipResponse(
- id=tenant.id, slug=tenant.slug, name=tenant.name, role=role
+ id=tenant.id,
+ slug=tenant.slug,
+ name=tenant.name,
+ role=role,
+ organization_role=organization_role,
)
)
return memberships
@@ -424,7 +443,7 @@ async def list_tenant_memberships(
session_factory,
user_store,
user_id,
- await tenants_of_user(session_factory, user_id),
+ await tenants_bindable_by(session_factory, user_id),
)
@@ -443,7 +462,7 @@ async def initial_tenant_claim(
is checked against current memberships here too, so signing in again is
still how a session whose workspace was taken away recovers.
"""
- memberships = await tenants_of_user(session_factory, user.id)
+ memberships = await tenants_bindable_by(session_factory, user.id)
last = user_store.last_tenant_id(user)
if last is not None and last in memberships:
return last
@@ -541,6 +560,10 @@ async def _resolve_tenant_id(
"""Which tenant a request binds, in the order set out in
`docs/old/multi-tenancy-phase2-tenants.md`, §4:
+ "Membership" below is any tenant the caller may bind
+ (`tenants_bindable_by`): one they hold a membership row in, or one their
+ organization's `org_admin` role covers.
+
1. A claim naming a tenant the caller belongs to → bind it.
2. A claim naming a tenant the caller does not belong to → 403
`tenant_selection_invalid`. The caller can fix this unaided — `GET
@@ -566,15 +589,16 @@ async def _resolve_tenant_id(
5. No memberships → 403 `tenant_membership_unresolved`, the one of the
three the caller genuinely cannot resolve alone.
- `tenants_of_user` is read once and used for every case below it, including
- the 409's body, so this is one round trip to the exemption regardless of
+ `tenants_bindable_by` is read once and used for every case below it,
+ including the 409's body, so this is the same two lookups regardless of
which case answers.
- It also stands in for the account check: a `tenant_members` row references
- its `users` row, so a caller with a membership exists. Only with none is
+ It also stands in for the account check: a `tenant_members` or
+ `organization_members` row references its `users` row, so a caller with a
+ membership exists. Only with none is
`users` asked, so a deleted account still gets 401 rather than a 403.
"""
- memberships = await tenants_of_user(session_factory, user_id)
+ memberships = await tenants_bindable_by(session_factory, user_id)
if not memberships:
await _require_user_exists(session_factory, user_store, user_id)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index e83e8088c..17e2e610f 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -906,7 +906,10 @@ class TenantMembershipResponse(BaseModel):
id: str
slug: str
name: str
+ # The role the caller acts with here: an organization's `org_admin` is
+ # reported as `owner` of each of its workspaces, membership row or not.
role: str
+ organization_role: str | None
class CurrentTenantResponse(TenantMembershipResponse):
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index fdc0b9ef6..093ff60ec 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -14,6 +14,7 @@ from sqlalchemy import select
from sqlalchemy.exc import DBAPIError, IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.authz import ORGANIZATION_ADMIN_ROLE
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.agent.registration_bootstrap import is_bootstrap_owner
from switch_core.clients.client_lifecycle_service import (
@@ -67,8 +68,8 @@ from switch_core.gateway.auth import (
get_current_user,
get_tenant_is_admin,
get_tenant_is_owner,
- is_tenant_member,
list_tenant_memberships,
+ may_bind_tenant,
require_tenant_admin,
set_session_cookie,
tenant_of_invitation_token,
@@ -205,6 +206,29 @@ def _member_detail(user: User, membership: TenantMember) -> MemberDetail:
)
+async def _refuse_organization_admin(
+ session: AsyncSession, user_store: UserStore, tenant_id: str, user_id: str
+) -> None:
+ """Raise 409 if `user_id` is `org_admin` of the bound tenant's organization.
+
+ Their standing here comes from the organization, not from their membership
+ row, so changing or removing the row here would take nothing away while
+ looking as if it had. It is changed in the organization's own members.
+ """
+ if (
+ await user_store.organization_role(session, tenant_id, user_id)
+ == ORGANIZATION_ADMIN_ROLE
+ ):
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "This member administers the workspace's organization, which "
+ "gives them admin rights in every one of its workspaces. Change "
+ "their role in the organization instead."
+ ),
+ )
+
+
def _require_owner(is_owner: bool, action: str) -> None:
"""Raise 403 unless the caller owns the bound tenant.
@@ -290,7 +314,7 @@ async def current_tenant(
"""
tenant_id = require_tenant_id()
tenant = await session.get(Tenant, tenant_id)
- role = await user_store.tenant_role(session, tenant_id, user.id)
+ role = await user_store.effective_tenant_role(session, tenant_id, user.id)
if tenant is None or role is None:
raise HTTPException(status_code=404, detail="Tenant not found")
return CurrentTenantResponse(
@@ -298,6 +322,9 @@ async def current_tenant(
slug=tenant.slug,
name=tenant.name,
role=role,
+ organization_role=await user_store.organization_role(
+ session, tenant_id, user.id
+ ),
administers=is_admin,
)
@@ -547,7 +574,11 @@ async def create_tenant(
response, user, config.keyring, config.gateway_cookie_secure, tenant.id
)
return TenantMembershipResponse(
- id=tenant.id, slug=tenant.slug, name=tenant.name, role="owner"
+ id=tenant.id,
+ slug=tenant.slug,
+ name=tenant.name,
+ role="owner",
+ organization_role="org_admin",
)
@@ -563,17 +594,17 @@ async def switch_tenant(
user_store: Annotated[UserStore, Depends(get_user_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> SessionUserResponse:
- """Select `tenant_id` for this session: verify membership, then re-mint
- the cookie carrying it as the tenant claim.
-
- The membership check is what keeps the claim from being a way in on its
- own: `_resolve_tenant_id` re-reads `tenant_members` on every request
- regardless of what the cookie says, so a forged or stale claim already
- buys nothing — but this route is the one place a *caller* picks the
- value that goes into it, and it must not let them pick a tenant they do
- not belong to.
+ """Select `tenant_id` for this session: verify the caller may bind it,
+ then re-mint the cookie carrying it as the tenant claim.
+
+ The check is what keeps the claim from being a way in on its own:
+ `_resolve_tenant_id` re-checks it on every request regardless of what the
+ cookie says, so a forged or stale claim already buys nothing — but this
+ route is the one place a *caller* picks the value that goes into it, and
+ it must not let them pick a tenant they may not bind: one they are a
+ member of, or one their organization's `org_admin` role covers.
"""
- if not await is_tenant_member(session_factory, user_id, tenant_id):
+ if not await may_bind_tenant(session_factory, user_id, tenant_id):
raise HTTPException(status_code=403, detail="Not a member of this tenant")
user = await user_store.get(session, user_id)
@@ -996,16 +1027,14 @@ async def accept_invitation(
raise HTTPException(status_code=404, detail="Invitation not found")
_require_invitation_usable(invitation, caller.email)
- tenant, user, role = await _join_through(
+ membership, user = await _join_through(
session, invitation, caller, user_store, invitation_store
)
set_session_cookie(
response, user, config.keyring, config.gateway_cookie_secure, tenant_id
)
- return TenantMembershipResponse(
- id=tenant.id, slug=tenant.slug, name=tenant.name, role=role
- )
+ return membership
async def _join_through(
@@ -1014,7 +1043,7 @@ async def _join_through(
caller: AuthenticatedCaller,
user_store: UserStore,
invitation_store: InvitationStore,
-) -> tuple[Tenant, User, str]:
+) -> tuple[TenantMembershipResponse, User]:
"""Make `caller` a member of the invitation's tenant, spending one use,
select that tenant for them, and commit.
@@ -1058,11 +1087,8 @@ async def _join_through(
"invitation_accepted",
{"age_hours": age_hours(invitation.created_at)},
)
- else:
- role = existing_role
- tenant, user = await _enter(session, tenant_id, caller, user_store)
- return tenant, user, role
+ return await _enter(session, tenant_id, caller, user_store)
async def _enter(
@@ -1070,14 +1096,26 @@ async def _enter(
tenant_id: str,
caller: AuthenticatedCaller,
user_store: UserStore,
-) -> tuple[Tenant, User]:
+) -> tuple[TenantMembershipResponse, User]:
"""Select the tenant `session` is bound to for `caller`, and commit.
The last step of every way of joining a workspace, run once the caller is
- a member of it.
+ a member of it. Returns the caller's standing there, read before the
+ commit expires what the session holds.
"""
tenant = await session.get(Tenant, tenant_id)
assert tenant is not None
+ role = await user_store.effective_tenant_role(session, tenant_id, caller.id)
+ assert role is not None
+ membership = TenantMembershipResponse(
+ id=tenant.id,
+ slug=tenant.slug,
+ name=tenant.name,
+ role=role,
+ organization_role=await user_store.organization_role(
+ session, tenant_id, caller.id
+ ),
+ )
# `users` is global, so the caller's row is writable from a session
# bound to any tenant — this one included.
user = await user_store.get(session, caller.id)
@@ -1085,7 +1123,7 @@ async def _enter(
raise HTTPException(status_code=401, detail="User not found")
await user_store.record_last_tenant(session, user, tenant_id)
await session.commit()
- return tenant, user
+ return membership, user
@router.get("/invitations/mine")
@@ -1172,7 +1210,7 @@ async def accept_my_invitation(
):
raise HTTPException(status_code=404, detail="Invitation not found")
_require_invitation_usable(invitation, caller.email)
- tenant, user, role = await _join_through(
+ membership, user = await _join_through(
session, invitation, caller, user_store, invitation_store
)
@@ -1183,9 +1221,7 @@ async def accept_my_invitation(
config.gateway_cookie_secure,
req.tenant_id,
)
- return TenantMembershipResponse(
- id=tenant.id, slug=tenant.slug, name=tenant.name, role=role
- )
+ return membership
# ── Joining by e-mail domain ──────────────────────────────────────────────────
@@ -1373,14 +1409,12 @@ async def join_tenant_by_domain(
target_id=caller.id,
details={"role": role, "domain": domain},
)
- tenant, user = await _enter(session, tenant_id, caller, user_store)
+ membership, user = await _enter(session, tenant_id, caller, user_store)
set_session_cookie(
response, user, config.keyring, config.gateway_cookie_secure, tenant_id
)
- return TenantMembershipResponse(
- id=tenant.id, slug=tenant.slug, name=tenant.name, role=role
- )
+ return membership
# ── Members ───────────────────────────────────────────────────────────────────
@@ -1428,6 +1462,7 @@ async def update_member_role(
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")
+ await _refuse_organization_admin(session, user_store, tenant_id, user_id)
if req.role == "owner" and membership.role != "owner":
_require_owner(is_owner, "grant ownership")
@@ -1502,6 +1537,7 @@ async def remove_member(
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")
+ await _refuse_organization_admin(session, user_store, tenant_id, user_id)
if membership.role == "owner":
_require_owner(is_owner, "remove an owner")
diff --git a/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_administered_through_organization.py b/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_administered_through_organization.py
new file mode 100644
index 000000000..d7d0d4dd2
--- /dev/null
+++ b/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_administered_through_organization.py
@@ -0,0 +1,47 @@
+"""the lookup that finds the workspaces a person administers through an organization
+
+An organization's `org_admin` administers every workspace in it and may bind
+one without a membership row there. Resolving which workspaces those are
+happens before any is bound, so this adds the fourteenth lookup to the
+exemption from row-level security. See `db/tenant_lookup.py` for what it
+discloses.
+
+The DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py` as it
+stood when this migration was written, copied rather than imported so a later
+edit cannot change what this revision means.
+
+Revision ID: 5c2e8f17a9d4
+Revises: 238c68b7306e
+Create Date: 2026-10-29 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+from alembic import op
+
+revision: str = "5c2e8f17a9d4"
+down_revision: str | Sequence[str] | None = "238c68b7306e"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+expand_only: bool = True
+
+SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
+
+CREATE_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION = f"""CREATE OR REPLACE FUNCTION tenants_administered_through_organization(p_user_id text)
+ RETURNS SETOF text
+ LANGUAGE sql STABLE SECURITY DEFINER
+ SET search_path = {SECURE_SEARCH_PATH}
+AS $$SELECT tenants.id FROM tenants JOIN organization_members ON organization_members.organization_id = tenants.organization_id WHERE organization_members.user_id = p_user_id AND organization_members.role = 'org_admin' ORDER BY tenants.id$$"""
+
+DROP_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION = (
+ "DROP FUNCTION IF EXISTS tenants_administered_through_organization(text)"
+)
+
+
+def upgrade() -> None:
+ op.execute(CREATE_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION)
+
+
+def downgrade() -> None:
+ op.execute(DROP_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION)
diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.py
index 1989201e6..8dd2f206c 100644
--- a/core/tests/switch_core/accounts/test_account_deletion.py
+++ b/core/tests/switch_core/accounts/test_account_deletion.py
@@ -34,6 +34,7 @@ from switch_core.db.models import (
Invitation,
MessagingInstall,
OidcIdentity,
+ OrganizationMember,
Reference,
Room,
Template,
@@ -259,6 +260,50 @@ async def test_the_only_owner_of_a_shared_workspace_is_refused(
assert reason is not None and "only owner of Acme" in reason
+async def _organization_role(session: AsyncSession, user: User, role: str) -> None:
+ """`user` holds `role` in tenant zero's organization, which shares its id."""
+ session.add(
+ OrganizationMember(organization_id=TENANT_ZERO_ID, user_id=user.id, role=role)
+ )
+ await session.flush()
+
+
+async def test_the_only_org_admin_of_an_organization_with_others_is_refused(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ deletion, _, _ = _deletion(session_factory)
+ async with session_factory() as session:
+ admin = await _user(session, "org-admin")
+ other = await _user(session, "other")
+ await _member(session, TENANT_ZERO_ID, admin, "admin")
+ await _member(session, TENANT_ZERO_ID, other, "owner")
+ await _organization_role(session, admin, "org_admin")
+ await _organization_role(session, other, "member")
+ await session.commit()
+ reason = await deletion.refusal(
+ session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "owner")]
+ )
+ assert reason is not None and "only organization admin" in reason
+
+
+async def test_an_org_admin_with_another_org_admin_beside_them_is_not_refused(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ deletion, _, _ = _deletion(session_factory)
+ async with session_factory() as session:
+ admin = await _user(session, "org-admin")
+ other = await _user(session, "other")
+ await _member(session, TENANT_ZERO_ID, admin, "admin")
+ await _member(session, TENANT_ZERO_ID, other, "owner")
+ await _organization_role(session, admin, "org_admin")
+ await _organization_role(session, other, "org_admin")
+ await session.commit()
+ reason = await deletion.refusal(
+ session, admin, [Workspace(TENANT_ZERO_ID, "Acme", "owner")]
+ )
+ assert reason is None
+
+
async def test_a_connected_workspace_nobody_else_is_in_is_refused(
session_factory: async_sessionmaker[AsyncSession],
) -> None:
diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.py
index 3a0b6eef8..3452b37ea 100644
--- a/core/tests/switch_core/db/test_tenant_lookup.py
+++ b/core/tests/switch_core/db/test_tenant_lookup.py
@@ -107,6 +107,7 @@ _ADDED_SINCE = {
"tenants_inviting_email": "4b8e2d61c9f7",
"tenants_open_to_domain": "7d3f5a19e2c8",
"tenant_of_sign_in_flow": "e5956cbd3bdc",
+ "tenants_administered_through_organization": "5c2e8f17a9d4",
}
# A third kind of change, and the quietest: a lookup whose body a later
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index 0614b3ad9..717324c37 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -44,6 +44,7 @@ from switch_core.db.models import (
Client,
Invitation,
Organization,
+ OrganizationMember,
ServiceTokenIssuance,
SignInFlow,
Tenant,
@@ -1754,6 +1755,7 @@ class TestCurrentTenantRoute:
"slug": TENANT_A,
"name": TENANT_A,
"role": "member",
+ "organization_role": None,
"administers": False,
}
@@ -1784,6 +1786,192 @@ class TestCurrentTenantRoute:
assert response.json()["administers"] is True
+class TestOrganizationAdmins:
+ """An organization's `org_admin` administers every workspace in it, and
+ may bind one without holding a membership row there."""
+
+ async def _organization_of(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ *tenant_ids: str,
+ members: dict[str, str],
+ ) -> str:
+ """An organization owning `tenant_ids`, with `members` (user id ->
+ organization role)."""
+ organization_id = f"org-{uuid.uuid4().hex[:8]}"
+ async with session_factory() as session:
+ session.add(
+ Organization(id=organization_id, slug=organization_id, name="Acme")
+ )
+ await session.flush()
+ for tenant_id in tenant_ids:
+ session.add(
+ Tenant(
+ id=tenant_id,
+ slug=tenant_id,
+ name=tenant_id,
+ organization_id=organization_id,
+ )
+ )
+ for user_id, role in members.items():
+ session.add(
+ OrganizationMember(
+ organization_id=organization_id, user_id=user_id, role=role
+ )
+ )
+ await session.commit()
+ return organization_id
+
+ async def test_an_org_admin_binds_a_workspace_they_are_not_a_member_of(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ admin_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin", role="user"
+ )
+ await self._organization_of(
+ session_factory, TENANT_A, members={admin_id: "org_admin"}
+ )
+ token = _token(admin_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/current")
+
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "id": TENANT_A,
+ "slug": TENANT_A,
+ "name": TENANT_A,
+ "role": "owner",
+ "organization_role": "org_admin",
+ "administers": True,
+ }
+
+ async def test_an_org_admin_is_offered_and_may_switch_to_every_workspace_of_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ admin_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin", role="user"
+ )
+ await self._organization_of(
+ session_factory, TENANT_A, TENANT_B, members={admin_id: "org_admin"}
+ )
+ token = _token(admin_id, "[email protected]", None)
+
+ async with _client(_app(session_factory), token) as client:
+ listed = await client.get("/tenants")
+ switched = await client.post(f"/tenants/{TENANT_B}/switch")
+
+ assert listed.status_code == 200, listed.text
+ assert {
+ (t["id"], t["role"], t["organization_role"]) for t in listed.json()
+ } == {
+ (TENANT_A, "owner", "org_admin"),
+ (TENANT_B, "owner", "org_admin"),
+ }
+ assert switched.status_code == 200, switched.text
+ assert _tenant_claim(switched) == TENANT_B
+
+ async def test_an_org_admin_may_not_bind_another_organizations_workspace(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ admin_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin", role="user"
+ )
+ await self._organization_of(
+ session_factory, TENANT_A, members={admin_id: "org_admin"}
+ )
+ await self._organization_of(session_factory, TENANT_B, members={})
+ token = _token(admin_id, "[email protected]", TENANT_B)
+
+ async with _client(_app(session_factory), token) as client:
+ current = await client.get("/tenants/current")
+ switched = await client.post(f"/tenants/{TENANT_B}/switch")
+
+ assert current.status_code == 403
+ assert switched.status_code == 403
+
+ async def test_an_organization_member_binds_only_their_own_workspaces(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ member_id = await _make_unaffiliated_user(
+ session_factory, name="org-member", role="user"
+ )
+ await self._organization_of(
+ session_factory, TENANT_A, members={member_id: "member"}
+ )
+ token = _token(member_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/current")
+
+ assert response.status_code == 403
+
+ async def test_an_org_admin_manages_a_workspaces_members_and_owners(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ admin_id = await _make_unaffiliated_user(
+ session_factory, name="org-admin", role="user"
+ )
+ await self._organization_of(
+ session_factory, TENANT_A, members={admin_id: "org_admin"}
+ )
+ owner_id = await _make_member(
+ session_factory, name="ws-owner", tenant_id=TENANT_A, role="owner"
+ )
+ await _make_member(
+ session_factory, name="ws-owner-2", tenant_id=TENANT_A, role="owner"
+ )
+ token = _token(admin_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.patch(
+ f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["role"] == "member"
+
+ @pytest.mark.parametrize("method", ["patch", "delete"])
+ async def test_a_workspace_cannot_demote_or_remove_an_org_admin(
+ self, session_factory: async_sessionmaker[AsyncSession], method: str
+ ) -> None:
+ """Their standing comes from the organization; changing the row here
+ would take nothing away while looking as if it had."""
+ organization_id = await self._organization_of(
+ session_factory, TENANT_A, members={}
+ )
+ owner_id = await _make_member(
+ session_factory, name="ws-owner", tenant_id=TENANT_A, role="owner"
+ )
+ admin_id = await _make_member(
+ session_factory, name="org-admin", tenant_id=TENANT_A, role="owner"
+ )
+ async with session_factory() as session:
+ session.add(
+ OrganizationMember(
+ organization_id=organization_id, user_id=admin_id, role="org_admin"
+ )
+ )
+ await session.commit()
+ token = _token(owner_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ if method == "patch":
+ response = await client.patch(
+ f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "member"}
+ )
+ else:
+ response = await client.delete(
+ f"/tenants/{TENANT_A}/members/{admin_id}"
+ )
+
+ assert response.status_code == 409, response.text
+ assert "organization" in response.json()["detail"]
+ async with session_factory() as session:
+ membership = await session.get(TenantMember, (TENANT_A, admin_id))
+ assert membership is not None and membership.role == "owner"
+
+
class TestUsageRoute:
async def _spend(
self,
diff --git a/core/tests/switch_core/test_authz.py b/core/tests/switch_core/test_authz.py
index 4e2214287..9ac2ecedd 100644
--- a/core/tests/switch_core/test_authz.py
+++ b/core/tests/switch_core/test_authz.py
@@ -114,18 +114,46 @@ class TestAdministersTenant:
per-tenant `owner`/`admin` membership role, combined."""
def test_operator_administers_regardless_of_tenant_role(self) -> None:
- assert administers_tenant(is_operator=True, tenant_role=None)
- assert administers_tenant(is_operator=True, tenant_role="member")
+ assert administers_tenant(
+ is_operator=True, tenant_role=None, organization_role=None
+ )
+ assert administers_tenant(
+ is_operator=True, tenant_role="member", organization_role=None
+ )
def test_owner_or_admin_membership_administers(self) -> None:
- assert administers_tenant(is_operator=False, tenant_role="owner")
- assert administers_tenant(is_operator=False, tenant_role="admin")
+ assert administers_tenant(
+ is_operator=False, tenant_role="owner", organization_role=None
+ )
+ assert administers_tenant(
+ is_operator=False, tenant_role="admin", organization_role=None
+ )
def test_plain_member_does_not_administer(self) -> None:
- assert not administers_tenant(is_operator=False, tenant_role="member")
+ assert not administers_tenant(
+ is_operator=False, tenant_role="member", organization_role=None
+ )
def test_no_membership_does_not_administer(self) -> None:
- assert not administers_tenant(is_operator=False, tenant_role=None)
+ assert not administers_tenant(
+ is_operator=False, tenant_role=None, organization_role=None
+ )
+
+ def test_organization_admin_administers_every_workspace_of_it(self) -> None:
+ for tenant_role in (None, "member", "admin"):
+ assert administers_tenant(
+ is_operator=False,
+ tenant_role=tenant_role,
+ organization_role="org_admin",
+ )
+
+ def test_organization_member_is_no_more_than_their_workspace_role(self) -> None:
+ assert not administers_tenant(
+ is_operator=False, tenant_role="member", organization_role="member"
+ )
+ assert administers_tenant(
+ is_operator=False, tenant_role="admin", organization_role="member"
+ )
class TestOwnsTenant:
@@ -133,22 +161,44 @@ class TestOwnsTenant:
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")
+ assert owns_tenant(is_operator=True, tenant_role=None, organization_role=None)
+ assert owns_tenant(
+ is_operator=True, tenant_role="member", organization_role=None
+ )
def test_owner_membership_owns(self) -> None:
- assert owns_tenant(is_operator=False, tenant_role="owner")
+ assert owns_tenant(
+ is_operator=False, tenant_role="owner", organization_role=None
+ )
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")
+ assert administers_tenant(
+ is_operator=False, tenant_role="admin", organization_role=None
+ )
+ assert not owns_tenant(
+ is_operator=False, tenant_role="admin", organization_role=None
+ )
+
+ def test_organization_admin_owns_every_workspace_of_it(self) -> None:
+ """A workspace owner cannot take a workspace away from the
+ organization it belongs to."""
+ assert owns_tenant(
+ is_operator=False, tenant_role=None, organization_role="org_admin"
+ )
+ assert not owns_tenant(
+ is_operator=False, tenant_role="admin", organization_role="member"
+ )
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)
+ assert not owns_tenant(
+ is_operator=False, tenant_role="member", organization_role=None
+ )
+ assert not owns_tenant(
+ is_operator=False, tenant_role=None, organization_role=None
+ )
class TestValidateVisibilityPair: