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(organizations): ask the directory last, once every check has passed
Petr Bauchb211cdee3a22
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.pyindex 03128b004..5a2b93b2b 100644--- a/core/switch_core/accounts/deletion.py+++ b/core/switch_core/accounts/deletion.py@@ -303,7 +303,9 @@ class AccountDeletion:write that could leave an organization without an `org_admin` takes(`OrganizationStore.lock_admins`), so `refusal` holds against anotheradmin stepping down at the same moment. Every check runs before any- row goes."""+ row goes. Only Switch's rows go: a membership in a directory kept+ outside Switch (`organization_directory.py`) is the person's beyond+ Switch, and stays there."""organizations: dict[str, str] = {}for workspace in workspaces:async with tenant_session(self.session_factory, workspace.id) as session:diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex a2265fc2e..668e21dff 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -17,6 +17,7 @@ read back by its `org_admin`s. See `docs/design/organizations-v1.md`.from __future__ import annotations+from collections.abc import Awaitable, Callablefrom datetime import datetimefrom typing import Annotated, NamedTuple@@ -94,12 +95,13 @@ from switch_core.gateway.workspace_access import (revoke_workspace_access,)from switch_core.gateway.workspace_creation import (+ NOTHING_CHANGED,create_organization_for,create_workspace,- directory_refused,+ directory_failed,lock_workspace_allowance,)-from switch_core.organization_directory import DirectoryRefusal, OrganizationDirectory+from switch_core.organization_directory import DirectoryError, OrganizationDirectoryrouter = APIRouter()@@ -410,6 +412,38 @@ async def list_organization_members(]+# Why a change the directory did not make still took something away.+_ACCESS_ALREADY_ENDED = (+ "They keep their place in the organization, but what they held in "+ "workspaces they reached only as an organization admin has already been "+ "taken away."+)+++async def _ask_directory(+ change: Callable[..., Awaitable[None]],+ session: AsyncSession,+ organization_id: str,+ *args: str,+ access_ended: bool,+) -> None:+ """Ask the directory to make `change` to a member of `organization_id`,+ with `args`: after every check that can refuse, under the lock on the+ organization's admins, and before the write and its commit+ (`organization_directory.py`). `access_ended` says the person's access+ through the organization was ended on the way, which a refusal does not+ give back."""+ organization = await session.get(Organization, organization_id)+ if organization is None:+ raise RuntimeError(f"Organization {organization_id} is not visible here")+ try:+ await change(organization, *args)+ except DirectoryError as error:+ raise directory_failed(+ error, _ACCESS_ALREADY_ENDED if access_ended else NOTHING_CHANGED+ ) from None++async def _end_access_through_organization(session_factory: async_sessionmaker[AsyncSession],*,@@ -508,8 +542,8 @@ async def update_organization_member_role(Refuses to demote the last `org_admin`: nobody else could grant the roleagain. Demoting someone first takes away what they hold in the workspacesthey were in only as `org_admin` (`_end_access_through_organization`).- Once the rules pass, the directory is asked before anything is changed- (`organization_directory.py`). Recorded in the organization's audit log.+ The directory is asked last, once every check has passed+ (`_ask_directory`). Recorded in the organization's audit log."""access = await require_organization_admin(session, user_store, organization_store, user, operator_restores=True@@ -529,16 +563,6 @@ async def update_organization_member_role(and await organization_store.count_admins(session, organization_id) <= 1):raise last_admin- if member.role != req.role:- try:- await organization_directory.set_role(- session,- organization_id=organization_id,- user_id=user_id,- role=req.role,- )- except DirectoryRefusal as refusal:- raise directory_refused(refusal) from Nonewarning = Noneif demoting:@@ -571,6 +595,14 @@ async def update_organization_member_role()if member.role != req.role:+ await _ask_directory(+ organization_directory.set_role,+ session,+ organization_id,+ user_id,+ req.role,+ access_ended=demoting,+ )await record_organization_audit_event(session,organization_id=organization_id,@@ -619,8 +651,8 @@ async def remove_organization_member(one workspace at a time. An `org_admin` also stands in workspaces theyhold no membership row in, and what they hold there is taken away first(`_end_access_through_organization`). Refuses the last `org_admin` too.- Once the rules pass, the directory is asked before anything is changed- (`organization_directory.py`). Recorded in the organization's audit log.+ The directory is asked last, once every check has passed+ (`_ask_directory`). Recorded in the organization's audit log."""access = await require_organization_admin(session, user_store, organization_store, user, operator_restores=False@@ -651,13 +683,6 @@ async def remove_organization_member(status_code=409,detail=(f"Remove them from the organization's workspaces first: {names}"),)- try:- await organization_directory.remove(- session, organization_id=organization_id, user_id=user_id- )- except DirectoryRefusal as refusal:- raise directory_refused(refusal) from None-warning = Noneif was_admin:try:@@ -684,6 +709,13 @@ async def remove_organization_member(raise HTTPException(status_code=404, detail="Not a member of this organization")if member.role == ORGANIZATION_ADMIN_ROLE and admins <= 1:raise last_admin+ await _ask_directory(+ organization_directory.remove,+ session,+ organization_id,+ user_id,+ access_ended=was_admin,+ )role = member.roleawait session.execute(delete(OrganizationMember).where(diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 04933f4b2..93237fe42 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -28,6 +28,7 @@ from switch_core.connections.broker import (from switch_core.db.audit import AuditAction, list_audit_events, record_audit_eventfrom switch_core.db.models import (Invitation,+ Organization,OrganizationMember,Tenant,TenantJoinDomain,@@ -128,10 +129,11 @@ from switch_core.gateway.workspace_access import (revoke_workspace_access,)from switch_core.gateway.workspace_creation import (+ NOTHING_CHANGED,create_organization_for,- directory_refused,+ directory_failed,)-from switch_core.organization_directory import DirectoryRefusal, OrganizationDirectory+from switch_core.organization_directory import DirectoryError, OrganizationDirectoryfrom switch_core.telemetry import emit_safelyfrom switch_core.telemetry.ages import age_hoursfrom switch_core.tenant_context import current_tenant_id@@ -859,30 +861,35 @@ async def accept_invitation(return membership-async def _join_organization_of(- session: AsyncSession,- organization_directory: OrganizationDirectory,- tenant_id: str,- user_id: str,-) -> None:- """Ask the directory to make `user_id` a member of `tenant_id`'s- organization, before their workspace membership is written- (`organization_directory.py`). A refusal is answered with its reason, and- the caller's uncommitted writes (an invitation's use) are rolled back."""+async def _organization_to_join(+ session: AsyncSession, tenant_id: str, user_id: str+) -> Organization | None:+ """`tenant_id`'s organization, if joining the workspace makes `user_id` a+ new member of it, for the directory to be asked (`_join_in_directory`)."""tenant = await session.get(Tenant, tenant_id)if tenant is None:raise RuntimeError(f"Workspace {tenant_id} is not visible to this session")if tenant.organization_id is None:+ return None+ if await session.get(OrganizationMember, (tenant.organization_id, user_id)):+ return None+ return await session.get(Organization, tenant.organization_id)+++async def _join_in_directory(+ organization_directory: OrganizationDirectory,+ organization: Organization | None,+ user_id: str,+) -> None:+ """Ask the directory to make `user_id` a member of `organization`, after+ every write of the join and before its commit (`organization_directory.py`).+ A refusal is answered with its reason, and the join is rolled back."""+ if organization is None:returntry:- await organization_directory.join(- session,- organization_id=tenant.organization_id,- user_id=user_id,- role="member",- )- except DirectoryRefusal as refusal:- raise directory_refused(refusal) from None+ await organization_directory.join(organization, user_id, "member")+ except DirectoryError as error:+ raise directory_failed(error, NOTHING_CHANGED) from Noneasync def _join_through(@@ -911,9 +918,7 @@ async def _join_through(status_code=403, detail="This invitation has already been used") from excrole = invitation.role- await _join_organization_of(- session, organization_directory, tenant_id, caller.id- )+ joining = await _organization_to_join(session, tenant_id, caller.id)await user_store.add_membership(session,tenant_id=tenant_id,@@ -939,6 +944,7 @@ async def _join_through("invitation_accepted",{"age_hours": age_hours(invitation.created_at)},)+ await _join_in_directory(organization_directory, joining, caller.id)return await _enter(session, tenant_id, caller, user_store)@@ -1257,9 +1263,7 @@ async def join_tenant_by_domain(role = await user_store.tenant_role(session, tenant_id, caller.id)if role is None:role = "member"- await _join_organization_of(- session, organization_directory, tenant_id, caller.id- )+ joining = await _organization_to_join(session, tenant_id, caller.id)await user_store.add_membership(session,tenant_id=tenant_id,@@ -1276,6 +1280,7 @@ async def join_tenant_by_domain(target_id=caller.id,details={"role": role, "domain": domain},)+ await _join_in_directory(organization_directory, joining, caller.id)membership, user = await _enter(session, tenant_id, caller, user_store)set_session_cookie(diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.pyindex 7f5921941..ee689f728 100644--- a/core/switch_core/gateway/workspace_creation.py+++ b/core/switch_core/gateway/workspace_creation.py@@ -50,7 +50,12 @@ from switch_core.gateway.schemas import (OrganizationSummary,TenantMembershipResponse,)-from switch_core.organization_directory import DirectoryRefusal, OrganizationDirectory+from switch_core.organization_directory import (+ DirectoryError,+ DirectoryOrganization,+ DirectoryRefusal,+ OrganizationDirectory,+)from switch_core.telemetry import emit_safelylogger = logging.getLogger(__name__)@@ -89,15 +94,23 @@ def _slugs(name: str) -> list[str]:]-def directory_refused(refusal: DirectoryRefusal) -> HTTPException:- """The answer when the organization directory refuses a change, or can't- be reached: its reason, and that nothing was changed."""- logger.warning("The organization directory refused a change: %s", refusal.message)+def directory_failed(error: DirectoryError, outcome: str) -> HTTPException:+ """The answer when the organization directory did not make a change: 409+ when it refused by its own rules, 503 when it could not be reached, with+ its reason and `outcome`, what that leaves in Switch."""+ logger.warning(+ "The organization directory did not make a change: %s", error.message+ )return HTTPException(- status_code=503, detail=f"{refusal.message} Nothing was changed."+ status_code=409 if isinstance(error, DirectoryRefusal) else 503,+ detail=f"{error.message} {outcome}",)+# `directory_failed`'s outcome for a change that had written nothing yet.+NOTHING_CHANGED = "Nothing was changed."++def _no_free_slug(kind: str, name: str) -> HTTPException:logger.error("Could not find a free slug for %s %r after %d attempts",@@ -219,8 +232,8 @@ async def create_organization_for(name,workspace_name,)- except DirectoryRefusal as refusal:- raise directory_refused(refusal) from None+ except DirectoryError as error:+ raise directory_failed(error, NOTHING_CHANGED) from Noneif allowance is not None:allowance.workspaces_created += 1await session.commit()@@ -262,16 +275,56 @@ async def create_organization(`workspace_name`. `creator` becomes the organization's `org_admin` andthe workspace's `owner`, a member there in their own right.- The directory records it first (`organization_directory.py`); a refusal- raises `DirectoryRefusal` before anything is written here. The- organization is committed next, because the workspace references it.- If the workspace then cannot be created, for any reason, the organization- is deleted again, so a failed creation leaves nothing behind.+ The directory records it first (`organization_directory.py`), since the+ row keeps what the directory knows it by; a `DirectoryError` there leaves+ nothing written. If Switch's rows then cannot be created, for any reason,+ the directory is asked to discard it again."""# Both names are checked before anything is written.workspace_slugs = _slugs(workspace_name)organization_slugs = _slugs(name)recorded = await organization_directory.create_organization(creator, name)+ try:+ return await _create_organization_rows(+ session_factory,+ user_store,+ organization_store,+ client_lifecycle,+ creator,+ recorded,+ name,+ organization_slugs,+ workspace_name,+ workspace_slugs,+ )+ except BaseException:+ try:+ await organization_directory.discard_organization(recorded)+ except Exception:+ logger.exception(+ "Could not discard organization %r from the directory after "+ "creating it in Switch failed; it is left there",+ name,+ )+ raise+++async def _create_organization_rows(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ organization_store: OrganizationStore,+ client_lifecycle: ClientLifecycleService,+ creator: User,+ recorded: DirectoryOrganization,+ name: str,+ organization_slugs: list[str],+ workspace_name: str,+ workspace_slugs: list[str],+) -> tuple[Organization, Tenant]:+ """The organization's row, its first workspace and its creator's+ memberships. The organization is committed first, because the workspace+ references it; if the workspace then cannot be created, the organization+ is deleted again."""organization: Organization | None = Nonefor slug in organization_slugs:candidate = Organization(diff --git a/core/switch_core/organization_directory.py b/core/switch_core/organization_directory.pyindex 91c1ac17f..35e6d19d2 100644--- a/core/switch_core/organization_directory.py+++ b/core/switch_core/organization_directory.py@@ -2,19 +2,20 @@Authorization reads Switch's own tables, `organizations` and`organization_members`, on every server, so no request waits on anything-else. The directory is what decides them. Every route that creates an-organization, adds someone to one or changes or ends their role there asks the-directory first, then writes Switch's rows:+else. The directory is what decides them:- `LocalDirectory`: Switch's tables are the record, so the write to them isthe whole change and the directory's step is nothing.-- A directory kept outside Switch makes the change there first, and Switch's- rows follow it. If it refuses or can't be reached it raises- `DirectoryRefusal`, and the route changes nothing in Switch.--The rules (the last Org Admin, nobody granting above their own role, removal-refused while someone is still in a workspace) are checked by the routes-before they ask, so they hold whichever directory is in use.+- A directory kept outside Switch is the record, and Switch's rows follow it.++Every route that creates an organization, adds someone to one or changes or+ends their role there runs every check of its own that can refuse first (the+last Org Admin, nobody granting above their own role, removal while someone+is still in a workspace), then asks the directory, then writes and commits.+A directory that refuses or can't be reached raises `DirectoryError`, and+Switch's rows are left as they were. A failure after the directory has+changed (the commit) leaves Switch behind the directory, and it is the+directory's own record that brings Switch's rows up to date."""from __future__ import annotations@@ -22,9 +23,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Protocol-from sqlalchemy.ext.asyncio import AsyncSession--from switch_core.db.models import User+from switch_core.db.models import Organization, User@dataclass(frozen=True)@@ -36,40 +35,53 @@ class DirectoryOrganization:customer_id: str | None-class DirectoryRefusal(Exception):- """The directory refused a change or could not be reached. `message` says- why, for people to read; nothing was changed in Switch."""+class DirectoryError(Exception):+ """The directory did not make a change. `message` says why, for people to+ read."""def __init__(self, message: str) -> None:super().__init__(message)self.message = message+class DirectoryUnavailable(DirectoryError):+ """The directory could not be reached or failed: trying again may work."""+++class DirectoryRefusal(DirectoryError):+ """The directory refused the change by its own rules: trying again won't."""++class OrganizationDirectory(Protocol):+ """Implementations work outside Switch's database, over the network, and+ bound every call: they are handed rows, never a session, and a route may+ hold locks while it waits on them."""+async def create_organization(self, creator: User, name: str) -> DirectoryOrganization:"""Record a new organization named `name`, with `creator` its- `org_admin`, before its row is written."""+ `org_admin`, before its rows are written."""...- async def join(- self, session: AsyncSession, *, organization_id: str, user_id: str, role: str- ) -> None:- """Make `user_id` a `role` member of `organization_id`, if not one- already. An existing membership keeps its role."""+ async def discard_organization(self, organization: DirectoryOrganization) -> None:+ """Undo `create_organization` when Switch could not create the rows+ that follow it."""+ ...++ async def join(self, organization: Organization, user_id: str, role: str) -> None:+ """Make `user_id` a `role` member of `organization`. Only asked for+ someone who is not a member yet."""...async def set_role(- self, session: AsyncSession, *, organization_id: str, user_id: str, role: str+ self, organization: Organization, user_id: str, role: str) -> None:- """Change a member's role in `organization_id` to `role`."""+ """Change a member's role in `organization` to `role`."""...- async def remove(- self, session: AsyncSession, *, organization_id: str, user_id: str- ) -> None:- """End `user_id`'s membership of `organization_id`."""+ async def remove(self, organization: Organization, user_id: str) -> None:+ """End `user_id`'s membership of `organization`."""...@@ -82,17 +94,16 @@ class LocalDirectory:) -> DirectoryOrganization:return DirectoryOrganization(workos_organization_id=None, customer_id=None)- async def join(- self, session: AsyncSession, *, organization_id: str, user_id: str, role: str- ) -> None:+ async def discard_organization(self, organization: DirectoryOrganization) -> None:+ return None++ async def join(self, organization: Organization, user_id: str, role: str) -> None:return Noneasync def set_role(- self, session: AsyncSession, *, organization_id: str, user_id: str, role: str+ self, organization: Organization, user_id: str, role: str) -> None:return None- async def remove(- self, session: AsyncSession, *, organization_id: str, user_id: str- ) -> None:+ async def remove(self, organization: Organization, user_id: str) -> None:return Nonediff --git a/core/tests/switch_core/gateway/test_organization_directory_routes.py b/core/tests/switch_core/gateway/test_organization_directory_routes.pyindex 515b68fd1..df91a5064 100644--- a/core/tests/switch_core/gateway/test_organization_directory_routes.py+++ b/core/tests/switch_core/gateway/test_organization_directory_routes.py@@ -1,12 +1,14 @@-"""Every route that changes who is in an organization asks the directory first.+"""Every route that changes who is in an organization asks the directory.Against Postgres, through the real routes, with a directory that records what-it is asked, or refuses. A refusal changes nothing in Switch, and a change the-rules refuse is never put to the directory.+it is asked, can't be reached, or refuses. The directory is asked last, once+Switch's own checks have passed, so a change they refuse is never put to it,+and a change it does not make leaves Switch's rows as they were."""from __future__ import annotations+import asynciofrom datetime import UTC, datetime, timedeltaimport pytest@@ -26,8 +28,10 @@ from switch_core.db.stores.invitation_store import InvitationStorefrom switch_core.db.stores.join_domain_store import JoinDomainStorefrom switch_core.gateway import dependencies as gw_depsfrom switch_core.organization_directory import (+ DirectoryError,DirectoryOrganization,DirectoryRefusal,+ DirectoryUnavailable,)from tests.switch_core.gateway.test_organization_routes import (_app,@@ -42,19 +46,22 @@ from tests.switch_core.gateway.test_organization_routes import ()UNREACHABLE = "The organization directory could not be reached."+NOT_ALLOWED = "The organization's plan allows no more members."+NOTHING_CHANGED = "Nothing was changed."class _Directory:- """Records what it is asked, in order; refuses everything when `refusing`."""+ """Records what it is asked, in order, and fails every change with+ `failure` when one is given."""- def __init__(self, *, refusing: bool) -> None:- self.refusing = refusing+ def __init__(self, failure: DirectoryError | None) -> None:+ self.failure = failureself.asked: list[tuple] = []def _answer(self, *call: object) -> None:self.asked.append(call)- if self.refusing:- raise DirectoryRefusal(UNREACHABLE)+ if self.failure is not None:+ raise self.failureasync def create_organization(self, creator: User, name: str@@ -64,30 +71,34 @@ class _Directory:workos_organization_id="org_EXAMPLE", customer_id="customer-example")- async def join(- self, session: AsyncSession, *, organization_id: str, user_id: str, role: str- ) -> None:- self._answer("join", organization_id, user_id, role)+ async def discard_organization(self, organization: DirectoryOrganization) -> None:+ self._answer("discard", organization.workos_organization_id)++ async def join(self, organization: Organization, user_id: str, role: str) -> None:+ self._answer("join", organization.id, user_id, role)async def set_role(- self, session: AsyncSession, *, organization_id: str, user_id: str, role: str+ self, organization: Organization, user_id: str, role: str) -> None:- self._answer("set_role", organization_id, user_id, role)+ self._answer("set_role", organization.id, user_id, role)- async def remove(- self, session: AsyncSession, *, organization_id: str, user_id: str- ) -> None:- self._answer("remove", organization_id, user_id)+ async def remove(self, organization: Organization, user_id: str) -> None:+ self._answer("remove", organization.id, user_id)@pytest.fixturedef directory() -> _Directory:- return _Directory(refusing=False)+ return _Directory(None)+++def unavailable() -> _Directory:+ return _Directory(DirectoryUnavailable(UNREACHABLE))@pytest.fixturedef refusing() -> _Directory:- return _Directory(refusing=True)+ return _Directory(DirectoryRefusal(NOT_ALLOWED))def _with(@@ -100,9 +111,9 @@ def _with(return app-def _refused(response) -> None:+def _unavailable(response, outcome: str = NOTHING_CHANGED) -> None:assert response.status_code == 503, response.text- assert response.json()["detail"] == f"{UNREACHABLE} Nothing was changed."+ assert response.json()["detail"] == f"{UNREACHABLE} {outcome}"async def _organization_of(session_factory, tenant_id: str) -> str:@@ -124,6 +135,11 @@ async def _outsider(session_factory) -> str:return await _user(session_factory, "user")+class _FailingLifecycle:+ async def create_tenant(self, name: str, slug: str, organization_id: str):+ raise RuntimeError("provisioning failed")++class TestCreating:async def test_the_directory_records_it_first_and_its_ids_are_kept(self, session_factory, directory: _Directory@@ -143,16 +159,16 @@ class TestCreating:assert organization.workos_organization_id == "org_EXAMPLE"assert organization.customer_id == "customer-example"- async def test_a_refusal_creates_nothing_and_counts_nothing(- self, session_factory, refusing: _Directory+ async def test_an_unreachable_directory_creates_nothing_and_counts_nothing(+ self, session_factory, unavailable: _Directory) -> None:ada = await _user(session_factory, "user")name = _name("Refused")- async with _client(_with(session_factory, refusing), ada, None) as client:+ async with _client(_with(session_factory, unavailable), ada, None) as client:response = await client.post("/organizations", json={"name": name})- _refused(response)+ _unavailable(response)async with session_factory() as session:assert (await session.scalar(@@ -162,6 +178,32 @@ class TestCreating:)assert await _workspaces_created(session_factory, ada) == 0+ async def test_a_refusal_by_its_own_rules_is_409(+ self, session_factory, refusing: _Directory+ ) -> None:+ ada = await _user(session_factory, "user")++ async with _client(_with(session_factory, refusing), ada, None) as client:+ response = await client.post("/organizations", json={"name": "Acme"})++ assert response.status_code == 409, response.text+ assert response.json()["detail"] == f"{NOT_ALLOWED} {NOTHING_CHANGED}"++ async def test_the_directory_discards_it_when_switch_cannot_create_it(+ self, session_factory, directory: _Directory+ ) -> None:+ ada = await _user(session_factory, "user")+ app = _with(session_factory, directory)+ app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: (+ _FailingLifecycle()+ )++ async with _client(app, ada, None) as client:+ with pytest.raises(RuntimeError, match="provisioning failed"):+ await client.post("/organizations", json={"name": "Acme"})++ assert directory.asked == [("create", ada, "Acme"), ("discard", "org_EXAMPLE")]+async def test_an_unusable_name_is_refused_before_the_directory_is_asked(self, session_factory, directory: _Directory) -> None:@@ -205,29 +247,29 @@ class TestJoining:assert directory.asked == [("join", organization_id, bob, "member")]assert await _role(session_factory, tenant_id, bob) == "member"- async def test_a_refused_join_leaves_the_invitation_unspent(- self, session_factory, refusing: _Directory, directory: _Directory+ async def test_a_failed_join_leaves_the_invitation_unspent(+ self, session_factory, unavailable: _Directory, directory: _Directory) -> None:ada = _name("ada")tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})token = await _invitation(session_factory, tenant_id, ada)bob = await _outsider(session_factory)- async with _client(_with(session_factory, refusing), bob, None) as client:+ async with _client(_with(session_factory, unavailable), bob, None) as client:refused = await client.post("/invitations/accept", json={"token": token})async with tenant_session(session_factory, tenant_id) as session:membership = await session.get(TenantMember, (tenant_id, bob))async with _client(_with(session_factory, directory), bob, None) as client:again = await client.post("/invitations/accept", json={"token": token})- _refused(refused)+ _unavailable(refused)assert membership is Noneassert await _role(session_factory, tenant_id, bob) == "member"# The single use was still there to spend.assert again.status_code == 200, again.textasync def test_joining_by_domain_joins_the_organization_in_the_directory(- self, session_factory, directory: _Directory, refusing: _Directory+ self, session_factory, directory: _Directory, unavailable: _Directory) -> None:ada = _name("ada")tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})@@ -238,19 +280,42 @@ class TestJoining:await session.commit()bob = await _outsider(session_factory)- async with _client(_with(session_factory, refusing), bob, None) as client:+ async with _client(_with(session_factory, unavailable), bob, None) as client:refused = await client.post(f"/joinable-tenants/{tenant_id}/join")async with _client(_with(session_factory, directory), bob, None) as client:joined = await client.post(f"/joinable-tenants/{tenant_id}/join")- _refused(refused)+ _unavailable(refused)assert joined.status_code == 200, joined.textorganization_id = await _organization_of(session_factory, tenant_id)assert directory.asked == [("join", organization_id, bob, "member")]+ async def test_an_org_admin_joining_by_domain_is_not_asked_about(+ self, session_factory, directory: _Directory+ ) -> None:+ """Already in the organization, so joining a workspace of it changes+ nothing there: the directory is not asked, and can't demote them."""+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}+ )+ async with tenant_session(session_factory, tenant_id) as session:+ await JoinDomainStore().add(+ session, domain="example.invalid", created_by=ada+ )+ await session.delete(await session.get(TenantMember, (tenant_id, bob)))+ await session.commit()++ async with _client(_with(session_factory, directory), bob, None) as client:+ joined = await client.post(f"/joinable-tenants/{tenant_id}/join")++ assert joined.status_code == 200, joined.text+ assert directory.asked == []+ assert await _role(session_factory, tenant_id, bob) == "org_admin"+class TestChangingRoles:- async def test_the_directory_is_asked_before_the_role_changes(+ async def test_the_directory_is_asked_for_a_change_of_role(self, session_factory, directory: _Directory) -> None:ada, bob = _name("ada"), _name("bob")@@ -272,9 +337,12 @@ class TestChangingRoles:# The second asked for the role bob already had: nothing to ask.assert directory.asked == [("set_role", organization_id, bob, "org_admin")]- async def test_a_refused_demotion_takes_nothing_away(- self, session_factory, refusing: _Directory+ async def test_a_failed_demotion_says_what_was_already_taken_away(+ self, session_factory, unavailable: _Directory) -> None:+ """Ending what an admin held through the organization is a check that+ can refuse (agents they own there), so it runs before the directory+ is asked, and a directory that then fails doesn't give it back."""ada, bob = _name("ada"), _name("bob")first = await _workspace(session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}@@ -282,15 +350,47 @@ class TestChangingRoles:second = await _second_workspace(session_factory, first)key = await _personal_key(session_factory, second, bob)- async with _client(_with(session_factory, refusing), ada, first) as client:+ async with _client(_with(session_factory, unavailable), ada, first) as client:response = await client.patch(f"/organizations/current/members/{bob}", json={"role": "member"})- _refused(response)+ _unavailable(+ response,+ "They keep their place in the organization, but what they held in "+ "workspaces they reached only as an organization admin has already "+ "been taken away.",+ )assert await _role(session_factory, first, bob) == "org_admin"- # What bob held where only org_admin let him in is still his.- assert await _key_exists(session_factory, key)+ assert not await _key_exists(session_factory, key)++ async def test_two_admins_demoting_each_other_at_once_ask_once(+ self, session_factory, directory: _Directory+ ) -> None:+ """The lock decides which demotion stands before the directory is+ asked, so the directory is never asked to demote both."""+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("owner", "org_admin")}+ )+ app = _with(session_factory, directory)++ async with (+ _client(app, ada, tenant_id) as as_ada,+ _client(app, bob, tenant_id) as as_bob,+ ):+ responses = await asyncio.gather(+ as_ada.patch(+ f"/organizations/current/members/{bob}", json={"role": "member"}+ ),+ as_bob.patch(+ f"/organizations/current/members/{ada}", json={"role": "member"}+ ),+ )++ first, second = sorted(response.status_code for response in responses)+ assert first == 200 and second in (403, 409)+ assert [call[0] for call in directory.asked] == ["set_role"]async def test_demoting_the_last_org_admin_is_refused_before_asking(self, session_factory, directory: _Directory@@ -318,7 +418,7 @@ class TestRemoving:await session.commit()return ada, bob, tenant_id- async def test_the_directory_is_asked_before_they_are_removed(+ async def test_the_directory_is_asked_to_remove_them(self, session_factory, directory: _Directory) -> None:ada, bob, tenant_id = await self._bob_in_no_workspace(session_factory)@@ -331,15 +431,17 @@ class TestRemoving:assert directory.asked == [("remove", organization_id, bob)]assert await _role(session_factory, tenant_id, bob) is None- async def test_a_refused_removal_keeps_them(- self, session_factory, refusing: _Directory+ async def test_a_failed_removal_keeps_them(+ self, session_factory, unavailable: _Directory) -> None:ada, bob, tenant_id = await self._bob_in_no_workspace(session_factory)- async with _client(_with(session_factory, refusing), ada, tenant_id) as client:+ async with _client(+ _with(session_factory, unavailable), ada, tenant_id+ ) as client:response = await client.delete(f"/organizations/current/members/{bob}")- _refused(response)+ _unavailable(response)assert await _role(session_factory, tenant_id, bob) == "member"async def test_someone_still_in_a_workspace_is_refused_before_asking(