Skip to content

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

feat(organizations): ask an organization directory before changing who is in one

Petr Bauche70ec7e14e61
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index b9e0a31f1..120519d86 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -85,6 +85,7 @@ from switch_core.gateway.workspace_services import (
router as workspace_services_router,
)
from switch_core.keys import Purpose
+from switch_core.organization_directory import OrganizationDirectory
from switch_core.providers.hosted import HostedControllerSettings
from switch_core.request_validation import validation_error_response
from switch_core.room_service import RoomService
@@ -110,6 +111,7 @@ def create_gateway_app(
invitation_store: InvitationStore,
join_domain_store: JoinDomainStore,
organization_store: OrganizationStore,
+ organization_directory: OrganizationDirectory,
template_store: TemplateStore,
usage_store: UsageStore,
budget_store: BudgetStore,
@@ -139,6 +141,7 @@ def create_gateway_app(
invitation_store=invitation_store,
join_domain_store=join_domain_store,
organization_store=organization_store,
+ organization_directory=organization_directory,
template_store=template_store,
usage_store=usage_store,
budget_store=budget_store,
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index 0639be65a..0f3b90d00 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -31,6 +31,7 @@ from switch_core.db.stores.template_store import TemplateStore
from switch_core.db.stores.usage_store import UsageStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.invite_mail import InviteMailer
+from switch_core.organization_directory import OrganizationDirectory
from switch_core.room_service import RoomService
from switch_core.rooms_yaml import RoomYamlService
from switch_core.telemetry import TelemetryService
@@ -56,6 +57,7 @@ def init_dependencies(
invitation_store: InvitationStore,
join_domain_store: JoinDomainStore,
organization_store: OrganizationStore,
+ organization_directory: OrganizationDirectory,
template_store: TemplateStore,
usage_store: UsageStore,
budget_store: BudgetStore,
@@ -82,6 +84,7 @@ def init_dependencies(
_state["invitation_store"] = invitation_store
_state["join_domain_store"] = join_domain_store
_state["organization_store"] = organization_store
+ _state["organization_directory"] = organization_directory
_state["template_store"] = template_store
_state["usage_store"] = usage_store
_state["budget_store"] = budget_store
@@ -214,6 +217,10 @@ def get_organization_store() -> OrganizationStore:
return _state["organization_store"] # type: ignore[no-any-return]
+def get_organization_directory() -> OrganizationDirectory:
+ return _state["organization_directory"] # type: ignore[no-any-return]
+
+
def get_usage_store() -> UsageStore:
return _state["usage_store"] # type: ignore[no-any-return]
diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.py
index 215508275..a2265fc2e 100644
--- a/core/switch_core/gateway/organizations.py
+++ b/core/switch_core/gateway/organizations.py
@@ -69,6 +69,7 @@ from switch_core.gateway.dependencies import (
get_api_key_store,
get_client_lifecycle,
get_config,
+ get_organization_directory,
get_organization_store,
get_protocol,
get_session,
@@ -95,8 +96,10 @@ from switch_core.gateway.workspace_access import (
from switch_core.gateway.workspace_creation import (
create_organization_for,
create_workspace,
+ directory_refused,
lock_workspace_allowance,
)
+from switch_core.organization_directory import DirectoryRefusal, OrganizationDirectory
router = APIRouter()
@@ -193,6 +196,9 @@ async def create_organization(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> OrganizationCreateResponse:
@@ -213,6 +219,7 @@ async def create_organization(
session_factory,
user_store,
organization_store,
+ organization_directory,
client_lifecycle,
config,
name=req.name,
@@ -486,6 +493,9 @@ async def update_organization_member_role(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
@@ -498,7 +508,8 @@ async def update_organization_member_role(
Refuses to demote the last `org_admin`: nobody else could grant the role
again. Demoting someone first takes away what they hold in the workspaces
they were in only as `org_admin` (`_end_access_through_organization`).
- Recorded in the organization's audit log.
+ Once the rules pass, the directory is asked before anything is changed
+ (`organization_directory.py`). Recorded in the organization's audit log.
"""
access = await require_organization_admin(
session, user_store, organization_store, user, operator_restores=True
@@ -518,6 +529,16 @@ 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 None
warning = None
if demoting:
@@ -581,6 +602,9 @@ async def remove_organization_member(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
@@ -595,7 +619,8 @@ async def remove_organization_member(
one workspace at a time. An `org_admin` also stands in workspaces they
hold no membership row in, and what they hold there is taken away first
(`_end_access_through_organization`). Refuses the last `org_admin` too.
- Recorded in the organization's audit log.
+ Once the rules pass, the directory is asked before anything is changed
+ (`organization_directory.py`). Recorded in the organization's audit log.
"""
access = await require_organization_admin(
session, user_store, organization_store, user, operator_restores=False
@@ -626,6 +651,12 @@ 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 = None
if was_admin:
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 23a0f1b5d..04933f4b2 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -82,6 +82,7 @@ from switch_core.gateway.dependencies import (
get_invitation_store,
get_invite_mailer,
get_join_domain_store,
+ get_organization_directory,
get_organization_store,
get_protocol,
get_session,
@@ -126,7 +127,11 @@ from switch_core.gateway.workspace_access import (
finish_revocation,
revoke_workspace_access,
)
-from switch_core.gateway.workspace_creation import create_organization_for
+from switch_core.gateway.workspace_creation import (
+ create_organization_for,
+ directory_refused,
+)
+from switch_core.organization_directory import DirectoryRefusal, OrganizationDirectory
from switch_core.telemetry import emit_safely
from switch_core.telemetry.ages import age_hours
from switch_core.tenant_context import current_tenant_id
@@ -332,6 +337,9 @@ async def create_tenant(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> TenantMembershipResponse:
@@ -347,6 +355,7 @@ async def create_tenant(
session_factory,
user_store,
organization_store,
+ organization_directory,
client_lifecycle,
config,
name=req.name,
@@ -794,6 +803,9 @@ async def accept_invitation(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> TenantMembershipResponse:
"""Accept an invitation, joining its tenant, and switch the caller's
@@ -833,7 +845,12 @@ async def accept_invitation(
_require_invitation_usable(invitation, caller.email)
membership, user = await _join_through(
- session, invitation, caller, user_store, invitation_store
+ session,
+ invitation,
+ caller,
+ user_store,
+ invitation_store,
+ organization_directory,
)
set_session_cookie(
@@ -842,12 +859,39 @@ 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."""
+ 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
+ try:
+ 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
+
+
async def _join_through(
session: AsyncSession,
invitation: Invitation,
caller: AuthenticatedCaller,
user_store: UserStore,
invitation_store: InvitationStore,
+ organization_directory: OrganizationDirectory,
) -> tuple[TenantMembershipResponse, User]:
"""Make `caller` a member of the invitation's tenant, spending one use,
select that tenant for them, and commit.
@@ -867,6 +911,9 @@ async def _join_through(
status_code=403, detail="This invitation has already been used"
) from exc
role = invitation.role
+ await _join_organization_of(
+ session, organization_directory, tenant_id, caller.id
+ )
await user_store.add_membership(
session,
tenant_id=tenant_id,
@@ -994,6 +1041,9 @@ async def accept_my_invitation(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
invitation_store: Annotated[InvitationStore, Depends(get_invitation_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> TenantMembershipResponse:
"""Accept an invitation addressed to the caller, by id, without its token,
@@ -1017,7 +1067,12 @@ async def accept_my_invitation(
raise HTTPException(status_code=404, detail="Invitation not found")
_require_invitation_usable(invitation, caller.email)
membership, user = await _join_through(
- session, invitation, caller, user_store, invitation_store
+ session,
+ invitation,
+ caller,
+ user_store,
+ invitation_store,
+ organization_directory,
)
set_session_cookie(
@@ -1183,6 +1238,9 @@ async def join_tenant_by_domain(
],
user_store: Annotated[UserStore, Depends(get_user_store)],
join_domain_store: Annotated[JoinDomainStore, Depends(get_join_domain_store)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> TenantMembershipResponse:
"""Join a workspace open to the domain of the caller's address, as a
@@ -1199,6 +1257,9 @@ 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
+ )
await user_store.add_membership(
session,
tenant_id=tenant_id,
diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.py
index 4c3eb2de1..7f5921941 100644
--- a/core/switch_core/gateway/workspace_creation.py
+++ b/core/switch_core/gateway/workspace_creation.py
@@ -50,6 +50,7 @@ from switch_core.gateway.schemas import (
OrganizationSummary,
TenantMembershipResponse,
)
+from switch_core.organization_directory import DirectoryRefusal, OrganizationDirectory
from switch_core.telemetry import emit_safely
logger = logging.getLogger(__name__)
@@ -88,6 +89,15 @@ 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)
+ return HTTPException(
+ status_code=503, detail=f"{refusal.message} 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",
@@ -169,6 +179,7 @@ async def create_organization_for(
session_factory: async_sessionmaker[AsyncSession],
user_store: UserStore,
organization_store: OrganizationStore,
+ organization_directory: OrganizationDirectory,
client_lifecycle: ClientLifecycleService,
config: SwitchConfig,
*,
@@ -197,15 +208,19 @@ async def create_organization_for(
user = allowance = await lock_workspace_allowance(
session, caller.id, config, new_organization=True
)
- organization, tenant = await create_organization(
- session_factory,
- user_store,
- organization_store,
- client_lifecycle,
- caller.id,
- name,
- workspace_name,
- )
+ try:
+ organization, tenant = await create_organization(
+ session_factory,
+ user_store,
+ organization_store,
+ organization_directory,
+ client_lifecycle,
+ user,
+ name,
+ workspace_name,
+ )
+ except DirectoryRefusal as refusal:
+ raise directory_refused(refusal) from None
if allowance is not None:
allowance.workspaces_created += 1
await session.commit()
@@ -237,24 +252,35 @@ async def create_organization(
session_factory: async_sessionmaker[AsyncSession],
user_store: UserStore,
organization_store: OrganizationStore,
+ organization_directory: OrganizationDirectory,
client_lifecycle: ClientLifecycleService,
- creator_id: str,
+ creator: User,
name: str,
workspace_name: str,
) -> tuple[Organization, Tenant]:
"""Create an organization named `name` and its first workspace, named
- `workspace_name`. `creator_id` becomes the organization's `org_admin` and
+ `workspace_name`. `creator` becomes the organization's `org_admin` and
the workspace's `owner`, a member there in their own right.
- The organization is committed first, because the workspace references it.
+ 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.
"""
# 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)
organization: Organization | None = None
- for slug in _slugs(name):
- candidate = Organization(id=str(uuid.uuid4()), name=name, slug=slug)
+ for slug in organization_slugs:
+ candidate = Organization(
+ id=str(uuid.uuid4()),
+ name=name,
+ slug=slug,
+ workos_organization_id=recorded.workos_organization_id,
+ customer_id=recorded.customer_id,
+ )
try:
async with organization_session(session_factory, candidate.id) as session:
await organization_store.create(session, candidate)
@@ -291,7 +317,7 @@ async def create_organization(
session_factory,
user_store,
tenant,
- creator_id,
+ creator.id,
organization_role=ORGANIZATION_ADMIN_ROLE,
new_organization=organization,
)
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index b7283e649..7300c0f43 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -200,6 +200,7 @@ from switch_core.observability.pool import (
pool_stats,
)
from switch_core.observability.query import instrument_queries
+from switch_core.organization_directory import LocalDirectory
from switch_core.outbound import guarded_async_client
from switch_core.ownership import Ownership
from switch_core.process_identity import new_process_id
@@ -1250,6 +1251,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:
invitation_store=invitation_store,
join_domain_store=join_domain_store,
organization_store=organization_store,
+ organization_directory=LocalDirectory(),
template_store=template_store,
usage_store=usage_store,
budget_store=budget_store,
diff --git a/core/switch_core/organization_directory.py b/core/switch_core/organization_directory.py
new file mode 100644
index 000000000..91c1ac17f
--- /dev/null
+++ b/core/switch_core/organization_directory.py
@@ -0,0 +1,98 @@
+"""Who keeps the record of organizations and their members.
+
+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:
+
+- `LocalDirectory`: Switch's tables are the record, so the write to them is
+ the 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.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Protocol
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import User
+
+
+@dataclass(frozen=True)
+class DirectoryOrganization:
+ """What a new organization is known by in the directory, kept on its
+ `organizations` row. Both None for an organization Switch keeps itself."""
+
+ workos_organization_id: str | None
+ 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."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(message)
+ self.message = message
+
+
+class OrganizationDirectory(Protocol):
+ 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."""
+ ...
+
+ 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 set_role(
+ self, session: AsyncSession, *, organization_id: str, user_id: str, role: str
+ ) -> None:
+ """Change a member's role in `organization_id` to `role`."""
+ ...
+
+ async def remove(
+ self, session: AsyncSession, *, organization_id: str, user_id: str
+ ) -> None:
+ """End `user_id`'s membership of `organization_id`."""
+ ...
+
+
+class LocalDirectory:
+ """Switch's own tables are the record: each change is the route's write
+ to them, and nothing is asked first."""
+
+ async def create_organization(
+ self, creator: User, name: str
+ ) -> 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:
+ return None
+
+ async def set_role(
+ self, session: AsyncSession, *, organization_id: str, user_id: str, role: str
+ ) -> None:
+ return None
+
+ async def remove(
+ self, session: AsyncSession, *, organization_id: str, user_id: str
+ ) -> None:
+ return None
diff --git a/core/tests/switch_core/gateway/test_app_route_mounting.py b/core/tests/switch_core/gateway/test_app_route_mounting.py
index 9a1a21dfe..7f284689d 100644
--- a/core/tests/switch_core/gateway/test_app_route_mounting.py
+++ b/core/tests/switch_core/gateway/test_app_route_mounting.py
@@ -10,6 +10,7 @@ from __future__ import annotations
from unittest.mock import MagicMock
from switch_core.gateway.app import create_gateway_app
+from switch_core.organization_directory import LocalDirectory
from tests.switch_core.test_config_teams_app import _config
@@ -35,6 +36,7 @@ def _app(**overrides: object) -> object:
invitation_store=MagicMock(),
join_domain_store=MagicMock(),
organization_store=MagicMock(),
+ organization_directory=LocalDirectory(),
template_store=MagicMock(),
usage_store=MagicMock(),
budget_store=MagicMock(),
diff --git a/core/tests/switch_core/gateway/test_organization_directory_routes.py b/core/tests/switch_core/gateway/test_organization_directory_routes.py
new file mode 100644
index 000000000..515b68fd1
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_organization_directory_routes.py
@@ -0,0 +1,357 @@
+"""Every route that changes who is in an organization asks the directory first.
+
+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.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from fastapi import FastAPI
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ Organization,
+ OrganizationMember,
+ Tenant,
+ TenantMember,
+ User,
+)
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.invitation_store import InvitationStore
+from switch_core.db.stores.join_domain_store import JoinDomainStore
+from switch_core.gateway import dependencies as gw_deps
+from switch_core.organization_directory import (
+ DirectoryOrganization,
+ DirectoryRefusal,
+)
+from tests.switch_core.gateway.test_organization_routes import (
+ _app,
+ _client,
+ _key_exists,
+ _name,
+ _personal_key,
+ _second_workspace,
+ _user,
+ _workspace,
+ _workspaces_created,
+)
+
+UNREACHABLE = "The organization directory could not be reached."
+
+
+class _Directory:
+ """Records what it is asked, in order; refuses everything when `refusing`."""
+
+ def __init__(self, *, refusing: bool) -> None:
+ self.refusing = refusing
+ self.asked: list[tuple] = []
+
+ def _answer(self, *call: object) -> None:
+ self.asked.append(call)
+ if self.refusing:
+ raise DirectoryRefusal(UNREACHABLE)
+
+ async def create_organization(
+ self, creator: User, name: str
+ ) -> DirectoryOrganization:
+ self._answer("create", creator.id, name)
+ return DirectoryOrganization(
+ 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 set_role(
+ self, session: AsyncSession, *, organization_id: str, user_id: str, role: str
+ ) -> None:
+ 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)
+
+
+def directory() -> _Directory:
+ return _Directory(refusing=False)
+
+
+def refusing() -> _Directory:
+ return _Directory(refusing=True)
+
+
+def _with(
+ session_factory: async_sessionmaker[AsyncSession], directory: _Directory
+) -> FastAPI:
+ app = _app(session_factory)
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: directory
+ app.dependency_overrides[gw_deps.get_invitation_store] = lambda: InvitationStore()
+ app.dependency_overrides[gw_deps.get_join_domain_store] = lambda: JoinDomainStore()
+ return app
+
+
+def _refused(response) -> None:
+ assert response.status_code == 503, response.text
+ assert response.json()["detail"] == f"{UNREACHABLE} Nothing was changed."
+
+
+async def _organization_of(session_factory, tenant_id: str) -> str:
+ async with tenant_session(session_factory, tenant_id) as session:
+ tenant = await session.get(Tenant, tenant_id)
+ assert tenant is not None and tenant.organization_id is not None
+ return tenant.organization_id
+
+
+async def _role(session_factory, tenant_id: str, user_id: str) -> str | None:
+ organization_id = await _organization_of(session_factory, tenant_id)
+ async with tenant_session(session_factory, tenant_id) as session:
+ member = await session.get(OrganizationMember, (organization_id, user_id))
+ return None if member is None else member.role
+
+
+async def _outsider(session_factory) -> str:
+ """Someone signed in who belongs to no workspace of the organization."""
+ return await _user(session_factory, "user")
+
+
+class TestCreating:
+ async def test_the_directory_records_it_first_and_its_ids_are_kept(
+ self, session_factory, directory: _Directory
+ ) -> None:
+ ada = await _user(session_factory, "user")
+
+ async with _client(_with(session_factory, directory), ada, None) as client:
+ response = await client.post("/organizations", json={"name": "Acme"})
+
+ assert response.status_code == 201, response.text
+ assert directory.asked == [("create", ada, "Acme")]
+ async with session_factory() as session:
+ organization = await session.get(
+ Organization, response.json()["organization"]["id"]
+ )
+ assert organization is not None
+ 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
+ ) -> None:
+ ada = await _user(session_factory, "user")
+ name = _name("Refused")
+
+ async with _client(_with(session_factory, refusing), ada, None) as client:
+ response = await client.post("/organizations", json={"name": name})
+
+ _refused(response)
+ async with session_factory() as session:
+ assert (
+ await session.scalar(
+ select(Organization).where(Organization.name == name)
+ )
+ is None
+ )
+ assert await _workspaces_created(session_factory, ada) == 0
+
+ async def test_an_unusable_name_is_refused_before_the_directory_is_asked(
+ self, session_factory, directory: _Directory
+ ) -> None:
+ ada = await _user(session_factory, "user")
+
+ async with _client(_with(session_factory, directory), ada, None) as client:
+ response = await client.post("/organizations", json={"name": "!!!"})
+
+ assert response.status_code == 400
+ assert directory.asked == []
+
+
+async def _invitation(session_factory, tenant_id: str, inviter: str) -> str:
+ async with tenant_session(session_factory, tenant_id) as session:
+ _invitation, token = await InvitationStore().create(
+ session,
+ role="member",
+ email=None,
+ expires_at=datetime.now(UTC) + timedelta(hours=1),
+ uses_remaining=1,
+ created_by=inviter,
+ )
+ await session.commit()
+ return token
+
+
+class TestJoining:
+ async def test_accepting_an_invitation_joins_the_organization_in_the_directory(
+ self, session_factory, 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, directory), bob, None) as client:
+ response = await client.post("/invitations/accept", json={"token": token})
+
+ assert response.status_code == 200, response.text
+ organization_id = await _organization_of(session_factory, tenant_id)
+ 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
+ ) -> 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:
+ 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)
+ assert membership is None
+ assert await _role(session_factory, tenant_id, bob) == "member"
+ # The single use was still there to spend.
+ assert again.status_code == 200, again.text
+
+ async def test_joining_by_domain_joins_the_organization_in_the_directory(
+ self, session_factory, directory: _Directory, refusing: _Directory
+ ) -> None:
+ ada = _name("ada")
+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+ async with tenant_session(session_factory, tenant_id) as session:
+ await JoinDomainStore().add(
+ session, domain="example.invalid", created_by=ada
+ )
+ await session.commit()
+ bob = await _outsider(session_factory)
+
+ async with _client(_with(session_factory, refusing), 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)
+ assert joined.status_code == 200, joined.text
+ organization_id = await _organization_of(session_factory, tenant_id)
+ assert directory.asked == [("join", organization_id, bob, "member")]
+
+
+class TestChangingRoles:
+ async def test_the_directory_is_asked_before_the_role_changes(
+ self, session_factory, directory: _Directory
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ )
+
+ async with _client(_with(session_factory, directory), ada, tenant_id) as client:
+ granted = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}
+ )
+ unchanged = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}
+ )
+
+ assert granted.status_code == 200, granted.text
+ assert unchanged.status_code == 200, unchanged.text
+ organization_id = await _organization_of(session_factory, tenant_id)
+ # 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
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ first = await _workspace(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}
+ )
+ 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:
+ response = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "member"}
+ )
+
+ _refused(response)
+ 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)
+
+ async def test_demoting_the_last_org_admin_is_refused_before_asking(
+ self, session_factory, directory: _Directory
+ ) -> None:
+ ada = _name("ada")
+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+
+ async with _client(_with(session_factory, directory), ada, tenant_id) as client:
+ response = await client.patch(
+ f"/organizations/current/members/{ada}", json={"role": "member"}
+ )
+
+ assert response.status_code == 409
+ assert directory.asked == []
+
+
+class TestRemoving:
+ async def _bob_in_no_workspace(self, session_factory) -> tuple[str, str, str]:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ )
+ async with tenant_session(session_factory, tenant_id) as session:
+ await session.delete(await session.get(TenantMember, (tenant_id, bob)))
+ await session.commit()
+ return ada, bob, tenant_id
+
+ async def test_the_directory_is_asked_before_they_are_removed(
+ self, session_factory, directory: _Directory
+ ) -> None:
+ ada, bob, tenant_id = await self._bob_in_no_workspace(session_factory)
+
+ async with _client(_with(session_factory, directory), ada, tenant_id) as client:
+ response = await client.delete(f"/organizations/current/members/{bob}")
+
+ assert response.status_code == 200, response.text
+ organization_id = await _organization_of(session_factory, tenant_id)
+ 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
+ ) -> 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:
+ response = await client.delete(f"/organizations/current/members/{bob}")
+
+ _refused(response)
+ assert await _role(session_factory, tenant_id, bob) == "member"
+
+ async def test_someone_still_in_a_workspace_is_refused_before_asking(
+ self, session_factory, directory: _Directory
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ )
+
+ async with _client(_with(session_factory, directory), ada, tenant_id) as client:
+ response = await client.delete(f"/organizations/current/members/{bob}")
+
+ assert response.status_code == 409
+ assert directory.asked == []
diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.py
index 6ab920633..9bda047cc 100644
--- a/core/tests/switch_core/gateway/test_organization_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_routes.py
@@ -46,6 +46,7 @@ from switch_core.gateway.auth import create_jwt, decode_jwt
from switch_core.gateway.organizations import router as organizations_router
from switch_core.gateway.tenants import router as tenants_router
from switch_core.keys import Keyring
+from switch_core.organization_directory import LocalDirectory
from tests.telemetry_records import recording_telemetry
_KEYRING = Keyring.parse(
@@ -87,6 +88,9 @@ def _app(
app.dependency_overrides[gw_deps.get_system_session] = _session_dep
app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: (
+ LocalDirectory()
+ )
app.dependency_overrides[gw_deps.get_organization_store] = lambda: (
OrganizationStore()
)
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 237c8c7fa..b69751ff4 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -73,6 +73,7 @@ from switch_core.gateway.invite_mail import (
)
from switch_core.gateway.tenants import router as tenants_router
from switch_core.keys import Keyring
+from switch_core.organization_directory import LocalDirectory
from tests.ownership import NeverOwned
from tests.switch_core.statement_counts import StatementCounts
@@ -158,6 +159,9 @@ def _app(
app.dependency_overrides[gw_deps.get_system_session] = _session_dep
app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: (
+ LocalDirectory()
+ )
app.dependency_overrides[gw_deps.get_agent_store] = lambda: AgentStore()
app.dependency_overrides[gw_deps.get_api_key_store] = lambda: ApiKeyStore()
app.dependency_overrides[gw_deps.get_invitation_store] = lambda: InvitationStore()
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
index de9655512..cc8169960 100644
--- a/core/tests/switch_core/gateway/test_tenant_resolution.py
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -74,6 +74,7 @@ from switch_core.gateway.auth_routes import router as auth_router
from switch_core.gateway.schemas import LoginRequest
from switch_core.gateway.tenants import router as tenants_router
from switch_core.keys import Keyring
+from switch_core.organization_directory import LocalDirectory
from tests.conftest import empty_the_database
_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
@@ -97,6 +98,9 @@ def _app(
app.dependency_overrides[gw_deps.get_session] = _session_dep
app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: (
+ LocalDirectory()
+ )
app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
keyring=_KEYRING, gateway_tenant_choice_enabled=choice_enabled
)
@@ -134,6 +138,9 @@ def _tenants_app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
app.dependency_overrides[gw_deps.get_system_session] = _session_dep
app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: (
+ LocalDirectory()
+ )
app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
keyring=_KEYRING,
gateway_cookie_secure=False,
@@ -160,6 +167,9 @@ def _session_app(
app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
app.dependency_overrides[gw_deps.get_system_session] = _session_dep
app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: (
+ LocalDirectory()
+ )
app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
keyring=_KEYRING,
gateway_signup_mode=signup_mode,
diff --git a/scripts/e2e_surface.py b/scripts/e2e_surface.py
index 1f75eb592..82a0aa305 100644
--- a/scripts/e2e_surface.py
+++ b/scripts/e2e_surface.py
@@ -98,6 +98,7 @@ _COLLABORATORS = (
"invitation_store",
"join_domain_store",
"organization_store",
+ "organization_directory",
"template_store",
"usage_store",
"budget_store",