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 WorkOS only for changes it needs (CHOO-3906)
Petr Bauch30eaa6efd304
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 3c4bfe364..b84940696 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -273,6 +273,18 @@ class UserStore:await session.flush()return await session.get(User, identity.user_id)+ async def oidc_subject(+ self, session: AsyncSession, user_id: str, iss: str+ ) -> str | None:+ """The `sub` `user_id` signs in as at issuer `iss`, or None if they+ have no identity there."""+ subject: str | None = await session.scalar(+ select(OidcIdentity.sub).where(+ OidcIdentity.user_id == user_id, OidcIdentity.iss == iss+ )+ )+ return subject+async def get_or_create_oidc_user(self,session: AsyncSession,diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex 8f852f26c..85ff261ae 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -23,7 +23,7 @@ from typing import Annotated, NamedTuplefrom fastapi import APIRouter, Depends, HTTPException, Query, Request, Responsefrom fastapi.responses import JSONResponse-from sqlalchemy import delete, select+from sqlalchemy import deletefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.authz import ORGANIZATION_ADMIN_ROLE@@ -41,7 +41,6 @@ from switch_core.db.audit import (record_organization_audit_event,)from switch_core.db.models import (- OidcIdentity,Organization,OrganizationMember,Tenant,@@ -89,7 +88,10 @@ from switch_core.gateway.schemas import (WorkspaceCreateRequest,)from switch_core.gateway.service_connections import service_refusal-from switch_core.gateway.workos_sign_in_routes import directory_access_token+from switch_core.gateway.workos_sign_in_routes import (+ directory_access_token,+ directory_subject,+)from switch_core.gateway.workspace_creation import (NOTHING_CHANGED,create_organization_for,@@ -103,6 +105,7 @@ from switch_core.organization_access import (workspaces_where_they_own_agents,)from switch_core.organization_directory import (+ NO_DIRECTORY_CHANGE,DirectoryError,DirectorySignInRequired,MemberChange,@@ -479,79 +482,97 @@ _ACCESS_ALREADY_ENDED = (async def _ask_directory(change: Callable[..., Awaitable[None]],- session: AsyncSession,- organization_id: str,+ organization: Organization,*args: str,member_change: MemberChange,access_ended: bool,) -> None:- """Ask the directory to make `change` to a member of `organization_id`,- with `args` and `member_change`: 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")+ """Ask the directory to make `change` to a member of `organization`, with+ `args` and `member_change`: 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."""outcome = _ACCESS_ALREADY_ENDED if access_ended else NOTHING_CHANGEDtry:await change(organization, *args, member_change)except DirectorySignInRequired as error:- raise _sign_in_required(error, outcome) from None+ raise _sign_in_required(error, outcome, access_ended) from Noneexcept DirectoryError as error:raise directory_failed(error, outcome) from None-def _sign_in_required(error: DirectorySignInRequired, outcome: str) -> HTTPException:+def _sign_in_required(+ error: DirectorySignInRequired, outcome: str, access_ended: bool+) -> HTTPException:"""403 the dashboard tells apart by its `error`: it sends the admin tosign in to the organization's WorkOS account and back to make the change- again (`gateway/workos_sign_in_routes.py`)."""+ again (`gateway/workos_sign_in_routes.py`). With `access_ended`, part of+ the change was made already, so the dashboard says so before it sends+ them anywhere."""return HTTPException(status_code=403,detail={"error": "directory_sign_in_required","message": f"{error.message} {outcome}",+ "access_ended": access_ended,},)+# Why an operator restoring an `org_admin` can't make the change in WorkOS.+_OPERATOR_CANNOT_SIGN_IN = (+ "This organization's admins are kept in its account settings, and an "+ "operator can't change them there. Have someone made org_admin in the "+ "organization's account settings; Switch follows once it reads them "+ "again. Nothing was changed."+)++async def _member_change(session: AsyncSession,+ user_store: UserStore,organization_directory: OrganizationDirectory,token: OrganizationToken | None,- organization_id: str,+ access: _OrganizationAccess,+ organization: Organization,user_id: str,+ role: str | None,) -> MemberChange:- """What a change to `user_id`'s membership carries for the directory: the- admin's token, when it was issued for the organization's WorkOS- organization, and `user_id`'s id there. Refuses, before anything is- changed, a change the directory takes only with a token there is none- of."""- organization = await session.get(Organization, organization_id)- if organization is None:- raise RuntimeError(f"Organization {organization_id} is not visible here")+ """What giving `user_id` `role` in `organization`, or removing them when+ `role` is None, needs of the directory, with the admin's token when it+ was issued for the organization's WorkOS organization. Asked before+ anything is changed and before any lock is taken, so a refusal or a+ sign-in costs nothing. An operator let in to restore an `org_admin` has+ no token to sign in for, and is told who can make the change instead."""access_token = (token.access_tokenif token is not Noneand token.workos_organization_id == organization.workos_organization_idelse None)+ subject = await directory_subject(+ session, user_store, organization_directory, user_id+ )try:- organization_directory.check_can_change(organization, access_token)- except DirectorySignInRequired as error:- raise _sign_in_required(error, NOTHING_CHANGED) from None- subject = (- await session.scalar(- select(OidcIdentity.sub).where(- OidcIdentity.user_id == user_id,- OidcIdentity.iss == organization_directory.identity_issuer,- )+ return await organization_directory.prepare_change(+ organization, subject, role, access_token)- if organization_directory.identity_issuer is not None- else None- )- return MemberChange(access_token=access_token, subject=subject)+ except DirectorySignInRequired as error:+ if access.platform_access:+ raise HTTPException(+ status_code=409, detail=_OPERATOR_CANNOT_SIGN_IN+ ) from None+ raise _sign_in_required(error, NOTHING_CHANGED, access_ended=False) from None+ except DirectoryError as error:+ raise directory_failed(error, NOTHING_CHANGED) from None+++async def _organization(session: AsyncSession, organization_id: str) -> Organization:+ organization = await session.get(Organization, organization_id)+ if organization is None:+ raise RuntimeError(f"Organization {organization_id} is not visible here")+ return organizationasync def _end_access_through_organization(@@ -637,16 +658,20 @@ async def update_organization_member_role(demoting = (member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE)+ organization = await _organization(session, organization_id)member_change = (await _member_change(session,+ user_store,organization_directory,directory_token,- organization_id,+ access,+ organization,user_id,+ req.role,)if member.role != req.role- else MemberChange(access_token=None, subject=None)+ else NO_DIRECTORY_CHANGE)last_admin = HTTPException(status_code=409, detail="Cannot demote the last organization admin"@@ -692,8 +717,7 @@ async def update_organization_member_role(if member.role != req.role:await _ask_directory(organization_directory.set_role,- session,- organization_id,+ organization,user_id,req.role,member_change=member_change,@@ -769,9 +793,7 @@ async def remove_organization_member(and await organization_store.count_admins(session, organization_id) <= 1):raise last_admin- member_change = await _member_change(- session, organization_directory, directory_token, organization_id, user_id- )+ organization = await _organization(session, organization_id)# Let go of the request's connection while each workspace is read on a# session of its own.await session.commit()@@ -785,6 +807,17 @@ async def remove_organization_member(status_code=409,detail=(f"Remove them from the organization's workspaces first: {names}"),)+ member_change = await _member_change(+ session,+ user_store,+ organization_directory,+ directory_token,+ access,+ organization,+ user_id,+ None,+ )+ await session.commit()warning = Noneif was_admin:try:@@ -815,8 +848,7 @@ async def remove_organization_member(raise last_adminawait _ask_directory(organization_directory.remove,- session,- organization_id,+ organization,user_id,member_change=member_change,access_ended=was_admin,diff --git a/core/switch_core/gateway/workos_sign_in_routes.py b/core/switch_core/gateway/workos_sign_in_routes.pyindex 6897e8f5a..8b6f1c9b7 100644--- a/core/switch_core/gateway/workos_sign_in_routes.py+++ b/core/switch_core/gateway/workos_sign_in_routes.py@@ -19,14 +19,12 @@ from typing import Annotatedfrom urllib.parse import urlsplitfrom fastapi import APIRouter, Depends, HTTPException, Request-from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom starlette.responses import RedirectResponsefrom switch_core.authz import ORGANIZATION_ADMIN_ROLEfrom switch_core.config import SwitchConfigfrom switch_core.db.models import (- OidcIdentity,Organization,Tenant,User,@@ -56,10 +54,13 @@ router = APIRouter()_PENDING_KEY = "workos_organization_sign_in"_TOKEN_KEY = "workos_organization_token"-# A change is started only with a token that outlasts it.-_TOKEN_MARGIN_SECONDS = 60-# A dashboard path, and nothing that could leave it.-_RETURN_TO = re.compile(r"^/[A-Za-z0-9/_.-]*$")+# A change is started only with a token that outlasts it: a demotion or a+# removal ends workspace access, one workspace at a time, before the members+# service is called.+_TOKEN_MARGIN_SECONDS = 120+# A dashboard path, and nothing that could leave it: no `//`, which a browser+# reads as another host.+_RETURN_TO = re.compile(r"^/(?!/)[A-Za-z0-9/_.-]*$")def _sign_in(request: Request) -> WorkOSOrganizationSignIn:@@ -72,18 +73,21 @@ def _sign_in(request: Request) -> WorkOSOrganizationSignIn:return sign_in-async def _subject_of(- session: AsyncSession, organization_directory: OrganizationDirectory, user: User+async def directory_subject(+ session: AsyncSession,+ user_store: UserStore,+ organization_directory: OrganizationDirectory,+ user_id: str,) -> str | None:+ """The directory's id for `user_id`: their subject under its+ `identity_issuer`, or None where it has none or they have no identity+ there. What the admin's token must be issued to, and what a change to+ someone's membership names them by."""if organization_directory.identity_issuer is None:return None- subject: str | None = await session.scalar(- select(OidcIdentity.sub).where(- OidcIdentity.user_id == user.id,- OidcIdentity.iss == organization_directory.identity_issuer,- )+ return await user_store.oidc_subject(+ session, user_id, organization_directory.identity_issuer)- return subject@router.get("/auth/workos/organization")@@ -146,6 +150,7 @@ async def finish_organization_sign_in(code: str,state: str,session: Annotated[AsyncSession, Depends(get_session)],+ user_store: Annotated[UserStore, Depends(get_user_store)],config: Annotated[SwitchConfig, Depends(get_config)],organization_directory: Annotated[OrganizationDirectory, Depends(get_organization_directory)@@ -177,7 +182,9 @@ async def finish_organization_sign_in(except DirectoryUnavailable as error:logger.warning("WorkOS organization sign-in failed: %s", error.message)raise HTTPException(status_code=503, detail=error.message) from error- if token.subject != await _subject_of(session, organization_directory, user):+ if token.subject != await directory_subject(+ session, user_store, organization_directory, user.id+ ):logger.warning("User %s signed in to WorkOS as %s, which is not the WorkOS user ""their account signs in as; the token is dropped",diff --git a/core/switch_core/members_service.py b/core/switch_core/members_service.pyindex 52edeea86..5dae0650c 100644--- a/core/switch_core/members_service.py+++ b/core/switch_core/members_service.py@@ -8,10 +8,10 @@ WorkOS access token for the organization (`gateway/workos_sign_in.py`), nevera credential of its own: the service sees who acted and decides by theirlive role there, as it does for its own product.-The calls, each acting on the organization the token was issued for:+The calls, each acting on the organization the token was issued for and on+a membership by its WorkOS id (`workos_directory.py` reads it with the API+key, before any lock is taken):-- `GET {url}/v1/auth/tenants/members?limit=&offset=`: its members, a page at- a time, `{"data": [{"id", "user_id", "role": {"slug"}}], "total"}`;- `PATCH {url}/v1/auth/tenants/members/{id}` with `{"role": <slug>}`;- `DELETE {url}/v1/auth/tenants/members/{id}`.@@ -20,8 +20,6 @@ A refusal comes back as `{"error": <reason>}`.from __future__ import annotations-from typing import Any-import httpxfrom switch_core.organization_directory import (@@ -32,8 +30,6 @@ from switch_core.organization_directory import (# Bounds every call: a route holds locks while it waits.MEMBERS_SERVICE_TIMEOUT_SECONDS = 10.0-# The service's largest page.-_PAGE = 100SIGN_IN_AGAIN = ("Your sign-in to your organization's account has ended. Confirm it again "@@ -46,40 +42,6 @@ class MembersService:self._http = httpself._url = url.rstrip("/")- async def membership_of(self, access_token: str, subject: str) -> str | None:- """The id of WorkOS user `subject`'s membership of the token's- organization, or None when they have none."""- offset = 0- while True:- body = await self._call(- "GET",- "/v1/auth/tenants/members",- access_token,- params={"limit": str(_PAGE), "offset": str(offset)},- )- page = body.get("data")- total = body.get("total")- if not isinstance(page, list) or not isinstance(total, int):- raise DirectoryUnavailable(- "The members service answered with something Switch can't read."- )- for membership in page:- if not isinstance(membership, dict):- raise DirectoryUnavailable(- "The members service answered with something Switch can't read."- )- if membership.get("user_id") == subject:- found = membership.get("id")- if not isinstance(found, str):- raise DirectoryUnavailable(- "The members service answered with a membership "- "that has no id."- )- return found- offset += len(page)- if not page or offset >= total:- return None-async def set_role(self, access_token: str, membership_id: str, role: str) -> None:await self._call("PATCH",@@ -99,14 +61,12 @@ class MembersService:path: str,access_token: str,*,- params: dict[str, str] | None = None,json: dict[str, str] | None = None,- ) -> dict[str, Any]:+ ) -> None:try:response = await self._http.request(method,f"{self._url}{path}",- params=params,json=json,headers={"Authorization": f"Bearer {access_token}"},timeout=MEMBERS_SERVICE_TIMEOUT_SECONDS,@@ -123,19 +83,6 @@ class MembersService:raise DirectoryUnavailable(f"The members service answered {response.status_code}.")- if method == "DELETE" or not response.content:- return {}- try:- body = response.json()- except ValueError as error:- raise DirectoryUnavailable(- "The members service answered with no JSON."- ) from error- if not isinstance(body, dict):- raise DirectoryUnavailable(- "The members service answered with something Switch can't read."- )- return bodydef _reason(response: httpx.Response) -> str:diff --git a/core/switch_core/organization_directory.py b/core/switch_core/organization_directory.pyindex afde3a9f6..4e2a50f55 100644--- a/core/switch_core/organization_directory.py+++ b/core/switch_core/organization_directory.py@@ -72,14 +72,17 @@ class DirectorySignInRequired(DirectoryError):@dataclass(frozen=True)class MemberChange:- """What a change made from Switch to someone's membership carries for the- directory: the access token the directory issued the admin making it for- the organization, and the directory's own id for the person it is about- (their `oidc_identities` subject under `identity_issuer`). Either is None- where there is none."""+ """What a change made from Switch to someone's membership needs the+ directory to do, worked out by `prepare_change` before anything is+ changed: the directory's own id for the membership to change, None when+ the directory needs no change, and the access token the directory issued+ the admin making it for the organization, None when there is none."""access_token: str | None- subject: str | None+ membership_id: str | None+++NO_DIRECTORY_CHANGE = MemberChange(access_token=None, membership_id=None)class OrganizationDirectory(Protocol):@@ -88,15 +91,24 @@ class OrganizationDirectory(Protocol):hold locks while it waits on them."""# The OIDC issuer whose subjects are the directory's ids for people, for- # a route to read a `MemberChange.subject` with; None where it has none.+ # a route to look up the subject `prepare_change` takes; None where it has+ # none.identity_issuer: str | None- def check_can_change(- self, organization: Organization, access_token: str | None- ) -> None:- """Raise `DirectorySignInRequired` when a change to `organization`'s- members needs a token from the admin and `access_token` is None.- Asked before a route changes anything, so a sign-in costs nothing."""+ async def prepare_change(+ self,+ organization: Organization,+ subject: str | None,+ role: str | None,+ access_token: str | None,+ ) -> MemberChange:+ """What giving the person the directory knows as `subject` the role+ `role` in `organization`, or removing them when `role` is None, needs+ of the directory. Asked before a route changes anything, and before+ it takes any lock: raises `DirectorySignInRequired` when the directory+ has to change and takes the change only with a token from the admin,+ and `access_token` is None; `DirectoryRefusal` when it won't take it+ at all."""...def sends_changes_for(self, organization: Organization) -> bool:@@ -144,13 +156,15 @@ class OrganizationDirectory(Protocol):role: str,change: MemberChange,) -> None:- """Change a member's role in `organization` to `role`."""+ """Change a member's role in `organization` to `role`, with what+ `prepare_change` worked out for it."""...async def remove(self, organization: Organization, user_id: str, change: MemberChange) -> None:- """End `user_id`'s membership of `organization`."""+ """End `user_id`'s membership of `organization`, with what+ `prepare_change` worked out for it."""...@@ -160,10 +174,14 @@ class LocalDirectory:identity_issuer: str | None = None- def check_can_change(- self, organization: Organization, access_token: str | None- ) -> None:- return None+ async def prepare_change(+ self,+ organization: Organization,+ subject: str | None,+ role: str | None,+ access_token: str | None,+ ) -> MemberChange:+ return NO_DIRECTORY_CHANGEdef sends_changes_for(self, organization: Organization) -> bool:return Falsediff --git a/core/switch_core/workos_directory.py b/core/switch_core/workos_directory.pyindex a2928fee9..a021de0d1 100644--- a/core/switch_core/workos_directory.py+++ b/core/switch_core/workos_directory.py@@ -18,9 +18,9 @@ user id, which the sign-in's `sub` is.Changes made from Switch to a linked organization go through the membersservice (`members_service.py`), with the admin's own WorkOS token for it, notthrough this module's API key, so each product's rules apply in one place.-Making someone Org Admin makes them `org_admin` in WorkOS; making them a-Member makes them `viewer` there, the least a member of a shared organization-can be. Adding someone stays refused: nobody from Switch can add a person to+Making someone Org Admin makes them `org_admin` in WorkOS; making an+`org_admin` there a Member makes them `viewer`, the least a member of a shared+organization can be. A change WorkOS doesn't need is not sent. Adding someone stays refused: nobody from Switch can add a person tothe organization yet. Where no members service is configured, those thatgrant are refused, and those that take away (a removal, a demotion) changeonly Switch, so an Org Admin can end access WorkOS has already ended, until@@ -40,6 +40,7 @@ from switch_core.authz import ORGANIZATION_ADMIN_ROLEfrom switch_core.db.models import Organization, Userfrom switch_core.members_service import MembersServicefrom switch_core.organization_directory import (+ NO_DIRECTORY_CHANGE,DirectoryMembership,DirectoryOrganization,DirectoryRefusal,@@ -63,6 +64,9 @@ NOT_FROM_SWITCH_YET = ("This organization's members are managed in your organization's account ""settings, not here yet.")+NOT_IN_THE_ACCOUNT = (+ "They are not a member of your organization's account; add them there first."+)SIGN_IN_FIRST = ("Confirm your sign-in to your organization's account to change its members.")@@ -204,17 +208,31 @@ class WorkOSDirectory:) -> str | None:"""Switch's role for WorkOS user `subject`'s active membership of`workos_organization_id`, or None if they hold none."""- memberships = await self._list(+ membership = await self._active_membership(subject, workos_organization_id)+ return None if membership is None else switch_role(membership[1])++ async def _active_membership(+ self, subject: str, workos_organization_id: str+ ) -> tuple[str, str] | None:+ """The id and WorkOS role of WorkOS user `subject`'s active membership+ of `workos_organization_id`, or None if they hold none. One filtered+ read, however many members the organization has."""+ for item in await self._list("/user_management/organization_memberships",{"user_id": subject,"organization_id": workos_organization_id,"statuses": "active",},- )- for membership in self._read_memberships(memberships):- if membership.workos_organization_id == workos_organization_id:- return membership.role+ ):+ if item.get("organization_id") != workos_organization_id:+ continue+ membership_id = item.get("id")+ role = item.get("role")+ slug = role.get("slug") if isinstance(role, dict) else None+ if not isinstance(membership_id, str) or not isinstance(slug, str):+ raise _unreadable("a membership")+ return membership_id, slugreturn Noneasync def organization_members(self, workos_organization_id: str) -> dict[str, str]:@@ -273,15 +291,46 @@ class WorkOSDirectory:existing accounts."""return await self._list("/user_management/users", {"email": email})- def check_can_change(- self, organization: Organization, access_token: str | None- ) -> None:- if (- organization.workos_organization_id is not None- and self._members is not None- and access_token is None- ):+ async def prepare_change(+ self,+ organization: Organization,+ subject: str | None,+ role: str | None,+ access_token: str | None,+ ) -> MemberChange:+ """Nothing for an organization nobody linked. Through the members+ service, WorkOS changes only where it has to: making someone Org Admin+ is refused for someone WorkOS doesn't list, and needs nothing for+ someone it already has as `org_admin`; making them a Member changes+ WorkOS only where it has them as `org_admin`, so a role they hold+ there for another product stays; a removal ends the membership WorkOS+ has. Someone with no WorkOS identity is in no WorkOS organization, and+ someone WorkOS no longer lists needs nothing: Switch is catching up.+ Without the service, granting is refused and taking away changes only+ Switch."""+ workos_organization_id = organization.workos_organization_id+ if workos_organization_id is None:+ return NO_DIRECTORY_CHANGE+ promoting = role == ORGANIZATION_ADMIN_ROLE+ if self._members is None:+ if promoting:+ raise DirectoryRefusal(NOT_FROM_SWITCH_YET)+ return NO_DIRECTORY_CHANGE+ membership = (+ None+ if subject is None+ else await self._active_membership(subject, workos_organization_id)+ )+ if membership is None:+ if promoting:+ raise DirectoryRefusal(NOT_IN_THE_ACCOUNT)+ return NO_DIRECTORY_CHANGE+ membership_id, workos_role = membership+ if role is not None and (workos_role == ORGANIZATION_ADMIN_ROLE) == promoting:+ return NO_DIRECTORY_CHANGE+ if access_token is None:raise DirectorySignInRequired(SIGN_IN_FIRST)+ return MemberChange(access_token=access_token, membership_id=membership_id)def sends_changes_for(self, organization: Organization) -> bool:return (@@ -314,62 +363,34 @@ class WorkOSDirectory:role: str,change: MemberChange,) -> None:- """Through the members service where there is one. A demotion of- someone WorkOS no longer lists needs nothing: it is Switch catching up.- Without the service, taking Org Admin away needs nothing from WorkOS- either, and a sign-in or the mirror makes them Org Admin again for as- long as WorkOS still has them as one."""- if organization.workos_organization_id is None:- return None- promoting = role == ORGANIZATION_ADMIN_ROLE- if self._members is None:- if promoting:- raise DirectoryRefusal(NOT_FROM_SWITCH_YET)- return None- access_token = _token_of(change)- membership = await self._membership(access_token, user_id, change)- if membership is None:- if promoting:- raise DirectoryRefusal(- "They are not a member of your organization's account; "- "add them there first."- )+ if change.membership_id is None:return None- await self._members.set_role(- access_token,- membership,- ORGANIZATION_ADMIN_ROLE if promoting else MEMBER_ROLE_IN_WORKOS,+ await self._members_service().set_role(+ _token_of(change),+ change.membership_id,+ ORGANIZATION_ADMIN_ROLE+ if role == ORGANIZATION_ADMIN_ROLE+ else MEMBER_ROLE_IN_WORKOS,)async def remove(self, organization: Organization, user_id: str, change: MemberChange) -> None:- """Through the members service where there is one; someone WorkOS no- longer lists needs nothing. Without it, as with a demotion: Switch- catching up with a removal in WorkOS, undone for as long as WorkOS- still lists them."""- if organization.workos_organization_id is None or self._members is None:+ if change.membership_id is None:return None- access_token = _token_of(change)- membership = await self._membership(access_token, user_id, change)- if membership is not None:- await self._members.remove(access_token, membership)+ await self._members_service().remove(_token_of(change), change.membership_id)- async def _membership(- self, access_token: str, user_id: str, change: MemberChange- ) -> str | None:- assert self._members is not None- if change.subject is None:- raise DirectoryRefusal(- f"User {user_id} has no WorkOS identity, so their membership "- "there can't be changed from Switch."+ def _members_service(self) -> MembersService:+ if self._members is None:+ raise RuntimeError(+ "A membership change for the members service, where there is none")- return await self._members.membership_of(access_token, change.subject)+ return self._membersdef _token_of(change: MemberChange) -> str:- """The admin's token; `check_can_change` has refused a change without one- before anything was changed, so its absence here is a route's mistake."""+ """The admin's token; `prepare_change` has refused a change that needs+ one without it, so its absence here is a route's mistake."""if change.access_token is None:raise DirectorySignInRequired(SIGN_IN_FIRST)return change.access_tokendiff --git a/core/tests/switch_core/gateway/test_organization_directory_routes.py b/core/tests/switch_core/gateway/test_organization_directory_routes.pyindex c2cca1577..00da2e3f8 100644--- a/core/tests/switch_core/gateway/test_organization_directory_routes.py+++ b/core/tests/switch_core/gateway/test_organization_directory_routes.py@@ -28,6 +28,7 @@ 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 (+ NO_DIRECTORY_CHANGE,DirectoryError,DirectoryOrganization,DirectoryRefusal,@@ -61,10 +62,14 @@ class _Directory:self.failure = failureself.asked: list[tuple] = []- def check_can_change(- self, organization: Organization, access_token: str | None- ) -> None:- return None+ async def prepare_change(+ self,+ organization: Organization,+ subject: str | None,+ role: str | None,+ access_token: str | None,+ ) -> MemberChange:+ return NO_DIRECTORY_CHANGEdef sends_changes_for(self, organization: Organization) -> bool:return Truediff --git a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py b/core/tests/switch_core/gateway/test_workos_sign_in_routes.pyindex 510fb0a2f..c363db181 100644--- a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py+++ b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py@@ -33,6 +33,7 @@ from tests.switch_core.gateway.test_organization_routes import (_app,_client,_name,+ _operator,_workspace,)@@ -42,14 +43,16 @@ ADMIN_TOKEN_OF = "token-of-"class _WorkOS:- """WorkOS's sign-in, answering every code as `signs_in_as` in- `organization`, and the members service, listing `members` (WorkOS user- -> membership id) and recording each change with the token it came with."""+ """WorkOS, answering every sign-in code as `signs_in_as` in+ `organization` and listing `members` (WorkOS user -> (membership id,+ role)) to the API key, and the members service, recording each change+ with the token it came with, or answering it with `refuses_with`."""- def __init__(self, members: dict[str, str]) -> None:+ def __init__(self, members: dict[str, tuple[str, str]]) -> None:self.signs_in_as = ""self.organization = WORKOS_ORGANIZATIONself.members = members+ self.refuses_with: int | None = Noneself.changes: list[tuple[str, str, str]] = []def sign_in(self, request: httpx.Request) -> httpx.Response:@@ -66,18 +69,30 @@ class _WorkOS:},)+ def api(self, request: httpx.Request) -> httpx.Response:+ assert request.url.path == "/user_management/organization_memberships"+ subject = request.url.params["user_id"]+ listed = self.members.get(subject)+ return httpx.Response(+ 200,+ json={+ "data": []+ if listed is None+ else [+ {+ "id": listed[0],+ "user_id": subject,+ "organization_id": request.url.params["organization_id"],+ "role": {"slug": listed[1]},+ }+ ],+ "list_metadata": {"after": None},+ },+ )+def members_service(self, request: httpx.Request) -> httpx.Response:- if request.method == "GET":- return httpx.Response(- 200,- json={- "data": [- {"id": membership, "user_id": subject}- for subject, membership in self.members.items()- ],- "total": len(self.members),- },- )+ if self.refuses_with is not None:+ return httpx.Response(self.refuses_with, json={"error": "refused"})self.changes.append((request.method,@@ -93,9 +108,7 @@ def _with() -> FastAPI:app = _app(session_factory)directory = WorkOSDirectory(- httpx.AsyncClient(- transport=httpx.MockTransport(lambda request: httpx.Response(500))- ),+ httpx.AsyncClient(transport=httpx.MockTransport(workos.api)),"workos-api-key-placeholder","https://api.workos.example.test",ISSUER,@@ -176,7 +189,7 @@ class TestChangingMembers:tenant_id, organization_id = await _linked(session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")})- workos = _WorkOS({f"user_{bob}": "om_bob"})+ workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})workos.signs_in_as = f"user_{ada}"async with _client(_with(session_factory, workos), ada, tenant_id) as client:@@ -205,7 +218,7 @@ class TestChangingMembers:tenant_id, organization_id = await _linked(session_factory, {ada: ("owner", "org_admin"), cy: ("admin", "org_admin")})- workos = _WorkOS({f"user_{cy}": "om_cy"})+ workos = _WorkOS({f"user_{cy}": ("om_cy", "org_admin")})async with _client(_with(session_factory, workos), ada, tenant_id) as client:refused = await client.patch(@@ -236,7 +249,7 @@ class TestChangingMembers:)session.add(OidcIdentity(user_id=dee, iss=ISSUER, sub=f"user_{dee}"))await session.commit()- workos = _WorkOS({f"user_{dee}": "om_dee"})+ workos = _WorkOS({f"user_{dee}": ("om_dee", "viewer")})workos.signs_in_as = f"user_{ada}"async with _client(_with(session_factory, workos), ada, tenant_id) as client:@@ -247,6 +260,125 @@ class TestChangingMembers:assert [(m, om) for m, om, _ in workos.changes] == [("DELETE", "om_dee")]assert await _role(session_factory, organization_id, dee) is None+ async def test_a_change_workos_does_not_need_waits_for_no_sign_in(+ self, session_factory+ ) -> None:+ """Someone WorkOS lists in a role of another product, or not at all,+ or who has no WorkOS identity, is made a Member in Switch alone."""+ ada, cy, eli, fay = _name("ada"), _name("cy"), _name("eli"), _name("fay")+ tenant_id, organization_id = await _linked(+ session_factory,+ {+ ada: ("owner", "org_admin"),+ cy: ("admin", "org_admin"),+ eli: ("admin", "org_admin"),+ fay: ("admin", "org_admin"),+ },+ )+ async with session_factory() as session:+ identity = await session.scalar(+ select(OidcIdentity).where(OidcIdentity.user_id == fay)+ )+ await session.delete(identity)+ await session.commit()+ workos = _WorkOS({f"user_{cy}": ("om_cy", "editor")})++ async with _client(_with(session_factory, workos), ada, tenant_id) as client:+ made = [+ await client.patch(+ f"/organizations/current/members/{who}", json={"role": "member"}+ )+ for who in (cy, eli, fay)+ ]++ assert [response.status_code for response in made] == [200, 200, 200]+ assert workos.changes == []+ for who in (cy, eli, fay):+ assert await _role(session_factory, organization_id, who) == "member"++ async def test_a_removal_refused_for_its_workspaces_asks_for_no_sign_in(+ self, session_factory+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id, _ = await _linked(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}+ )+ workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})++ async with _client(_with(session_factory, workos), ada, tenant_id) as client:+ refused = await client.delete(f"/organizations/current/members/{bob}")++ assert refused.status_code == 409+ assert "workspaces first" in refused.json()["detail"]++ async def test_a_token_refused_after_access_was_ended_says_so(+ self, session_factory+ ) -> None:+ ada, cy = _name("ada"), _name("cy")+ tenant_id, organization_id = await _linked(+ session_factory, {ada: ("owner", "org_admin"), cy: ("admin", "org_admin")}+ )+ workos = _WorkOS({f"user_{cy}": ("om_cy", "org_admin")})+ workos.signs_in_as = f"user_{ada}"++ async with _client(_with(session_factory, workos), ada, tenant_id) as client:+ await _sign_in_to_workos(client)+ workos.refuses_with = 401+ refused = await client.patch(+ f"/organizations/current/members/{cy}", json={"role": "member"}+ )++ assert refused.status_code == 403+ detail = refused.json()["detail"]+ assert detail["error"] == "directory_sign_in_required"+ assert detail["access_ended"] is True+ assert "already been taken away" in detail["message"]+ assert await _role(session_factory, organization_id, cy) == "org_admin"+++class TestOperatorRestoring:+ async def test_an_operator_is_told_who_can_make_the_change(+ self, session_factory+ ) -> None:+ bob = _name("bob")+ tenant_id, organization_id = await _linked(+ session_factory, {bob: ("owner", "member")}+ )+ operator_id = await _operator(session_factory)+ workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})++ async with _client(+ _with(session_factory, workos), operator_id, tenant_id+ ) as client:+ refused = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}+ )++ assert refused.status_code == 409+ assert "account settings" in refused.json()["detail"]+ assert await _role(session_factory, organization_id, bob) == "member"++ async def test_an_operator_restores_whom_workos_already_has_as_org_admin(+ self, session_factory+ ) -> None:+ bob = _name("bob")+ tenant_id, organization_id = await _linked(+ session_factory, {bob: ("owner", "member")}+ )+ operator_id = await _operator(session_factory)+ workos = _WorkOS({f"user_{bob}": ("om_bob", "org_admin")})++ async with _client(+ _with(session_factory, workos), operator_id, tenant_id+ ) as client:+ restored = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}+ )++ assert restored.status_code == 200, restored.text+ assert workos.changes == []+ assert await _role(session_factory, organization_id, bob) == "org_admin"+class TestSigningIn:async def test_signing_in_as_someone_else_keeps_no_token(@@ -256,7 +388,7 @@ class TestSigningIn:tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")})- workos = _WorkOS({f"user_{bob}": "om_bob"})+ workos = _WorkOS({f"user_{bob}": ("om_bob", "viewer")})workos.signs_in_as = f"user_{bob}"async with _client(_with(session_factory, workos), ada, tenant_id) as client:@@ -318,14 +450,19 @@ class TestSigningIn:"/auth/workos/organization", params={"return_to": "/organization"})async with _client(app, ada, tenant_id) as client:- elsewhere = await client.get(- "/auth/workos/organization",- params={"return_to": "https://elsewhere.example.test/"},- )+ elsewhere = [+ await client.get(+ "/auth/workos/organization", params={"return_to": return_to}+ )+ for return_to in (+ "https://elsewhere.example.test/",+ "//elsewhere.example.test/organization",+ )+ ]assert as_member.status_code == 403assert not_linked.status_code == 409- assert elsewhere.status_code == 400+ assert [response.status_code for response in elsewhere] == [400, 400]async def test_nothing_to_sign_in_to_where_changes_are_not_sent(self, session_factorydiff --git a/core/tests/switch_core/test_members_service.py b/core/tests/switch_core/test_members_service.pyindex e999738c6..1b20af049 100644--- a/core/tests/switch_core/test_members_service.py+++ b/core/tests/switch_core/test_members_service.py@@ -24,47 +24,6 @@ def _service(handler) -> MembersService:)-def _membership(membership_id: str, subject: str) -> dict:- return {"id": membership_id, "user_id": subject, "role": {"slug": "viewer"}}---class TestFindingAMembership:- async def test_pages_through_with_the_admins_token(self) -> None:- seen: list[httpx.Request] = []-- def handler(request: httpx.Request) -> httpx.Response:- seen.append(request)- offset = int(request.url.params["offset"])- page = (- [_membership(f"om_{i}", f"user_{i}") for i in range(100)]- if offset == 0- else [_membership("om_x", "user_wanted")]- )- return httpx.Response(200, json={"data": page, "total": 101})-- found = await _service(handler).membership_of(TOKEN, "user_wanted")-- assert found == "om_x"- assert [r.url.params["offset"] for r in seen] == ["0", "100"]- assert all(r.headers["Authorization"] == f"Bearer {TOKEN}" for r in seen)- assert seen[0].url.path == "/v1/auth/tenants/members"-- async def test_someone_not_listed_has_none(self) -> None:- def handler(request: httpx.Request) -> httpx.Response:- return httpx.Response(- 200, json={"data": [_membership("om_1", "user_1")], "total": 1}- )-- assert await _service(handler).membership_of(TOKEN, "user_2") is None-- async def test_an_answer_switch_cannot_read_is_unavailable(self) -> None:- def handler(request: httpx.Request) -> httpx.Response:- return httpx.Response(200, json={"items": []})-- with pytest.raises(DirectoryUnavailable):- await _service(handler).membership_of(TOKEN, "user_1")--class TestChanging:async def test_a_role_is_set_by_membership(self) -> None:seen: list[httpx.Request] = []@@ -81,6 +40,7 @@ class TestChanging:"/v1/auth/tenants/members/om_1",)assert json.loads(request.content) == {"role": "org_admin"}+ assert request.headers["Authorization"] == f"Bearer {TOKEN}"async def test_a_membership_is_removed(self) -> None:seen: list[httpx.Request] = []diff --git a/core/tests/switch_core/test_workos_directory.py b/core/tests/switch_core/test_workos_directory.pyindex ef0fd1fc0..ae051fcf3 100644--- a/core/tests/switch_core/test_workos_directory.py+++ b/core/tests/switch_core/test_workos_directory.py@@ -11,6 +11,7 @@ import pytestfrom switch_core.members_service import MembersServicefrom switch_core.organization_directory import (+ NO_DIRECTORY_CHANGE,DirectoryMembership,DirectoryOrganization,DirectoryRefusal,@@ -85,7 +86,6 @@ class _WorkOS:ISSUER = "https://sign-in.example.test"-NO_CHANGE = MemberChange(access_token=None, subject=None)def _directory(handler) -> WorkOSDirectory:@@ -210,7 +210,7 @@ class TestChangesFromSwitch:for change in (directory.join(linked, "u", "member"), # type: ignore[arg-type]- directory.set_role(linked, "u", "org_admin", NO_CHANGE), # type: ignore[arg-type]+ directory.prepare_change(linked, "user_u", "org_admin", "admin-token"), # type: ignore[arg-type]):with pytest.raises(DirectoryRefusal):await change@@ -221,8 +221,11 @@ class TestChangesFromSwitch:directory = _directory(lambda request: httpx.Response(500))linked = SimpleNamespace(workos_organization_id="org_a")- await directory.set_role(linked, "u", "member", NO_CHANGE) # type: ignore[arg-type]- await directory.remove(linked, "u", NO_CHANGE) # type: ignore[arg-type]+ for role in ("member", None):+ assert (+ await directory.prepare_change(linked, "user_u", role, None) # type: ignore[arg-type]+ == NO_DIRECTORY_CHANGE+ )def test_it_keeps_the_members_of_a_linked_organization_only(self) -> None:directory = _directory(lambda request: httpx.Response(500))@@ -239,8 +242,8 @@ class TestChangesFromSwitch:local = SimpleNamespace(workos_organization_id=None)await directory.join(local, "u", "member") # type: ignore[arg-type]- await directory.set_role(local, "u", "org_admin", NO_CHANGE) # type: ignore[arg-type]- await directory.remove(local, "u", NO_CHANGE) # type: ignore[arg-type]+ await directory.set_role(local, "u", "org_admin", NO_DIRECTORY_CHANGE) # type: ignore[arg-type]+ await directory.remove(local, "u", NO_DIRECTORY_CHANGE) # type: ignore[arg-type]async def test_a_new_organization_is_switchs_own_until_linked(self) -> None:directory = _directory(lambda request: httpx.Response(500))@@ -253,122 +256,176 @@ class TestChangesFromSwitch:await directory.discard_organization(created)-def _with_members(handler) -> WorkOSDirectory:- """A directory whose members service is answered by `handler`; WorkOS- itself fails, being asked nothing."""+def _with_members(+ listed: dict[str, tuple[str, str]], changes: list[tuple[str, str, object]]+) -> WorkOSDirectory:+ """A directory over a WorkOS organization `org_a` listing `listed` (WorkOS+ user -> (membership id, WorkOS role)), whose members service records each+ change as (method, membership id, body)."""++ def workos(request: httpx.Request) -> httpx.Response:+ assert request.url.path == "/user_management/organization_memberships"+ assert request.headers["Authorization"] == f"Bearer {KEY}"+ assert request.url.params["organization_id"] == "org_a"+ subject = request.url.params["user_id"]+ return httpx.Response(+ 200,+ json={+ "data": [+ {+ "id": listed[subject][0],+ "user_id": subject,+ "organization_id": "org_a",+ "role": {"slug": listed[subject][1]},+ }+ ]+ if subject in listed+ else [],+ "list_metadata": {"after": None},+ },+ )++ def members_service(request: httpx.Request) -> httpx.Response:+ body = json.loads(request.content) if request.content else None+ changes.append((request.method, request.url.path.rsplit("/", 1)[1], body))+ return httpx.Response(200, json={})+return WorkOSDirectory(- httpx.AsyncClient(- transport=httpx.MockTransport(lambda request: httpx.Response(500))- ),+ httpx.AsyncClient(transport=httpx.MockTransport(workos)),KEY,API,ISSUER,MembersService(- httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ httpx.AsyncClient(transport=httpx.MockTransport(members_service)),"https://members.example.test",),)-def _members_service(listed: dict[str, str], changes: list[tuple[str, str, object]]):- """Lists `listed` (WorkOS user -> membership id) and records each change- as (method, membership id, body)."""-- def handler(request: httpx.Request) -> httpx.Response:- if request.method == "GET":- return httpx.Response(- 200,- json={- "data": [- {- "id": membership,- "user_id": subject,- "role": {"slug": "viewer"},- }- for subject, membership in listed.items()- ],- "total": len(listed),- },- )- body = json.loads(request.content) if request.content else None- changes.append((request.method, request.url.path.rsplit("/", 1)[1], body))- return httpx.Response(200, json={})-- return handler+LINKED = SimpleNamespace(workos_organization_id="org_a")+TOKEN = "admin-token"-LINKED = SimpleNamespace(workos_organization_id="org_a")-WITH_TOKEN = MemberChange(access_token="admin-token", subject="user_bob")+async def _change(+ directory: WorkOSDirectory, subject: str | None, role: str | None+) -> None:+ """Prepare the change and make it, as a route does."""+ change = await directory.prepare_change(LINKED, subject, role, TOKEN) # type: ignore[arg-type]+ if role is None:+ await directory.remove(LINKED, "bob", change) # type: ignore[arg-type]+ else:+ await directory.set_role(LINKED, "bob", role, change) # type: ignore[arg-type]class TestChangesThroughTheMembersService:- def test_a_change_to_a_linked_organization_needs_the_admins_token(self) -> None:- directory = _with_members(lambda request: httpx.Response(500))+ async def test_a_change_workos_needs_waits_for_the_admins_token(self) -> None:+ directory = _with_members({"user_bob": ("om_bob", "viewer")}, [])with pytest.raises(DirectorySignInRequired):- directory.check_can_change(LINKED, None) # type: ignore[arg-type]- directory.check_can_change(LINKED, "admin-token") # type: ignore[arg-type]- directory.check_can_change(- SimpleNamespace(workos_organization_id=None), # type: ignore[arg-type]- None,- )+ await directory.prepare_change(LINKED, "user_bob", "org_admin", None) # type: ignore[arg-type]+ assert await directory.prepare_change(+ LINKED, # type: ignore[arg-type]+ "user_bob",+ "org_admin",+ TOKEN,+ ) == MemberChange(access_token=TOKEN, membership_id="om_bob")assert directory.sends_changes_for(LINKED) # type: ignore[arg-type]- def test_without_the_service_nothing_needs_a_token(self) -> None:+ async def test_an_organization_nobody_linked_needs_nothing(self) -> None:+ directory = _with_members({}, [])++ assert (+ await directory.prepare_change(+ SimpleNamespace(workos_organization_id=None), # type: ignore[arg-type]+ "user_bob",+ "org_admin",+ None,+ )+ == NO_DIRECTORY_CHANGE+ )++ def test_without_the_service_changes_are_not_sent(self) -> None:directory = _directory(lambda request: httpx.Response(500))- directory.check_can_change(LINKED, None) # type: ignore[arg-type]assert not directory.sends_changes_for(LINKED) # type: ignore[arg-type]- async def test_org_admin_is_org_admin_and_member_is_viewer(self) -> None:+ async def test_org_admin_is_org_admin_and_an_org_admin_made_member_is_viewer(+ self,+ ) -> None:changes: list[tuple[str, str, object]] = []- directory = _with_members(_members_service({"user_bob": "om_bob"}, changes))- await directory.set_role(LINKED, "bob", "org_admin", WITH_TOKEN) # type: ignore[arg-type]- await directory.set_role(LINKED, "bob", "member", WITH_TOKEN) # type: ignore[arg-type]+ await _change(+ _with_members({"user_bob": ("om_bob", "viewer")}, changes),+ "user_bob",+ "org_admin",+ )+ await _change(+ _with_members({"user_bob": ("om_bob", "org_admin")}, changes),+ "user_bob",+ "member",+ )assert changes == [("PATCH", "om_bob", {"role": "org_admin"}),("PATCH", "om_bob", {"role": "viewer"}),]+ async def test_a_role_workos_already_has_is_not_sent_and_needs_no_token(+ self,+ ) -> None:+ """Someone `editor` in WorkOS for another product keeps that role when+ Switch makes them a Member."""+ for listed_as, role in (("org_admin", "org_admin"), ("editor", "member")):+ directory = _with_members({"user_bob": ("om_bob", listed_as)}, [])++ assert (+ await directory.prepare_change(LINKED, "user_bob", role, None) # type: ignore[arg-type]+ == NO_DIRECTORY_CHANGE+ )+async def test_a_removal_removes_their_membership(self) -> None:changes: list[tuple[str, str, object]] = []- directory = _with_members(_members_service({"user_bob": "om_bob"}, changes))- await directory.remove(LINKED, "bob", WITH_TOKEN) # type: ignore[arg-type]+ await _change(+ _with_members({"user_bob": ("om_bob", "editor")}, changes),+ "user_bob",+ None,+ )assert changes == [("DELETE", "om_bob", None)]async def test_taking_away_what_workos_has_ended_needs_nothing(self) -> None:- changes: list[tuple[str, str, object]] = []- directory = _with_members(_members_service({}, changes))-- await directory.set_role(LINKED, "bob", "member", WITH_TOKEN) # type: ignore[arg-type]- await directory.remove(LINKED, "bob", WITH_TOKEN) # type: ignore[arg-type]+ directory = _with_members({}, [])- assert changes == []+ for role in ("member", None):+ assert (+ await directory.prepare_change(LINKED, "user_bob", role, None) # type: ignore[arg-type]+ == NO_DIRECTORY_CHANGE+ )- async def test_someone_workos_does_not_list_cannot_be_made_org_admin(+ async def test_someone_with_no_workos_identity_is_in_no_workos_organization(self,) -> None:- directory = _with_members(_members_service({}, []))+ directory = _with_members({}, [])+ for role in ("member", None):+ assert (+ await directory.prepare_change(LINKED, None, role, None) # type: ignore[arg-type]+ == NO_DIRECTORY_CHANGE+ )with pytest.raises(DirectoryRefusal, match="add them there first"):- await directory.set_role(LINKED, "bob", "org_admin", WITH_TOKEN) # type: ignore[arg-type]+ await directory.prepare_change(LINKED, None, "org_admin", TOKEN) # type: ignore[arg-type]- async def test_someone_with_no_workos_identity_is_refused(self) -> None:- directory = _with_members(_members_service({}, []))+ async def test_someone_workos_does_not_list_cannot_be_made_org_admin(+ self,+ ) -> None:+ directory = _with_members({}, [])- with pytest.raises(DirectoryRefusal, match="no WorkOS identity"):- await directory.remove(- LINKED, # type: ignore[arg-type]- "bob",- MemberChange(access_token="admin-token", subject=None),- )+ with pytest.raises(DirectoryRefusal, match="add them there first"):+ await directory.prepare_change(LINKED, "user_bob", "org_admin", TOKEN) # type: ignore[arg-type]async def test_adding_someone_is_still_refused(self) -> None:- directory = _with_members(_members_service({}, []))+ directory = _with_members({}, [])with pytest.raises(DirectoryRefusal):await directory.join(LINKED, "bob", "member") # type: ignore[arg-type]@@ -461,7 +518,11 @@ class TestWhatTheMirrorReads:200,json={"data": [- {"organization_id": "org_a", "role": {"slug": "org_admin"}}+ {+ "id": "om_A",+ "organization_id": "org_a",+ "role": {"slug": "org_admin"},+ }]},)diff --git a/docs/old/workos-directory.md b/docs/old/workos-directory.mdindex f7e46f3e1..4b911ef7f 100644--- a/docs/old/workos-directory.md+++ b/docs/old/workos-directory.md@@ -119,11 +119,10 @@ stays) apply once for all of them. Switch can send its changes to such aservice. Set all three, or none:- `MEMBERS_SERVICE_URL`: the service. Switch calls, with the admin's token,- `GET /v1/auth/tenants/members` (paginated with `limit` and `offset`,- answering `{"data": [{"id", "user_id"}], "total"}`),- `PATCH /v1/auth/tenants/members/{id}` with `{"role": <slug>}`, and+ `PATCH /v1/auth/tenants/members/{id}` with `{"role": <slug>}` and`DELETE /v1/auth/tenants/members/{id}`, each acting on the organization- the token was issued for, and reads a refusal's `{"error": ...}`.+ the token was issued for, and reads a refusal's `{"error": ...}`. The+ membership `id` is WorkOS's, which Switch reads with its API key.- `WORKOS_CLIENT_ID`: the AuthKit application Switch signs admins in to forthat token.- `WORKOS_REDIRECT_URL`: its callback, `.../gateway/auth/workos/callback`,@@ -132,15 +131,24 @@ service. Set all three, or none:Then, on a linked organization, making a member Org Admin makes them`org_admin` in WorkOS, making an Org Admin a Member makes them `viewer`there, and removing someone removes their membership there, so each change-lasts. Switch uses no credential of its own for this: the first time an admin-changes the members, the dashboard sends them to sign in to the organization+lasts. Switch first reads the person's membership from WorkOS and sends only+what WorkOS needs: someone WorkOS already has as `org_admin` is not made one+again, someone it holds in another product's role keeps that role when made+a Member, and someone it no longer lists, or who has no WorkOS identity, is+changed in Switch alone. Switch uses no credential of its own for the change+itself: the first time an admin makes one WorkOS needs, the dashboard sends them to sign in to the organizationthrough the AuthKit application (usually without a prompt, while theirAuthKit session lasts) and makes the change on their return. Switch keeps theaccess token that sign-in gives, encrypted in the browser's short-livedsign-in cookie, only for as long as the token lasts, and keeps no refreshtoken. A sign-in as another WorkOS user than the one the Switch account signsin as, or to another organization, is refused. Switch's own checks still run-first; the service may refuse by its own rules, and its reason is shown.+first; the service may refuse by its own rules, and its reason is shown. If+the token runs out after a demotion or removal has already taken away the+person's workspace access, the dashboard says so before sending the admin to+sign in again to finish. A platform operator restoring an Org Admin can't+sign in there: unless WorkOS already has that person as `org_admin`, they are+told to have someone made one in the organization's account settings.Adding someone new to a linked organization from Switch is still refused.diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 3639c276c..c6ceb14c6 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1481,8 +1481,13 @@ export function oidcLoginUrl(): string {/** Where an admin signs in to their organization's WorkOS account, for the* token a change to its members needs, and comes back to `returnTo`. */+// A dashboard path, and nothing that could leave it: no `//`, which a browser+// reads as another host. The server checks the same.+const DASHBOARD_PATH = /^\/(?!\/)[A-Za-z0-9/_.-]*$/;+export function organizationSignInUrl(returnTo: string): string {- return `${BASE}/auth/workos/organization?return_to=${encodeURIComponent(returnTo)}`;+ const path = DASHBOARD_PATH.test(returnTo) ? returnTo : "/organization";+ return `${BASE}/auth/workos/organization?return_to=${encodeURIComponent(path)}`;}/** The server's answer when a change to a linked organization's members@@ -1492,6 +1497,15 @@ export function needsOrganizationSignIn(err: unknown): boolean {return (err.detail as Record<string, unknown>).error === "directory_sign_in_required";}+/** Whether the change that asked for a sign-in had already taken away the+ * person's workspace access before it did. */+export function signInAfterAccessEnded(err: unknown): boolean {+ return (+ needsOrganizationSignIn(err) &&+ (err as ApiError & { detail: Record<string, unknown> }).detail.access_ended === true+ );+}+export async function changePassword(currentPassword: string,newPassword: string,diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsxindex e2fe688e8..92b210baf 100644--- a/gateway/src/pages/organization/OrganizationMembersSection.tsx+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx@@ -1,6 +1,7 @@import DeleteOutline from "@mui/icons-material/DeleteOutline";import {Alert,+ Button,CircularProgress,IconButton,MenuItem,@@ -20,6 +21,7 @@ import {needsOrganizationSignIn,organizationSignInUrl,removeOrganizationMember,+ signInAfterAccessEnded,updateOrganizationRole,} from "../../data/api";import { formatDate } from "../../theme/hootFormat";@@ -33,9 +35,13 @@ const ROLE_LABELS: Record<OrganizationRole, string> = {};/** A change kept across the sign-in to the organization's WorkOS account it- * waited on, made again once, on coming back. */+ * waited on, made again once, on coming back: only in the organization it was+ * made in, and only while the sign-in it waited on could still be coming back+ * (the server keeps a started sign-in for ten minutes). */type MemberChange = { userId: string; role: OrganizationRole } | { userId: string; remove: true };+type PendingChange = { change: MemberChange; organizationId: string; savedAt: number };const PENDING_CHANGE_KEY = "switch.pendingOrganizationMemberChange";+const PENDING_CHANGE_TTL_MS = 10 * 60 * 1000;function make(change: MemberChange): Promise<{ warning: string | null }> {return "remove" in change@@ -43,12 +49,26 @@ function make(change: MemberChange): Promise<{ warning: string | null }> {: updateOrganizationRole(change.userId, change.role);}-function takePendingChange(): MemberChange | null {+function signInThenMake(change: MemberChange, organizationId: string): void {+ const pending: PendingChange = { change, organizationId, savedAt: Date.now() };+ window.sessionStorage.setItem(PENDING_CHANGE_KEY, JSON.stringify(pending));+ window.location.href = organizationSignInUrl(window.location.pathname);+}++function takePendingChange(organizationId: string): MemberChange | null {const kept = window.sessionStorage.getItem(PENDING_CHANGE_KEY);window.sessionStorage.removeItem(PENDING_CHANGE_KEY);if (kept === null) return null;try {- return JSON.parse(kept) as MemberChange;+ const pending = JSON.parse(kept) as PendingChange;+ if (+ pending.organizationId !== organizationId ||+ typeof pending.savedAt !== "number" ||+ Date.now() - pending.savedAt > PENDING_CHANGE_TTL_MS+ ) {+ return null;+ }+ return pending.change;} catch {return null;}@@ -62,12 +82,14 @@ function takePendingChange(): MemberChange | null {* revoked at a vendor comes back as a warning, shown too. */export default function OrganizationMembersSection({selfId,+ organizationId,asOperator,fromDirectory,directoryTakesChanges,onChanged,}: {selfId: string;+ organizationId: string;// The platform operator, who is no admin here, may manage the members only// while the organization has no admin left, to make one.asOperator: boolean;@@ -87,6 +109,9 @@ export default function OrganizationMembersSection({const [actionError, setActionError] = useState<string | null>(null);const [actionWarning, setActionWarning] = useState<string | null>(null);const [busy, setBusy] = useState<string | null>(null);+ // A change that ended someone's workspace access and then asked for a+ // sign-in, for the admin to finish knowingly.+ const [toFinish, setToFinish] = useState<MemberChange | null>(null);const { refresh } = useAuth();const act = useCallback(@@ -94,6 +119,7 @@ export default function OrganizationMembersSection({setBusy(change.userId);setActionError(null);setActionWarning(null);+ setToFinish(null);try {const { warning } = await make(change);setActionWarning(warning);@@ -105,26 +131,29 @@ export default function OrganizationMembersSection({// Once only: a change made again after the sign-in that still asks// for one is shown as the failure it is, not sent round again. The// operator is no member there and has nothing to sign in as.+ // A change that already took something away says so first.if (needsOrganizationSignIn(err) && !replayed && !asOperator) {- window.sessionStorage.setItem(PENDING_CHANGE_KEY, JSON.stringify(change));- window.location.href = organizationSignInUrl(window.location.pathname);- return;+ if (!signInAfterAccessEnded(err)) {+ signInThenMake(change, organizationId);+ return;+ }+ setToFinish(change);}setActionError(err instanceof Error ? err.message : "The change failed");} finally {setBusy(null);}},- [asOperator, onChanged, refetch, refresh, selfId],+ [asOperator, onChanged, organizationId, refetch, refresh, selfId],);const replayed = useRef(false);useEffect(() => {if (replayed.current) return;replayed.current = true;- const pending = takePendingChange();+ const pending = takePendingChange(organizationId);if (pending !== null) void act(pending, true);- }, [act]);+ }, [act, organizationId]);const columns = useMemo<GridColDef<MemberRow>[]>(() => [@@ -244,7 +273,24 @@ export default function OrganizationMembersSection({</Alert>)}{actionError && (- <Alert severity="error" onClose={() => setActionError(null)}>+ <Alert+ severity="error"+ onClose={() => {+ setActionError(null);+ setToFinish(null);+ }}+ action={+ toFinish && (+ <Button+ color="inherit"+ size="small"+ onClick={() => signInThenMake(toFinish, organizationId)}+ >+ Confirm sign-in to finish+ </Button>+ )+ }+ >{actionError}</Alert>)}diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsxindex 91d8d1072..0a785e400 100644--- a/gateway/src/pages/organization/OrganizationPage.test.tsx+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx@@ -469,17 +469,79 @@ describe("OrganizationPage", () => {"/gateway/auth/workos/organization?return_to=%2Forganization",),);- expect(JSON.parse(window.sessionStorage.getItem("switch.pendingOrganizationMemberChange")!)).toEqual({- userId: "u2",- role: "org_admin",+ expect(+ JSON.parse(window.sessionStorage.getItem("switch.pendingOrganizationMemberChange")!),+ ).toMatchObject({ change: { userId: "u2", role: "org_admin" }, organizationId: "o1" });+ });++ it("comes back only to a dashboard path", async () => {+ window.location.pathname = "//elsewhere.example.test/organization";+ signedInAs(session("org_admin", true));+ answer(routes(signInFirst));+ structured({ error: "directory_sign_in_required", message: "Confirm your sign-in." });++ render(<OrganizationPage />);+ fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));+ fireEvent.click(await screen.findByRole("option", { name: "Org Admin" }));++ await waitFor(() =>+ expect(window.location.href).toBe(+ "/gateway/auth/workos/organization?return_to=%2Forganization",+ ),+ );+ });++ it("says what was already taken away before sending the admin to sign in", async () => {+ signedInAs(session("org_admin", true));+ answer(routes(signInFirst));+ structured({+ error: "directory_sign_in_required",+ message: "Your sign-in has ended. Access was already taken away.",+ access_ended: true,});++ render(<OrganizationPage />);+ fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));+ fireEvent.click(await screen.findByRole("option", { name: "Org Admin" }));++ expect(+ await screen.findByText("Your sign-in has ended. Access was already taken away."),+ ).toBeTruthy();+ expect(window.location.href).toBe("");+ fireEvent.click(screen.getByRole("button", { name: "Confirm sign-in to finish" }));+ expect(window.location.href).toBe(+ "/gateway/auth/workos/organization?return_to=%2Forganization",+ );});- it("makes the kept change on coming back", async () => {+ const keep = (organizationId: string, savedAt: number) =>window.sessionStorage.setItem("switch.pendingOrganizationMemberChange",- JSON.stringify({ userId: "u2", role: "org_admin" }),+ JSON.stringify({ change: { userId: "u2", role: "org_admin" }, organizationId, savedAt }),);+ const patched = (fetchMock: ReturnType<typeof answer>) =>+ fetchMock.mock.calls.some(([, init]) => init?.method === "PATCH");++ it("drops a kept change from another organization, or one too old", async () => {+ for (const [organizationId, savedAt] of [+ ["o2", Date.now()],+ ["o1", Date.now() - 11 * 60 * 1000],+ ] as const) {+ keep(organizationId, savedAt);+ signedInAs(session("org_admin", true));+ const fetchMock = answer(routes({ ...bob, role: "org_admin", warning: null }));++ const { unmount } = render(<OrganizationPage />);+ await screen.findByTestId("row-u2");++ expect(patched(fetchMock)).toBe(false);+ expect(window.sessionStorage.getItem("switch.pendingOrganizationMemberChange")).toBeNull();+ unmount();+ }+ });++ it("makes the kept change on coming back", async () => {+ keep("o1", Date.now());signedInAs(session("org_admin", true));const fetchMock = answer(routes({ ...bob, role: "org_admin", warning: null }));@@ -497,10 +559,7 @@ describe("OrganizationPage", () => {});it("shows a kept change that still asks for a sign-in as a failure", async () => {- window.sessionStorage.setItem(- "switch.pendingOrganizationMemberChange",- JSON.stringify({ userId: "u2", role: "org_admin" }),- );+ keep("o1", Date.now());signedInAs(session("org_admin", true));answer(routes(signInFirst));structured({ error: "directory_sign_in_required", message: "Confirm your sign-in." });diff --git a/gateway/src/pages/organization/OrganizationPage.tsx b/gateway/src/pages/organization/OrganizationPage.tsxindex 2835f7c89..3cb33ffbe 100644--- a/gateway/src/pages/organization/OrganizationPage.tsx+++ b/gateway/src/pages/organization/OrganizationPage.tsx@@ -50,6 +50,7 @@ export default function OrganizationPage() {{(isAdmin || session.user.is_operator) && (<OrganizationMembersSectionselfId={session.user.id}+ organizationId={tenant.organization_id}asOperator={!isAdmin}fromDirectory={organization?.members_from_directory === true}directoryTakesChanges={organization?.directory_takes_changes === true}