Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Store organizations' connector apps and service settings
Petr Bauch41d6bae9beaf
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.pyindex 6b2419fa8..03128b004 100644--- a/core/switch_core/accounts/deletion.py+++ b/core/switch_core/accounts/deletion.py@@ -142,6 +142,8 @@ USER_REFERENCES: dict[tuple[str, str], Handling] = {("service_connections", "user_id"): "database cascades",("sign_in_flows", "user_id"): "database cascades",("clients", "user_id"): "database clears",+ ("organization_app_credentials", "updated_by"): "database clears",+ ("organization_service_settings", "updated_by"): "database clears",}diff --git a/core/switch_core/db/key_rotation.py b/core/switch_core/db/key_rotation.pyindex 8915f2b17..d4ba951e3 100644--- a/core/switch_core/db/key_rotation.py+++ b/core/switch_core/db/key_rotation.py@@ -36,6 +36,7 @@ from switch_core.db.models import (CollaborationBridge,MachineWorkspace,MessagingInstall,+ OrganizationAppCredential,ProviderConnection,ServerConnector,ServiceAppCredential,@@ -43,6 +44,7 @@ from switch_core.db.models import (ServiceOAuthClient,ServiceTokenIssuance,SignInFlow,+ Tenant,TrustSettings,)from switch_core.db.session_scope import tenant_session@@ -68,6 +70,14 @@ _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.+_ORGANIZATION_ENCRYPTED_TEXT_COLUMNS: tuple[tuple[type[Any], str], ...] = (+ (OrganizationAppCredential, "encrypted_secrets"),+)# In tables no tenant holds (`db/rls_ddl.py`, GLOBAL_TABLES), one row set for# the whole deployment (`trust_settings`, `service_oauth_clients`,# `service_app_credentials`): rewritten@@ -181,6 +191,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()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.pyindex b21093a67..c851999cc 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -4535,6 +4535,83 @@ class ServiceAppCredential(Base):)+class OrganizationAppCredential(OrganizationScoped, Base):+ """The app an organization registered at a service's vendor, for every+ workspace in it.++ The organization's counterpart of `ServiceAppCredential`, in the same+ shape: a GitHub App or a static OAuth client, `client_id` and `settings`+ in the clear, every secret the kind has in `encrypted_secrets`. Where a+ workspace's organization has one, the workspace signs in through it rather+ than through the server's app.++ `updated_by` is cleared when that account is deleted rather than handed+ on: the person may have left every workspace of the organization by then,+ and the organization's audit log keeps who made each change.+ """++ __tablename__ = "organization_app_credentials"+ __table_args__ = (PrimaryKeyConstraint("organization_id", "service"),)++ service: Mapped[str] = mapped_column(Text, nullable=False)+ client_id: Mapped[str] = mapped_column(Text, nullable=False)+ settings: Mapped[dict] = mapped_column(JSONB, nullable=False)+ encrypted_secrets: Mapped[str] = mapped_column(Text, nullable=False)+ updated_by: Mapped[str | None] = mapped_column(+ Text,+ ForeignKey(+ "users.id",+ ondelete="SET NULL",+ name="fk_organization_app_credentials_updated_by",+ ),+ nullable=True,+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ )+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.now(), nullable=False+ )+++class OrganizationServiceSetting(OrganizationScoped, Base):+ """An organization's admin switched a catalog service on or off for every+ workspace in it.++ 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`+ is cleared when that account is deleted, for the reason+ `OrganizationAppCredential` gives.+ """++ __tablename__ = "organization_service_settings"+ __table_args__ = (PrimaryKeyConstraint("organization_id", "service"),)++ service: Mapped[str] = mapped_column(Text, nullable=False)+ enabled: Mapped[bool] = mapped_column(Boolean, nullable=False)+ locked: Mapped[bool] = mapped_column(Boolean, nullable=False)+ updated_by: Mapped[str | None] = mapped_column(+ Text,+ ForeignKey(+ "users.id",+ ondelete="SET NULL",+ name="fk_organization_service_settings_updated_by",+ ),+ nullable=True,+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ )++class ServerAuditEvent(Base):"""One change to the server as a whole: who did what, to what, when.diff --git a/core/switch_core/db/stores/organization_app_credential_store.py b/core/switch_core/db/stores/organization_app_credential_store.pynew file mode 100644index 000000000..3388a415e--- /dev/null+++ b/core/switch_core/db/stores/organization_app_credential_store.py@@ -0,0 +1,119 @@+"""The apps organizations registered at connectors' vendors, one per+organization and service.++The organization's counterpart of `ServiceAppCredentialStore`, and the same+rules for secrets: one keyring-encrypted JSON object per row, and a save that+names only some of them keeps the rest. Every method names the organization;+the table's policy (`db/rls_ddl.py`) also holds the session to the+organization it has bound, directly or through a bound workspace.+"""++from __future__ import annotations++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 (+ decrypt_app_secrets,+ encrypt_merged_secrets,+)+from switch_core.keys import Keyring+++class OrganizationAppCredentialStore:+ def __init__(self, keyring: Keyring) -> None:+ self._keyring = keyring++ async def get(+ self, session: AsyncSession, organization_id: str, service: str+ ) -> OrganizationAppCredential | None:+ result = await session.execute(+ select(OrganizationAppCredential)+ .where(+ OrganizationAppCredential.organization_id == organization_id,+ OrganizationAppCredential.service == service,+ )+ .execution_options(populate_existing=True)+ )+ return result.scalar_one_or_none()++ async def list_all(+ self, session: AsyncSession, organization_id: str+ ) -> dict[str, OrganizationAppCredential]:+ return {+ row.service: row+ for row in await session.scalars(+ select(OrganizationAppCredential)+ .where(OrganizationAppCredential.organization_id == organization_id)+ .execution_options(populate_existing=True)+ )+ }++ def secrets(self, row: OrganizationAppCredential) -> dict[str, str]:+ """The row's secrets. Raises `UndecryptableError` when no key opens them."""+ return decrypt_app_secrets(self._keyring, row.encrypted_secrets, row.service)++ async def save(+ self,+ session: AsyncSession,+ *,+ organization_id: str,+ service: str,+ client_id: str,+ settings: dict[str, str],+ secrets: dict[str, str],+ secret_names: frozenset[str],+ updated_by: str,+ ) -> OrganizationAppCredential:+ """Write the row, merging `secrets` over those already stored+ (`encrypt_merged_secrets`).++ Saves of one organization's service are serialised by a lock held to+ the end of the caller's transaction, as the server's are.+ """+ await session.execute(+ text("SELECT pg_advisory_xact_lock(hashtextextended(:key, 0))"),+ {"key": f"organization-app-credential:{organization_id}:{service}"},+ )+ row = await self.get(session, organization_id, service)+ encrypted = encrypt_merged_secrets(+ self._keyring,+ service=service,+ stored=None if row is None else row.encrypted_secrets,+ secrets=secrets,+ secret_names=secret_names,+ )+ if row is None:+ row = OrganizationAppCredential(+ organization_id=organization_id,+ service=service,+ client_id=client_id,+ settings=dict(settings),+ encrypted_secrets=encrypted,+ updated_by=updated_by,+ )+ session.add(row)+ else:+ row.client_id = client_id+ row.settings = dict(settings)+ row.encrypted_secrets = encrypted+ row.updated_by = updated_by+ await session.flush()+ await session.refresh(row)+ return row++ async def remove(+ self, session: AsyncSession, organization_id: str, service: str+ ) -> OrganizationAppCredential | None:+ """Delete the row; the one removed, or None when there was none."""+ row = await self.get(session, organization_id, service)+ if row is not None:+ await session.execute(+ delete(OrganizationAppCredential).where(+ OrganizationAppCredential.organization_id == organization_id,+ OrganizationAppCredential.service == service,+ )+ )+ await session.flush()+ return rowdiff --git a/core/switch_core/db/stores/organization_service_store.py b/core/switch_core/db/stores/organization_service_store.pynew file mode 100644index 000000000..3b944b4bb--- /dev/null+++ b/core/switch_core/db/stores/organization_service_store.py@@ -0,0 +1,72 @@+"""Which catalog services an organization switched on or off for its+workspaces, and whether each is locked.++No row means the organization has no say in that service. Every method names+the organization; the table's policy (`db/rls_ddl.py`) also holds the session+to the organization it has bound, directly or through a bound workspace.+"""++from __future__ import annotations++from sqlalchemy import delete, func, select+from sqlalchemy.dialects.postgresql import insert+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import OrganizationServiceSetting+++class OrganizationServiceStore:+ async def list_settings(+ self, session: AsyncSession, organization_id: str+ ) -> dict[str, OrganizationServiceSetting]:+ """Every service the organization has a say in, by service."""+ return {+ setting.service: setting+ for setting in await session.scalars(+ select(OrganizationServiceSetting)+ .where(OrganizationServiceSetting.organization_id == organization_id)+ .execution_options(populate_existing=True)+ )+ }++ async def set(+ self,+ session: AsyncSession,+ organization_id: str,+ service: str,+ *,+ enabled: bool,+ locked: bool,+ user_id: str,+ ) -> None:+ await session.execute(+ insert(OrganizationServiceSetting)+ .values(+ organization_id=organization_id,+ service=service,+ enabled=enabled,+ locked=locked,+ updated_by=user_id,+ )+ .on_conflict_do_update(+ index_elements=["organization_id", "service"],+ set_={+ "enabled": enabled,+ "locked": locked,+ "updated_by": user_id,+ "updated_at": func.now(),+ },+ )+ )++ async def clear(+ self, session: AsyncSession, organization_id: str, service: str+ ) -> bool:+ """Give up the organization's say in `service`; whether it had one."""+ result = await session.execute(+ delete(OrganizationServiceSetting).where(+ OrganizationServiceSetting.organization_id == organization_id,+ OrganizationServiceSetting.service == service,+ )+ )+ return bool(result.rowcount) # type: ignore[attr-defined]diff --git a/core/switch_core/db/stores/service_app_credential_store.py b/core/switch_core/db/stores/service_app_credential_store.pyindex bc1860b53..a3f20d4fe 100644--- a/core/switch_core/db/stores/service_app_credential_store.py+++ b/core/switch_core/db/stores/service_app_credential_store.py@@ -25,6 +25,53 @@ class MissingSecretsError(ValueError):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@@ -49,12 +96,7 @@ class ServiceAppCredentialStore:def secrets(self, row: ServiceAppCredential) -> dict[str, str]:"""The row's secrets. Raises `UndecryptableError` when no key opens them."""- values = json.loads(self._keyring.decrypt(row.encrypted_secrets))- if not isinstance(values, dict) or not all(- isinstance(value, str) for value in values.values()- ):- raise ValueError(f"The stored secrets for {row.service} are malformed.")- return values+ return decrypt_app_secrets(self._keyring, row.encrypted_secrets, row.service)async def save(self,@@ -67,12 +109,8 @@ class ServiceAppCredentialStore:secret_names: frozenset[str],updated_by: str,) -> ServiceAppCredential:- """Write the row, merging `secrets` over those already stored.-- `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`.+ """Write the row, merging `secrets` over those already stored+ (`encrypt_merged_secrets`).Saves of one service are serialised by a lock held to the end of thecaller's transaction, so two operators saving different secrets at@@ -83,22 +121,13 @@ class ServiceAppCredentialStore:{"key": f"service-app-credential:{service}"},)row = await self.get(session, service)- if set(secrets) - secret_names:- raise ValueError(- f"{service} has no secret named {sorted(set(secrets) - secret_names)}."- )- stored = (- {} if row is None or secret_names <= set(secrets) else self.secrets(row)+ encrypted = encrypt_merged_secrets(+ self._keyring,+ service=service,+ stored=None if row is None else row.encrypted_secrets,+ secrets=secrets,+ secret_names=secret_names,)- merged = {- name: value- for name, value in {**stored, **secrets}.items()- if name in secret_names- }- missing = secret_names - set(merged)- if missing:- raise MissingSecretsError(sorted(missing))- encrypted = self._keyring.encrypt(json.dumps(merged))if row is None:row = ServiceAppCredential(service=service,diff --git a/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.py b/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.pynew file mode 100644index 000000000..ab92d25ad--- /dev/null+++ b/core/switch_core/migrations/versions/10f6d02ac5bc_organization_connector_apps.py@@ -0,0 +1,105 @@+"""organization connector apps and service settings++Two organization-scoped tables, each with the policy every+organization-scoped table carries (`db/rls_ddl.py`), compared against the+`require_organization_id()` function `238c68b7306e` created:++- `organization_app_credentials`: the app an organization registered at a+ service's vendor (a GitHub App, a static OAuth client), in the shape of+ `service_app_credentials`, its secrets encrypted with the keyring.+- `organization_service_settings`: a service an organization switched on or+ off for its workspaces, and whether that is locked.++`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+when this migration was written, copied rather than imported for the reason+`265ed188ad6f` gives.++Expand only: a process from before this revision never reads the tables.++Revision ID: 10f6d02ac5bc+Revises: 9d41b7e2c6a3+Create Date: 2026-10-30 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "10f6d02ac5bc"+down_revision: str | Sequence[str] | None = "9d41b7e2c6a3"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++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")+++def _timestamp(name: str) -> sa.Column:+ return sa.Column(+ name,+ sa.DateTime(timezone=True),+ server_default=sa.text("now()"),+ nullable=False,+ )+++def _organization(table: str) -> list[sa.Column | sa.Constraint]:+ return [+ sa.Column("organization_id", sa.Text(), nullable=False),+ sa.Column("updated_by", sa.Text(), nullable=True),+ sa.ForeignKeyConstraint(+ ["organization_id"],+ ["organizations.id"],+ name=f"fk_{table}_organization",+ ),+ sa.ForeignKeyConstraint(+ ["updated_by"],+ ["users.id"],+ name=f"fk_{table}_updated_by",+ ondelete="SET NULL",+ ),+ sa.PrimaryKeyConstraint("organization_id", "service"),+ ]+++def upgrade() -> None:+ op.create_table(+ "organization_app_credentials",+ sa.Column("service", sa.Text(), nullable=False),+ sa.Column("client_id", sa.Text(), nullable=False),+ sa.Column("settings", postgresql.JSONB(), nullable=False),+ sa.Column("encrypted_secrets", sa.Text(), nullable=False),+ _timestamp("updated_at"),+ _timestamp("created_at"),+ *_organization("organization_app_credentials"),+ )+ op.create_table(+ "organization_service_settings",+ sa.Column("service", sa.Text(), nullable=False),+ sa.Column("enabled", sa.Boolean(), nullable=False),+ sa.Column("locked", sa.Boolean(), nullable=False),+ _timestamp("updated_at"),+ *_organization("organization_service_settings"),+ )+ for table in _TABLES:+ op.execute(f'ALTER TABLE "{table}" ENABLE ROW LEVEL SECURITY')+ op.execute(+ f'CREATE POLICY {ORGANIZATION_POLICY_NAME} ON "{table}"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+ )+++def downgrade() -> None:+ 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.pynew file mode 100644index 000000000..176411cf9--- /dev/null+++ b/core/tests/switch_core/db/stores/test_organization_connector_stores.py@@ -0,0 +1,257 @@+"""Organizations' connector apps and service settings, against Postgres.++Every assertion goes through `rls_harness.restricted`, the role the policies+apply to; `owner` only arranges fixtures. The merging of secrets is shared+with the server's store and tested there+(`test_service_app_credential_store.py`).+"""++from __future__ import annotations++import json+import uuid++import pytest+from sqlalchemy import delete, select+from sqlalchemy.exc import DBAPIError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ Organization,+ OrganizationAppCredential,+ OrganizationServiceSetting,+ Tenant,+ User,+)+from switch_core.db.session_scope import organization_session, tenant_session+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++APPS = OrganizationAppCredentialStore(TEST_KEYRING)+SERVICES = OrganizationServiceStore()+GITHUB_SECRETS = frozenset({"client_secret", "private_key"})+++def _id(prefix: str) -> str:+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++async def _organization(owner: async_sessionmaker[AsyncSession]) -> tuple[str, str]:+ """An organization with one workspace."""+ organization_id, tenant_id = _id("org"), _id("tenant")+ async with owner() as session:+ session.add(Organization(id=organization_id, slug=organization_id, name="O"))+ await session.flush()+ session.add(+ Tenant(+ id=tenant_id, slug=tenant_id, name="W", organization_id=organization_id+ )+ )+ await session.commit()+ return organization_id, tenant_id+++async def _user(owner: async_sessionmaker[AsyncSession]) -> str:+ async with owner() as session:+ user = User(name="admin", email=f"{_id('admin')}@example.invalid", role="user")+ session.add(user)+ await session.commit()+ return user.id+++async def _save(+ session: AsyncSession,+ organization_id: str,+ user_id: str,+ secrets: dict[str, str],+) -> OrganizationAppCredential:+ return await APPS.save(+ session,+ organization_id=organization_id,+ service="github",+ client_id="example-client-id",+ settings={"slug": "example-app"},+ secrets=secrets,+ secret_names=GITHUB_SECRETS,+ updated_by=user_id,+ )+++class TestAppCredentials:+ async def test_saved_encrypted_and_read_back(self, rls_harness: RLSHarness) -> None:+ organization_id, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ async with organization_session(rls_harness.restricted, organization_id) as s:+ await _save(+ s, organization_id, admin, {"client_secret": "a", "private_key": "k"}+ )+ await s.commit()++ async with organization_session(rls_harness.restricted, organization_id) as s:+ row = await APPS.get(s, organization_id, "github")+ assert row is not None+ assert row.encrypted_secrets.startswith(TEST_KEYRING.current_prefix())+ assert "private_key" not in row.encrypted_secrets+ assert APPS.secrets(row) == {"client_secret": "a", "private_key": "k"}+ assert row.updated_by == admin++ async def test_a_partial_save_keeps_the_other_secret(+ self, rls_harness: RLSHarness+ ) -> None:+ organization_id, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ async with organization_session(rls_harness.restricted, organization_id) as s:+ await _save(+ s, organization_id, admin, {"client_secret": "a", "private_key": "k"}+ )+ await s.commit()+ async with organization_session(rls_harness.restricted, organization_id) as s:+ row = await _save(s, organization_id, admin, {"client_secret": "b"})+ await s.commit()+ assert APPS.secrets(row) == {"client_secret": "b", "private_key": "k"}++ async def test_a_first_save_needs_every_secret(+ self, rls_harness: RLSHarness+ ) -> None:+ organization_id, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ async with organization_session(rls_harness.restricted, organization_id) as s:+ with pytest.raises(MissingSecretsError):+ await _save(s, organization_id, admin, {"client_secret": "a"})++ async def test_a_workspace_sees_its_own_organizations_app_only(+ self, rls_harness: RLSHarness+ ) -> None:+ org_a, tenant_a = await _organization(rls_harness.owner)+ org_b, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ for organization_id in (org_a, org_b):+ async with organization_session(+ rls_harness.restricted, organization_id+ ) as s:+ await _save(+ s,+ organization_id,+ admin,+ {"client_secret": "a", "private_key": "k"},+ )+ await s.commit()++ async with tenant_session(rls_harness.restricted, tenant_a) as s:+ assert await APPS.get(s, org_a, "github") is not None+ assert await APPS.get(s, org_b, "github") is None+ visible = await s.scalars(select(OrganizationAppCredential.organization_id))+ assert set(visible) == {org_a}++ async def test_another_organizations_app_cannot_be_written(+ self, rls_harness: RLSHarness+ ) -> None:+ org_a, _ = await _organization(rls_harness.owner)+ org_b, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ async with organization_session(rls_harness.restricted, org_a) as s:+ with pytest.raises(DBAPIError):+ await _save(s, org_b, admin, {"client_secret": "a", "private_key": "k"})++ async def test_remove_returns_the_row_and_leaves_none(+ self, rls_harness: RLSHarness+ ) -> None:+ organization_id, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ async with organization_session(rls_harness.restricted, organization_id) as s:+ await _save(+ s, organization_id, admin, {"client_secret": "a", "private_key": "k"}+ )+ await s.commit()+ async with organization_session(rls_harness.restricted, organization_id) as s:+ removed = await APPS.remove(s, organization_id, "github")+ await s.commit()+ assert removed is not None and removed.client_id == "example-client-id"+ assert await APPS.list_all(s, organization_id) == {}+ assert await APPS.remove(s, organization_id, "github") is None++ async def test_deleting_the_account_that_saved_it_clears_updated_by(+ self, rls_harness: RLSHarness+ ) -> None:+ organization_id, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ async with organization_session(rls_harness.restricted, organization_id) as s:+ await _save(+ s, organization_id, admin, {"client_secret": "a", "private_key": "k"}+ )+ await SERVICES.set(+ s, organization_id, "github", enabled=False, locked=True, user_id=admin+ )+ await s.commit()+ async with rls_harness.owner() as s:+ await s.execute(delete(User).where(User.id == admin))+ await s.commit()++ async with organization_session(rls_harness.restricted, organization_id) as s:+ 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 setting.updated_by is None+++class TestServiceSettings:+ async def test_set_overwrites_and_clear_gives_up_the_say(+ self, rls_harness: RLSHarness+ ) -> None:+ organization_id, tenant_id = await _organization(rls_harness.owner)+ 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+ )+ await SERVICES.set(+ s, organization_id, "github", enabled=False, locked=True, user_id=admin+ )+ await s.commit()++ async with tenant_session(rls_harness.restricted, tenant_id) as s:+ settings = await SERVICES.list_settings(s, organization_id)+ assert {+ service: (setting.enabled, setting.locked)+ for service, setting in settings.items()+ } == {"github": (False, True)}++ async with organization_session(rls_harness.restricted, organization_id) as s:+ assert await SERVICES.clear(s, organization_id, "github") is True+ assert await SERVICES.clear(s, organization_id, "github") is False+ await s.commit()+ assert await SERVICES.list_settings(s, organization_id) == {}++ async def test_a_workspace_sees_its_own_organizations_settings_only(+ self, rls_harness: RLSHarness+ ) -> None:+ org_a, tenant_a = await _organization(rls_harness.owner)+ org_b, _ = await _organization(rls_harness.owner)+ admin = await _user(rls_harness.owner)+ for organization_id in (org_a, org_b):+ async with organization_session(+ rls_harness.restricted, organization_id+ ) as s:+ await SERVICES.set(+ s,+ organization_id,+ "github",+ enabled=True,+ locked=True,+ user_id=admin,+ )+ await s.commit()++ async with tenant_session(rls_harness.restricted, tenant_a) as s:+ assert await SERVICES.list_settings(s, org_b) == {}+ visible = await s.scalars(+ select(OrganizationServiceSetting.organization_id)+ )+ assert set(visible) == {org_a}diff --git a/core/tests/switch_core/db/test_key_rotation.py b/core/tests/switch_core/db/test_key_rotation.pyindex 732369ae2..d1c4c33a2 100644--- a/core/tests/switch_core/db/test_key_rotation.py+++ b/core/tests/switch_core/db/test_key_rotation.py@@ -27,6 +27,8 @@ from switch_core.db.models import (Client,CollaborationBridge,MessagingInstall,+ Organization,+ OrganizationAppCredential,ServiceAppCredential,ServiceConnection,ServiceTokenIssuance,@@ -290,6 +292,43 @@ async def test_the_operators_connector_apps_end_up_under_the_current_key(assert _NEW.decrypt(secret) == '{"client_secret": "example"}'+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}"+ 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,+ service="github",+ client_id="example-client-id",+ settings={},+ encrypted_secrets=_OLD.encrypt('{"client_secret": "example"}'),+ updated_by=admin,+ )+ )+ await session.commit()++ await reencrypt_stored_secrets(rls_harness.restricted, _NEW, [tenant_id])++ secret = await _raw_where(+ rls_harness.owner,+ "SELECT encrypted_secrets FROM organization_app_credentials "+ "WHERE organization_id = :organization_id",+ {"organization_id": organization_id},+ )+ assert isinstance(secret, str) and secret.startswith(_NEW.current_prefix())+ assert _NEW.decrypt(secret) == '{"client_secret": "example"}'++async def test_a_connector_app_no_key_opens_stops_the_boot(rls_harness: RLSHarness,) -> None:diff --git a/core/tests/switch_core/db/test_row_level_security.py b/core/tests/switch_core/db/test_row_level_security.pyindex a8359af38..7e3963026 100644--- a/core/tests/switch_core/db/test_row_level_security.py+++ b/core/tests/switch_core/db/test_row_level_security.py@@ -382,6 +382,8 @@ class TestCatalogueCoverage:"organizations": "id","organization_members": "organization_id","organization_audit_events": "organization_id",+ "organization_app_credentials": "organization_id",+ "organization_service_settings": "organization_id",}assert len(scoped) >= 30, scopedassert scoped["tenants"] == "id"