Skip to content

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

Rotate organizations' secrets per organization, and tidy the new stores

Petr Baucha0fd5908928f
diff --git a/core/switch_core/db/key_rotation.py b/core/switch_core/db/key_rotation.py
index d4ba951e3..9583ea6f1 100644
--- a/core/switch_core/db/key_rotation.py
+++ b/core/switch_core/db/key_rotation.py
@@ -44,11 +44,11 @@ from switch_core.db.models import (
ServiceOAuthClient,
ServiceTokenIssuance,
SignInFlow,
- Tenant,
TrustSettings,
)
-from switch_core.db.session_scope import tenant_session
+from switch_core.db.session_scope import organization_session, tenant_session
from switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStore
+from switch_core.db.tenant_lookup import all_organization_ids
from switch_core.keys import Keyring
from switch_core.process_lease import read_leases
@@ -70,11 +70,8 @@ _ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = (
(SignInFlow, "encrypted_verifier"),
(SignInFlow, "encrypted_result"),
)
-# In organization-scoped tables: rewritten through each workspace's session,
-# which sees its own organization's rows (`db/rls_ddl.py`). That reaches every
-# organization, since each has at least one workspace and none can be
-# deleted; one with several is visited once per workspace, and a value already
-# under the current key is left alone.
+# In organization-scoped tables: rewritten once per organization, in a session
+# bound to it alone.
_ORGANIZATION_ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = (
(OrganizationAppCredential, "encrypted_secrets"),
)
@@ -182,8 +179,8 @@ async def reencrypt_stored_secrets(
keyring: Keyring,
tenant_ids: list[str],
) -> None:
- """Bring every tenant's encrypted values, plus the deployment's global
- ones, onto the current key."""
+ """Bring every tenant's and every organization's encrypted values, plus
+ the deployment's global ones, onto the current key."""
total = 0
for tenant_id in tenant_ids:
async with tenant_session(session_factory, tenant_id) as session:
@@ -191,11 +188,11 @@ async def reencrypt_stored_secrets(
total += await reencrypt_stale_values(session, model, column)
for model, column in _ENCRYPTED_TEXT_COLUMNS:
total += await reencrypt_stale_text(session, keyring, model, column)
- if await session.scalar(
- select(Tenant.organization_id).where(Tenant.id == tenant_id)
- ):
- for model, column in _ORGANIZATION_ENCRYPTED_TEXT_COLUMNS:
- total += await reencrypt_stale_text(session, keyring, model, column)
+ await session.commit()
+ for organization_id in await all_organization_ids(session_factory):
+ async with organization_session(session_factory, organization_id) as session:
+ for model, column in _ORGANIZATION_ENCRYPTED_TEXT_COLUMNS:
+ total += await reencrypt_stale_text(session, keyring, model, column)
await session.commit()
async with session_factory() as session:
for model, column in _GLOBAL_ENCRYPTED_TEXT_COLUMNS:
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index c851999cc..565082d20 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -4584,7 +4584,8 @@ class OrganizationServiceSetting(OrganizationScoped, Base):
Unlocked, it is what a workspace gets until its own admin touches the
switch. Locked, it overrides every workspace's setting, and an
organization's setting of off, locked, is how it keeps a service out of
- all its workspaces. No row means the organization has no say. `updated_by`
+ all its workspaces. No row means the organization has no say. Stored
+ ahead of being applied: workspaces do not consult it yet. `updated_by`
is cleared when that account is deleted, for the reason
`OrganizationAppCredential` gives.
"""
diff --git a/core/switch_core/db/stores/app_secrets.py b/core/switch_core/db/stores/app_secrets.py
new file mode 100644
index 000000000..807ccdb4f
--- /dev/null
+++ b/core/switch_core/db/stores/app_secrets.py
@@ -0,0 +1,66 @@
+"""The secrets of an app registered at a connector's vendor, as a row stores
+them: one keyring-encrypted JSON object holding every secret the app's kind
+has. Shared by the server's apps (`service_app_credential_store.py`) and
+organizations' (`organization_app_credential_store.py`).
+"""
+
+from __future__ import annotations
+
+import json
+
+from switch_core.keys import Keyring
+
+
+class MissingSecretsError(ValueError):
+ """A save would leave the service without every secret its kind has."""
+
+ def __init__(self, names: list[str]) -> None:
+ super().__init__(f"Missing: {', '.join(names)}.")
+ self.names = names
+
+
+def decrypt_app_secrets(
+ keyring: Keyring, encrypted: str, service: str
+) -> dict[str, str]:
+ """An app row's secrets. Raises `UndecryptableError` when no key opens them."""
+ values = json.loads(keyring.decrypt(encrypted))
+ if not isinstance(values, dict) or not all(
+ isinstance(value, str) for value in values.values()
+ ):
+ raise ValueError(f"The stored secrets for {service} are malformed.")
+ return values
+
+
+def encrypt_merged_secrets(
+ keyring: Keyring,
+ *,
+ service: str,
+ stored: str | None,
+ secrets: dict[str, str],
+ secret_names: frozenset[str],
+) -> str:
+ """`secrets` merged over those `stored`, encrypted for the row.
+
+ `secret_names` are every secret the service's kind has. A save naming
+ them all replaces what is stored without reading it, so one under a key
+ since retired can be entered again; any other save must find the rest
+ stored, or raises `MissingSecretsError`.
+ """
+ if set(secrets) - secret_names:
+ raise ValueError(
+ f"{service} has no secret named {sorted(set(secrets) - secret_names)}."
+ )
+ kept = (
+ {}
+ if stored is None or secret_names <= set(secrets)
+ else decrypt_app_secrets(keyring, stored, service)
+ )
+ merged = {
+ name: value
+ for name, value in {**kept, **secrets}.items()
+ if name in secret_names
+ }
+ missing = secret_names - set(merged)
+ if missing:
+ raise MissingSecretsError(sorted(missing))
+ return keyring.encrypt(json.dumps(merged))
diff --git a/core/switch_core/db/stores/organization_app_credential_store.py b/core/switch_core/db/stores/organization_app_credential_store.py
index 3388a415e..8e5e5cf79 100644
--- a/core/switch_core/db/stores/organization_app_credential_store.py
+++ b/core/switch_core/db/stores/organization_app_credential_store.py
@@ -14,7 +14,7 @@ from sqlalchemy import delete, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import OrganizationAppCredential
-from switch_core.db.stores.service_app_credential_store import (
+from switch_core.db.stores.app_secrets import (
decrypt_app_secrets,
encrypt_merged_secrets,
)
diff --git a/core/switch_core/db/stores/organization_service_store.py b/core/switch_core/db/stores/organization_service_store.py
index 3b944b4bb..b800a7d79 100644
--- a/core/switch_core/db/stores/organization_service_store.py
+++ b/core/switch_core/db/stores/organization_service_store.py
@@ -37,7 +37,7 @@ class OrganizationServiceStore:
*,
enabled: bool,
locked: bool,
- user_id: str,
+ updated_by: str,
) -> None:
await session.execute(
insert(OrganizationServiceSetting)
@@ -46,14 +46,14 @@ class OrganizationServiceStore:
service=service,
enabled=enabled,
locked=locked,
- updated_by=user_id,
+ updated_by=updated_by,
)
.on_conflict_do_update(
index_elements=["organization_id", "service"],
set_={
"enabled": enabled,
"locked": locked,
- "updated_by": user_id,
+ "updated_by": updated_by,
"updated_at": func.now(),
},
)
diff --git a/core/switch_core/db/stores/service_app_credential_store.py b/core/switch_core/db/stores/service_app_credential_store.py
index a3f20d4fe..256a99209 100644
--- a/core/switch_core/db/stores/service_app_credential_store.py
+++ b/core/switch_core/db/stores/service_app_credential_store.py
@@ -8,70 +8,17 @@ keeps the rest.
from __future__ import annotations
-import json
-
from sqlalchemy import delete, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import ServiceAppCredential
+from switch_core.db.stores.app_secrets import (
+ decrypt_app_secrets,
+ encrypt_merged_secrets,
+)
from switch_core.keys import Keyring
-class MissingSecretsError(ValueError):
- """A save would leave the service without every secret its kind has."""
-
- def __init__(self, names: list[str]) -> None:
- super().__init__(f"Missing: {', '.join(names)}.")
- self.names = names
-
-
-def decrypt_app_secrets(
- keyring: Keyring, encrypted: str, service: str
-) -> dict[str, str]:
- """An app row's secrets. Raises `UndecryptableError` when no key opens them."""
- values = json.loads(keyring.decrypt(encrypted))
- if not isinstance(values, dict) or not all(
- isinstance(value, str) for value in values.values()
- ):
- raise ValueError(f"The stored secrets for {service} are malformed.")
- return values
-
-
-def encrypt_merged_secrets(
- keyring: Keyring,
- *,
- service: str,
- stored: str | None,
- secrets: dict[str, str],
- secret_names: frozenset[str],
-) -> str:
- """`secrets` merged over those `stored`, encrypted for the row.
-
- `secret_names` are every secret the service's kind has. A save naming
- them all replaces what is stored without reading it, so one under a key
- since retired can be entered again; any other save must find the rest
- stored, or raises `MissingSecretsError`.
- """
- if set(secrets) - secret_names:
- raise ValueError(
- f"{service} has no secret named {sorted(set(secrets) - secret_names)}."
- )
- kept = (
- {}
- if stored is None or secret_names <= set(secrets)
- else decrypt_app_secrets(keyring, stored, service)
- )
- merged = {
- name: value
- for name, value in {**kept, **secrets}.items()
- if name in secret_names
- }
- missing = secret_names - set(merged)
- if missing:
- raise MissingSecretsError(sorted(missing))
- return keyring.encrypt(json.dumps(merged))
-
-
class ServiceAppCredentialStore:
def __init__(self, keyring: Keyring) -> None:
self._keyring = keyring
diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.py
index f6994d7e5..52c639cfa 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 fourteen functions.
+"""The whole exemption from row-level security, written out as fifteen 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
@@ -65,7 +65,9 @@ them about *metadata* rather than rows:
So the property this design actually holds is: **the exemption discloses the
shape of the deployment — which tenants exist, and which tenant a given user,
credential, room, bridge, connector, invitation or installed workspace belongs
-to — and no row of any tenant-scoped table.** It is a boundary on data, not on
+to — and no row of any tenant-scoped table.** The same holds for organizations:
+`all_organization_ids()` discloses which exist, and no row of an
+organization-scoped table. It is a boundary on data, not on
metadata. Narrowing
the second is a question about who may hold the runtime role's credentials at
all, since everything above is reachable by anyone who has them.
@@ -177,6 +179,12 @@ 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
@@ -261,7 +269,7 @@ class TenantLookup:
return f"{self.name}({', '.join('text' for _ in self.arguments)})"
-# The fourteen of them. Ordered as the three shapes above: enumeration, then
+# The fifteen 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(
@@ -274,6 +282,17 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
"the boot enumerations and the runtime-state sweep need."
),
),
+ TenantLookup(
+ name="all_organization_ids",
+ arguments=(),
+ query="SELECT id FROM organizations ORDER BY created_at, id",
+ purpose=(
+ "Every organization in the deployment, oldest first, for the boot "
+ "passes over organization-scoped tables. An organization is "
+ "visited directly rather than through its workspaces, so one "
+ "with none is not missed."
+ ),
+ ),
TenantLookup(
name="tenants_of_user",
arguments=("user_id",),
@@ -500,15 +519,18 @@ 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 fourteen names are fixed and known here, so there is nothing
+# at call time: the fifteen 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 fifteenth lookup with no entry here fails at import, not
+# `TENANT_LOOKUPS`: a sixteenth 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"),
+ "all_organization_ids": text(
+ "SELECT organization_id FROM all_organization_ids() AS organization_id"
+ ),
"tenants_of_user": text(
"SELECT tenant_id FROM tenants_of_user(:user_id) AS tenant_id"
),
@@ -601,6 +623,12 @@ async def all_tenant_ids(
return await _call(session_factory, TENANT_LOOKUPS_BY_NAME["all_tenant_ids"])
+async def all_organization_ids(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> list[str]:
+ return await _call(session_factory, TENANT_LOOKUPS_BY_NAME["all_organization_ids"])
+
+
async def tenants_of_user(
session_factory: async_sessionmaker[AsyncSession], user_id: str
) -> list[str]:
diff --git a/core/switch_core/gateway/connector_apps.py b/core/switch_core/gateway/connector_apps.py
index 2b43e9e9e..611211602 100644
--- a/core/switch_core/gateway/connector_apps.py
+++ b/core/switch_core/gateway/connector_apps.py
@@ -53,7 +53,7 @@ from switch_core.db.models import (
User,
)
from switch_core.db.session_scope import tenant_session
-from switch_core.db.stores.service_app_credential_store import MissingSecretsError
+from switch_core.db.stores.app_secrets import MissingSecretsError
from switch_core.db.tenant_lookup import all_tenant_ids
from switch_core.gateway.auth import require_admin
from switch_core.gateway.dependencies import get_session, get_session_factory
diff --git a/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.py b/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.py
index ab92d25ad..d5e19974c 100644
--- a/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.py
+++ b/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.py
@@ -12,7 +12,12 @@ organization-scoped table carries (`db/rls_ddl.py`), compared against the
`updated_by` on both is cleared when the account is deleted.
-The policy DDL is a verbatim copy of `switch_core/db/rls_ddl.py` as it stood
+And the fifteenth lookup exempt from row-level security,
+`all_organization_ids()`, so the boot's key rotation reaches every
+organization directly. See `db/tenant_lookup.py` for what it discloses.
+
+The policy and function DDL are verbatim copies of `switch_core/db/rls_ddl.py`
+and `switch_core/db/tenant_lookup.py` as they stood
when this migration was written, copied rather than imported for the reason
`265ed188ad6f` gives.
@@ -40,6 +45,15 @@ REQUIRE_ORGANIZATION_FUNCTION_NAME = "require_organization_id"
ORGANIZATION_POLICY_NAME = "organization_isolation"
_PREDICATE = f'"organization_id" = (SELECT {REQUIRE_ORGANIZATION_FUNCTION_NAME}())'
_TABLES = ("organization_app_credentials", "organization_service_settings")
+SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
+
+CREATE_ALL_ORGANIZATION_IDS = f"""CREATE OR REPLACE FUNCTION all_organization_ids()
+ RETURNS SETOF text
+ LANGUAGE sql STABLE SECURITY DEFINER
+ SET search_path = {SECURE_SEARCH_PATH}
+AS $$SELECT id FROM organizations ORDER BY created_at, id$$"""
+
+DROP_ALL_ORGANIZATION_IDS = "DROP FUNCTION IF EXISTS all_organization_ids()"
def _timestamp(name: str) -> sa.Column:
@@ -97,9 +111,11 @@ def upgrade() -> None:
f" USING ({_PREDICATE})\n"
f" WITH CHECK ({_PREDICATE})"
)
+ op.execute(CREATE_ALL_ORGANIZATION_IDS)
def downgrade() -> None:
+ op.execute(DROP_ALL_ORGANIZATION_IDS)
for table in reversed(_TABLES):
op.execute(f'DROP POLICY IF EXISTS {ORGANIZATION_POLICY_NAME} ON "{table}"')
op.drop_table(table)
diff --git a/core/tests/switch_core/db/stores/test_organization_connector_stores.py b/core/tests/switch_core/db/stores/test_organization_connector_stores.py
index 176411cf9..014a58342 100644
--- a/core/tests/switch_core/db/stores/test_organization_connector_stores.py
+++ b/core/tests/switch_core/db/stores/test_organization_connector_stores.py
@@ -8,7 +8,6 @@ with the server's store and tested there
from __future__ import annotations
-import json
import uuid
import pytest
@@ -24,11 +23,11 @@ from switch_core.db.models import (
User,
)
from switch_core.db.session_scope import organization_session, tenant_session
+from switch_core.db.stores.app_secrets import MissingSecretsError
from switch_core.db.stores.organization_app_credential_store import (
OrganizationAppCredentialStore,
)
from switch_core.db.stores.organization_service_store import OrganizationServiceStore
-from switch_core.db.stores.service_app_credential_store import MissingSecretsError
from tests.conftest import TEST_KEYRING, RLSHarness
pytestmark = pytest.mark.no_ambient_tenant
@@ -186,7 +185,12 @@ class TestAppCredentials:
s, organization_id, admin, {"client_secret": "a", "private_key": "k"}
)
await SERVICES.set(
- s, organization_id, "github", enabled=False, locked=True, user_id=admin
+ s,
+ organization_id,
+ "github",
+ enabled=False,
+ locked=True,
+ updated_by=admin,
)
await s.commit()
async with rls_harness.owner() as s:
@@ -197,7 +201,7 @@ class TestAppCredentials:
row = await APPS.get(s, organization_id, "github")
setting = (await SERVICES.list_settings(s, organization_id))["github"]
assert row is not None and row.updated_by is None
- assert json.loads(TEST_KEYRING.decrypt(row.encrypted_secrets))
+ assert APPS.secrets(row) == {"client_secret": "a", "private_key": "k"}
assert setting.updated_by is None
@@ -209,10 +213,20 @@ class TestServiceSettings:
admin = await _user(rls_harness.owner)
async with organization_session(rls_harness.restricted, organization_id) as s:
await SERVICES.set(
- s, organization_id, "github", enabled=True, locked=False, user_id=admin
+ s,
+ organization_id,
+ "github",
+ enabled=True,
+ locked=False,
+ updated_by=admin,
)
await SERVICES.set(
- s, organization_id, "github", enabled=False, locked=True, user_id=admin
+ s,
+ organization_id,
+ "github",
+ enabled=False,
+ locked=True,
+ updated_by=admin,
)
await s.commit()
@@ -245,7 +259,7 @@ class TestServiceSettings:
"github",
enabled=True,
locked=True,
- user_id=admin,
+ updated_by=admin,
)
await s.commit()
diff --git a/core/tests/switch_core/db/stores/test_service_app_credential_store.py b/core/tests/switch_core/db/stores/test_service_app_credential_store.py
index 99945dfe3..2e946e23c 100644
--- a/core/tests/switch_core/db/stores/test_service_app_credential_store.py
+++ b/core/tests/switch_core/db/stores/test_service_app_credential_store.py
@@ -12,8 +12,8 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import ServiceAppCredential, User
+from switch_core.db.stores.app_secrets import MissingSecretsError
from switch_core.db.stores.service_app_credential_store import (
- MissingSecretsError,
ServiceAppCredentialStore,
)
from switch_core.keys import Keyring, UndecryptableError
diff --git a/core/tests/switch_core/db/test_key_rotation.py b/core/tests/switch_core/db/test_key_rotation.py
index d1c4c33a2..dec031534 100644
--- a/core/tests/switch_core/db/test_key_rotation.py
+++ b/core/tests/switch_core/db/test_key_rotation.py
@@ -295,16 +295,13 @@ async def test_the_operators_connector_apps_end_up_under_the_current_key(
async def test_an_organizations_connector_app_ends_up_under_the_current_key(
rls_harness: RLSHarness,
) -> None:
- """An organization's app is rewritten through its workspace's session, by
- the per-tenant fan-out."""
- tenant_id, admin = await _tenant_with_user(rls_harness.owner)
- organization_id = f"org-{tenant_id}"
+ """Rewritten in a pass per organization, which reaches one with no
+ workspace to be seen through."""
+ _, admin = await _tenant_with_user(rls_harness.owner)
+ 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 = await session.get(Tenant, tenant_id)
- assert tenant is not None
- tenant.organization_id = organization_id
session.add(
OrganizationAppCredential(
organization_id=organization_id,
@@ -317,7 +314,7 @@ async def test_an_organizations_connector_app_ends_up_under_the_current_key(
)
await session.commit()
- await reencrypt_stored_secrets(rls_harness.restricted, _NEW, [tenant_id])
+ await reencrypt_stored_secrets(rls_harness.restricted, _NEW, [])
secret = await _raw_where(
rls_harness.owner,
diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
index 83d7ddd76..97c4ed628 100644
--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py
@@ -87,6 +87,10 @@ _ALLOWED_MODULES = {
# resolution shape as the line above, through the same `tenant_of_api_key`,
# with the row then read scoped to the tenant it produced.
"switch_core.management.auth",
+ # The boot-time re-encryption sweep visits every organization, including
+ # one with no workspace to reach it through, binding each in turn
+ # (`organization_session`) to rewrite its connector apps' secrets.
+ "switch_core.db.key_rotation",
# Core keeps which controller runs each agent in memory, so at startup
# every tenant's placed definitions are read back into it: enumerate the
# tenants, then read each one's definitions under its own policy, the same
diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.py
index abd58e380..ded1835e4 100644
--- a/core/tests/switch_core/db/test_tenant_lookup.py
+++ b/core/tests/switch_core/db/test_tenant_lookup.py
@@ -53,6 +53,7 @@ from switch_core.db.models import (
CollaborationBridge,
Invitation,
MessagingInstall,
+ Organization,
Room,
ServerConnector,
Tenant,
@@ -64,6 +65,7 @@ from switch_core.db.tenant_lookup import (
SECURE_SEARCH_PATH,
TENANT_LOOKUPS,
TENANT_LOOKUPS_BY_NAME,
+ all_organization_ids,
all_tenant_ids,
create_lookup_ddl,
tenant_of_agent_oauth_client,
@@ -108,6 +110,7 @@ _ADDED_SINCE = {
"tenants_open_to_domain": "7d3f5a19e2c8",
"tenant_of_sign_in_flow": "e5956cbd3bdc",
"tenants_bindable_by_user": "5c2e8f17a9d4",
+ "all_organization_ids": "10f6d02ac5bc",
}
# A third kind of change, and the quietest: a lookup whose body a later
@@ -388,6 +391,22 @@ class TestWhatTheyAnswer:
found = await all_tenant_ids(rls_harness.restricted)
assert {fixture.tenant_a, fixture.tenant_b} <= set(found)
+ async def test_all_organization_ids_sees_every_organization(
+ self, rls_harness: RLSHarness
+ ) -> None:
+ """Including one with no workspace, which no pass over workspaces
+ would reach."""
+ found_before = set(await all_organization_ids(rls_harness.restricted))
+ ids = [f"org-{uuid.uuid4().hex[:8]}" for _ in range(2)]
+ async with rls_harness.owner() as session:
+ for organization_id in ids:
+ session.add(
+ Organization(id=organization_id, slug=organization_id, name="O")
+ )
+ await session.commit()
+ found = set(await all_organization_ids(rls_harness.restricted))
+ assert found - found_before == set(ids)
+
async def test_the_same_question_asked_the_ordinary_way_sees_one_tenant(
self, rls_harness: RLSHarness
) -> None: