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
[CHOO-3906] Address review: session state, early name check, leaner listings
Petr Bauch41401cfb9c93
diff --git a/console/tooling-e2e/src/fast/organizations.ts b/console/tooling-e2e/src/fast/organizations.tsindex 2ab11739f..9c1b2984e 100644--- a/console/tooling-e2e/src/fast/organizations.ts+++ b/console/tooling-e2e/src/fast/organizations.ts@@ -6,8 +6,8 @@ import type { FastScenario } from './scenario.ts';* Anyone signed in creates an organization, and its admin adds workspaces to* it: a new user, in the default workspace, creates an organization and lands* in its first workspace, adds a second, and sees both, in an organization- * listed beside the default one. A plain member of the default workspace may- * not add one there.+ * listed beside those they were already in. A plain member of the default+ * workspace may not add one there.** Users and workspaces cannot be deleted, so this runs only on a stack thrown* away after the run.@@ -47,6 +47,8 @@ export const organizations: FastScenario = {// Signing in joins the default workspace, and so its organization.const defaultWorkspace = await founder.tenantId();await member.tenantId();+ // The default workspace's organization is listed too, if it has one.+ const before = await founder.organizations();try {await member.createOrganizationWorkspace(names.name('not-theirs'));@@ -75,6 +77,8 @@ export const organizations: FastScenario = {const listed = await founder.organizations();expect(listed.find((row) => row.id === organization.id)?.role).toBe('org_admin');- expect(listed.length, 'the default organization too').toBe(2);+ expect(listed.map((row) => row.id).sort(), 'the new one beside the rest').toEqual(+ [...before.map((row) => row.id), organization.id].sort()+ );},};diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex dd45e191f..68721e5f1 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -14,10 +14,16 @@ from fastapi import Depends, HTTPException, Request, Responsefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom starlette.requests import HTTPConnection-from switch_core.authz import Action, Principal, require+from switch_core.authz import (+ ORGANIZATION_ADMIN_ROLE,+ ORGANIZATION_ADMIN_TENANT_ROLE,+ Action,+ Principal,+ require,+)from switch_core.config import SwitchConfigfrom switch_core.db.audit import AuditAction, record_audit_event-from switch_core.db.models import Room, Tenant, User+from switch_core.db.models import Organization, Room, Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore@@ -36,6 +42,7 @@ from switch_core.gateway.dependencies import (get_user_store,)from switch_core.gateway.schemas import (+ OrganizationSummary,SessionStateResponse,SessionStateUser,TenantMembershipResponse,@@ -382,6 +389,102 @@ async def workspaces_in_organization(return found+async def organizations_bindable_by(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user_id: str,+) -> list[OrganizationSummary]:+ """The organizations of the workspaces `user_id` may bind, and their role+ in each, sorted by name.++ One short session per workspace, one after another; the organization's+ row is read on the first session bound to one of its workspaces, where+ its policy lets it be read, and skipped on the rest. An organization+ `user_id` belongs to without being able to bind any of its workspaces is+ left out: there is nothing in it they could open.+ """+ found: dict[str, OrganizationSummary] = {}+ for tenant_id in await tenants_bindable_by(session_factory, user_id):+ async with tenant_session(session_factory, tenant_id) as session:+ tenant = await session.get(Tenant, tenant_id)+ if tenant is None or tenant.organization_id is None:+ continue+ if tenant.organization_id in found:+ continue+ organization = await session.get(Organization, tenant.organization_id)+ role = await user_store.organization_role(session, tenant_id, user_id)+ if organization is None or role is None:+ logger.warning(+ "User %s may bind workspace %s, but its organization %s or "+ "their role there was gone by the time it was read",+ user_id,+ tenant_id,+ tenant.organization_id,+ )+ continue+ found[organization.id] = OrganizationSummary(+ id=organization.id,+ slug=organization.slug,+ name=organization.name,+ role=role,+ )+ return sorted(found.values(), key=lambda row: (row.name, row.id))+++async def organization_workspaces_bindable_by(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user_id: str,+ organization_id: str,+ *,+ is_operator: bool,+) -> list[TenantMembershipResponse]:+ """The workspaces of `organization_id` that `user_id` may bind, and their+ role in each: every one for its `org_admin`, their own for a member.++ The platform operator may bind any workspace, and is shown every one of+ the organization's, as `admin` where they hold no role, the standing+ `platform_access` gives them. Each candidate is read on its own short+ session, and only those in the organization are described further.+ """+ candidates = (+ await all_tenant_ids(session_factory)+ if is_operator+ else await tenants_bindable_by(session_factory, user_id)+ )+ found: list[TenantMembershipResponse] = []+ for tenant_id in candidates:+ async with tenant_session(session_factory, tenant_id) as session:+ tenant = await session.get(Tenant, tenant_id)+ if tenant is None or tenant.organization_id != organization_id:+ continue+ role = await user_store.effective_tenant_role(session, tenant_id, user_id)+ organization_role = await user_store.organization_role(+ session, tenant_id, user_id+ )+ if role is None and is_operator:+ role = ORGANIZATION_ADMIN_TENANT_ROLE+ if role is None:+ logger.warning(+ "tenants_bindable_by named tenant %s for user %s, but their "+ "role there was gone by the time it was read",+ tenant_id,+ user_id,+ )+ continue+ found.append(+ TenantMembershipResponse(+ id=tenant.id,+ slug=tenant.slug,+ name=tenant.name,+ role=role,+ organization_role=organization_role,+ organization_id=tenant.organization_id,+ )+ )+ return found++async def _operator_may_enter(session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,@@ -575,7 +678,7 @@ def workspace_creation_refusal(return Noneif new_organization and config.gateway_signup_mode == "invite_only":return (- "Creating workspaces is turned off on this server. Ask a "+ "Creating organizations is turned off on this server. Ask a ""workspace admin for an invitation.")limit = config.gateway_max_workspaces_per_user@@ -618,6 +721,15 @@ def describe_session_state(state = "needs_workspace"is_operator = user.role == "admin"++ def refusal(new_organization: bool) -> str | None:+ return workspace_creation_refusal(+ config,+ is_operator=is_operator,+ workspaces_created=user.workspaces_created,+ new_organization=new_organization,+ )+return SessionStateResponse(user=SessionStateUser(id=user.id, name=user.name, email=user.email, is_operator=is_operator@@ -626,15 +738,12 @@ def describe_session_state(tenants=tenants,state=state,# A deployment that is not isolating tenants keeps to the one it has,- # for operators too: `POST /organizations` would refuse any name.- can_create_workspace=tenants_isolated- and workspace_creation_refusal(- config,- is_operator=is_operator,- workspaces_created=user.workspaces_created,- new_organization=True,- )- is None,+ # for operators too: creating would refuse any name.+ can_create_workspace=tenants_isolated and refusal(True) is None,+ can_add_workspace=tenants_isolated+ and tenant is not None+ and tenant.organization_role == ORGANIZATION_ADMIN_ROLE+ and refusal(False) is None,invite_email_enabled=config.invite_email_enabled,)diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex e6d4f634f..03f0d5b61 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -14,8 +14,6 @@ See `docs/design/organizations-v1.md`.from __future__ import annotations-import logging-from collections import defaultdictfrom typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException, Response@@ -27,13 +25,11 @@ from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.audit import AuditAction, record_audit_eventfrom switch_core.db.models import (- Organization,OrganizationMember,Tenant,User,require_tenant_id,)-from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.organization_store import OrganizationStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (@@ -41,7 +37,8 @@ from switch_core.gateway.auth import (get_authenticated_caller,get_authenticated_user_id,get_current_user,- list_tenant_memberships,+ organization_workspaces_bindable_by,+ organizations_bindable_by,workspaces_in_organization,)from switch_core.gateway.dependencies import (@@ -68,8 +65,6 @@ from switch_core.gateway.workspace_creation import (lock_workspace_allowance,)-logger = logging.getLogger(__name__)-router = APIRouter()@@ -134,44 +129,10 @@ async def list_organizations() -> list[OrganizationSummary]:"""The organizations of the workspaces the caller may enter, and theirrole in each. Like `GET /tenants`, it needs no workspace selected.-- Read through the workspaces, each on its own short session, so it needs- no lookup across organizations of its own. An organization the caller- belongs to without being in any of its workspaces is left out: there is- nothing in it they could open.+ An organization the caller belongs to without being in any of its+ workspaces is left out (`gateway/auth.organizations_bindable_by`)."""- by_organization: dict[str, list[TenantMembershipResponse]] = defaultdict(list)- for membership in await list_tenant_memberships(- session_factory, user_store, user_id- ):- if membership.organization_id is not None:- by_organization[membership.organization_id].append(membership)-- found: list[OrganizationSummary] = []- for organization_id, memberships in by_organization.items():- role = memberships[0].organization_role- # The organization's row is readable on a session bound to any of its- # workspaces.- async with tenant_session(session_factory, memberships[0].id) as session:- organization = await session.get(Organization, organization_id)- if organization is None or role is None:- logger.warning(- "User %s may enter workspace %s, but its organization %s or "- "their role there was gone by the time it was read",- user_id,- memberships[0].id,- organization_id,- )- continue- found.append(- OrganizationSummary(- id=organization.id,- slug=organization.slug,- name=organization.name,- role=role,- )- )- return sorted(found, key=lambda organization: (organization.name, organization.id))+ return await organizations_bindable_by(session_factory, user_store, user_id)@router.post("/organizations", status_code=201)@@ -222,18 +183,19 @@ async def list_organization_workspaces(user: Annotated[User, Depends(get_current_user)],) -> list[TenantMembershipResponse]:"""The organization's workspaces the caller may enter, and their role in- each: every one for an `org_admin`, their own for a member."""+ each: every one for an `org_admin`, their own for a member, and every one+ for the platform operator, who may enter any."""organization_id = await _current_organization_id(session)# Let go of the request's connection while each workspace is read on a# session of its own.await session.commit()- return [- membership- for membership in await list_tenant_memberships(- session_factory, user_store, user.id- )- if membership.organization_id == organization_id- ]+ return await organization_workspaces_bindable_by(+ session_factory,+ user_store,+ user.id,+ organization_id,+ is_operator=user.role == "admin",+ )@router.post("/organizations/current/workspaces", status_code=201)@@ -261,30 +223,26 @@ async def create_organization_workspace(organization_id = await _require_organization_admin(session, user_store, organization_store, user, operator_restores=False)- if user.role == "admin":- # Not held across provisioning, which opens a session per tenant.- await session.commit()- tenant = await create_workspace(- session_factory,- user_store,- client_lifecycle,- organization_id,- user.id,- req.name,- )- else:- locked = await lock_workspace_allowance(+ allowance = (+ None+ if user.role == "admin"+ else await lock_workspace_allowance(session, user.id, config, new_organization=False)- tenant = await create_workspace(- session_factory,- user_store,- client_lifecycle,- organization_id,- user.id,- req.name,- )- locked.workspaces_created += 1+ )+ if allowance is None:+ # Not held across provisioning, which opens a session per tenant.+ await session.commit()+ tenant = await create_workspace(+ session_factory,+ user_store,+ client_lifecycle,+ organization_id,+ user.id,+ req.name,+ )+ if allowance is not None:+ allowance.workspaces_created += 1await session.commit()return TenantMembershipResponse(id=tenant.id,diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex ce01f084f..2e0dccdcb 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -993,7 +993,13 @@ class SessionStateResponse(BaseModel):tenant: TenantMembershipResponse | Nonetenants: list[TenantMembershipResponse]state: Literal["ready", "needs_selection", "needs_workspace"]+ # Whether the caller may create a new organization with its first+ # workspace (`POST /organizations`, and `POST /tenants` before it).can_create_workspace: bool+ # Whether the caller may add a workspace to the bound workspace's+ # organization (`POST /organizations/current/workspaces`): its+ # `org_admin`, within their allowance. False with no workspace bound.+ can_add_workspace: bool# Whether an invitation addressed to an e-mail is sent there, or only# minted for the admin to share.invite_email_enabled: booldiff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.pyindex 4bedaf5a0..313be202e 100644--- a/core/switch_core/gateway/workspace_creation.py+++ b/core/switch_core/gateway/workspace_creation.py@@ -178,35 +178,29 @@ async def create_organization_for(because the person provisioning for other people is the one caller aself-service bound must not stop; nothing is counted for them."""+ allowance: User | None = Noneif caller.is_operator:- user = await user_store.get(session, caller.id)- if user is None:+ operator = await user_store.get(session, caller.id)+ if operator is None:raise HTTPException(status_code=401, detail="User not found")+ user = operator# Not held across provisioning, which opens a session per tenant.await session.commit()- organization, tenant = await create_organization(- session_factory,- user_store,- organization_store,- client_lifecycle,- caller.id,- name,- workspace_name,- )else:- user = await lock_workspace_allowance(+ user = allowance = await lock_workspace_allowance(session, caller.id, config, new_organization=True)- organization, tenant = await create_organization(- session_factory,- user_store,- organization_store,- client_lifecycle,- caller.id,- name,- workspace_name,- )- user.workspaces_created += 1+ organization, tenant = await create_organization(+ session_factory,+ user_store,+ organization_store,+ client_lifecycle,+ caller.id,+ name,+ workspace_name,+ )+ if allowance is not None:+ allowance.workspaces_created += 1await session.commit()await user_store.record_last_tenant(session, user, tenant.id)@@ -249,6 +243,8 @@ async def create_organization(If the workspace then cannot be created, for any reason, the organizationis deleted again, so a failed creation leaves nothing behind."""+ # Both names are checked before anything is written.+ workspace_slugs = _slugs(workspace_name)organization: Organization | None = Nonefor slug in _slugs(name):candidate = Organization(id=str(uuid.uuid4()), name=name, slug=slug)@@ -264,7 +260,9 @@ async def create_organization(raise _no_free_slug("organization", name)try:- tenant = await _create_tenant(client_lifecycle, organization.id, workspace_name)+ tenant = await _create_tenant(+ client_lifecycle, organization.id, workspace_name, workspace_slugs+ )except BaseException:# A failure after the workspace committed leaves it referencing the# organization, and the discard is refused; the workspace's own@@ -314,7 +312,7 @@ async def create_workspace(an organization does for its first workspace, so it stays theirs if theystop being `org_admin`."""- tenant = await _create_tenant(client_lifecycle, organization_id, name)+ tenant = await _create_tenant(client_lifecycle, organization_id, name, _slugs(name))await _add_creator(session_factory,user_store,@@ -333,9 +331,12 @@ async def create_workspace(async def _create_tenant(- client_lifecycle: ClientLifecycleService, organization_id: str, name: str+ client_lifecycle: ClientLifecycleService,+ organization_id: str,+ name: str,+ slugs: list[str],) -> Tenant:- for slug in _slugs(name):+ for slug in slugs:try:return await client_lifecycle.create_tenant(name, slug, organization_id)except TenantSlugTaken:diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex ccdf74feb..7e39f5191 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -575,6 +575,27 @@ class TestCreatingAnOrganization:assert response.status_code == 201, response.textassert response.json()["workspace"]["name"] == "Globex"+ async def test_an_unusable_workspace_name_is_refused_before_anything_is_written(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada = await _user(session_factory, "user")+ name = _name("Nameless")++ async with _client(_app(session_factory), ada, None) as client:+ response = await client.post(+ "/organizations", json={"name": name, "workspace_name": "!!!"}+ )++ assert response.status_code == 400+ async with session_factory() as session:+ assert (+ await session.scalar(+ select(Organization).where(Organization.name == name)+ )+ is None+ )+ assert await _workspaces_created(session_factory, ada) == 0+async def test_invite_only_sign_up_refuses_it(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -696,6 +717,30 @@ class TestListingOrganizationsAndWorkspaces:assert as_member.status_code == 200, as_member.textassert [row["id"] for row in as_member.json()] == [tenant_id]+ async def test_the_platform_operator_sees_every_workspace_of_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """There on the operator flag alone, the operator may enter every+ workspace of the organization, and is shown each as its admin."""+ ada = _name("ada")+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})+ app = _app(session_factory)+ async with _client(app, ada, tenant_id) as client:+ created = await client.post(+ "/organizations/current/workspaces", json={"name": "Second"}+ )+ assert created.status_code == 201, created.text+ operator = await _operator(session_factory)++ async with _client(app, operator, tenant_id) as client:+ response = await client.get("/organizations/current/workspaces")++ assert response.status_code == 200, response.text+ assert {(row["id"], row["role"]) for row in response.json()} == {+ (tenant_id, "admin"),+ (created.json()["id"], "admin"),+ }+async def test_the_caller_sees_each_of_their_organizations_once(self, session_factory: async_sessionmaker[AsyncSession]) -> None:diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.pyindex a819179c7..23a3a1248 100644--- a/core/tests/switch_core/gateway/test_tenant_resolution.py+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py@@ -49,7 +49,13 @@ from sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_enginefrom switch_core.db.engine import create_session_factory-from switch_core.db.models import TENANT_ZERO_ID, Tenant, TenantMember, User+from switch_core.db.models import (+ TENANT_ZERO_ID,+ OrganizationMember,+ Tenant,+ TenantMember,+ User,+)from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway import auth as gw_authfrom switch_core.gateway import dependencies as gw_deps@@ -476,6 +482,60 @@ class TestSessionStateEndpoint:assert body["tenants"] == []assert body["can_create_workspace"] is True+ async def test_invite_only_still_lets_an_org_admin_add_a_workspace(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`invite_only` refuses new organizations, not a workspace an+ `org_admin` adds to theirs, and the session state says both."""+ admin_id = await _make_user(+ session_factory, name="org-admin", tenant_id=TENANT_ZERO_ID+ )+ member_id = await _make_user(+ session_factory, name="plain-member", tenant_id=TENANT_ZERO_ID+ )+ async with session_factory() as session:+ for user_id, role in ((admin_id, "org_admin"), (member_id, "member")):+ member = await session.get(+ OrganizationMember, (TENANT_ZERO_ID, user_id)+ )+ if member is None:+ session.add(+ OrganizationMember(+ organization_id=TENANT_ZERO_ID, user_id=user_id, role=role+ )+ )+ else:+ member.role = role+ await session.commit()++ as_admin = (+ await self._get(+ session_factory,+ create_jwt(+ admin_id, "[email protected]", "user", _KEYRING, TENANT_ZERO_ID+ ),+ signup_mode="invite_only",+ )+ ).json()+ as_member = (+ await self._get(+ session_factory,+ create_jwt(+ member_id, "[email protected]", "user", _KEYRING, TENANT_ZERO_ID+ ),+ signup_mode="invite_only",+ )+ ).json()++ assert (as_admin["can_create_workspace"], as_admin["can_add_workspace"]) == (+ False,+ True,+ )+ assert (+ as_member["can_create_workspace"],+ as_member["can_add_workspace"],+ ) == (False, False)+async def test_invite_only_offers_no_workspace_creation(self, session_factory: async_sessionmaker[AsyncSession]) -> None: