Skip to content

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

[CHOO-3906] Keep organization roles independent and close two creation gaps

Petr Bauchf82c52970bb1
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index fccda9c1f..cb263fc8d 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -113,6 +113,17 @@ class OrganizationMember(Base):
`member` is what joining any of its workspaces makes someone. Workspace
roles stay on `TenantMember`. A checked string, as `tenant_members.role`
is.
+
+ Not derived from workspace roles, and never recomputed from them: an
+ organization's admin administers every workspace in it, so promoting a
+ workspace's admin to `org_admin` would hand them every other workspace
+ too. Joining a workspace adds a `member` row when there is none, and
+ changing or removing a workspace membership leaves this row as it is. Only
+ an organization's own `org_admin`s grant or revoke `org_admin`, through
+ the organization's API. The one exception is migration `238c68b7306e`:
+ it made each existing workspace's owners and admins `org_admin` of the
+ organization it created for that workspace alone, which gave them nothing
+ they did not already administer.
"""
__tablename__ = "organization_members"
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index ebe5e3a3c..4d7327298 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -5,6 +5,7 @@ from collections.abc import Collection
from datetime import timedelta
from sqlalchemy import case, func, select
+from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
@@ -475,17 +476,14 @@ class UserStore:
user_id,
)
return
- existing = await session.get(
- OrganizationMember, (tenant.organization_id, user_id)
+ # Two joins into one organization (an invitation to one workspace, a
+ # domain join to another) may both find no row; the second must not
+ # fail its workspace membership on the first's insert.
+ await session.execute(
+ insert(OrganizationMember)
+ .values(organization_id=tenant.organization_id, user_id=user_id, role=role)
+ .on_conflict_do_nothing(index_elements=["organization_id", "user_id"])
)
- if existing is not None:
- return
- session.add(
- OrganizationMember(
- organization_id=tenant.organization_id, user_id=user_id, role=role
- )
- )
- await session.flush()
async def tenant_role(
self, session: AsyncSession, tenant_id: str, user_id: str
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 233eae038..fdc0b9ef6 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -390,6 +390,23 @@ async def _provision_workspace(
session_factory, organization_store, organization.id
)
raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except BaseException:
+ # A failure after the workspace committed leaves it referencing
+ # the organization, and the discard is refused; the workspace's
+ # own failure is the one to report.
+ try:
+ await _discard_organization(
+ session_factory, organization_store, organization.id
+ )
+ except Exception:
+ logger.exception(
+ "Could not discard organization %s after creating workspace "
+ "%r (slug %s) failed",
+ organization.id,
+ name,
+ slug,
+ )
+ raise
break
if tenant is None:
logger.error(
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index 03994ffb6..0614b3ad9 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -43,6 +43,7 @@ from switch_core.db.models import (
ApiKey,
Client,
Invitation,
+ Organization,
ServiceTokenIssuance,
SignInFlow,
Tenant,
@@ -107,6 +108,13 @@ class _ProvisioningFailsLifecycle(_FakeClientLifecycle):
raise IntegrityError("INSERT INTO clients ...", None, Exception("duplicate"))
+class _FailsBeforeTheWorkspaceLifecycle(_FakeClientLifecycle):
+ """Fails before writing anything, the way a dropped connection does."""
+
+ async def create_tenant(self, name: str, slug: str, organization_id: str) -> Tenant:
+ raise ConnectionResetError("connection to the database was lost")
+
+
class _RecordingMailer:
def __init__(self) -> None:
self.sent: list[InviteEmail] = []
@@ -495,6 +503,34 @@ class TestCreateTenant:
await client.post("/tenants", json={"name": "Unlucky Co"})
assert lifecycle.calls == 1
+ async with session_factory() as session:
+ tenant = await session.scalar(
+ select(Tenant).where(Tenant.name == "Unlucky Co")
+ )
+ assert tenant is not None and tenant.organization_id is not None
+
+ async def test_any_failure_before_the_workspace_discards_its_organization(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Left behind, the organization would hold the slug in
+ `organizations.slug` and push the next workspace of that name onto a
+ suffix."""
+ user_id = await _make_unaffiliated_user(
+ session_factory, name="disconnected", role="user"
+ )
+ token = _token(user_id, "[email protected]", None)
+ lifecycle = _FailsBeforeTheWorkspaceLifecycle(session_factory)
+
+ app = _app(session_factory, client_lifecycle=lifecycle, signup_mode="open")
+ async with _client(app, token) as client:
+ with pytest.raises(ConnectionResetError):
+ await client.post("/tenants", json={"name": "Disconnected Co"})
+
+ async with session_factory() as session:
+ organization = await session.scalar(
+ select(Organization).where(Organization.slug == "disconnected-co")
+ )
+ assert organization is None
async def test_a_name_with_no_slug_characters_is_400(
self, session_factory: async_sessionmaker[AsyncSession]