Skip to content

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

fix(organizations): address review of the combined phase 3 (CHOO-3906)

Petr Bauchaa67a74c4555
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 94a944053..a6c45cbda 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -2647,7 +2647,8 @@ class DirectoryEventCursor(Base):
`after` is the last event applied, null until the first; until then the
events are read from `started_at`, when the mirror first ran. Applying
an event re-reads the membership it names, so reading one twice changes
- nothing, and the row needs no fence against a holder taken over.
+ nothing. The row is written only while the mirror's ownership fence holds
+ (`WorkOSMirror._write_cursor`), so a holder taken over can't move it.
Not tenant-scoped: one directory's events reach every organization.
"""
diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.py
index a46a39478..cdc5d07e1 100644
--- a/core/switch_core/db/tenant_lookup.py
+++ b/core/switch_core/db/tenant_lookup.py
@@ -1,4 +1,4 @@
-"""The whole exemption from row-level security, written out as sixteen functions.
+"""The whole exemption from row-level security, written out as eighteen functions.
Row-level security is enforced by `require_tenant_id()` (`db/rls_ddl.py`),
which raises when no tenant is bound. That is the property everything else
@@ -171,7 +171,13 @@ two. It discloses which workspaces a person belongs to or administers
through an organization; the gateway asks it only about the signed-in
caller.
-**`directory_organizations_of_user` is the fifteenth**, and the one that
+**`all_organization_ids` is the fifteenth**, and `all_tenant_ids` one level
+up. A few tables belong to an organization rather than a workspace, and a
+boot pass over them (rewriting an organization's connector-app secrets under
+the current key) has to visit every organization, including one with no
+workspace to reach it through. It discloses which organizations exist.
+
+**`directory_organizations_of_user` is the sixteenth**, and the one that
answers with organizations rather than workspaces. Under the WorkOS directory
(`workos_directory.py`) a sign-in names the WorkOS organizations the person
belongs to; which Switch organizations follow those, and which ones the
@@ -183,12 +189,20 @@ organization, and which linked organizations a person belongs to; the
gateway asks it only about the signed-in person and the organizations WorkOS
says they belong to.
-**`directory_organizations` is the sixteenth**: every organization that
+**`directory_organizations` is the seventeenth**: every organization that
follows one in the WorkOS directory. The directory mirror acts for no tenant
and no person: it reads the directory's changes and has to know which
organizations they may reach before it binds any of them. It discloses which
organizations are linked; the mirror is its only caller.
+**`tenants_of_organization` is the eighteenth**: the workspaces of one
+organization. The platform operator may bind any workspace and holds no
+membership to narrow by, so listing an organization's workspaces for them, or
+reading what needs attention in each, would otherwise mean binding every
+tenant on the server in turn to find the few that belong to it. It discloses
+which workspaces an organization has, what `all_tenant_ids` already
+discloses, narrowed; the gateway asks it only for the platform operator.
+
Why not the obvious alternatives is argued in
`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the short
version is that returning rows instead of tenant ids would put a second copy
@@ -197,12 +211,6 @@ to "any row of every table they read", and that a second engine connected as the
would make the exemption ambient again — reachable from anything holding the
factory, and no longer a list anybody can read.
-**`all_organization_ids` is the fifteenth**, and `all_tenant_ids` one level
-up. A few tables belong to an organization rather than a workspace, and a
-boot pass over them (rewriting an organization's connector-app secrets under
-the current key) has to visit every organization, including one with no
-workspace to reach it through. It discloses which organizations exist.
-
**A fan-out over `all_tenant_ids()` filters what it reads back.** Every such
loop keeps only the rows whose own `tenant_id` matches the tenant it bound.
That looks redundant — the policy has already narrowed the read — and it is
@@ -288,7 +296,7 @@ class TenantLookup:
return f"{self.name}({', '.join('text' for _ in self.arguments)})"
-# The sixteen of them. Ordered as the three shapes above: enumeration, then
+# The eighteen of them. Ordered as the three shapes above: enumeration, then
# credential resolution, then deriving a tenant from an identifier in hand.
TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
TenantLookup(
@@ -496,6 +504,18 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
"the directory mirror to read each one's link with it bound."
),
),
+ TenantLookup(
+ name="tenants_of_organization",
+ arguments=("organization_id",),
+ query=(
+ "SELECT id FROM tenants WHERE organization_id = p_organization_id "
+ "ORDER BY id"
+ ),
+ purpose=(
+ "The workspaces of one organization, for the platform operator, "
+ "who may bind any workspace and holds no membership to narrow by."
+ ),
+ ),
TenantLookup(
name="tenant_of_messaging_install",
arguments=("platform", "external_workspace_id"),
@@ -569,12 +589,12 @@ def attach_tenant_lookups(metadata: MetaData) -> None:
# ── Calling them ──────────────────────────────────────────────────────────────
# One `text()` per lookup, written out rather than assembled from `lookup.name`
-# at call time: the sixteen names are fixed and known here, so there is nothing
+# at call time: the eighteen names are fixed and known here, so there is nothing
# for a call site to build. Each bind is named after the lookup's own argument,
# which is what lets `_call` zip them positionally against the dataclass and
# fail loudly on a mismatch rather than binding the workspace to the platform.
# The assertion below is what keeps this dict from quietly falling behind
-# `TENANT_LOOKUPS`: a sixteenth lookup with no entry here fails at import, not
+# `TENANT_LOOKUPS`: a nineteenth lookup with no entry here fails at import, not
# with a `KeyError` on whatever request reaches it first.
_LOOKUP_STATEMENTS: dict[str, TextClause] = {
"all_tenant_ids": text("SELECT tenant_id FROM all_tenant_ids() AS tenant_id"),
@@ -629,6 +649,9 @@ _LOOKUP_STATEMENTS: dict[str, TextClause] = {
"SELECT tenant_id FROM directory_organizations_of_user("
":user_id, :workos_organization_ids) AS tenant_id"
),
+ "tenants_of_organization": text(
+ "SELECT tenant_id FROM tenants_of_organization(:organization_id) AS tenant_id"
+ ),
}
assert _LOOKUP_STATEMENTS.keys() == TENANT_LOOKUPS_BY_NAME.keys(), (
@@ -805,3 +828,13 @@ async def directory_organizations(
return await _call(
session_factory, TENANT_LOOKUPS_BY_NAME["directory_organizations"]
)
+
+
+async def tenants_of_organization(
+ session_factory: async_sessionmaker[AsyncSession], organization_id: str
+) -> list[str]:
+ return await _call(
+ session_factory,
+ TENANT_LOOKUPS_BY_NAME["tenants_of_organization"],
+ organization_id,
+ )
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 27d8b1703..6dd91859b 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -33,6 +33,7 @@ from switch_core.db.tenant_lookup import (
tenant_of_invitation,
tenants_bindable_by_user,
tenants_inviting_email,
+ tenants_of_organization,
tenants_of_user,
tenants_open_to_domain,
)
@@ -389,16 +390,20 @@ async def _in_organization(
return found
-async def tenants_bindable_or_any(
+async def organization_candidates(
session_factory: async_sessionmaker[AsyncSession],
user_id: str,
+ organization_id: str,
*,
is_operator: bool,
) -> list[str]:
- """`tenants_bindable_by`, or every tenant for the platform operator, who
- may bind any."""
+ """Where to look for `organization_id`'s workspaces: its own, for the
+ platform operator, who may bind any workspace and holds no membership to
+ narrow by (`tenants_of_organization`); those `user_id` may bind,
+ otherwise. Either way a caller keeps only those still in the
+ organization when it reads them."""
if is_operator:
- return await all_tenant_ids(session_factory)
+ return await tenants_of_organization(session_factory, organization_id)
return await tenants_bindable_by(session_factory, user_id)
@@ -524,8 +529,8 @@ async def organization_workspaces_bindable_by(
`platform_access` gives them. Each candidate is read on its own short
session, and only those in the organization are described further.
"""
- candidates = await tenants_bindable_or_any(
- session_factory, user_id, is_operator=is_operator
+ candidates = await organization_candidates(
+ session_factory, user_id, organization_id, is_operator=is_operator
)
found: list[TenantMembershipResponse] = []
for tenant in await _in_organization(session_factory, candidates, organization_id):
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 8b2c1fb1e..1b7c45244 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -362,6 +362,29 @@ async def oidc_callback(
iss = claims.get("iss") or config.gateway_oidc_issuer_url
if not iss:
raise HTTPException(status_code=401, detail="OIDC token missing issuer")
+ # Under the WorkOS directory every other reader of these identities (the
+ # mirror, the organization sign-in, `switch-link-workos`) looks them up
+ # under the issuer as configured. An identity stored under another
+ # spelling of it would match none of them, so a mismatch is a
+ # configuration mistake to name, not a sign-in to let through.
+ if (
+ config.organization_directory == "workos"
+ and iss != config.gateway_oidc_issuer_url
+ ):
+ logger.error(
+ "OIDC sign-in refused: the token's issuer %r is not "
+ "GATEWAY_OIDC_ISSUER_URL %r exactly, which the WorkOS directory "
+ "looks identities up under; set it to the token's issuer",
+ iss,
+ config.gateway_oidc_issuer_url,
+ )
+ raise HTTPException(
+ status_code=503,
+ detail=(
+ "Sign-in is misconfigured: the identity provider's issuer "
+ "does not match this server's configuration"
+ ),
+ )
# A first sign-in provisions the account just in time. Where it lands is
# `gateway_signup_mode`'s decision. Under "default_tenant" it joins tenant
# zero, named here rather than left to `TenantScoped`'s fallback, which
diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.py
index 937987c0b..5597795dd 100644
--- a/core/switch_core/gateway/organizations.py
+++ b/core/switch_core/gateway/organizations.py
@@ -56,9 +56,9 @@ from switch_core.gateway.auth import (
get_authenticated_caller,
get_authenticated_user_id,
get_current_user,
+ organization_candidates,
organization_workspaces_bindable_by,
organizations_bindable_by,
- tenants_bindable_or_any,
workspaces_in_organization,
workspaces_reached_through_organization,
)
@@ -438,8 +438,11 @@ async def list_organization_issues(
user_store,
organization_id=access.organization_id,
admins=admins,
- candidates=await tenants_bindable_or_any(
- session_factory, user.id, is_operator=access.platform_access
+ candidates=await organization_candidates(
+ session_factory,
+ user.id,
+ access.organization_id,
+ is_operator=access.platform_access,
),
)
return [
@@ -554,6 +557,8 @@ async def _member_change(
subject = await directory_subject(
session, user_store, organization_directory, user_id
)
+ # Let go of the request's connection while the directory is asked.
+ await session.commit()
try:
return await organization_directory.prepare_change(
organization, subject, role, access_token
@@ -658,6 +663,14 @@ async def update_organization_member_role(
demoting = (
member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE
)
+ last_admin = HTTPException(
+ status_code=409, detail="Cannot demote the last organization admin"
+ )
+ if (
+ demoting
+ and await organization_store.count_admins(session, organization_id) <= 1
+ ):
+ raise last_admin
organization = await _organization(session, organization_id)
member_change = (
await _member_change(
@@ -673,14 +686,6 @@ async def update_organization_member_role(
if member.role != req.role
else NO_DIRECTORY_CHANGE
)
- last_admin = HTTPException(
- status_code=409, detail="Cannot demote the last organization admin"
- )
- if (
- demoting
- and await organization_store.count_admins(session, organization_id) <= 1
- ):
- raise last_admin
warning = None
if demoting:
@@ -817,7 +822,6 @@ async def remove_organization_member(
user_id,
None,
)
- await session.commit()
warning = None
if was_admin:
try:
diff --git a/core/switch_core/migrations/versions/a7c3e9f15b20_directory_mirror.py b/core/switch_core/migrations/versions/a7c3e9f15b20_directory_mirror.py
index 3d8be13b1..74f0c878f 100644
--- a/core/switch_core/migrations/versions/a7c3e9f15b20_directory_mirror.py
+++ b/core/switch_core/migrations/versions/a7c3e9f15b20_directory_mirror.py
@@ -4,7 +4,7 @@
events, one row per directory. A global table: no tenant column and no
row-level security policy (`db/rls_ddl.py`'s `GLOBAL_TABLES`).
-`directory_organizations` is the sixteenth lookup in the exemption from
+`directory_organizations` is the seventeenth lookup in the exemption from
row-level security: every organization that follows one in the directory.
See `db/tenant_lookup.py` for what it discloses. Its DDL is a verbatim copy
of `switch_core/db/tenant_lookup.py` as it stood when this migration was
diff --git a/core/switch_core/migrations/versions/c3d9a1f7b246_tenants_of_organization.py b/core/switch_core/migrations/versions/c3d9a1f7b246_tenants_of_organization.py
new file mode 100644
index 000000000..7f7d77d5e
--- /dev/null
+++ b/core/switch_core/migrations/versions/c3d9a1f7b246_tenants_of_organization.py
@@ -0,0 +1,45 @@
+"""the lookup that lists one organization's workspaces
+
+The platform operator may bind any workspace and holds no membership to
+narrow by, so listing an organization's workspaces for them meant binding
+every tenant in turn. This adds the eighteenth lookup to the exemption from
+row-level security, `tenants_of_organization`. See `db/tenant_lookup.py` for
+what it discloses.
+
+The DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py` as it
+stood when this migration was written, copied rather than imported so a later
+edit cannot change what this revision means.
+
+Revision ID: c3d9a1f7b246
+Revises: a7c3e9f15b20
+Create Date: 2026-11-05 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+from alembic import op
+
+revision: str = "c3d9a1f7b246"
+down_revision: str | Sequence[str] | None = "a7c3e9f15b20"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+expand_only: bool = True
+
+SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
+
+CREATE_TENANTS_OF_ORGANIZATION = f"""CREATE OR REPLACE FUNCTION tenants_of_organization(p_organization_id text)
+ RETURNS SETOF text
+ LANGUAGE sql STABLE SECURITY DEFINER
+ SET search_path = {SECURE_SEARCH_PATH}
+AS $$SELECT id FROM tenants WHERE organization_id = p_organization_id ORDER BY id$$"""
+
+DROP_TENANTS_OF_ORGANIZATION = "DROP FUNCTION IF EXISTS tenants_of_organization(text)"
+
+
+def upgrade() -> None:
+ op.execute(CREATE_TENANTS_OF_ORGANIZATION)
+
+
+def downgrade() -> None:
+ op.execute(DROP_TENANTS_OF_ORGANIZATION)
diff --git a/core/switch_core/migrations/versions/f2b8d6c1a4e9_directory_organizations_of_user.py b/core/switch_core/migrations/versions/f2b8d6c1a4e9_directory_organizations_of_user.py
index 8e8e5f9c2..11c33484f 100644
--- a/core/switch_core/migrations/versions/f2b8d6c1a4e9_directory_organizations_of_user.py
+++ b/core/switch_core/migrations/versions/f2b8d6c1a4e9_directory_organizations_of_user.py
@@ -3,7 +3,7 @@
Under the WorkOS directory a sign-in names the WorkOS organizations the
person belongs to, and which Switch organizations follow those, and which
ones following WorkOS the person is already in, has to be read before
-anything is bound. This adds the fifteenth lookup to the exemption from
+anything is bound. This adds the sixteenth lookup to the exemption from
row-level security. See `db/tenant_lookup.py` for what it discloses.
The DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py` as it
diff --git a/core/switch_core/workos_directory.py b/core/switch_core/workos_directory.py
index a021de0d1..c9ceeb740 100644
--- a/core/switch_core/workos_directory.py
+++ b/core/switch_core/workos_directory.py
@@ -30,7 +30,9 @@ under the local directory, and that is what a new organization is until then.
from __future__ import annotations
+import json
import logging
+import re
from collections.abc import Mapping
from typing import Any
@@ -92,11 +94,14 @@ def switch_role(workos_role: str) -> str:
class WorkOSRefused(DirectoryUnavailable):
- """WorkOS answered, with something other than 200."""
+ """WorkOS answered, with something other than 200. `detail` is what it
+ said, as it said it, for the log and for telling one refusal from
+ another."""
- def __init__(self, message: str, status_code: int) -> None:
+ def __init__(self, message: str, status_code: int, detail: str) -> None:
super().__init__(message)
self.status_code = status_code
+ self.detail = detail
class EventCursorRejected(DirectoryUnavailable):
@@ -104,6 +109,22 @@ class EventCursorRejected(DirectoryUnavailable):
start time it no longer keeps."""
+# A refusal of where the events are read from names the parameter it refused;
+# one of the request itself (an event type, how the list is sent) does not,
+# and starting again from now would not cure it.
+_NAMES_THE_CURSOR = re.compile(r"\b(after|range_start)\b")
+# Enough of a refusal to say what it was, not a page of it in the log.
+_DETAIL_LIMIT = 500
+
+
+def _refusal_detail(response: httpx.Response) -> str:
+ try:
+ body = response.json()
+ except ValueError:
+ return response.text[:_DETAIL_LIMIT]
+ return json.dumps(body)[:_DETAIL_LIMIT]
+
+
def _unreadable(what: str) -> DirectoryUnavailable:
return DirectoryUnavailable(f"WorkOS answered with {what} Switch cannot read.")
@@ -138,9 +159,11 @@ class WorkOSDirectory:
f"WorkOS could not be reached ({type(error).__name__})."
) from error
if response.status_code != 200:
+ detail = _refusal_detail(response)
raise WorkOSRefused(
- f"WorkOS answered {response.status_code} for {path}.",
+ f"WorkOS answered {response.status_code} for {path}: {detail}",
response.status_code,
+ detail,
)
try:
body = response.json()
@@ -271,7 +294,9 @@ class WorkOSDirectory:
try:
page = await self._get("/events", params)
except WorkOSRefused as error:
- if error.status_code in (400, 404, 422):
+ if error.status_code in (400, 404, 422) and _NAMES_THE_CURSOR.search(
+ error.detail
+ ):
raise EventCursorRejected(error.message) from error
raise
data = page.get("data")
diff --git a/core/switch_core/workos_mirror.py b/core/switch_core/workos_mirror.py
index 1db83ddb1..f64fcd681 100644
--- a/core/switch_core/workos_mirror.py
+++ b/core/switch_core/workos_mirror.py
@@ -116,14 +116,18 @@ class WorkOSMirror:
self._attempts: dict[str, int] = {}
# Organizations to check in full on every pass until that succeeds.
self._recheck: set[str] = set()
+ # The linked organizations as of the last pass, and the WorkOS
+ # organization each follows, read again only when they change.
+ self._linked_now: dict[str, str] | None = None
async def poll_once(self, fence: Fence) -> int:
"""Re-check what is due, then apply the events since the cursor, page
by page, moving the cursor past each one. Returns how many events
were read."""
cursor = await self._cursor()
+ linked = await self._linked()
if self._recheck:
- await self._check_all(fence, await self._linked(), only=set(self._recheck))
+ await self._check_all(fence, linked, only=set(self._recheck))
polled_at = datetime.now(UTC)
try:
events = await self._directory.events(
@@ -140,11 +144,11 @@ class WorkOSMirror:
fence, started_at=polled_at - _START_OVERLAP, after=None
)
return 0
- linked = await self._linked()
following = {workos: own for own, workos in linked.items()}
read = 0
after = cursor.after
while events:
+ page_from = after
for event in events:
event_id = event.get("id")
if not isinstance(event_id, str):
@@ -156,7 +160,9 @@ class WorkOSMirror:
await self._write_cursor(fence, started_at=None, after=event_id)
after = event_id
read += 1
- if after is None:
+ # A page with no event to move past would be asked for again,
+ # and again: leave it to the next pass.
+ if after is None or after == page_from:
return read
events = await self._directory.events(
EVENT_TYPES, after=after, range_start=cursor.started_at.isoformat()
@@ -409,9 +415,19 @@ class WorkOSMirror:
self._recheck |= set(await self._linked())
async def _linked(self) -> dict[str, str]:
- """Each linked organization's WorkOS organization, by its id."""
+ """Each linked organization's WorkOS organization, by its id. Which
+ organizations are linked is read on every pass, in one lookup; each
+ one's WorkOS organization only when that list changes, one short
+ session each, since an organization is readable only bound to it (a
+ link is never changed in place: `workos_linking.py` refuses). An
+ organization linked since the last pass is checked in full: an
+ operator links it from another process, and its members would
+ otherwise wait for the daily check."""
+ ids = await directory_organizations(self._session_factory)
+ if self._linked_now is not None and set(ids) == set(self._linked_now):
+ return self._linked_now
linked: dict[str, str] = {}
- for organization_id in await directory_organizations(self._session_factory):
+ for organization_id in ids:
async with organization_session(
self._session_factory, organization_id
) as session:
@@ -422,6 +438,9 @@ class WorkOSMirror:
)
if workos_organization_id is not None:
linked[organization_id] = workos_organization_id
+ if self._linked_now is not None:
+ self._recheck |= set(linked) - set(self._linked_now)
+ self._linked_now = linked
return linked
async def _users_of(self, subjects: list[str]) -> dict[str, str]:
diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.py
index 7cde7c7a9..e63e3b8a4 100644
--- a/core/tests/switch_core/db/test_tenant_lookup.py
+++ b/core/tests/switch_core/db/test_tenant_lookup.py
@@ -76,6 +76,7 @@ from switch_core.db.tenant_lookup import (
tenant_of_room,
tenant_of_server_connector,
tenants_inviting_email,
+ tenants_of_organization,
tenants_of_user,
tenants_open_to_domain,
)
@@ -113,6 +114,7 @@ _ADDED_SINCE = {
"all_organization_ids": "10f6d02ac5bc",
"directory_organizations_of_user": "f2b8d6c1a4e9",
"directory_organizations": "a7c3e9f15b20",
+ "tenants_of_organization": "c3d9a1f7b246",
}
# A third kind of change, and the quietest: a lookup whose body a later
@@ -393,6 +395,25 @@ class TestWhatTheyAnswer:
found = await all_tenant_ids(rls_harness.restricted)
assert {fixture.tenant_a, fixture.tenant_b} <= set(found)
+ async def test_tenants_of_organization_sees_only_its_workspaces(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ fixture = await _two_populated_tenants(rls_harness)
+ organization_id = f"org-{uuid.uuid4().hex[:8]}"
+ async with rls_harness.owner() as session:
+ session.add(
+ Organization(id=organization_id, slug=organization_id, name="O")
+ )
+ await session.flush()
+ tenant_a = await session.get(Tenant, fixture.tenant_a)
+ assert tenant_a is not None
+ tenant_a.organization_id = organization_id
+ await session.commit()
+
+ assert await tenants_of_organization(
+ rls_harness.restricted, organization_id
+ ) == [fixture.tenant_a]
+
async def test_all_organization_ids_sees_every_organization(
self, rls_harness: RLSHarness
) -> None:
diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.py
index 25c5bb90a..6cf0c0302 100644
--- a/core/tests/switch_core/gateway/test_oidc_routes.py
+++ b/core/tests/switch_core/gateway/test_oidc_routes.py
@@ -232,6 +232,31 @@ class TestSigningInWithADirectory:
assert refused.value.status_code == 409
assert "administrator" in refused.value.detail
+ async def test_an_issuer_other_than_the_configured_one_is_refused(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """Stored under another spelling of the issuer, the identity would
+ match nothing the directory looks up, so nothing is stored."""
+ token = {"userinfo": {**self._TOKEN["userinfo"], "iss": "https://idp.example/"}}
+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))
+
+ async with session_factory() as session:
+ with pytest.raises(HTTPException) as refused:
+ await oidc_routes.oidc_callback(
+ request=SimpleNamespace(session={}), # type: ignore[arg-type]
+ config=self._config(),
+ session=session,
+ session_factory=session_factory,
+ user_store=UserStore(),
+ organization_directory=_Directory([]), # type: ignore[arg-type]
+ )
+ stored = await UserStore().get_by_email(session, "[email protected]")
+
+ assert refused.value.status_code == 503
+ assert stored is None
+
class TestOidcCallback:
async def test_provisions_user_and_sets_session_cookie(
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
index c363db181..06883f17b 100644
--- a/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
+++ b/core/tests/switch_core/gateway/test_workos_sign_in_routes.py
@@ -296,6 +296,24 @@ class TestChangingMembers:
for who in (cy, eli, fay):
assert await _role(session_factory, organization_id, who) == "member"
+ async def test_demoting_the_last_org_admin_is_refused_before_any_sign_in(
+ self, session_factory
+ ) -> None:
+ ada = _name("ada")
+ tenant_id, organization_id = await _linked(
+ session_factory, {ada: ("owner", "org_admin")}
+ )
+ workos = _WorkOS({f"user_{ada}": ("om_ada", "org_admin")})
+
+ async with _client(_with(session_factory, workos), ada, tenant_id) as client:
+ refused = await client.patch(
+ f"/organizations/current/members/{ada}", json={"role": "member"}
+ )
+
+ assert refused.status_code == 409
+ assert refused.json()["detail"] == "Cannot demote the last organization admin"
+ assert await _role(session_factory, organization_id, ada) == "org_admin"
+
async def test_a_removal_refused_for_its_workspaces_asks_for_no_sign_in(
self, session_factory
) -> None:
diff --git a/core/tests/switch_core/test_workos_directory.py b/core/tests/switch_core/test_workos_directory.py
index ae051fcf3..d6bb7c024 100644
--- a/core/tests/switch_core/test_workos_directory.py
+++ b/core/tests/switch_core/test_workos_directory.py
@@ -493,21 +493,50 @@ class TestWhatTheMirrorReads:
@pytest.mark.parametrize("status", [400, 404, 422])
async def test_a_refused_cursor_says_so(self, status: int) -> None:
- directory = _directory(lambda request: httpx.Response(status))
+ directory = _directory(
+ lambda request: httpx.Response(
+ status,
+ json={
+ "code": "invalid_request_parameters",
+ "errors": [{"field": "after", "code": "not_found"}],
+ },
+ )
+ )
with pytest.raises(EventCursorRejected):
await directory.events(
("organization.deleted",), after="event_old", range_start="x"
)
- async def test_other_refusals_are_not_the_cursor(self) -> None:
- directory = _directory(lambda request: httpx.Response(401))
+ @pytest.mark.parametrize(
+ ("status", "body"),
+ [
+ (401, {"message": "Unauthorized"}),
+ (
+ 400,
+ {
+ "code": "invalid_request_parameters",
+ "errors": [{"field": "events", "code": "invalid_enum_value"}],
+ },
+ ),
+ ],
+ )
+ async def test_other_refusals_are_not_the_cursor_and_say_what_they_were(
+ self, status: int, body: dict
+ ) -> None:
+ """A refusal of the request itself would come back however far the
+ events were read from: starting again from now would not cure it."""
+ directory = _directory(lambda request: httpx.Response(status, json=body))
with pytest.raises(DirectoryUnavailable) as refused:
await directory.events(
("organization.deleted",), after="event_1", range_start="x"
)
assert not isinstance(refused.value, EventCursorRejected)
+ assert str(status) in refused.value.message
+ assert (
+ next(iter(body.values())) if status == 401 else "invalid_enum_value"
+ ) in refused.value.message
async def test_one_membership_is_read_as_it_is_now(self) -> None:
def handler(request: httpx.Request) -> httpx.Response:
diff --git a/core/tests/switch_core/test_workos_mirror.py b/core/tests/switch_core/test_workos_mirror.py
index df2c4160f..fe2702e9a 100644
--- a/core/tests/switch_core/test_workos_mirror.py
+++ b/core/tests/switch_core/test_workos_mirror.py
@@ -404,6 +404,43 @@ class TestRecovering:
assert await _roles(owner, organization_id) == {ada: "member"}
+ async def test_a_page_with_no_event_to_move_past_is_left_to_the_next_pass(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Asking again from the same place would get the same page back, and
+ again: the pass ends instead of spinning on it."""
+ owner = rls_harness.owner
+ _, workos_id = await _linked(owner)
+ await _person(owner, "user_ADA")
+ workos = _WorkOS()
+ mirror = await _mirror(rls_harness, workos)
+ await mirror.poll_once()
+ workos.change("user_ADA", workos_id, "member")
+ await mirror.poll_once()
+ workos.log.append({"event": "organization_membership.updated"})
+ asked = len(workos.asked)
+
+ assert await mirror.poll_once() == 0
+
+ assert len(workos.asked) == asked + 1
+
+ async def test_an_organization_linked_since_the_last_pass_is_checked_in_full(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """An operator links it from another process, with no event to say
+ so: its members don't wait for the daily check."""
+ owner = rls_harness.owner
+ ada = await _person(owner, "user_ADA")
+ workos = _WorkOS()
+ mirror = await _mirror(rls_harness, workos)
+ await mirror.poll_once()
+ organization_id, workos_id = await _linked(owner)
+ workos.memberships[("user_ADA", workos_id)] = "org_admin"
+
+ await mirror.poll_once()
+
+ assert await _roles(owner, organization_id) == {ada: "org_admin"}
+
async def test_an_empty_pass_moves_the_start_forward(
self, rls_harness: RLSHarness
) -> None:
diff --git a/docs/old/workos-directory.md b/docs/old/workos-directory.md
index 4b911ef7f..fe5daab69 100644
--- a/docs/old/workos-directory.md
+++ b/docs/old/workos-directory.md
@@ -14,7 +14,10 @@ off by default; this page says what works today and what does not yet.
- The gateway's OIDC sign-in (`GATEWAY_OIDC_*`, see
[`GATEWAY_OIDC_SETUP.md`](GATEWAY_OIDC_SETUP.md)) set up against an AuthKit
application of the same environment. The sign-in's subject is the person's
- WorkOS user id.
+ WorkOS user id. `GATEWAY_OIDC_ISSUER_URL` must be exactly the issuer the
+ tokens name, trailing slash included: Switch looks people's WorkOS
+ identities up under it, so a sign-in whose token names another issuer is
+ refused, and the log says which one it named.
- `GATEWAY_SIGNUP_MODE=invite_only`. Organizations cannot be created in WorkOS
from Switch yet, so nobody but the operator creates one; the server refuses
to start with any other mode.