Skip to content

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

feat(organizations): make linked organizations' member changes in WorkOS, as the admin

Petr Bauchbb30220bcba2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf52d086a..6abafc11e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -141,10 +141,14 @@ version of their own to them without also giving them a release of their own.
seconds, and in a full check once a day. A change from WorkOS is applied
even when it breaks a rule Switch keeps (the last Org Admin, agents left
without an owner who can act for them), and the Organization page tells
- its admins what is left to fix. Adding someone to a linked organization or
- making them Org Admin is done in WorkOS, and the dashboard says so; taking
- either away in Switch ends access at once but lasts only while WorkOS
- agrees. Setup and limits: `docs/old/workos-directory.md`.
+ its admins what is left to fix. With a members service configured
+ (`MEMBERS_SERVICE_URL`, `WORKOS_CLIENT_ID`, `WORKOS_REDIRECT_URL`), an Org
+ Admin's role changes and removals on the Organization page are made in
+ WorkOS too, with the admin's own WorkOS token, which the dashboard gets by
+ sending them through the organization's sign-in when needed. Without one,
+ making someone Org Admin is done in WorkOS, and taking it away in Switch
+ lasts only while WorkOS agrees. Adding someone new is done in WorkOS either
+ way. Setup and limits: `docs/old/workos-directory.md`.
- **A reconnect storm is paced instead of taking the pool.** When a pod goes
away, every agent and controller it held opens a connection on the pods
left within seconds. On staging (two pods, 1,000 agents, one pod deleted)
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 104344661..7911fb2d5 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -402,6 +402,17 @@ class SwitchConfig(BaseSettings):
organization_directory: Literal["local", "workos"] = "local"
workos_api_key: str | None = None
workos_api_url: str = "https://api.workos.com"
+ # Changes made from Switch to a linked organization's members, sent to
+ # the service every product in the WorkOS environment changes them
+ # through (`members_service.py`), with the admin's own WorkOS access
+ # token. All three or none; unset, Switch takes nothing to WorkOS,
+ # refuses what grants, and what it takes away lasts only until WorkOS is
+ # read again. `WORKOS_CLIENT_ID` is the AuthKit application Switch signs
+ # admins in to for that token, and `WORKOS_REDIRECT_URL` its callback
+ # (`.../gateway/auth/workos/callback`), registered on that application.
+ members_service_url: str | None = None
+ workos_client_id: str | None = None
+ workos_redirect_url: str | None = None
# Outbound mail for invitations addressed to an e-mail. Setting the host
# turns it on; any SMTP relay works. Unset, an addressed invitation is
@@ -1536,6 +1547,11 @@ class SwitchConfig(BaseSettings):
@model_validator(mode="after")
def _validate_organization_directory(self) -> "SwitchConfig":
if self.organization_directory != "workos":
+ if self.members_service_url:
+ raise ValueError(
+ "MEMBERS_SERVICE_URL is for ORGANIZATION_DIRECTORY=workos: "
+ "under the local directory there is nobody to send changes to."
+ )
return self
if not self.workos_api_key:
raise ValueError(
@@ -1555,6 +1571,18 @@ class SwitchConfig(BaseSettings):
"customer's organization is linked by an operator "
"(switch-link-workos), not created by whoever signs up."
)
+ changes = (
+ self.members_service_url,
+ self.workos_client_id,
+ self.workos_redirect_url,
+ )
+ if 0 < sum(1 for value in changes if value) < len(changes):
+ raise ValueError(
+ "MEMBERS_SERVICE_URL, WORKOS_CLIENT_ID and WORKOS_REDIRECT_URL "
+ "are set together: changes to a linked organization's members "
+ "go to the members service with a token from that AuthKit "
+ "application."
+ )
return self
@model_validator(mode="after")
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index 120519d86..3731aba6e 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -81,6 +81,9 @@ from switch_core.gateway.template_runs import router as template_runs_router
from switch_core.gateway.templates import router as templates_router
from switch_core.gateway.tenants import router as tenants_router
from switch_core.gateway.trust_settings import router as trust_settings_router
+from switch_core.gateway.workos_sign_in_routes import (
+ router as workos_sign_in_router,
+)
from switch_core.gateway.workspace_services import (
router as workspace_services_router,
)
@@ -180,6 +183,9 @@ def create_gateway_app(
# Sign-ins under way, GitHub's and the catalog's, in Postgres so that any
# switch-core process can take any step of one.
app.state.sign_in_flows = SignInFlows(session_factory, config.keyring)
+ # Set by the server when changes to linked organizations' members are
+ # sent to WorkOS (`workos_sign_in.py`).
+ app.state.workos_sign_in = None
app.state.service_flows = ServiceFlows(
config.gateway_public_url, app.state.sign_in_flows
)
@@ -220,6 +226,7 @@ def create_gateway_app(
)
app.include_router(auth_router, tags=["auth"])
app.include_router(oidc_router, tags=["auth"])
+ app.include_router(workos_sign_in_router, tags=["auth"])
app.include_router(tenants_router, tags=["tenants"])
app.include_router(organizations_router, tags=["organizations"])
app.include_router(rooms_router, prefix="/rooms", tags=["rooms"])
diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.py
index 6b6527348..8f852f26c 100644
--- a/core/switch_core/gateway/organizations.py
+++ b/core/switch_core/gateway/organizations.py
@@ -23,7 +23,7 @@ from typing import Annotated, NamedTuple
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import JSONResponse
-from sqlalchemy import delete
+from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.authz import ORGANIZATION_ADMIN_ROLE
@@ -41,6 +41,7 @@ from switch_core.db.audit import (
record_organization_audit_event,
)
from switch_core.db.models import (
+ OidcIdentity,
Organization,
OrganizationMember,
Tenant,
@@ -88,6 +89,7 @@ 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.workspace_creation import (
NOTHING_CHANGED,
create_organization_for,
@@ -100,11 +102,17 @@ from switch_core.organization_access import (
end_access_through_organization,
workspaces_where_they_own_agents,
)
-from switch_core.organization_directory import DirectoryError, OrganizationDirectory
+from switch_core.organization_directory import (
+ DirectoryError,
+ DirectorySignInRequired,
+ MemberChange,
+ OrganizationDirectory,
+)
from switch_core.organization_issues import (
organization_wide_issues,
workspace_issues,
)
+from switch_core.workos_sign_in import OrganizationToken
router = APIRouter()
@@ -254,6 +262,7 @@ async def current_organization(
name=organization.name,
role=await user_store.organization_role(session, require_tenant_id(), user.id),
members_from_directory=organization_directory.keeps_members_of(organization),
+ directory_takes_changes=organization_directory.sends_changes_for(organization),
)
@@ -473,23 +482,76 @@ async def _ask_directory(
session: AsyncSession,
organization_id: str,
*args: str,
+ member_change: MemberChange,
access_ended: bool,
) -> None:
"""Ask the directory to make `change` to a member of `organization_id`,
- with `args`: after every check that can refuse, under the lock on the
- organization's admins, and before the write and its commit
- (`organization_directory.py`). `access_ended` says the person's access
- through the organization was ended on the way, which a refusal does not
- give back."""
+ 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")
+ outcome = _ACCESS_ALREADY_ENDED if access_ended else NOTHING_CHANGED
try:
- await change(organization, *args)
+ await change(organization, *args, member_change)
+ except DirectorySignInRequired as error:
+ raise _sign_in_required(error, outcome) from None
except DirectoryError as error:
- raise directory_failed(
- error, _ACCESS_ALREADY_ENDED if access_ended else NOTHING_CHANGED
- ) from None
+ raise directory_failed(error, outcome) from None
+
+
+def _sign_in_required(error: DirectorySignInRequired, outcome: str) -> HTTPException:
+ """403 the dashboard tells apart by its `error`: it sends the admin to
+ sign in to the organization's WorkOS account and back to make the change
+ again (`gateway/workos_sign_in_routes.py`)."""
+ return HTTPException(
+ status_code=403,
+ detail={
+ "error": "directory_sign_in_required",
+ "message": f"{error.message} {outcome}",
+ },
+ )
+
+
+async def _member_change(
+ session: AsyncSession,
+ organization_directory: OrganizationDirectory,
+ token: OrganizationToken | None,
+ organization_id: str,
+ user_id: str,
+) -> 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")
+ access_token = (
+ token.access_token
+ if token is not None
+ and token.workos_organization_id == organization.workos_organization_id
+ else None
+ )
+ 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,
+ )
+ )
+ if organization_directory.identity_issuer is not None
+ else None
+ )
+ return MemberChange(access_token=access_token, subject=subject)
async def _end_access_through_organization(
@@ -551,6 +613,9 @@ async def update_organization_member_role(
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
+ directory_token: Annotated[
+ OrganizationToken | None, Depends(directory_access_token)
+ ],
user: Annotated[User, Depends(get_current_user)],
) -> OrganizationMemberDetail | JSONResponse:
"""Make a member `org_admin`, or an `org_admin` a `member`. `org_admin` only,
@@ -572,6 +637,17 @@ async def update_organization_member_role(
demoting = (
member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE
)
+ member_change = (
+ await _member_change(
+ session,
+ organization_directory,
+ directory_token,
+ organization_id,
+ user_id,
+ )
+ if member.role != req.role
+ else MemberChange(access_token=None, subject=None)
+ )
last_admin = HTTPException(
status_code=409, detail="Cannot demote the last organization admin"
)
@@ -620,6 +696,7 @@ async def update_organization_member_role(
organization_id,
user_id,
req.role,
+ member_change=member_change,
access_ended=demoting,
)
await record_organization_audit_event(
@@ -660,6 +737,9 @@ async def remove_organization_member(
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
broker: Annotated[ServiceBroker, Depends(get_service_broker)],
protocol: Annotated[AgentCore, Depends(get_protocol)],
+ directory_token: Annotated[
+ OrganizationToken | None, Depends(directory_access_token)
+ ],
user: Annotated[User, Depends(get_current_user)],
) -> dict | JSONResponse:
"""Remove someone from the organization. `org_admin` only.
@@ -689,6 +769,9 @@ 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
+ )
# Let go of the request's connection while each workspace is read on a
# session of its own.
await session.commit()
@@ -735,6 +818,7 @@ async def remove_organization_member(
session,
organization_id,
user_id,
+ member_change=member_change,
access_ended=was_admin,
)
role = member.role
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index cdaa74e38..7b09f6847 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1070,13 +1070,16 @@ class CurrentOrganizationResponse(BaseModel):
"""The bound workspace's organization, and the caller's role in it: None
for the platform operator there on the operator flag alone.
`members_from_directory`: its members and `org_admin`s come from a
- directory kept outside Switch (`OrganizationDirectory.keeps_members_of`)."""
+ directory kept outside Switch (`OrganizationDirectory.keeps_members_of`);
+ `directory_takes_changes`: changes made here to them are made there too
+ (`OrganizationDirectory.sends_changes_for`)."""
id: str
slug: str
name: str
role: str | None
members_from_directory: bool
+ directory_takes_changes: bool
class OrganizationIssueDetail(BaseModel):
diff --git a/core/switch_core/gateway/workos_sign_in_routes.py b/core/switch_core/gateway/workos_sign_in_routes.py
new file mode 100644
index 000000000..6897e8f5a
--- /dev/null
+++ b/core/switch_core/gateway/workos_sign_in_routes.py
@@ -0,0 +1,239 @@
+"""Signing an admin in to their linked organization's WorkOS account, for the
+token the members service takes changes from (`workos_sign_in.py`).
+
+The dashboard sends the browser here when a change to the members answers
+`directory_sign_in_required`, and comes back to `return_to` to make it again.
+The token is kept in the sign-in cookie, encrypted and bound to the Switch
+account that asked for it, and is offered to a change only while it lasts.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import logging
+import re
+import secrets
+from typing import Annotated
+from urllib.parse import urlsplit
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from starlette.responses import RedirectResponse
+
+from switch_core.authz import ORGANIZATION_ADMIN_ROLE
+from switch_core.config import SwitchConfig
+from switch_core.db.models import (
+ OidcIdentity,
+ Organization,
+ Tenant,
+ User,
+ require_tenant_id,
+)
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway.auth import get_current_user
+from switch_core.gateway.dependencies import (
+ get_config,
+ get_organization_directory,
+ get_session,
+ get_user_store,
+)
+from switch_core.organization_directory import (
+ DirectoryUnavailable,
+ OrganizationDirectory,
+)
+from switch_core.workos_sign_in import (
+ OrganizationToken,
+ SignInRefused,
+ WorkOSOrganizationSignIn,
+)
+
+logger = logging.getLogger(__name__)
+
+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/_.-]*$")
+
+
+def _sign_in(request: Request) -> WorkOSOrganizationSignIn:
+ sign_in: WorkOSOrganizationSignIn | None = request.app.state.workos_sign_in
+ if sign_in is None:
+ raise HTTPException(
+ status_code=404,
+ detail="Changes to organization members are not sent to WorkOS here",
+ )
+ return sign_in
+
+
+async def _subject_of(
+ session: AsyncSession, organization_directory: OrganizationDirectory, user: User
+) -> str | None:
+ 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 subject
+
+
[email protected]("/auth/workos/organization")
+async def start_organization_sign_in(
+ request: Request,
+ return_to: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> RedirectResponse:
+ """Send the signed-in Org Admin to sign in to the WorkOS organization the
+ bound workspace's organization follows, and back to `return_to`."""
+ sign_in = _sign_in(request)
+ if not _RETURN_TO.match(return_to):
+ raise HTTPException(
+ status_code=400, detail="return_to must be a dashboard path"
+ )
+ tenant_id = require_tenant_id()
+ if await user_store.organization_role(session, tenant_id, user.id) != (
+ ORGANIZATION_ADMIN_ROLE
+ ):
+ raise HTTPException(
+ status_code=403, detail="Only an organization admin may do this"
+ )
+ tenant = await session.get(Tenant, tenant_id)
+ organization = (
+ await session.get(Organization, tenant.organization_id)
+ if tenant is not None and tenant.organization_id is not None
+ else None
+ )
+ if organization is None or organization.workos_organization_id is None:
+ raise HTTPException(
+ status_code=409, detail="This organization does not follow WorkOS"
+ )
+ verifier = secrets.token_urlsafe(48)
+ state = secrets.token_urlsafe(24)
+ request.session[_PENDING_KEY] = {
+ "state": state,
+ "verifier": verifier,
+ "user_id": user.id,
+ "workos_organization_id": organization.workos_organization_id,
+ "return_to": return_to,
+ }
+ challenge = (
+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
+ .rstrip(b"=")
+ .decode()
+ )
+ return RedirectResponse(
+ url=sign_in.authorize_url(
+ organization.workos_organization_id, state, challenge
+ ),
+ status_code=302,
+ )
+
+
[email protected]("/auth/workos/callback")
+async def finish_organization_sign_in(
+ request: Request,
+ code: str,
+ state: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ organization_directory: Annotated[
+ OrganizationDirectory, Depends(get_organization_directory)
+ ],
+ user: Annotated[User, Depends(get_current_user)],
+) -> RedirectResponse:
+ """Exchange the code for the admin's token, once it is shown to be theirs
+ and for the organization they were sent to, and go back to `return_to`."""
+ sign_in = _sign_in(request)
+ pending = request.session.pop(_PENDING_KEY, None)
+ if (
+ not isinstance(pending, dict)
+ or not secrets.compare_digest(str(pending.get("state", "")), state)
+ or pending.get("user_id") != user.id
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail="This sign-in was not started here, or has expired; try again",
+ )
+ try:
+ token = await sign_in.authenticate(code, str(pending["verifier"]))
+ except SignInRefused as error:
+ logger.warning(
+ "WorkOS organization sign-in refused for user %s: %s", user.id, error
+ )
+ raise HTTPException(
+ status_code=401, detail="WorkOS refused the sign-in; try again"
+ ) from error
+ 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):
+ 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",
+ user.id,
+ token.subject,
+ )
+ raise HTTPException(
+ status_code=403,
+ detail=(
+ "You signed in to WorkOS as someone else than this Switch "
+ "account; sign in as yourself"
+ ),
+ )
+ if token.workos_organization_id != pending["workos_organization_id"]:
+ raise HTTPException(
+ status_code=403,
+ detail="WorkOS signed you in to another organization; try again",
+ )
+ request.session[_TOKEN_KEY] = config.keyring.encrypt(
+ json.dumps(
+ {
+ "user_id": user.id,
+ "subject": token.subject,
+ "workos_organization_id": token.workos_organization_id,
+ "access_token": token.access_token,
+ "expires_at": token.expires_at,
+ }
+ )
+ )
+ origin = urlsplit(config.frontend_base_url or "")
+ base = f"{origin.scheme}://{origin.netloc}" if origin.netloc else ""
+ return RedirectResponse(url=f"{base}{pending['return_to']}", status_code=303)
+
+
+def directory_access_token(
+ request: Request,
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> OrganizationToken | None:
+ """The signed-in admin's WorkOS token from `finish_organization_sign_in`,
+ while it is theirs and lasts beyond the change about to be made."""
+ sealed = request.session.get(_TOKEN_KEY)
+ if not isinstance(sealed, str):
+ return None
+ try:
+ kept = json.loads(config.keyring.decrypt(sealed))
+ except Exception:
+ logger.warning("A kept WorkOS organization token could not be read; dropped")
+ request.session.pop(_TOKEN_KEY, None)
+ return None
+ if not isinstance(kept, dict) or kept.get("user_id") != user.id:
+ return None
+ token = OrganizationToken(
+ subject=str(kept["subject"]),
+ workos_organization_id=str(kept["workos_organization_id"]),
+ access_token=str(kept["access_token"]),
+ expires_at=int(kept["expires_at"]),
+ )
+ return token if token.lasts_beyond(_TOKEN_MARGIN_SECONDS) else None
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 4cf8dd370..60188ec0f 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -187,6 +187,7 @@ from switch_core.gateway.ui import GatewayUi
from switch_core.logging_config import configure_logging
from switch_core.management.template_updates import TemplateUpdates
from switch_core.management.wiring import Management, create_management
+from switch_core.members_service import MembersService
from switch_core.messages.notify import MessageListener
from switch_core.observability.bootstrap import (
Observability,
@@ -234,6 +235,7 @@ from switch_core.user_changes import LocalUserChanges, SignalUserChanges
from switch_core.version import switch_core_version
from switch_core.workos_directory import WorkOSDirectory
from switch_core.workos_mirror import WorkOSMirror, own_workos_mirror
+from switch_core.workos_sign_in import WorkOSOrganizationSignIn
logger = logging.getLogger(__name__)
@@ -530,9 +532,19 @@ def _organization_directory(
"""The directory `ORGANIZATION_DIRECTORY` names (`organization_directory.py`)."""
if config.organization_directory == "local":
return LocalDirectory()
- # `_validate_organization_directory` has refused a missing key already.
+ # `_validate_organization_directory` has refused a missing key or
+ # sign-in already.
assert config.workos_api_key is not None
- return WorkOSDirectory(http, config.workos_api_key, config.workos_api_url)
+ assert config.gateway_oidc_issuer_url is not None
+ return WorkOSDirectory(
+ http,
+ config.workos_api_key,
+ config.workos_api_url,
+ config.gateway_oidc_issuer_url,
+ MembersService(http, config.members_service_url)
+ if config.members_service_url
+ else None,
+ )
async def _close_by(
@@ -1401,6 +1413,19 @@ async def run(config: SwitchConfig, process_id: str) -> None:
agent_bridge_app.state.service_broker = service_broker
gateway_app.state.service_broker = service_broker
gateway_app.state.organization_apps = organization_apps
+ if config.members_service_url:
+ # Checked set together, under the WorkOS directory
+ # (`_validate_organization_directory`).
+ assert config.workos_api_key is not None
+ assert config.workos_client_id is not None
+ assert config.workos_redirect_url is not None
+ gateway_app.state.workos_sign_in = WorkOSOrganizationSignIn(
+ service_http,
+ config.workos_api_key,
+ config.workos_api_url,
+ config.workos_client_id,
+ config.workos_redirect_url,
+ )
# A connector app the operator saves or removes, put to work in every process.
ConnectorAppSignals(
apps=connector_apps,
diff --git a/core/switch_core/members_service.py b/core/switch_core/members_service.py
new file mode 100644
index 000000000..52edeea86
--- /dev/null
+++ b/core/switch_core/members_service.py
@@ -0,0 +1,149 @@
+"""The service a shared WorkOS environment's members are changed through.
+
+When several products share one WorkOS environment, one service owns each
+customer's account there and every product changes its members through it,
+so each product's rules (nobody grants above their own role, the last
+`org_admin` stays) apply in one place. Switch calls it with the admin's own
+WorkOS access token for the organization (`gateway/workos_sign_in.py`), never
+a credential of its own: the service sees who acted and decides by their
+live role there, as it does for its own product.
+
+The calls, each acting on the organization the token was issued for:
+
+- `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}`.
+
+A refusal comes back as `{"error": <reason>}`.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+
+from switch_core.organization_directory import (
+ DirectoryRefusal,
+ DirectorySignInRequired,
+ DirectoryUnavailable,
+)
+
+# Bounds every call: a route holds locks while it waits.
+MEMBERS_SERVICE_TIMEOUT_SECONDS = 10.0
+# The service's largest page.
+_PAGE = 100
+
+SIGN_IN_AGAIN = (
+ "Your sign-in to your organization's account has ended. Confirm it again "
+ "to change the organization's members."
+)
+
+
+class MembersService:
+ def __init__(self, http: httpx.AsyncClient, url: str) -> None:
+ self._http = http
+ self._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",
+ f"/v1/auth/tenants/members/{membership_id}",
+ access_token,
+ json={"role": role},
+ )
+
+ async def remove(self, access_token: str, membership_id: str) -> None:
+ await self._call(
+ "DELETE", f"/v1/auth/tenants/members/{membership_id}", access_token
+ )
+
+ async def _call(
+ self,
+ method: str,
+ path: str,
+ access_token: str,
+ *,
+ params: dict[str, str] | None = None,
+ json: dict[str, str] | None = None,
+ ) -> dict[str, Any]:
+ 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,
+ )
+ except httpx.HTTPError as error:
+ raise DirectoryUnavailable(
+ f"The members service could not be reached ({type(error).__name__})."
+ ) from error
+ if response.status_code == 401:
+ raise DirectorySignInRequired(SIGN_IN_AGAIN)
+ if response.status_code in (400, 403, 404, 409, 422):
+ raise DirectoryRefusal(_reason(response))
+ if response.status_code >= 300:
+ 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 body
+
+
+def _reason(response: httpx.Response) -> str:
+ """The service's own words for a refusal, or its status when it gave none."""
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ if isinstance(body, dict) and isinstance(body.get("error"), str):
+ return f"Your organization's account settings refused: {body['error']}."
+ return f"Your organization's account settings refused ({response.status_code})."
diff --git a/core/switch_core/organization_directory.py b/core/switch_core/organization_directory.py
index b972070b7..afde3a9f6 100644
--- a/core/switch_core/organization_directory.py
+++ b/core/switch_core/organization_directory.py
@@ -63,11 +63,48 @@ class DirectoryRefusal(DirectoryError):
"""The directory refused the change by its own rules: trying again won't."""
+class DirectorySignInRequired(DirectoryError):
+ """The directory takes the change only from the admin as it knows them,
+ and Switch holds no token of theirs for it: they sign in there for the
+ organization (`gateway/workos_sign_in.py`) and try again. Raised before
+ anything is changed."""
+
+
+@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."""
+
+ access_token: str | None
+ subject: str | None
+
+
class OrganizationDirectory(Protocol):
"""Implementations work outside Switch's database, over the network, and
bound every call: they are handed rows, never a session, and a route may
hold locks while it waits on them."""
+ # 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.
+ 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."""
+ ...
+
+ def sends_changes_for(self, organization: Organization) -> bool:
+ """Whether changes made from Switch to `organization`'s members are
+ made in the directory too, so that they last. False where Switch's
+ tables are the record."""
+ ...
+
def keeps_members_of(self, organization: Organization) -> bool:
"""Whether the directory, not Switch, is the record of who is in
`organization` and who is its `org_admin`: then adding someone or
@@ -101,12 +138,18 @@ class OrganizationDirectory(Protocol):
...
async def set_role(
- self, organization: Organization, user_id: str, role: str
+ self,
+ organization: Organization,
+ user_id: str,
+ role: str,
+ change: MemberChange,
) -> None:
"""Change a member's role in `organization` to `role`."""
...
- async def remove(self, organization: Organization, user_id: str) -> None:
+ async def remove(
+ self, organization: Organization, user_id: str, change: MemberChange
+ ) -> None:
"""End `user_id`'s membership of `organization`."""
...
@@ -115,6 +158,16 @@ class LocalDirectory:
"""Switch's own tables are the record: each change is the route's write
to them, and nothing is asked first."""
+ identity_issuer: str | None = None
+
+ def check_can_change(
+ self, organization: Organization, access_token: str | None
+ ) -> None:
+ return None
+
+ def sends_changes_for(self, organization: Organization) -> bool:
+ return False
+
def keeps_members_of(self, organization: Organization) -> bool:
return False
@@ -135,9 +188,15 @@ class LocalDirectory:
return None
async def set_role(
- self, organization: Organization, user_id: str, role: str
+ self,
+ organization: Organization,
+ user_id: str,
+ role: str,
+ change: MemberChange,
) -> None:
return None
- async def remove(self, organization: Organization, user_id: str) -> None:
+ async def remove(
+ self, organization: Organization, user_id: str, change: MemberChange
+ ) -> None:
return None
diff --git a/core/switch_core/workos_directory.py b/core/switch_core/workos_directory.py
index 52d1fcfda..a2928fee9 100644
--- a/core/switch_core/workos_directory.py
+++ b/core/switch_core/workos_directory.py
@@ -15,13 +15,17 @@ 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 to a linked organization 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 those that grant (adding someone, making them Org Admin). Those that
-take away (a removal, a demotion) change only Switch, so an Org Admin can end
-access WorkOS has already ended. An organization nobody has linked is Switch's own, as under the
-local directory, and that is what a new organization is until then.
+Changes made from Switch to a linked organization go through the members
+service (`members_service.py`), with the admin's own WorkOS token for it, not
+through 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
+the organization yet. Where no members service is configured, those that
+grant are refused, and those that take away (a removal, a demotion) change
+only Switch, so an Org Admin can end access WorkOS has already ended, until
+WorkOS is read again. An organization nobody has linked is Switch's own, as
+under the local directory, and that is what a new organization is until then.
"""
from __future__ import annotations
@@ -34,11 +38,14 @@ import httpx
from switch_core.authz import ORGANIZATION_ADMIN_ROLE
from switch_core.db.models import Organization, User
+from switch_core.members_service import MembersService
from switch_core.organization_directory import (
DirectoryMembership,
DirectoryOrganization,
DirectoryRefusal,
+ DirectorySignInRequired,
DirectoryUnavailable,
+ MemberChange,
)
logger = logging.getLogger(__name__)
@@ -56,6 +63,12 @@ NOT_FROM_SWITCH_YET = (
"This organization's members are managed in your organization's account "
"settings, not here yet."
)
+SIGN_IN_FIRST = (
+ "Confirm your sign-in to your organization's account to change its members."
+)
+# The WorkOS role of a member Switch makes a Member: the least a member of a
+# shared organization can be.
+MEMBER_ROLE_IN_WORKOS = "viewer"
def customer_id_of(organization: dict[str, Any]) -> str | None:
@@ -92,10 +105,19 @@ def _unreadable(what: str) -> DirectoryUnavailable:
class WorkOSDirectory:
- def __init__(self, http: httpx.AsyncClient, api_key: str, api_url: str) -> None:
+ def __init__(
+ self,
+ http: httpx.AsyncClient,
+ api_key: str,
+ api_url: str,
+ identity_issuer: str,
+ members: MembersService | None,
+ ) -> None:
self._http = http
self._api_key = api_key
self._api_url = api_url.rstrip("/")
+ self.identity_issuer: str | None = identity_issuer
+ self._members = members
async def _get(
self, path: str, params: Mapping[str, str | list[str]]
@@ -251,6 +273,22 @@ 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
+ ):
+ raise DirectorySignInRequired(SIGN_IN_FIRST)
+
+ def sends_changes_for(self, organization: Organization) -> bool:
+ return (
+ organization.workos_organization_id is not None
+ and self._members is not None
+ )
+
def keeps_members_of(self, organization: Organization) -> bool:
"""Only an organization an operator linked follows WorkOS; any other
is still Switch's own."""
@@ -270,18 +308,68 @@ class WorkOSDirectory:
raise DirectoryRefusal(NOT_FROM_SWITCH_YET)
async def set_role(
- self, organization: Organization, user_id: str, role: str
+ self,
+ organization: Organization,
+ user_id: str,
+ role: str,
+ change: MemberChange,
) -> None:
- """Taking Org Admin away in Switch needs nothing from WorkOS: it is how
- Switch catches up with a demotion there, and a sign-in makes them Org
- Admin again for as long as WorkOS still has them as one."""
+ """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
- if role == ORGANIZATION_ADMIN_ROLE:
- raise DirectoryRefusal(NOT_FROM_SWITCH_YET)
- 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."
+ )
+ return None
+ await self._members.set_role(
+ access_token,
+ membership,
+ ORGANIZATION_ADMIN_ROLE if promoting else MEMBER_ROLE_IN_WORKOS,
+ )
- async def remove(self, organization: Organization, user_id: str) -> None:
- """As with a demotion: Switch catching up with a removal in WorkOS,
- undone at the next sign-in for as long as WorkOS still lists them."""
- return None
+ 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:
+ 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)
+
+ 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."
+ )
+ return await self._members.membership_of(access_token, change.subject)
+
+
+def _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."""
+ if change.access_token is None:
+ raise DirectorySignInRequired(SIGN_IN_FIRST)
+ return change.access_token
diff --git a/core/switch_core/workos_linking.py b/core/switch_core/workos_linking.py
index d8f62b1ac..7c9e875d0 100644
--- a/core/switch_core/workos_linking.py
+++ b/core/switch_core/workos_linking.py
@@ -221,8 +221,13 @@ async def _run(config: SwitchConfig, arguments: argparse.Namespace) -> int:
engine = create_engine_from_config(config)
try:
async with guarded_async_client(config.outbound_policy) as http:
+ # Linking reads WorkOS and changes nobody's membership there.
directory = WorkOSDirectory(
- http, config.workos_api_key, config.workos_api_url
+ http,
+ config.workos_api_key,
+ config.workos_api_url,
+ config.gateway_oidc_issuer_url,
+ None,
)
session_factory = create_session_factory(engine)
try:
diff --git a/core/switch_core/workos_sign_in.py b/core/switch_core/workos_sign_in.py
new file mode 100644
index 000000000..07c1b5aa0
--- /dev/null
+++ b/core/switch_core/workos_sign_in.py
@@ -0,0 +1,147 @@
+"""An admin's own WorkOS access token for a linked organization.
+
+The members service takes changes to a linked organization's members only
+from the admin as WorkOS knows them, with an AuthKit access token issued for
+that organization (`members_service.py`). Switch's own sign-in proves who the
+admin is but holds no such token, and Switch keeps no long-lived WorkOS
+credential of anyone's. So when an admin changes the members, Switch sends
+them through the AuthKit application's sign-in for the organization (silent
+while their AuthKit session lasts), exchanges the code for an access token,
+and keeps only that token, encrypted, in the short-lived sign-in cookie, for
+as long as it lasts (`gateway/workos_sign_in_routes.py`). The refresh token
+that comes with it is dropped.
+"""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import urlencode
+
+import httpx
+import jwt
+
+from switch_core.organization_directory import DirectoryUnavailable
+
+WORKOS_SIGN_IN_TIMEOUT_SECONDS = 10.0
+
+
+class SignInRefused(Exception):
+ """WorkOS refused the code: the sign-in has to start again."""
+
+
+@dataclass(frozen=True)
+class OrganizationToken:
+ """An access token WorkOS issued `subject` for `workos_organization_id`,
+ good until `expires_at` (Unix seconds)."""
+
+ subject: str
+ workos_organization_id: str
+ access_token: str
+ expires_at: int
+
+ def lasts_beyond(self, seconds: int) -> bool:
+ return self.expires_at > time.time() + seconds
+
+
+class WorkOSOrganizationSignIn:
+ def __init__(
+ self,
+ http: httpx.AsyncClient,
+ api_key: str,
+ api_url: str,
+ client_id: str,
+ redirect_url: str,
+ ) -> None:
+ self._http = http
+ self._api_key = api_key
+ self._api_url = api_url.rstrip("/")
+ self._client_id = client_id
+ self._redirect_url = redirect_url
+
+ def authorize_url(
+ self, workos_organization_id: str, state: str, challenge: str
+ ) -> str:
+ """Where the browser goes to sign in to `workos_organization_id`."""
+ query = urlencode(
+ {
+ "client_id": self._client_id,
+ "redirect_uri": self._redirect_url,
+ "response_type": "code",
+ "provider": "authkit",
+ "organization_id": workos_organization_id,
+ "state": state,
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ }
+ )
+ return f"{self._api_url}/user_management/authorize?{query}"
+
+ async def authenticate(self, code: str, verifier: str) -> OrganizationToken:
+ """The token the sign-in's `code` is good for. Raises `SignInRefused`
+ when WorkOS refuses the code, `DirectoryUnavailable` when it can't be
+ reached or answers with something else."""
+ try:
+ response = await self._http.post(
+ f"{self._api_url}/user_management/authenticate",
+ json={
+ "client_id": self._client_id,
+ "client_secret": self._api_key,
+ "grant_type": "authorization_code",
+ "code": code,
+ "code_verifier": verifier,
+ },
+ timeout=WORKOS_SIGN_IN_TIMEOUT_SECONDS,
+ )
+ except httpx.HTTPError as error:
+ raise DirectoryUnavailable(
+ f"WorkOS could not be reached ({type(error).__name__})."
+ ) from error
+ if response.status_code in (400, 401, 403):
+ raise SignInRefused(f"WorkOS refused the sign-in ({response.status_code}).")
+ if response.status_code != 200:
+ raise DirectoryUnavailable(
+ f"WorkOS answered the sign-in with {response.status_code}."
+ )
+ try:
+ body: Any = response.json()
+ except ValueError as error:
+ raise DirectoryUnavailable(
+ "WorkOS answered the sign-in with no JSON."
+ ) from error
+ return _token_from(body)
+
+
+def _token_from(body: Any) -> OrganizationToken:
+ unreadable = DirectoryUnavailable(
+ "WorkOS answered the sign-in with something Switch can't read."
+ )
+ if not isinstance(body, dict):
+ raise unreadable
+ user = body.get("user")
+ organization_id = body.get("organization_id")
+ access_token = body.get("access_token")
+ if (
+ not isinstance(user, dict)
+ or not isinstance(user.get("id"), str)
+ or not isinstance(organization_id, str)
+ or not isinstance(access_token, str)
+ ):
+ raise unreadable
+ # Read for its expiry only: it came from WorkOS over TLS, in answer to a
+ # request authenticated with the API key, and the members service
+ # verifies it.
+ try:
+ claims = jwt.decode(access_token, options={"verify_signature": False})
+ except jwt.PyJWTError as error:
+ raise unreadable from error
+ expires_at = claims.get("exp")
+ if not isinstance(expires_at, int):
+ raise unreadable
+ return OrganizationToken(
+ subject=user["id"],
+ workos_organization_id=organization_id,
+ access_token=access_token,
+ expires_at=expires_at,
+ )
diff --git a/core/tests/switch_core/gateway/test_organization_directory_routes.py b/core/tests/switch_core/gateway/test_organization_directory_routes.py
index 2d0c86891..c2cca1577 100644
--- a/core/tests/switch_core/gateway/test_organization_directory_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_directory_routes.py
@@ -32,6 +32,7 @@ from switch_core.organization_directory import (
DirectoryOrganization,
DirectoryRefusal,
DirectoryUnavailable,
+ MemberChange,
)
from tests.switch_core.gateway.test_organization_routes import (
_app,
@@ -54,10 +55,20 @@ class _Directory:
"""Records what it is asked, in order, and fails every change with
`failure` when one is given."""
+ identity_issuer: str | None = None
+
def __init__(self, failure: DirectoryError | None) -> None:
self.failure = failure
self.asked: list[tuple] = []
+ def check_can_change(
+ self, organization: Organization, access_token: str | None
+ ) -> None:
+ return None
+
+ def sends_changes_for(self, organization: Organization) -> bool:
+ return True
+
def _answer(self, *call: object) -> None:
self.asked.append(call)
if self.failure is not None:
@@ -81,11 +92,17 @@ class _Directory:
self._answer("join", organization.id, user_id, role)
async def set_role(
- self, organization: Organization, user_id: str, role: str
+ self,
+ organization: Organization,
+ user_id: str,
+ role: str,
+ change: MemberChange,
) -> None:
self._answer("set_role", organization.id, user_id, role)
- async def remove(self, organization: Organization, user_id: str) -> None:
+ async def remove(
+ self, organization: Organization, user_id: str, change: MemberChange
+ ) -> None:
self._answer("remove", organization.id, user_id)
diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.py
index 04c41131c..9ca1f8311 100644
--- a/core/tests/switch_core/gateway/test_organization_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_routes.py
@@ -15,6 +15,7 @@ import pytest
from fastapi import FastAPI
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from starlette.middleware.sessions import SessionMiddleware
from switch_core.connections.broker import ServiceBroker
from switch_core.connections.loader import CATALOG
@@ -45,6 +46,9 @@ from switch_core.gateway import workspace_creation
from switch_core.gateway.auth import create_jwt, decode_jwt
from switch_core.gateway.organizations import router as organizations_router
from switch_core.gateway.tenants import router as tenants_router
+from switch_core.gateway.workos_sign_in_routes import (
+ router as workos_sign_in_router,
+)
from switch_core.keys import Keyring
from switch_core.organization_directory import LocalDirectory
from tests.telemetry_records import recording_telemetry
@@ -103,6 +107,11 @@ def _app(
api_key_cache=SimpleNamespace(invalidate=lambda key_hash: None)
)
app.state.sign_in_flows = SignInFlows(session_factory, _KEYRING)
+ app.state.workos_sign_in = None
+ app.include_router(workos_sign_in_router)
+ # As the gateway has it: the sign-in cookie holds a WorkOS organization
+ # token (`workos_sign_in_routes.py`).
+ app.add_middleware(SessionMiddleware, secret_key="test-sign-in-cookie")
app.state.service_broker = ServiceBroker(
session_factory=session_factory,
keyring=_KEYRING,
diff --git a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
new file mode 100644
index 000000000..510fb0a2f
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
@@ -0,0 +1,343 @@
+"""Changing a linked organization's members from Switch, with the admin's own
+WorkOS token: refused until they sign in to the organization there, nothing
+changed on the way, then made through the members service.
+
+Against Postgres, through the real routes, with WorkOS and the members
+service answered in process.
+"""
+
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+import jwt
+from fastapi import FastAPI
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import (
+ OidcIdentity,
+ Organization,
+ OrganizationMember,
+ User,
+)
+from switch_core.gateway import dependencies as gw_deps
+from switch_core.members_service import MembersService
+from switch_core.workos_directory import WorkOSDirectory
+from switch_core.workos_sign_in import WorkOSOrganizationSignIn
+from tests.switch_core.gateway.test_organization_routes import (
+ _KEYRING,
+ _app,
+ _client,
+ _name,
+ _workspace,
+)
+
+ISSUER = "https://sign-in.example.test"
+WORKOS_ORGANIZATION = "org_EXAMPLE"
+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."""
+
+ def __init__(self, members: dict[str, str]) -> None:
+ self.signs_in_as = ""
+ self.organization = WORKOS_ORGANIZATION
+ self.members = members
+ self.changes: list[tuple[str, str, str]] = []
+
+ def sign_in(self, request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "user": {"id": self.signs_in_as},
+ "organization_id": self.organization,
+ "access_token": jwt.encode(
+ {"exp": int(time.time()) + 300, "sub": self.signs_in_as},
+ "test-signing-key-long-enough-for-hs256",
+ algorithm="HS256",
+ ),
+ },
+ )
+
+ 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),
+ },
+ )
+ self.changes.append(
+ (
+ request.method,
+ request.url.path.rsplit("/", 1)[1],
+ request.headers["Authorization"],
+ )
+ )
+ return httpx.Response(200, json={})
+
+
+def _with(
+ session_factory: async_sessionmaker[AsyncSession], workos: _WorkOS
+) -> FastAPI:
+ app = _app(session_factory)
+ directory = WorkOSDirectory(
+ httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda request: httpx.Response(500))
+ ),
+ "workos-api-key-placeholder",
+ "https://api.workos.example.test",
+ ISSUER,
+ MembersService(
+ httpx.AsyncClient(transport=httpx.MockTransport(workos.members_service)),
+ "https://members.example.test",
+ ),
+ )
+ app.dependency_overrides[gw_deps.get_organization_directory] = lambda: directory
+ app.state.workos_sign_in = WorkOSOrganizationSignIn(
+ httpx.AsyncClient(transport=httpx.MockTransport(workos.sign_in)),
+ "workos-api-key-placeholder",
+ "https://api.workos.example.test",
+ "client_EXAMPLE",
+ "https://switch.example.test/gateway/auth/workos/callback",
+ )
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ keyring=_KEYRING,
+ gateway_cookie_secure=False,
+ gateway_tenant_choice_enabled=False,
+ gateway_signup_mode="open",
+ gateway_max_workspaces_per_user=3,
+ frontend_base_url=None,
+ )
+ return app
+
+
+async def _linked(
+ session_factory: async_sessionmaker[AsyncSession], members: dict[str, tuple]
+) -> tuple[str, str]:
+ """A workspace in an organization linked to WorkOS, each member with a
+ WorkOS identity `user_<name>`. Returns (tenant, organization)."""
+ tenant_id = await _workspace(session_factory, members)
+ async with session_factory() as session:
+ organization_id = await session.scalar(
+ select(OrganizationMember.organization_id).where(
+ OrganizationMember.user_id == next(iter(members))
+ )
+ )
+ organization = await session.get(Organization, organization_id)
+ assert organization is not None
+ organization.workos_organization_id = WORKOS_ORGANIZATION
+ for name in members:
+ session.add(OidcIdentity(user_id=name, iss=ISSUER, sub=f"user_{name}"))
+ await session.commit()
+ return tenant_id, organization.id
+
+
+async def _role(
+ session_factory: async_sessionmaker[AsyncSession],
+ 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 _sign_in_to_workos(client: httpx.AsyncClient) -> httpx.Response:
+ started = await client.get(
+ "/auth/workos/organization", params={"return_to": "/organization"}
+ )
+ assert started.status_code == 302, started.text
+ location = urlsplit(started.headers["location"])
+ query = parse_qs(location.query)
+ assert query["organization_id"] == [WORKOS_ORGANIZATION]
+ return await client.get(
+ "/auth/workos/callback",
+ params={"code": "the-code", "state": query["state"][0]},
+ )
+
+
+class TestChangingMembers:
+ async def test_a_change_waits_for_the_admin_to_sign_in_to_workos(
+ self, session_factory
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id, organization_id = await _linked(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ )
+ workos = _WorkOS({f"user_{bob}": "om_bob"})
+ workos.signs_in_as = f"user_{ada}"
+
+ async with _client(_with(session_factory, workos), ada, tenant_id) as client:
+ refused = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}
+ )
+ signed_in = await _sign_in_to_workos(client)
+ made = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}
+ )
+
+ assert refused.status_code == 403
+ assert refused.json()["detail"]["error"] == "directory_sign_in_required"
+ assert signed_in.status_code == 303
+ assert signed_in.headers["location"] == "/organization"
+ assert made.status_code == 200, made.text
+ [(method, membership, authorization)] = workos.changes
+ assert (method, membership) == ("PATCH", "om_bob")
+ assert authorization.startswith("Bearer ")
+ assert await _role(session_factory, organization_id, bob) == "org_admin"
+
+ async def test_a_refused_demotion_takes_nothing_away(self, session_factory) -> None:
+ """Asked before anything changes: no workspace access is ended for a
+ change that then waits on a sign-in."""
+ 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"})
+
+ async with _client(_with(session_factory, workos), ada, tenant_id) as client:
+ refused = await client.patch(
+ f"/organizations/current/members/{cy}", json={"role": "member"}
+ )
+
+ assert refused.status_code == 403
+ assert "Nothing was changed." in refused.json()["detail"]["message"]
+ assert await _role(session_factory, organization_id, cy) == "org_admin"
+ assert workos.changes == []
+
+ async def test_a_removal_goes_through_the_members_service(
+ self, session_factory
+ ) -> None:
+ ada, dee = _name("ada"), _name("dee")
+ tenant_id, organization_id = await _linked(
+ session_factory, {ada: ("owner", "org_admin")}
+ )
+ async with session_factory() as session:
+ session.add(
+ User(id=dee, name=dee, email=f"{dee}@example.invalid", role="user")
+ )
+ await session.flush()
+ session.add(
+ OrganizationMember(
+ organization_id=organization_id, user_id=dee, role="member"
+ )
+ )
+ session.add(OidcIdentity(user_id=dee, iss=ISSUER, sub=f"user_{dee}"))
+ await session.commit()
+ workos = _WorkOS({f"user_{dee}": "om_dee"})
+ 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)
+ removed = await client.delete(f"/organizations/current/members/{dee}")
+
+ assert removed.status_code == 200, removed.text
+ assert [(m, om) for m, om, _ in workos.changes] == [("DELETE", "om_dee")]
+ assert await _role(session_factory, organization_id, dee) is None
+
+
+class TestSigningIn:
+ async def test_signing_in_as_someone_else_keeps_no_token(
+ 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"})
+ workos.signs_in_as = f"user_{bob}"
+
+ async with _client(_with(session_factory, workos), ada, tenant_id) as client:
+ signed_in = await _sign_in_to_workos(client)
+ refused = await client.patch(
+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}
+ )
+
+ assert signed_in.status_code == 403
+ assert refused.status_code == 403
+ assert workos.changes == []
+
+ async def test_a_token_for_another_organization_is_not_kept(
+ self, session_factory
+ ) -> None:
+ ada = _name("ada")
+ tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin")})
+ workos = _WorkOS({})
+ workos.signs_in_as = f"user_{ada}"
+ workos.organization = "org_SOMEWHERE_ELSE"
+
+ async with _client(_with(session_factory, workos), ada, tenant_id) as client:
+ signed_in = await _sign_in_to_workos(client)
+
+ assert signed_in.status_code == 403
+
+ async def test_a_callback_not_started_here_is_refused(
+ self, session_factory
+ ) -> None:
+ ada = _name("ada")
+ tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin")})
+
+ async with _client(
+ _with(session_factory, _WorkOS({})), ada, tenant_id
+ ) as client:
+ response = await client.get(
+ "/auth/workos/callback", params={"code": "c", "state": "forged"}
+ )
+
+ assert response.status_code == 400
+
+ async def test_only_an_org_admin_of_a_linked_organization_starts_one(
+ self, session_factory
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id, _ = await _linked(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ )
+ eve = _name("eve")
+ unlinked = await _workspace(session_factory, {eve: ("owner", "org_admin")})
+ app = _with(session_factory, _WorkOS({}))
+
+ async with _client(app, bob, tenant_id) as client:
+ as_member = await client.get(
+ "/auth/workos/organization", params={"return_to": "/organization"}
+ )
+ async with _client(app, eve, unlinked) as client:
+ not_linked = await client.get(
+ "/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/"},
+ )
+
+ assert as_member.status_code == 403
+ assert not_linked.status_code == 409
+ assert elsewhere.status_code == 400
+
+ async def test_nothing_to_sign_in_to_where_changes_are_not_sent(
+ self, session_factory
+ ) -> None:
+ ada = _name("ada")
+ tenant_id, _ = await _linked(session_factory, {ada: ("owner", "org_admin")})
+ app = _with(session_factory, _WorkOS({}))
+ app.state.workos_sign_in = None
+
+ async with _client(app, ada, tenant_id) as client:
+ response = await client.get(
+ "/auth/workos/organization", params={"return_to": "/organization"}
+ )
+
+ assert response.status_code == 404
diff --git a/core/tests/switch_core/test_config_organization_directory.py b/core/tests/switch_core/test_config_organization_directory.py
index f687d5b12..938998eb7 100644
--- a/core/tests/switch_core/test_config_organization_directory.py
+++ b/core/tests/switch_core/test_config_organization_directory.py
@@ -47,3 +47,36 @@ def test_workos_with_self_service_sign_up_is_refused(mode: str) -> None:
workos_api_key="sk_test_example", # gitleaks:allow
**{**OIDC, "gateway_signup_mode": mode},
)
+
+
+CHANGES = dict(
+ members_service_url="https://members.example.test",
+ workos_client_id="client_EXAMPLE",
+ workos_redirect_url="https://switch.example.test/gateway/auth/workos/callback",
+)
+
+
+def test_changes_sent_to_workos_are_accepted_with_all_three_settings() -> None:
+ config: SwitchConfig = _config(
+ organization_directory="workos",
+ workos_api_key="sk_test_example", # gitleaks:allow
+ **OIDC,
+ **CHANGES,
+ )
+ assert config.members_service_url == "https://members.example.test"
+
+
[email protected]("missing", sorted(CHANGES))
+def test_changes_sent_to_workos_need_all_three_settings(missing: str) -> None:
+ with pytest.raises(ValidationError, match="set together"):
+ _config(
+ organization_directory="workos",
+ workos_api_key="sk_test_example", # gitleaks:allow
+ **OIDC,
+ **{key: value for key, value in CHANGES.items() if key != missing},
+ )
+
+
+def test_changes_sent_to_workos_need_the_workos_directory() -> None:
+ with pytest.raises(ValidationError, match="ORGANIZATION_DIRECTORY=workos"):
+ _config(**CHANGES)
diff --git a/core/tests/switch_core/test_members_service.py b/core/tests/switch_core/test_members_service.py
new file mode 100644
index 000000000..e999738c6
--- /dev/null
+++ b/core/tests/switch_core/test_members_service.py
@@ -0,0 +1,129 @@
+"""The members service client: what it sends, and how it reads the answers."""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+
+from switch_core.members_service import MembersService
+from switch_core.organization_directory import (
+ DirectoryRefusal,
+ DirectorySignInRequired,
+ DirectoryUnavailable,
+)
+
+URL = "https://members.example.test"
+TOKEN = "token-of-the-admin"
+
+
+def _service(handler) -> MembersService:
+ return MembersService(
+ httpx.AsyncClient(transport=httpx.MockTransport(handler)), URL
+ )
+
+
+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] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ return httpx.Response(200, json={"id": "om_1"})
+
+ await _service(handler).set_role(TOKEN, "om_1", "org_admin")
+
+ [request] = seen
+ assert (request.method, request.url.path) == (
+ "PATCH",
+ "/v1/auth/tenants/members/om_1",
+ )
+ assert json.loads(request.content) == {"role": "org_admin"}
+
+ async def test_a_membership_is_removed(self) -> None:
+ seen: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ return httpx.Response(204)
+
+ await _service(handler).remove(TOKEN, "om_1")
+
+ assert [(r.method, r.url.path) for r in seen] == [
+ ("DELETE", "/v1/auth/tenants/members/om_1")
+ ]
+
+
+class TestRefusals:
+ async def test_a_token_it_no_longer_takes_asks_for_a_sign_in(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, json={"error": "unauthorized"})
+
+ with pytest.raises(DirectorySignInRequired):
+ await _service(handler).remove(TOKEN, "om_1")
+
+ async def test_its_own_rules_refuse_in_its_words(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 409, json={"error": "cannot remove the last org_admin"}
+ )
+
+ with pytest.raises(DirectoryRefusal, match="cannot remove the last org_admin"):
+ await _service(handler).remove(TOKEN, "om_1")
+
+ @pytest.mark.parametrize("status", [500, 502, 503])
+ async def test_a_failure_is_unavailable(self, status: int) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(status, text="upstream failed")
+
+ with pytest.raises(DirectoryUnavailable):
+ await _service(handler).set_role(TOKEN, "om_1", "viewer")
+
+ async def test_an_unreachable_service_is_unavailable(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("refused", request=request)
+
+ with pytest.raises(DirectoryUnavailable):
+ await _service(handler).remove(TOKEN, "om_1")
diff --git a/core/tests/switch_core/test_workos_directory.py b/core/tests/switch_core/test_workos_directory.py
index fa377bd6f..ef0fd1fc0 100644
--- a/core/tests/switch_core/test_workos_directory.py
+++ b/core/tests/switch_core/test_workos_directory.py
@@ -9,11 +9,14 @@ from types import SimpleNamespace
import httpx
import pytest
+from switch_core.members_service import MembersService
from switch_core.organization_directory import (
DirectoryMembership,
DirectoryOrganization,
DirectoryRefusal,
+ DirectorySignInRequired,
DirectoryUnavailable,
+ MemberChange,
)
from switch_core.workos_directory import (
EventCursorRejected,
@@ -81,9 +84,17 @@ class _WorkOS:
return httpx.Response(404)
+ISSUER = "https://sign-in.example.test"
+NO_CHANGE = MemberChange(access_token=None, subject=None)
+
+
def _directory(handler) -> WorkOSDirectory:
return WorkOSDirectory(
- httpx.AsyncClient(transport=httpx.MockTransport(handler)), KEY, API
+ httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ KEY,
+ API,
+ ISSUER,
+ None,
)
@@ -189,9 +200,9 @@ class TestWhatAnOperatorLinks:
class TestChangesFromSwitch:
- """Changes made from Switch to a linked organization go through the
- service that owns the customer record; until that is wired in, those that
- grant are refused, and an organization nobody linked stays Switch's own."""
+ """Without a members service, changes from Switch to a linked
+ organization that grant are refused, and an organization nobody linked
+ stays Switch's own."""
async def test_a_linked_organization_refuses_those_that_grant(self) -> None:
directory = _directory(lambda request: httpx.Response(500))
@@ -199,7 +210,7 @@ class TestChangesFromSwitch:
for change in (
directory.join(linked, "u", "member"), # type: ignore[arg-type]
- directory.set_role(linked, "u", "org_admin"), # type: ignore[arg-type]
+ directory.set_role(linked, "u", "org_admin", NO_CHANGE), # type: ignore[arg-type]
):
with pytest.raises(DirectoryRefusal):
await change
@@ -210,8 +221,8 @@ class TestChangesFromSwitch:
directory = _directory(lambda request: httpx.Response(500))
linked = SimpleNamespace(workos_organization_id="org_a")
- await directory.set_role(linked, "u", "member") # type: ignore[arg-type]
- await directory.remove(linked, "u") # type: ignore[arg-type]
+ await directory.set_role(linked, "u", "member", NO_CHANGE) # type: ignore[arg-type]
+ await directory.remove(linked, "u", NO_CHANGE) # type: ignore[arg-type]
def test_it_keeps_the_members_of_a_linked_organization_only(self) -> None:
directory = _directory(lambda request: httpx.Response(500))
@@ -228,8 +239,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") # type: ignore[arg-type]
- await directory.remove(local, "u") # 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]
async def test_a_new_organization_is_switchs_own_until_linked(self) -> None:
directory = _directory(lambda request: httpx.Response(500))
@@ -242,6 +253,127 @@ 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."""
+ return WorkOSDirectory(
+ httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda request: httpx.Response(500))
+ ),
+ KEY,
+ API,
+ ISSUER,
+ MembersService(
+ httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ "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")
+WITH_TOKEN = MemberChange(access_token="admin-token", subject="user_bob")
+
+
+class TestChangesThroughTheMembersService:
+ def test_a_change_to_a_linked_organization_needs_the_admins_token(self) -> None:
+ directory = _with_members(lambda request: httpx.Response(500))
+
+ 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,
+ )
+ assert directory.sends_changes_for(LINKED) # type: ignore[arg-type]
+
+ def test_without_the_service_nothing_needs_a_token(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:
+ 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]
+
+ assert changes == [
+ ("PATCH", "om_bob", {"role": "org_admin"}),
+ ("PATCH", "om_bob", {"role": "viewer"}),
+ ]
+
+ 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]
+
+ 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]
+
+ assert changes == []
+
+ async def test_someone_workos_does_not_list_cannot_be_made_org_admin(
+ self,
+ ) -> None:
+ directory = _with_members(_members_service({}, []))
+
+ with pytest.raises(DirectoryRefusal, match="add them there first"):
+ await directory.set_role(LINKED, "bob", "org_admin", WITH_TOKEN) # type: ignore[arg-type]
+
+ async def test_someone_with_no_workos_identity_is_refused(self) -> None:
+ directory = _with_members(_members_service({}, []))
+
+ with pytest.raises(DirectoryRefusal, match="no WorkOS identity"):
+ await directory.remove(
+ LINKED, # type: ignore[arg-type]
+ "bob",
+ MemberChange(access_token="admin-token", subject=None),
+ )
+
+ async def test_adding_someone_is_still_refused(self) -> None:
+ directory = _with_members(_members_service({}, []))
+
+ with pytest.raises(DirectoryRefusal):
+ await directory.join(LINKED, "bob", "member") # type: ignore[arg-type]
+
+
class TestWhatTheMirrorReads:
async def test_events_are_asked_for_by_type_from_the_cursor_oldest_first(
self,
diff --git a/core/tests/switch_core/test_workos_sign_in.py b/core/tests/switch_core/test_workos_sign_in.py
new file mode 100644
index 000000000..3e7dc8d8c
--- /dev/null
+++ b/core/tests/switch_core/test_workos_sign_in.py
@@ -0,0 +1,117 @@
+"""Exchanging an AuthKit sign-in for the admin's token for an organization."""
+
+from __future__ import annotations
+
+import json
+import time
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+import jwt
+import pytest
+
+from switch_core.organization_directory import DirectoryUnavailable
+from switch_core.workos_sign_in import SignInRefused, WorkOSOrganizationSignIn
+
+API = "https://api.workos.example.test"
+KEY = "workos-api-key-placeholder"
+CLIENT_ID = "client_EXAMPLE"
+REDIRECT = "https://switch.example.test/gateway/auth/workos/callback"
+
+
+def access_token(expires_at: int) -> str:
+ return jwt.encode(
+ {"exp": expires_at, "sub": "user_A"},
+ "test-signing-key-long-enough-for-hs256",
+ algorithm="HS256",
+ )
+
+
+def _sign_in(handler) -> WorkOSOrganizationSignIn:
+ return WorkOSOrganizationSignIn(
+ httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ KEY,
+ API,
+ CLIENT_ID,
+ REDIRECT,
+ )
+
+
+def test_the_browser_is_sent_to_sign_in_for_the_organization() -> None:
+ url = _sign_in(lambda request: httpx.Response(500)).authorize_url(
+ "org_A", "the-state", "the-challenge"
+ )
+
+ parts = urlsplit(url)
+ assert f"{parts.scheme}://{parts.netloc}{parts.path}" == (
+ f"{API}/user_management/authorize"
+ )
+ assert {key: value[0] for key, value in parse_qs(parts.query).items()} == {
+ "client_id": CLIENT_ID,
+ "redirect_uri": REDIRECT,
+ "response_type": "code",
+ "provider": "authkit",
+ "organization_id": "org_A",
+ "state": "the-state",
+ "code_challenge": "the-challenge",
+ "code_challenge_method": "S256",
+ }
+
+
+async def test_a_code_is_exchanged_for_the_token_and_its_expiry() -> None:
+ expires_at = int(time.time()) + 300
+ seen: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ return httpx.Response(
+ 200,
+ json={
+ "user": {"id": "user_A"},
+ "organization_id": "org_A",
+ "access_token": access_token(expires_at),
+ "refresh_token": "dropped",
+ },
+ )
+
+ token = await _sign_in(handler).authenticate("the-code", "the-verifier")
+
+ assert (token.subject, token.workos_organization_id, token.expires_at) == (
+ "user_A",
+ "org_A",
+ expires_at,
+ )
+ [request] = seen
+ assert request.url.path == "/user_management/authenticate"
+ assert json.loads(request.content) == {
+ "client_id": CLIENT_ID,
+ "client_secret": KEY,
+ "grant_type": "authorization_code",
+ "code": "the-code",
+ "code_verifier": "the-verifier",
+ }
+
+
+async def test_a_refused_code_is_refused() -> None:
+ with pytest.raises(SignInRefused):
+ await _sign_in(lambda request: httpx.Response(400)).authenticate("c", "v")
+
+
+ "answer",
+ [
+ httpx.Response(500),
+ httpx.Response(200, json={"user": {"id": "user_A"}}),
+ httpx.Response(
+ 200,
+ json={
+ "user": {"id": "user_A"},
+ "organization_id": "org_A",
+ "access_token": "not-a-token",
+ },
+ ),
+ ],
+)
+async def test_anything_else_is_unavailable(answer: httpx.Response) -> None:
+ with pytest.raises(DirectoryUnavailable):
+ await _sign_in(lambda request: answer).authenticate("c", "v")
diff --git a/docs/old/workos-directory.md b/docs/old/workos-directory.md
index 45160d044..f7e46f3e1 100644
--- a/docs/old/workos-directory.md
+++ b/docs/old/workos-directory.md
@@ -110,13 +110,49 @@ operator, who may then make one), a workspace with no owner, agents whose
owner can no longer act for them, and a linked WorkOS organization that was
deleted. The audit log keeps the history.
+## Changes made from Switch
+
+When several products share one WorkOS environment, one service usually owns
+each customer's account there, and every product changes its members through
+it, so its rules (nobody grants above their own role, the last `org_admin`
+stays) apply once for all of them. Switch can send its changes to such a
+service. 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
+ `DELETE /v1/auth/tenants/members/{id}`, each acting on the organization
+ the token was issued for, and reads a refusal's `{"error": ...}`.
+- `WORKOS_CLIENT_ID`: the AuthKit application Switch signs admins in to for
+ that token.
+- `WORKOS_REDIRECT_URL`: its callback, `.../gateway/auth/workos/callback`,
+ registered on that application.
+
+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
+through the AuthKit application (usually without a prompt, while their
+AuthKit session lasts) and makes the change on their return. Switch keeps the
+access token that sign-in gives, encrypted in the browser's short-lived
+sign-in cookie, only for as long as the token lasts, and keeps no refresh
+token. A sign-in as another WorkOS user than the one the Switch account signs
+in 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.
+
+Adding someone new to a linked organization from Switch is still refused.
+
## In the dashboard
On a linked organization's Organization page, the Members section says that
its members and Org Admins come from the organization's account settings
-(WorkOS), and does not offer making a member Org Admin. Removing someone or
-making an Org Admin a Member is still offered: it ends their access at once,
-and the page says it lasts only until WorkOS is read again (their next
+(WorkOS). With changes sent to WorkOS (above), it offers every change but
+adding someone, and says the admin may be asked to confirm their sign-in
+there. Without, it does not offer making a member Org Admin; removing someone
+or making an Org Admin a Member is still offered: it ends their access at
+once, and the page says it lasts only until WorkOS is read again (their next
sign-in, or the daily check) unless the same change is made there. The
platform operator, on a linked organization with no admin, is told the admin
has to be made in WorkOS. A workspace's Invitations section says that only
@@ -125,9 +161,9 @@ anyone new to it.
## Not done yet
-- **Granting from Switch is refused** for a linked organization: adding a
- member (from the dashboard or by invitation) or making one Org Admin. Make
- those changes in WorkOS. Removing a member or taking Org Admin away from
- Switch is allowed and changes only Switch; whatever WorkOS still grants
- comes back at the next sign-in or check.
+- **Adding someone to a linked organization from Switch is refused**, from
+ the dashboard or by invitation: add them in WorkOS. Without changes sent to
+ WorkOS (above), making someone Org Admin is refused too, and a removal or
+ demotion changes only Switch; whatever WorkOS still grants comes back at
+ the next sign-in or check.
- A new organization created on the server is Switch's own until it is linked.
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 748626342..3639c276c 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1267,6 +1267,9 @@ export interface CurrentOrganization {
// Its members, and who is its Org Admin, come from a directory kept outside
// Switch: people are added and made Org Admin there, not here.
members_from_directory: boolean;
+ // Changes made here to those members are made in that directory too, so
+ // they last; the admin may first be sent to sign in there.
+ directory_takes_changes: boolean;
}
export interface OperatorWorkspace {
@@ -1476,6 +1479,19 @@ export function oidcLoginUrl(): string {
return `${BASE}/auth/oidc/login`;
}
+/** 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`. */
+export function organizationSignInUrl(returnTo: string): string {
+ return `${BASE}/auth/workos/organization?return_to=${encodeURIComponent(returnTo)}`;
+}
+
+/** The server's answer when a change to a linked organization's members
+ * waits on the admin signing in to its WorkOS account. */
+export function needsOrganizationSignIn(err: unknown): boolean {
+ if (!(err instanceof ApiError) || !err.detail || typeof err.detail !== "object") return false;
+ return (err.detail as Record<string, unknown>).error === "directory_sign_in_required";
+}
+
export async function changePassword(
currentPassword: string,
newPassword: string,
diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsx
index 22b1b8f8b..e2fe688e8 100644
--- a/gateway/src/pages/organization/OrganizationMembersSection.tsx
+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx
@@ -10,13 +10,15 @@ import {
Typography,
} from "@mui/material";
import type { GridColDef } from "@mui/x-data-grid";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import DataTable from "../../components/DataTable";
import { useAuth } from "../../data/AuthContext";
import {
type OrganizationMember,
type OrganizationRole,
fetchOrganizationMembers,
+ needsOrganizationSignIn,
+ organizationSignInUrl,
removeOrganizationMember,
updateOrganizationRole,
} from "../../data/api";
@@ -30,6 +32,28 @@ const ROLE_LABELS: Record<OrganizationRole, string> = {
member: "Member",
};
+/** A change kept across the sign-in to the organization's WorkOS account it
+ * waited on, made again once, on coming back. */
+type MemberChange = { userId: string; role: OrganizationRole } | { userId: string; remove: true };
+const PENDING_CHANGE_KEY = "switch.pendingOrganizationMemberChange";
+
+function make(change: MemberChange): Promise<{ warning: string | null }> {
+ return "remove" in change
+ ? removeOrganizationMember(change.userId)
+ : updateOrganizationRole(change.userId, change.role);
+}
+
+function takePendingChange(): 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;
+ } catch {
+ return null;
+ }
+}
+
/** Everyone in the organization, across its workspaces, and their role in it.
* The server refuses demoting or removing the last organization admin, and
* removing someone still in one of its workspaces, naming them; its message
@@ -40,6 +64,7 @@ export default function OrganizationMembersSection({
selfId,
asOperator,
fromDirectory,
+ directoryTakesChanges,
onChanged,
}: {
selfId: string;
@@ -50,6 +75,10 @@ export default function OrganizationMembersSection({
// made Org Admin here, and what is taken away here comes back while those
// settings still grant it.
fromDirectory: boolean;
+ // Changes made here are made in those account settings too, so they last
+ // and Org Admin can be given here; the admin may first be sent to sign in
+ // there, and the change is made on coming back.
+ directoryTakesChanges: boolean;
// Called after each change that went through.
onChanged: () => void;
}) {
@@ -61,26 +90,42 @@ export default function OrganizationMembersSection({
const { refresh } = useAuth();
const act = useCallback(
- async (userId: string, action: () => Promise<{ warning: string | null }>) => {
- setBusy(userId);
+ async (change: MemberChange, replayed = false) => {
+ setBusy(change.userId);
setActionError(null);
setActionWarning(null);
try {
- const { warning } = await action();
+ const { warning } = await make(change);
setActionWarning(warning);
onChanged();
await refetch();
// Your own role decides what this page offers you.
- if (userId === selfId) await refresh();
+ if (change.userId === selfId) await refresh();
} catch (err) {
+ // 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.
+ if (needsOrganizationSignIn(err) && !replayed && !asOperator) {
+ window.sessionStorage.setItem(PENDING_CHANGE_KEY, JSON.stringify(change));
+ window.location.href = organizationSignInUrl(window.location.pathname);
+ return;
+ }
setActionError(err instanceof Error ? err.message : "The change failed");
} finally {
setBusy(null);
}
},
- [onChanged, refetch, refresh, selfId],
+ [asOperator, onChanged, refetch, refresh, selfId],
);
+ const replayed = useRef(false);
+ useEffect(() => {
+ if (replayed.current) return;
+ replayed.current = true;
+ const pending = takePendingChange();
+ if (pending !== null) void act(pending, true);
+ }, [act]);
+
const columns = useMemo<GridColDef<MemberRow>[]>(
() => [
{
@@ -101,9 +146,7 @@ export default function OrganizationMembersSection({
value={row.role}
disabled={busy !== null}
onChange={(e) =>
- act(row.user_id, () =>
- updateOrganizationRole(row.user_id, e.target.value as OrganizationRole),
- )
+ act({ userId: row.user_id, role: e.target.value as OrganizationRole })
}
aria-label={`Organization role for ${row.email}`}
sx={{ fontSize: "0.875rem" }}
@@ -112,7 +155,12 @@ export default function OrganizationMembersSection({
<MenuItem
key={role}
value={role}
- disabled={fromDirectory && role === "org_admin" && row.role !== "org_admin"}
+ disabled={
+ fromDirectory &&
+ !directoryTakesChanges &&
+ role === "org_admin" &&
+ row.role !== "org_admin"
+ }
>
{ROLE_LABELS[role]}
</MenuItem>
@@ -138,7 +186,7 @@ export default function OrganizationMembersSection({
<IconButton
size="small"
disabled={busy !== null}
- onClick={() => act(row.user_id, () => removeOrganizationMember(row.user_id))}
+ onClick={() => act({ userId: row.user_id, remove: true })}
aria-label={`Remove ${row.email} from the organization`}
>
<DeleteOutline fontSize="small" />
@@ -148,7 +196,7 @@ export default function OrganizationMembersSection({
),
},
],
- [act, busy, fromDirectory, selfId],
+ [act, busy, directoryTakesChanges, fromDirectory, selfId],
);
// The operator restores an admin and nothing more: removing a member is
// refused to them, so there is nothing to offer.
@@ -178,7 +226,15 @@ export default function OrganizationMembersSection({
"members an admin; the change is recorded in its audit log, marked as yours."}
</Alert>
)}
- {fromDirectory && !asOperator && (
+ {fromDirectory && directoryTakesChanges && !asOperator && (
+ <Alert severity="info">
+ This organization's members, and who is its admin, come from your organization's
+ account settings. Changes you make here are made there too; you may be asked to
+ confirm your sign-in there first. New people can't be added from here yet: add them
+ there.
+ </Alert>
+ )}
+ {fromDirectory && !directoryTakesChanges && !asOperator && (
<Alert severity="info">
This organization's members, and who is its admin, come from your organization's
account settings. Add people and make someone an organization admin there; the change
diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsx
index 0d08591f9..91d8d1072 100644
--- a/gateway/src/pages/organization/OrganizationPage.test.tsx
+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx
@@ -1,5 +1,5 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Session } from "../../data/api";
import { useAuth } from "../../data/AuthContext";
import { app } from "../connector-apps/testFixtures";
@@ -395,6 +395,123 @@ describe("OrganizationPage", () => {
expect(screen.getByLabelText("Remove [email protected] from the organization")).toBeTruthy();
});
+ describe("where changes go to the organization's account settings", () => {
+ const originalLocation = window.location;
+ const bob = { user_id: "u2", name: "Bob", email: "[email protected]", role: "member", created_at: "2026-01-01" };
+ const routes = (patchAnswer: unknown) => ({
+ "GET /organizations/current": {
+ id: "o1",
+ slug: "acme",
+ name: "Acme Inc",
+ role: "org_admin",
+ members_from_directory: true,
+ directory_takes_changes: true,
+ },
+ "GET /organizations/current/workspaces": [workspace("t1", "Acme")],
+ "GET /organizations/current/members": [bob],
+ "GET /organizations/current/audit-events": [],
+ "GET /organizations/current/issues": [],
+ "PATCH /organizations/current/members/u2": patchAnswer,
+ });
+ const signInFirst = new Refusal(403, "");
+ // `answer` sends a refusal's detail as a string; this one is structured.
+ const structured = (detail: unknown) => {
+ const fetchMock = vi.mocked(fetch);
+ const original = fetchMock.getMockImplementation()!;
+ fetchMock.mockImplementation(async (input, init) => {
+ if (init?.method === "PATCH") {
+ return new Response(JSON.stringify({ detail }), { status: 403 });
+ }
+ return original(input, init);
+ });
+ };
+
+ beforeEach(() => {
+ window.sessionStorage.clear();
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: { ...originalLocation, href: "", pathname: "/organization" },
+ });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+ });
+
+ it("offers Org Admin and says changes are made there too", async () => {
+ signedInAs(session("org_admin", true));
+ answer(routes({ ...bob, role: "org_admin", warning: null }));
+
+ render(<OrganizationPage />);
+
+ expect(await screen.findByText(/Changes you make here are made there too/)).toBeTruthy();
+ fireEvent.mouseDown(within(await screen.findByTestId("row-u2")).getByRole("combobox"));
+ const promote = await screen.findByRole("option", { name: "Org Admin" });
+ expect(promote.getAttribute("aria-disabled")).toBeNull();
+ });
+
+ it("sends the admin to sign in there, keeping the change", async () => {
+ 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",
+ ),
+ );
+ expect(JSON.parse(window.sessionStorage.getItem("switch.pendingOrganizationMemberChange")!)).toEqual({
+ userId: "u2",
+ role: "org_admin",
+ });
+ });
+
+ it("makes the kept change on coming back", async () => {
+ window.sessionStorage.setItem(
+ "switch.pendingOrganizationMemberChange",
+ JSON.stringify({ userId: "u2", role: "org_admin" }),
+ );
+ signedInAs(session("org_admin", true));
+ const fetchMock = answer(routes({ ...bob, role: "org_admin", warning: null }));
+
+ render(<OrganizationPage />);
+
+ await waitFor(() =>
+ expect(
+ fetchMock.mock.calls.some(
+ ([input, init]) =>
+ init?.method === "PATCH" && String(input).endsWith("/organizations/current/members/u2"),
+ ),
+ ).toBe(true),
+ );
+ expect(window.sessionStorage.getItem("switch.pendingOrganizationMemberChange")).toBeNull();
+ });
+
+ 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" }),
+ );
+ signedInAs(session("org_admin", true));
+ answer(routes(signInFirst));
+ structured({ error: "directory_sign_in_required", message: "Confirm your sign-in." });
+
+ render(<OrganizationPage />);
+
+ expect(await screen.findByText("Confirm your sign-in.")).toBeTruthy();
+ expect(window.location.href).toBe("");
+ });
+ });
+
it("says nothing of account settings for an organization kept here", async () => {
signedInAs(session("org_admin", true));
answer({
diff --git a/gateway/src/pages/organization/OrganizationPage.tsx b/gateway/src/pages/organization/OrganizationPage.tsx
index 61736bb67..2835f7c89 100644
--- a/gateway/src/pages/organization/OrganizationPage.tsx
+++ b/gateway/src/pages/organization/OrganizationPage.tsx
@@ -52,6 +52,7 @@ export default function OrganizationPage() {
selfId={session.user.id}
asOperator={!isAdmin}
fromDirectory={organization?.members_from_directory === true}
+ directoryTakesChanges={organization?.directory_takes_changes === true}
onChanged={onMembersChanged}
/>
)}