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
feat(organizations): sign in through the WorkOS directory
Petr Bauchdd32a658320a
diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex f0a93849c..5b7cd91a7 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -394,6 +394,15 @@ class SwitchConfig(BaseSettings):# docs/old/multi-tenancy-phase2-tenants.md, §5.gateway_max_workspaces_per_user: int = 3+ # Who keeps the record of organizations and their members+ # (`organization_directory.py`). "local": this server, in its own tables.+ # "workos": the WorkOS environment behind the gateway's OIDC sign-in, read+ # with `WORKOS_API_KEY`; organization membership comes from there, and+ # workspaces and their roles stay here.+ organization_directory: Literal["local", "workos"] = "local"+ workos_api_key: str | None = None+ workos_api_url: str = "https://api.workos.com"+# Outbound mail for invitations addressed to an e-mail. Setting the host# turns it on; any SMTP relay works. Unset, an addressed invitation is# still created and the admin is told nothing was sent, so they can share@@ -1524,6 +1533,23 @@ class SwitchConfig(BaseSettings):)return self+ @model_validator(mode="after")+ def _validate_organization_directory(self) -> "SwitchConfig":+ if self.organization_directory != "workos":+ return self+ if not self.workos_api_key:+ raise ValueError(+ "ORGANIZATION_DIRECTORY=workos needs WORKOS_API_KEY, to read "+ "who belongs to which organization."+ )+ if not self.gateway_oidc_issuer_url:+ raise ValueError(+ "ORGANIZATION_DIRECTORY=workos needs the gateway's OIDC sign-in "+ "(GATEWAY_OIDC_*) set up against the same WorkOS environment: "+ "the sign-in is what names the person there."+ )+ return self+@model_validator(mode="after")def _validate_gateway_oidc(self) -> "SwitchConfig":required = (diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex 03bd46ad5..d6ea6bf92 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -83,6 +83,8 @@ class OrganizationAuditAction(StrEnum):CONNECTOR_APP_REMOVED = "organization.connector_app_removed"SERVICE_SET = "organization.service_set"SERVICE_CLEARED = "organization.service_cleared"+ # Brought in from a directory kept outside Switch when they signed in.+ MEMBER_ADDED_AT_SIGN_IN = "organization.member_added_at_sign_in"class ServerAuditAction(StrEnum):diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 4b7d0e169..d222fa5b3 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -283,10 +283,17 @@ class UserStore:sub: str,email_verified: bool,join_tenant: bool,+ link_by_email: bool,) -> OidcUser:"""Resolve an OIDC identity to a gateway user, provisioning on firstlogin (JIT). `created` says whether this call made the account.+ `link_by_email` false refuses to link a new identity to an existing+ account by email at all, verified or not: where the identity provider+ is shared with other products (the WorkOS directory), its subject is+ the only link, and an existing account is linked to it by an+ administrator, never by a matching address.+`join_tenant` decides whether an account this creates, or links, isgiven a membership in the tenant bound to the caller's context. Withit false, the account is left with none: that is how a deployment with@@ -328,6 +335,12 @@ class UserStore:existing = await self.get_by_email(session, email)if existing is not None:+ if not link_by_email:+ raise OidcIdentityConflictError(+ f"An account with email {email!r} already exists here, "+ "and this sign-in is not linked to it. Ask your "+ "administrator to link it."+ )if not email_verified:raise OidcIdentityConflictError(f"An account with email {email!r} already exists and "diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.pyindex 52c639cfa..8a0d9cada 100644--- a/core/switch_core/db/tenant_lookup.py+++ b/core/switch_core/db/tenant_lookup.py@@ -171,6 +171,15 @@ two. It discloses which workspaces a person belongs to or administersthrough an organization; the gateway asks it only about the signed-incaller.+**`organization_of_customer` is the fifteenth**, and the one that answers+with an organization rather than a workspace. Under the WorkOS directory+(`workos_directory.py`) a sign-in names the customers the person belongs to,+by the customer's id; which Switch organization each one is has to be read+before anything is bound, to bring the person's membership rows up to date.+It discloses whether a customer has a Switch organization, and its id; the+gateway asks it only about customers WorkOS says the signed-in person belongs+to.+Why not the obvious alternatives is argued in`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the shortversion is that returning rows instead of tenant ids would put a second copy@@ -446,6 +455,17 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = ("the tenant this names."),),+ TenantLookup(+ name="organization_of_customer",+ arguments=("customer_id",),+ query="SELECT id FROM organizations WHERE customer_id = p_customer_id",+ purpose=(+ "Which organization is a customer's, from the customer's id a "+ "WorkOS sign-in names. Read before anything is bound, to bring the "+ "person's organization memberships up to date; unique by "+ "constraint."+ ),+ ),TenantLookup(name="tenant_of_messaging_install",arguments=("platform", "external_workspace_id"),@@ -572,6 +592,9 @@ _LOOKUP_STATEMENTS: dict[str, TextClause] = {"tenant_of_sign_in_flow": text("SELECT tenant_id FROM tenant_of_sign_in_flow(:state) AS tenant_id"),+ "organization_of_customer": text(+ "SELECT tenant_id FROM organization_of_customer(:customer_id) AS tenant_id"+ ),}assert _LOOKUP_STATEMENTS.keys() == TENANT_LOOKUPS_BY_NAME.keys(), (@@ -727,3 +750,10 @@ async def tenant_of_sign_in_flow() -> str | None:lookup = TENANT_LOOKUPS_BY_NAME["tenant_of_sign_in_flow"]return _at_most_one(lookup, await _call(session_factory, lookup, state))+++async def organization_of_customer(+ session_factory: async_sessionmaker[AsyncSession], customer_id: str+) -> str | None:+ lookup = TENANT_LOOKUPS_BY_NAME["organization_of_customer"]+ return _at_most_one(lookup, await _call(session_factory, lookup, customer_id))diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.pyindex 2ba8e3acd..113c77fc3 100644--- a/core/switch_core/gateway/oidc_routes.py+++ b/core/switch_core/gateway/oidc_routes.py@@ -29,10 +29,16 @@ from switch_core.gateway.auth import initial_tenant_claim, set_session_cookiefrom switch_core.gateway.dependencies import (current_telemetry,get_config,+ get_organization_directory,get_session_factory,get_system_session,get_user_store,)+from switch_core.organization_directory import (+ DirectoryUnavailable,+ OrganizationDirectory,+)+from switch_core.organization_mirror import bring_in_membershipsfrom switch_core.telemetry import emit_safelyfrom switch_core.tenant_context import tenant_scope@@ -221,6 +227,30 @@ async def oidc_login(return await client.authorize_redirect(request, redirect_uri, **params)+async def _bring_in_organizations(+ session_factory: async_sessionmaker[AsyncSession],+ organization_directory: OrganizationDirectory,+ user: User,+ subject: str,+) -> None:+ """Bring the person's organization memberships up to date with a directory+ kept outside Switch (`organization_mirror.py`). One that can't be reached+ doesn't stop the sign-in: authorization reads Switch's rows, which stay as+ they were, and the failure is logged."""+ try:+ memberships = await organization_directory.memberships_at_sign_in(subject)+ except DirectoryUnavailable as error:+ logger.warning(+ "Could not read user %s's organizations at sign-in; Switch's are "+ "left as they were: %s",+ user.id,+ error.message,+ )+ return+ if memberships is not None:+ await bring_in_memberships(session_factory, user.id, memberships)++@router.get("/auth/oidc/callback", name="oidc_callback")async def oidc_callback(request: Request,@@ -230,6 +260,9 @@ async def oidc_callback(async_sessionmaker[AsyncSession], Depends(get_session_factory)],user_store: Annotated[UserStore, Depends(get_user_store)],+ organization_directory: Annotated[+ OrganizationDirectory, Depends(get_organization_directory)+ ],) -> RedirectResponse:# `get_system_session`: nobody is signed in yet, so there is no principal# to take a tenant from — the tenant this route writes into is chosen@@ -339,6 +372,7 @@ async def oidc_callback(sub=sub,email_verified=verified,join_tenant=join_tenant,+ link_by_email=config.organization_directory == "local",)except OidcIdentityConflictError as exc:logger.warning("OIDC identity conflict: %s", exc)@@ -357,6 +391,7 @@ async def oidc_callback(await session.commit()if created:emit_safely(current_telemetry(), "account_created", {"method": "oidc"})+ await _bring_in_organizations(session_factory, organization_directory, user, sub)# Verify-at-login only: we don't persist the IdP tokens.handoff = request.session.pop(_HANDOFF_SESSION_KEY, None)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 7300c0f43..4c88cc6c4 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -200,7 +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.organization_directory import LocalDirectory, OrganizationDirectoryfrom switch_core.outbound import guarded_async_clientfrom switch_core.ownership import Ownershipfrom switch_core.process_identity import new_process_id@@ -230,6 +230,7 @@ from switch_core.trust.setup import build_trust_clientfrom switch_core.trust.signals import TrustSettingsSignalsfrom switch_core.user_changes import LocalUserChanges, SignalUserChangesfrom switch_core.version import switch_core_version+from switch_core.workos_directory import WorkOSDirectorylogger = logging.getLogger(__name__)@@ -520,6 +521,17 @@ async def _drain_telemetry(logger.warning("Telemetry HTTP client did not close.", exc_info=True)+def _organization_directory(+ config: SwitchConfig, http: httpx.AsyncClient+) -> OrganizationDirectory:+ """The directory `ORGANIZATION_DIRECTORY` names (`organization_directory.py`)."""+ if config.organization_directory == "local":+ return LocalDirectory()+ if config.workos_api_key is None:+ raise RuntimeError("ORGANIZATION_DIRECTORY=workos needs WORKOS_API_KEY")+ return WorkOSDirectory(http, config.workos_api_key, config.workos_api_url)++async def _close_by(closing: Coroutine[object, object, None], deadline: float, what: str) -> None:@@ -1251,7 +1263,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(),+ organization_directory=_organization_directory(config, service_http),template_store=template_store,usage_store=usage_store,budget_store=budget_store,diff --git a/core/switch_core/migrations/versions/f2b8d6c1a4e9_organization_of_customer.py b/core/switch_core/migrations/versions/f2b8d6c1a4e9_organization_of_customer.pynew file mode 100644index 000000000..11bfcbe8e--- /dev/null+++ b/core/switch_core/migrations/versions/f2b8d6c1a4e9_organization_of_customer.py@@ -0,0 +1,45 @@+"""the lookup that finds a customer's organization++Under the WorkOS directory a sign-in names the customers the person belongs+to by the customer's id, and which Switch organization each one is has to be+read before anything is bound. This adds the fifteenth lookup to the+exemption from row-level security. See `db/tenant_lookup.py` for what it+discloses.++The DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py` as it+stood when this migration was written, copied rather than imported so a later+edit cannot change what this revision means.++Revision ID: f2b8d6c1a4e9+Revises: 10f6d02ac5bc+Create Date: 2026-11-02 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "f2b8d6c1a4e9"+down_revision: str | Sequence[str] | None = "10f6d02ac5bc"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"++CREATE_ORGANIZATION_OF_CUSTOMER = f"""CREATE OR REPLACE FUNCTION organization_of_customer(p_customer_id text)+ RETURNS SETOF text+ LANGUAGE sql STABLE SECURITY DEFINER+ SET search_path = {SECURE_SEARCH_PATH}+AS $$SELECT id FROM organizations WHERE customer_id = p_customer_id$$"""++DROP_ORGANIZATION_OF_CUSTOMER = "DROP FUNCTION IF EXISTS organization_of_customer(text)"+++def upgrade() -> None:+ op.execute(CREATE_ORGANIZATION_OF_CUSTOMER)+++def downgrade() -> None:+ op.execute(DROP_ORGANIZATION_OF_CUSTOMER)diff --git a/core/switch_core/organization_directory.py b/core/switch_core/organization_directory.pyindex 35e6d19d2..9d7efbbd8 100644--- a/core/switch_core/organization_directory.py+++ b/core/switch_core/organization_directory.py@@ -35,6 +35,15 @@ class DirectoryOrganization:customer_id: str | None+@dataclass(frozen=True)+class DirectoryMembership:+ """Someone's membership of a customer's organization, as the directory+ has it: the customer, and whether they are its `org_admin`."""++ customer_id: str+ role: str++class DirectoryError(Exception):"""The directory did not make a change. `message` says why, for people toread."""@@ -57,6 +66,14 @@ class OrganizationDirectory(Protocol):bound every call: they are handed rows, never a session, and a route mayhold locks while it waits on them."""+ async def memberships_at_sign_in(+ self, subject: str+ ) -> list[DirectoryMembership] | None:+ """The organizations the person who signed in as `subject` (their+ OIDC `sub`) belongs to, for Switch's rows to be brought up to date+ with; None where Switch's rows are the record."""+ ...+async def create_organization(self, creator: User, name: str) -> DirectoryOrganization:@@ -89,6 +106,11 @@ class LocalDirectory:"""Switch's own tables are the record: each change is the route's writeto them, and nothing is asked first."""+ async def memberships_at_sign_in(+ self, subject: str+ ) -> list[DirectoryMembership] | None:+ return None+async def create_organization(self, creator: User, name: str) -> DirectoryOrganization:diff --git a/core/switch_core/organization_mirror.py b/core/switch_core/organization_mirror.pynew file mode 100644index 000000000..73225a28b--- /dev/null+++ b/core/switch_core/organization_mirror.py@@ -0,0 +1,79 @@+"""Switch's organization rows brought up to date with a directory kept+outside Switch (`organization_directory.py`), for one person at sign-in.++Only customers that already have a Switch organization are touched: a+customer starts using Switch by creating its organization here, not by one of+its people signing in. Someone the directory lists in such an organization+and Switch does not is added, with the directory's role, and the addition is+recorded in the organization's audit log. A role that differs, or a+membership the directory no longer lists, is left as it is and logged: taking+a role away also takes away what it reached, which is the directory mirror's+to do, not a sign-in's.+"""++from __future__ import annotations++import logging++from sqlalchemy.dialects.postgresql import insert+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.audit import (+ OrganizationAuditAction,+ record_organization_audit_event,+)+from switch_core.db.models import OrganizationMember+from switch_core.db.session_scope import organization_session+from switch_core.db.tenant_lookup import organization_of_customer+from switch_core.organization_directory import DirectoryMembership++logger = logging.getLogger(__name__)+++async def bring_in_memberships(+ session_factory: async_sessionmaker[AsyncSession],+ user_id: str,+ memberships: list[DirectoryMembership],+) -> None:+ """Add `user_id` to each Switch organization of a customer in+ `memberships` that they are not in yet, one organization at a time."""+ for membership in memberships:+ organization_id = await organization_of_customer(+ session_factory, membership.customer_id+ )+ if organization_id is None:+ continue+ async with organization_session(session_factory, organization_id) as session:+ member = await session.get(OrganizationMember, (organization_id, user_id))+ if member is not None:+ if member.role != membership.role:+ logger.warning(+ "User %s is %s in organization %s and %s in its "+ "directory; the sign-in leaves Switch's role as it is",+ user_id,+ member.role,+ organization_id,+ membership.role,+ )+ continue+ added = await session.execute(+ insert(OrganizationMember)+ .values(+ organization_id=organization_id,+ user_id=user_id,+ role=membership.role,+ )+ .on_conflict_do_nothing(index_elements=["organization_id", "user_id"])+ .returning(OrganizationMember.user_id)+ )+ if added.first() is not None:+ await record_organization_audit_event(+ session,+ organization_id=organization_id,+ actor_user_id=None,+ action=OrganizationAuditAction.MEMBER_ADDED_AT_SIGN_IN,+ target_type="user",+ target_id=user_id,+ details={"role": membership.role},+ )+ await session.commit()diff --git a/core/switch_core/workos_directory.py b/core/switch_core/workos_directory.pynew file mode 100644index 000000000..e402ffa66--- /dev/null+++ b/core/switch_core/workos_directory.py@@ -0,0 +1,170 @@+"""Organizations kept in WorkOS (`ORGANIZATION_DIRECTORY=workos`).++The hosted service shares one WorkOS environment with other products. A+customer is one organization there, and a product may give it organizations+of its own beneath that one; every one of them carries the customer's id in+its metadata (`tenant_id`, the name the first product gave the customer), and+that id, not any one organization's WorkOS id, is what tells customers apart.+A Switch organization is one customer (`organizations.customer_id`).++WorkOS holds who belongs to a customer and who is its `org_admin`; Switch+holds which workspaces, and the roles there. At sign-in the person's+memberships are read from WorkOS (`memberships_at_sign_in`), by their WorkOS+user id, which the sign-in's `sub` is.++Changes made from Switch go through the service that owns the customer+record, not through this module's API key, so each product's rules apply in+one place; until that is wired in, this directory refuses them.+"""++from __future__ import annotations++import logging+from typing import Any++import httpx++from switch_core.authz import ORGANIZATION_ADMIN_ROLE+from switch_core.db.models import Organization, User+from switch_core.organization_directory import (+ DirectoryMembership,+ DirectoryOrganization,+ DirectoryRefusal,+ DirectoryUnavailable,+)++logger = logging.getLogger(__name__)++# Bounds every call: a sign-in waits on these.+WORKOS_TIMEOUT_SECONDS = 10.0+# WorkOS's largest page.+_PAGE = 100+# The metadata key every organization of a customer carries its id under.+CUSTOMER_ID_KEY = "tenant_id"++NOT_FROM_SWITCH_YET = (+ "This organization's members are managed in your organization's account "+ "settings, not here yet."+)+++def customer_id_of(organization: dict[str, Any]) -> str | None:+ """The customer a WorkOS organization belongs to, or None if it names+ none. Root and child organizations of one customer answer alike."""+ metadata = organization.get("metadata") or {}+ value = metadata.get(CUSTOMER_ID_KEY)+ return value if isinstance(value, str) and value else None+++def switch_role(workos_role: str) -> str:+ """WorkOS's `org_admin` is Switch's; every other role there is a member+ here, since Switch adds no role of its own to a shared environment."""+ return (+ ORGANIZATION_ADMIN_ROLE if workos_role == ORGANIZATION_ADMIN_ROLE else "member"+ )+++class WorkOSDirectory:+ def __init__(self, http: httpx.AsyncClient, api_key: str, api_url: str) -> None:+ self._http = http+ self._api_key = api_key+ self._api_url = api_url.rstrip("/")++ async def _get(self, path: str, params: dict[str, str]) -> dict[str, Any]:+ try:+ response = await self._http.get(+ f"{self._api_url}{path}",+ params=params,+ headers={"Authorization": f"Bearer {self._api_key}"},+ timeout=WORKOS_TIMEOUT_SECONDS,+ )+ except httpx.HTTPError as error:+ raise DirectoryUnavailable(+ f"WorkOS could not be reached ({type(error).__name__})."+ ) from error+ if response.status_code != 200:+ raise DirectoryUnavailable(+ f"WorkOS answered {response.status_code} for {path}."+ )+ body = response.json()+ if not isinstance(body, dict):+ raise DirectoryUnavailable(f"WorkOS answered {path} with no object.")+ return body++ async def memberships_at_sign_in(+ self, subject: str+ ) -> list[DirectoryMembership] | None:+ """The active memberships of WorkOS user `subject`, one per customer.++ Someone in several organizations of one customer holds the highest of+ their roles there. An organization that names no customer is skipped,+ and logged: Switch cannot tell which customer it is part of.+ """+ roles: dict[str, str] = {}+ for membership in await self._memberships(subject):+ organization_id = membership.get("organization_id")+ role = (membership.get("role") or {}).get("slug")+ if not isinstance(organization_id, str) or not isinstance(role, str):+ raise DirectoryUnavailable(+ "WorkOS answered with a membership Switch cannot read."+ )+ organization = await self._get(f"/organizations/{organization_id}", {})+ customer_id = customer_id_of(organization)+ if customer_id is None:+ logger.warning(+ "WorkOS organization %s names no customer (metadata.%s); "+ "user %s's membership of it is not brought into Switch",+ organization_id,+ CUSTOMER_ID_KEY,+ subject,+ )+ continue+ if roles.get(customer_id) != ORGANIZATION_ADMIN_ROLE:+ roles[customer_id] = switch_role(role)+ return [+ DirectoryMembership(customer_id=customer_id, role=role)+ for customer_id, role in sorted(roles.items())+ ]++ async def _memberships(self, user_id: str) -> list[dict[str, Any]]:+ found: list[dict[str, Any]] = []+ after: str | None = None+ while True:+ params = {"user_id": user_id, "statuses": "active", "limit": str(_PAGE)}+ if after is not None:+ params["after"] = after+ page = await self._get("/user_management/organization_memberships", params)+ data = page.get("data")+ if not isinstance(data, list):+ raise DirectoryUnavailable(+ "WorkOS answered the memberships with no list."+ )+ found.extend(item for item in data if isinstance(item, dict))+ after = (page.get("list_metadata") or {}).get("after")+ if not after:+ return found++ async def create_organization(+ self, creator: User, name: str+ ) -> DirectoryOrganization:+ raise DirectoryRefusal(NOT_FROM_SWITCH_YET)++ async def discard_organization(self, organization: DirectoryOrganization) -> None:+ raise DirectoryRefusal(NOT_FROM_SWITCH_YET)++ async def join(self, organization: Organization, user_id: str, role: str) -> None:+ if organization.customer_id is None:+ return None+ raise DirectoryRefusal(NOT_FROM_SWITCH_YET)++ async def set_role(+ self, organization: Organization, user_id: str, role: str+ ) -> None:+ if organization.customer_id is None:+ return None+ raise DirectoryRefusal(NOT_FROM_SWITCH_YET)++ async def remove(self, organization: Organization, user_id: str) -> None:+ if organization.customer_id is None:+ return None+ raise DirectoryRefusal(NOT_FROM_SWITCH_YET)diff --git a/core/tests/switch_core/db/stores/test_user_store_oidc.py b/core/tests/switch_core/db/stores/test_user_store_oidc.pyindex 7edd29a39..be3124669 100644--- a/core/tests/switch_core/db/stores/test_user_store_oidc.py+++ b/core/tests/switch_core/db/stores/test_user_store_oidc.py@@ -18,6 +18,47 @@ _ISS = "https://idp.example.com"class TestGetOrCreateOidcUser:+ async def test_without_linking_by_email_a_matching_account_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A shared identity provider's subject is the only link: a verified+ address matching an existing account joins nothing, and nothing new+ is written."""+ store = UserStore()+ async with session_factory() as session:+ existing = await store.get_or_create_oidc_user(+ session,+ iss="https://password.example",+ email="[email protected]",+ name="Kept",+ sub="first",+ email_verified=True,+ join_tenant=True,+ link_by_email=True,+ )+ await session.commit()++ async with session_factory() as session:+ with pytest.raises(OidcIdentityConflictError, match="administrator"):+ await store.get_or_create_oidc_user(+ session,+ iss=_ISS,+ email="[email protected]",+ name="Kept",+ sub="user_SHARED",+ email_verified=True,+ join_tenant=True,+ link_by_email=False,+ )+ async with session_factory() as session:+ assert (+ await store.get_by_oidc_identity(session, iss=_ISS, sub="user_SHARED")+ is None+ )+ assert (+ await store.get_by_email(session, "[email protected]")+ ).id == existing.id # type: ignore[union-attr]+async def test_creates_new_user_as_plain_user(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -31,6 +72,7 @@ class TestGetOrCreateOidcUser:sub="okta|9",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()assert created is True@@ -68,6 +110,7 @@ class TestGetOrCreateOidcUser:sub="okta|10",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()assert user.email == "[email protected]"@@ -85,6 +128,7 @@ class TestGetOrCreateOidcUser:sub="okta|1",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()first.role = "admin"@@ -98,6 +142,7 @@ class TestGetOrCreateOidcUser:sub="okta|1",email_verified=True,join_tenant=True,+ link_by_email=True,)assert again.id == first.idassert again.role == "admin"@@ -127,6 +172,7 @@ class TestGetOrCreateOidcUser:sub="okta|42",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()@@ -165,6 +211,7 @@ class TestGetOrCreateOidcUser:sub="okta|43",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()@@ -225,6 +272,7 @@ class TestGetOrCreateOidcUser:sub="okta|1",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()@@ -236,6 +284,7 @@ class TestGetOrCreateOidcUser:sub="okta|2",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()@@ -272,6 +321,7 @@ class TestGetOrCreateOidcUser:sub="okta|1",email_verified=False,join_tenant=True,+ link_by_email=True,)async def test_identity_already_bound_elsewhere_is_never_relinked(@@ -290,6 +340,7 @@ class TestGetOrCreateOidcUser:sub="okta|owned",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()@@ -310,6 +361,7 @@ class TestGetOrCreateOidcUser:sub="okta|owned",email_verified=True,join_tenant=True,+ link_by_email=True,)assert again.id == owner.id@@ -339,6 +391,7 @@ class TestGetOrCreateOidcUser:sub="okta|7",email_verified=True,join_tenant=True,+ link_by_email=True,)assert got.id == legacy_user.id@@ -377,6 +430,7 @@ class TestGetOrCreateOidcUser:sub="okta|8",email_verified=False,join_tenant=True,+ link_by_email=True,)assert got.id == legacy_admin.idassert got.role == "admin"@@ -400,6 +454,7 @@ class TestGetOrCreateOidcUser:sub="okta|logged",email_verified=True,join_tenant=True,+ link_by_email=True,)await session.commit()@@ -466,6 +521,7 @@ class TestGetOrCreateOidcUser:sub="okta|always-races",email_verified=True,join_tenant=True,+ link_by_email=True,)await winner_session.commit()@@ -485,6 +541,7 @@ class TestGetOrCreateOidcUser:sub="okta|always-races",email_verified=True,join_tenant=True,+ link_by_email=True,)async def test_concurrent_creation_of_the_same_identity_resolves_to_the_winner(@@ -505,6 +562,7 @@ class TestGetOrCreateOidcUser:sub="okta|race",email_verified=True,join_tenant=True,+ link_by_email=True,)await winner_session.commit()@@ -530,6 +588,7 @@ class TestGetOrCreateOidcUser:sub="okta|race",email_verified=True,join_tenant=True,+ link_by_email=True,)assert resolved.id == winner.id@@ -551,6 +610,7 @@ class TestGetOrCreateOidcUser:sub="okta|first",email_verified=True,join_tenant=True,+ link_by_email=True,)await winner_session.commit()@@ -574,6 +634,7 @@ class TestGetOrCreateOidcUser:sub="okta|second",email_verified=True,join_tenant=True,+ link_by_email=True,)assert resolved.id == winner.id@@ -608,6 +669,7 @@ class TestProvisioningWithoutJoiningATenant:sub="okta|loose",email_verified=True,join_tenant=False,+ link_by_email=True,)await session.commit()@@ -634,6 +696,7 @@ class TestProvisioningWithoutJoiningATenant:sub="okta|prior",email_verified=True,join_tenant=False,+ link_by_email=True,)await session.commit()diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex 97c4ed628..496e71b3b 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -132,6 +132,12 @@ _ALLOWED_MODULES = {# the flow's tenant, and the flow is then read scoped to it, so a wrong# answer is a missing flow rather than a cross-tenant read."switch_core.connections.sign_in_flows",+ # A WorkOS sign-in names the customers the person belongs to, by the+ # customer's id; which Switch organization each one is has to be read+ # before any is bound, and the membership is then written with that+ # organization bound, so a wrong answer is a missing row rather than a+ # write into another organization.+ "switch_core.organization_mirror",# `switch_core.transport.postgres` and `switch_core.clients.agent_consumer`# came off this list with `tenant_of_client`: both were built from a# `clients` row that already named the tenant, so they carry it instead ofdiff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.pyindex ded1835e4..4c8a4830b 100644--- a/core/tests/switch_core/db/test_tenant_lookup.py+++ b/core/tests/switch_core/db/test_tenant_lookup.py@@ -111,6 +111,7 @@ _ADDED_SINCE = {"tenant_of_sign_in_flow": "e5956cbd3bdc","tenants_bindable_by_user": "5c2e8f17a9d4","all_organization_ids": "10f6d02ac5bc",+ "organization_of_customer": "f2b8d6c1a4e9",}# A third kind of change, and the quietest: a lookup whose body a laterdiff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.pyindex 44143e9a5..b4d747480 100644--- a/core/tests/switch_core/gateway/test_oidc_routes.py+++ b/core/tests/switch_core/gateway/test_oidc_routes.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import uuidfrom types import SimpleNamespacefrom urllib.parse import parse_qs, urlsplit@@ -18,6 +19,8 @@ from switch_core.config import SwitchConfigfrom switch_core.db.models import (TENANT_ZERO_ID,OidcIdentity,+ Organization,+ OrganizationMember,Tenant,TenantMember,User,@@ -26,6 +29,11 @@ from switch_core.db.stores.user_store import OidcIdentityRaceError, UserStorefrom switch_core.gateway.auth import decode_jwt, hash_passwordfrom switch_core.gateway.auth_routes import auth_configfrom switch_core.gateway.dependencies import get_config+from switch_core.organization_directory import (+ DirectoryMembership,+ DirectoryUnavailable,+ LocalDirectory,+)def _tenant_claim(set_cookie: str) -> str | None:@@ -78,6 +86,126 @@ class _FakeClientNoUserinfoInToken:raise self._userinfo_error+class _Directory:+ """A directory kept outside Switch: answers `memberships`, or raises."""++ def __init__(self, memberships: object) -> None:+ self.memberships = memberships+ self.asked: list[str] = []++ async def memberships_at_sign_in(self, subject: str):+ self.asked.append(subject)+ if isinstance(self.memberships, Exception):+ raise self.memberships+ return self.memberships+++class TestSigningInWithADirectory:+ """Under the WorkOS directory the sign-in's subject names the person+ there; their organizations are brought into Switch, and an email match+ never joins an existing account."""++ _TOKEN = {+ "userinfo": {+ "email": "[email protected]",+ "email_verified": True,+ "sub": "user_DANA",+ "name": "Dana",+ }+ }++ def _config(self) -> SwitchConfig:+ return _config(+ organization_directory="workos",+ workos_api_key="sk_test_example",+ gateway_signup_mode="open",+ )++ async def test_their_organizations_are_brought_in(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ customer = f"ten_{uuid.uuid4().hex[:8]}"+ organization_id = f"org-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(+ Organization(+ id=organization_id,+ slug=organization_id,+ name="Acme",+ customer_id=customer,+ )+ )+ await session.commit()+ directory = _Directory([DirectoryMembership(customer, "org_admin")])+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(self._TOKEN))++ async with session_factory() as session:+ response = await oidc_routes.oidc_callback(+ request=SimpleNamespace(session={}), # type: ignore[arg-type]+ config=self._config(),+ session=session,+ session_factory=session_factory,+ user_store=UserStore(),+ organization_directory=directory, # type: ignore[arg-type]+ )+ user = await UserStore().get_by_email(session, "[email protected]")++ assert response.status_code == 303+ assert directory.asked == ["user_DANA"]+ assert user is not None+ async with session_factory() as session:+ member = await session.get(OrganizationMember, (organization_id, user.id))+ assert member is not None and member.role == "org_admin"++ async def test_an_unreachable_directory_does_not_stop_the_sign_in(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ directory = _Directory(DirectoryUnavailable("WorkOS answered 500."))+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(self._TOKEN))++ async with session_factory() as session:+ response = await oidc_routes.oidc_callback(+ request=SimpleNamespace(session={}), # type: ignore[arg-type]+ config=self._config(),+ session=session,+ session_factory=session_factory,+ user_store=UserStore(),+ organization_directory=directory, # type: ignore[arg-type]+ )++ assert response.status_code == 303+ assert "WorkOS answered 500." in caplog.text++ async def test_an_account_with_the_same_email_is_not_joined(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ async with session_factory() as session:+ session.add(User(name="Dana", email="[email protected]", role="user"))+ await session.commit()+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(self._TOKEN))++ async with session_factory() as session:+ with pytest.raises(HTTPException) as refused:+ await oidc_routes.oidc_callback(+ request=SimpleNamespace(session={}), # type: ignore[arg-type]+ config=self._config(),+ session=session,+ session_factory=session_factory,+ user_store=UserStore(),+ organization_directory=_Directory([]), # type: ignore[arg-type]+ )++ assert refused.value.status_code == 409+ assert "administrator" in refused.value.detail++class TestOidcCallback:async def test_provisions_user_and_sets_session_cookie(self,@@ -101,6 +229,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert response.status_code == 303@@ -150,6 +279,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 401@@ -181,6 +311,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert response.status_code == 303@@ -208,6 +339,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 401@@ -247,6 +379,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 409@@ -287,6 +420,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert response.status_code == 303@@ -326,6 +460,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert first.status_code == 303carol = await UserStore().get_by_email(session, "[email protected]")@@ -351,6 +486,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert response.status_code == 303linked = await UserStore().get_by_oidc_identity(@@ -400,6 +536,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert response.status_code == 303@@ -439,6 +576,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=_AlwaysRacingStore(), # type: ignore[arg-type]+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 503assert exc.value.headers is not None@@ -460,6 +598,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 401@@ -487,6 +626,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 502assert exc.value.detail == "OIDC provider did not respond"@@ -515,6 +655,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 502assert exc.value.detail == "OIDC provider did not respond"@@ -545,6 +686,7 @@ class TestOidcCallback:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)assert exc.value.status_code == 503assert exc.value.detail == (@@ -592,6 +734,7 @@ class TestTheCallbackPlacesTheUserInATenant:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)user = await UserStore().get_by_email(session, "[email protected]")assert user is not None@@ -636,6 +779,7 @@ class TestTheCallbackPlacesTheUserInATenant:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)memberships = await self._memberships(session, user_id)@@ -675,6 +819,7 @@ class TestTheCallbackPlacesTheUserInATenant:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)memberships = await self._memberships(session, user_id)@@ -722,6 +867,7 @@ class TestSignUpWithoutADefaultTenant:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)user = await UserStore().get_by_email(session, email)assert user is not None@@ -759,6 +905,7 @@ class TestSignUpWithoutADefaultTenant:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)identity = (await session.execute(@@ -805,6 +952,7 @@ class TestSignUpWithoutADefaultTenant:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)set_cookie = response.headers.get("set-cookie")@@ -1085,6 +1233,7 @@ class TestLoginOptionsAndHandoff:session=session,session_factory=session_factory,user_store=UserStore(),+ organization_directory=LocalDirectory(),)# No cookie in the browser: the code goes back to the app.assert response.headers.get("set-cookie") is Nonediff --git a/core/tests/switch_core/test_config_organization_directory.py b/core/tests/switch_core/test_config_organization_directory.pynew file mode 100644index 000000000..460de4d66--- /dev/null+++ b/core/tests/switch_core/test_config_organization_directory.py@@ -0,0 +1,38 @@+import pytest+from pydantic import ValidationError++from switch_core.config import SwitchConfig+from tests.switch_core.test_config_max_workspaces import _config++OIDC = dict(+ gateway_oidc_issuer_url="https://auth.example.test",+ gateway_oidc_client_id="client_example",+ gateway_oidc_client_secret="placeholder", # gitleaks:allow+ gateway_oidc_scopes="openid email profile",+)+++def test_a_server_keeps_its_own_organizations_by_default() -> None:+ assert _config().organization_directory == "local"+++def test_workos_with_its_key_and_sign_in_is_accepted() -> None:+ config: SwitchConfig = _config(+ organization_directory="workos",+ workos_api_key="sk_test_example", # gitleaks:allow+ **OIDC,+ )+ assert config.organization_directory == "workos"+++def test_workos_without_its_key_is_refused() -> None:+ with pytest.raises(ValidationError, match="WORKOS_API_KEY"):+ _config(organization_directory="workos", **OIDC)+++def test_workos_without_the_sign_in_is_refused() -> None:+ with pytest.raises(ValidationError, match="GATEWAY_OIDC"):+ _config(+ organization_directory="workos",+ workos_api_key="sk_test_example", # gitleaks:allow+ )diff --git a/core/tests/switch_core/test_organization_mirror.py b/core/tests/switch_core/test_organization_mirror.pynew file mode 100644index 000000000..e687cdb15--- /dev/null+++ b/core/tests/switch_core/test_organization_mirror.py@@ -0,0 +1,142 @@+"""A person's organization memberships brought up to date at sign-in from a+directory kept outside Switch, against Postgres, on the restricted role+row-level security applies to; `owner` only arranges fixtures and reads+results."""++from __future__ import annotations++import uuid++import pytest+from sqlalchemy import select++from switch_core.db.audit import OrganizationAuditAction+from switch_core.db.models import (+ Organization,+ OrganizationAuditEvent,+ OrganizationMember,+ User,+)+from switch_core.organization_directory import DirectoryMembership+from switch_core.organization_mirror import bring_in_memberships+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant+++def _id(prefix: str) -> str:+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++async def _organization(session_factory, customer_id: str | None) -> str:+ organization_id = _id("org")+ async with session_factory() as session:+ session.add(+ Organization(+ id=organization_id,+ slug=organization_id,+ name="Acme",+ customer_id=customer_id,+ )+ )+ await session.commit()+ return organization_id+++async def _person(session_factory) -> str:+ user_id = _id("user")+ async with session_factory() as session:+ session.add(+ User(+ id=user_id,+ name=user_id,+ email=f"{user_id}@example.invalid",+ role="user",+ )+ )+ await session.commit()+ return user_id+++async def _role(session_factory, organization_id: str, user_id: str) -> str | None:+ async with session_factory() as session:+ member = await session.get(OrganizationMember, (organization_id, user_id))+ return None if member is None else member.role+++async def _added(session_factory, organization_id: str) -> list[OrganizationAuditEvent]:+ async with session_factory() as session:+ return list(+ await session.scalars(+ select(OrganizationAuditEvent).where(+ OrganizationAuditEvent.organization_id == organization_id,+ OrganizationAuditEvent.action+ == OrganizationAuditAction.MEMBER_ADDED_AT_SIGN_IN,+ )+ )+ )+++class TestBringingInMemberships:+ async def test_adds_them_with_the_directorys_role_and_records_it(+ self, rls_harness: RLSHarness+ ) -> None:+ session_factory, restricted = rls_harness.owner, rls_harness.restricted+ customer = _id("ten")+ organization_id = await _organization(session_factory, customer)+ ada = await _person(session_factory)++ await bring_in_memberships(+ restricted, ada, [DirectoryMembership(customer, "org_admin")]+ )+ await bring_in_memberships(+ restricted, ada, [DirectoryMembership(customer, "org_admin")]+ )++ assert await _role(session_factory, organization_id, ada) == "org_admin"+ [event] = await _added(session_factory, organization_id)+ assert event.actor_user_id is None+ assert event.target_id == ada+ assert event.details == {"role": "org_admin"}++ async def test_a_customer_with_no_switch_organization_is_left_alone(+ self, rls_harness: RLSHarness+ ) -> None:+ session_factory, restricted = rls_harness.owner, rls_harness.restricted+ ada = await _person(session_factory)++ await bring_in_memberships(+ restricted, ada, [DirectoryMembership(_id("ten"), "member")]+ )++ async with session_factory() as session:+ assert (+ await session.scalars(+ select(OrganizationMember).where(OrganizationMember.user_id == ada)+ )+ ).all() == []++ async def test_a_role_that_differs_is_left_and_logged(+ self, rls_harness: RLSHarness, caplog: pytest.LogCaptureFixture+ ) -> None:+ """Taking a role away takes away what it reached, which is not a+ sign-in's to do."""+ session_factory, restricted = rls_harness.owner, rls_harness.restricted+ customer = _id("ten")+ organization_id = await _organization(session_factory, customer)+ ada = await _person(session_factory)+ async with session_factory() as session:+ session.add(+ OrganizationMember(+ organization_id=organization_id, user_id=ada, role="org_admin"+ )+ )+ await session.commit()++ await bring_in_memberships(+ restricted, ada, [DirectoryMembership(customer, "member")]+ )++ assert await _role(session_factory, organization_id, ada) == "org_admin"+ assert await _added(session_factory, organization_id) == []+ assert "leaves Switch's role as it is" in caplog.textdiff --git a/core/tests/switch_core/test_workos_directory.py b/core/tests/switch_core/test_workos_directory.pynew file mode 100644index 000000000..ca2759eae--- /dev/null+++ b/core/tests/switch_core/test_workos_directory.py@@ -0,0 +1,183 @@+"""The WorkOS directory reads a person's memberships at sign-in, against a+stand-in for the WorkOS API."""++from __future__ import annotations++import json+from types import SimpleNamespace++import httpx+import pytest++from switch_core.organization_directory import (+ DirectoryMembership,+ DirectoryRefusal,+ DirectoryUnavailable,+)+from switch_core.workos_directory import WorkOSDirectory++API = "https://workos.example.test"+KEY = "sk_test_example"+++class _WorkOS:+ """Answers the two reads the directory makes, from `organizations` (id ->+ metadata) and `memberships` (organization id, role), a page of `page` at+ a time."""++ def __init__(+ self,+ organizations: dict[str, dict],+ memberships: list[tuple[str, str]],+ *,+ page: int = 100,+ ) -> None:+ self.organizations = organizations+ self.memberships = memberships+ self.page = page+ self.requests: list[httpx.Request] = []++ def __call__(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ assert request.headers["Authorization"] == f"Bearer {KEY}"+ path = request.url.path+ if path == "/user_management/organization_memberships":+ assert request.url.params["user_id"] == "user_EXAMPLE"+ assert request.url.params["statuses"] == "active"+ start = int(request.url.params.get("after") or 0)+ chunk = self.memberships[start : start + self.page]+ after = start + self.page+ return httpx.Response(+ 200,+ json={+ "data": [+ {+ "organization_id": organization_id,+ "role": {"slug": role},+ "status": "active",+ }+ for organization_id, role in chunk+ ],+ "list_metadata": {+ "after": str(after) if after < len(self.memberships) else None+ },+ },+ )+ if path.startswith("/organizations/"):+ organization_id = path.removeprefix("/organizations/")+ return httpx.Response(+ 200,+ json={+ "id": organization_id,+ "name": "Example",+ "metadata": self.organizations[organization_id],+ },+ )+ return httpx.Response(404)+++def _directory(handler) -> WorkOSDirectory:+ return WorkOSDirectory(+ httpx.AsyncClient(transport=httpx.MockTransport(handler)), KEY, API+ )+++class TestMembershipsAtSignIn:+ async def test_one_membership_per_customer_with_the_highest_role(self) -> None:+ """A customer's own organization and one a product made beneath it+ name the same customer; an `org_admin` of either is its Org Admin."""+ workos = _WorkOS(+ organizations={+ "org_root": {"tenant_id": "ten_a"},+ "org_child": {"tenant_id": "ten_a"},+ "org_other": {"tenant_id": "ten_b"},+ },+ memberships=[+ ("org_root", "member"),+ ("org_child", "org_admin"),+ ("org_other", "editor"),+ ],+ )++ memberships = await _directory(workos).memberships_at_sign_in("user_EXAMPLE")++ assert memberships == [+ DirectoryMembership(customer_id="ten_a", role="org_admin"),+ DirectoryMembership(customer_id="ten_b", role="member"),+ ]++ async def test_every_page_is_read(self) -> None:+ workos = _WorkOS(+ organizations={f"org_{i}": {"tenant_id": f"ten_{i}"} for i in range(5)},+ memberships=[(f"org_{i}", "member") for i in range(5)],+ page=2,+ )++ memberships = await _directory(workos).memberships_at_sign_in("user_EXAMPLE")++ assert [membership.customer_id for membership in memberships] == [+ f"ten_{i}" for i in range(5)+ ]++ async def test_an_organization_naming_no_customer_is_skipped(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ workos = _WorkOS(+ organizations={"org_bare": {}, "org_a": {"tenant_id": "ten_a"}},+ memberships=[("org_bare", "org_admin"), ("org_a", "member")],+ )++ memberships = await _directory(workos).memberships_at_sign_in("user_EXAMPLE")++ assert memberships == [DirectoryMembership(customer_id="ten_a", role="member")]+ assert "org_bare names no customer" in caplog.text++ @pytest.mark.parametrize(+ "answer",+ [+ httpx.Response(500),+ httpx.Response(401),+ httpx.Response(200, json={"data": "not a list"}),+ httpx.Response(200, content=json.dumps([1, 2])),+ ],+ )+ async def test_an_answer_switch_cannot_use_is_unavailable(+ self, answer: httpx.Response+ ) -> None:+ with pytest.raises(DirectoryUnavailable):+ await _directory(lambda request: answer).memberships_at_sign_in(+ "user_EXAMPLE"+ )++ async def test_an_unreachable_workos_is_unavailable(self) -> None:+ def unreachable(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("refused", request=request)++ with pytest.raises(DirectoryUnavailable, match="ConnectError"):+ await _directory(unreachable).memberships_at_sign_in("user_EXAMPLE")+++class TestChangesFromSwitch:+ """Changes made from Switch go through the service that owns the customer+ record; until that is wired in, they are refused for a customer's+ organization, and an organization Switch keeps itself stays its own."""++ async def test_a_customers_organization_refuses_them(self) -> None:+ directory = _directory(lambda request: httpx.Response(500))+ customer = SimpleNamespace(customer_id="ten_a")++ for change in (+ directory.join(customer, "u", "member"), # type: ignore[arg-type]+ directory.set_role(customer, "u", "org_admin"), # type: ignore[arg-type]+ directory.remove(customer, "u"), # type: ignore[arg-type]+ ):+ with pytest.raises(DirectoryRefusal):+ await change++ async def test_an_organization_switch_keeps_itself_needs_nothing(self) -> None:+ directory = _directory(lambda request: httpx.Response(500))+ local = SimpleNamespace(customer_id=None)++ await directory.join(local, "u", "member") # type: ignore[arg-type]+ await directory.set_role(local, "u", "org_admin") # type: ignore[arg-type]+ await directory.remove(local, "u") # type: ignore[arg-type]diff --git a/gateway/src/pages/organization/OrganizationAuditSection.tsx b/gateway/src/pages/organization/OrganizationAuditSection.tsxindex 5d1c9e221..38932cd8f 100644--- a/gateway/src/pages/organization/OrganizationAuditSection.tsx+++ b/gateway/src/pages/organization/OrganizationAuditSection.tsx@@ -18,6 +18,7 @@ const ACTION_LABELS: Record<string, string> = {"organization.connector_app_removed": "Connector app removed","organization.service_set": "Service switched","organization.service_cleared": "Service left to workspaces",+ "organization.member_added_at_sign_in": "Member added at sign-in",};const COLUMNS: GridColDef<OrganizationAuditEvent>[] = [