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] Create organizations and the workspaces in them

Petr Bauch9256d028703f
diff --git a/console/tooling-e2e/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.ts
index 775aac93a..4b8eac4b6 100644
--- a/console/tooling-e2e/src/clients/switch-client.ts
+++ b/console/tooling-e2e/src/clients/switch-client.ts
@@ -222,6 +222,22 @@ interface SwitchRequest {
timeoutMs?: number;
}
+export interface OrganizationSummary {
+ id: string;
+ slug: string;
+ name: string;
+ role: string;
+}
+
+export interface WorkspaceMembership {
+ id: string;
+ slug: string;
+ name: string;
+ role: string;
+ organization_role: string | null;
+ organization_id: string | null;
+}
+
export class SwitchClient {
private readonly apiUrl: string;
/** The deployment-wide registration key; agents it registers belong to a bootstrap account. */
@@ -452,6 +468,59 @@ export class SwitchClient {
return (parsed as { id: string }).id;
}
+ /**
+ * `POST /gateway/organizations` — create an organization with its first
+ * workspace. The caller becomes its organization admin and the workspace's
+ * owner, and the server re-mints their session into the workspace, so from
+ * here on this client acts there.
+ */
+ async createOrganization(name: string): Promise<{
+ organization: OrganizationSummary;
+ workspace: WorkspaceMembership;
+ }> {
+ const { parsed, response } = await this.rawRequest(
+ "POST",
+ "/gateway/organizations",
+ {
+ cookie: await this.gatewayLogin(),
+ body: { name },
+ },
+ );
+ const cookie = sessionCookieFrom(response);
+ if (!cookie)
+ throw new Error(
+ "Creating an organization returned no switch_auth cookie for its workspace.",
+ );
+ this.issued.record(cookie.slice("switch_auth=".length));
+ this.gatewayCookie = cookie;
+ return parsed as {
+ organization: OrganizationSummary;
+ workspace: WorkspaceMembership;
+ };
+ }
+
+ /** `GET /gateway/organizations` — the caller's organizations and their role in each. */
+ async organizations(): Promise<OrganizationSummary[]> {
+ return this.gateway<OrganizationSummary[]>("GET", "/organizations");
+ }
+
+ /** `GET /gateway/organizations/current/workspaces` — the current organization's workspaces the caller may enter. */
+ async organizationWorkspaces(): Promise<WorkspaceMembership[]> {
+ return this.gateway<WorkspaceMembership[]>(
+ "GET",
+ "/organizations/current/workspaces",
+ );
+ }
+
+ /** `POST /gateway/organizations/current/workspaces` — add a workspace to the current organization; the session stays put. */
+ async createOrganizationWorkspace(name: string): Promise<WorkspaceMembership> {
+ return this.gateway<WorkspaceMembership>(
+ "POST",
+ "/organizations/current/workspaces",
+ { name },
+ );
+ }
+
/** `POST /gateway/agents/register` — an agent owned by the signed-in user, in their current workspace. */
async registerAgentAsUser(params: {
name: string;
diff --git a/console/tooling-e2e/src/fast/index.ts b/console/tooling-e2e/src/fast/index.ts
index 0db013a10..5fc41a473 100644
--- a/console/tooling-e2e/src/fast/index.ts
+++ b/console/tooling-e2e/src/fast/index.ts
@@ -6,6 +6,7 @@ import { addressedDelivery, unaddressedHistory } from "./agent-messaging.ts";
import { mattermostRoundtrip } from "./mattermost-roundtrip.ts";
import { operationsFrontDoor } from "./operations.ts";
import { organizationMembers } from "./organization-members.ts";
+import { organizations } from "./organizations.ts";
import { roomCapture } from "./room-capture.ts";
import { roomGroupPaths } from "./room-groups.ts";
import type { FastScenario } from "./scenario.ts";
@@ -23,4 +24,5 @@ export const FAST_SCENARIOS: readonly FastScenario[] = [
roomCapture,
followUps,
organizationMembers,
+ organizations,
];
diff --git a/console/tooling-e2e/src/fast/organizations.ts b/console/tooling-e2e/src/fast/organizations.ts
new file mode 100644
index 000000000..2ab11739f
--- /dev/null
+++ b/console/tooling-e2e/src/fast/organizations.ts
@@ -0,0 +1,80 @@
+import { expect } from 'vitest';
+import { SwitchHttpError } from '../clients/switch-client.ts';
+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.
+ *
+ * Users and workspaces cannot be deleted, so this runs only on a stack thrown
+ * away after the run.
+ */
+export const organizations: FastScenario = {
+ header: {
+ id: 'organizations',
+ covers: [
+ 'GET /gateway/organizations',
+ 'POST /gateway/organizations',
+ 'GET /gateway/organizations/current/workspaces',
+ 'POST /gateway/organizations/current/workspaces',
+ ],
+ lane: 'fast',
+ environments: ['ephemeral'],
+ owner: 'platform',
+ requires: [],
+ },
+ async run({ names, switchClient }) {
+ const password = `e2e-${names.runId}-${crypto.randomUUID()}`;
+ const founderEmail = `${names.name('founder')}@e2e.invalid`;
+ const memberEmail = `${names.name('member')}@e2e.invalid`;
+ await switchClient.createUser({
+ name: 'E2E founder',
+ email: founderEmail,
+ password,
+ role: 'user',
+ });
+ await switchClient.createUser({
+ name: 'E2E member',
+ email: memberEmail,
+ password,
+ role: 'user',
+ });
+ const founder = switchClient.as(founderEmail, password);
+ const member = switchClient.as(memberEmail, password);
+ // Signing in joins the default workspace, and so its organization.
+ const defaultWorkspace = await founder.tenantId();
+ await member.tenantId();
+
+ try {
+ await member.createOrganizationWorkspace(names.name('not-theirs'));
+ throw new Error('a member added a workspace to the organization');
+ } catch (error) {
+ if (!(error instanceof SwitchHttpError)) throw error;
+ expect(error.status, 'a member adding a workspace').toBe(403);
+ }
+
+ const { organization, workspace } = await founder.createOrganization(names.name('org'));
+ expect(organization.role).toBe('org_admin');
+ expect(workspace).toMatchObject({
+ role: 'owner',
+ organization_role: 'org_admin',
+ organization_id: organization.id,
+ });
+ expect(await founder.tenantId(), 'switched into the first workspace').toBe(workspace.id);
+
+ const second = await founder.createOrganizationWorkspace(names.name('second'));
+ expect(second.organization_id).toBe(organization.id);
+ expect(await founder.tenantId(), 'still in the first workspace').toBe(workspace.id);
+
+ const workspaces = await founder.organizationWorkspaces();
+ expect(workspaces.map((row) => row.id).sort()).toEqual([workspace.id, second.id].sort());
+ expect(workspaces.map((row) => row.id)).not.toContain(defaultWorkspace);
+
+ 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);
+ },
+};
diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.json
index cf8bb3620..dd10274ac 100644
--- a/console/tooling-e2e/surface/server-surface.json
+++ b/console/tooling-e2e/surface/server-surface.json
@@ -591,11 +591,21 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "GET /gateway/organizations",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "GET /gateway/organizations/current/members",
"auth": "session",
"flags": []
},
+ {
+ "route": "GET /gateway/organizations/current/workspaces",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "GET /gateway/packages",
"auth": "session",
@@ -1144,6 +1154,16 @@
"auth": "session",
"flags": []
},
+ {
+ "route": "POST /gateway/organizations",
+ "auth": "session",
+ "flags": []
+ },
+ {
+ "route": "POST /gateway/organizations/current/workspaces",
+ "auth": "session",
+ "flags": []
+ },
{
"route": "POST /gateway/packages",
"auth": "session",
diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.py
index f28c7377f..f44da3b18 100644
--- a/core/switch_core/clients/client_lifecycle_service.py
+++ b/core/switch_core/clients/client_lifecycle_service.py
@@ -240,7 +240,7 @@ class ClientLifecycleService:
nothing to repair that short of the next boot.
This is now the one seam a tenant comes into existence through, so
- that whatever offers tenant creation — `POST /tenants` today — has a
+ that whatever offers tenant creation — `POST /organizations` and `POST /organizations/current/workspaces` today — has a
single place to call rather than a row to insert and a checklist to
remember. Whether a caller is *allowed* to create one is decided
before this, at the route: this call provisions, it does not
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 8fcb890b8..d68e3e6cf 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -366,8 +366,8 @@ class SwitchConfig(BaseSettings):
"default_tenant"
)
- # How many workspaces one person may own here. 0 turns `POST /tenants` into
- # a 403 outright, so this single value is both the cap and the gate.
+ # How many workspaces one person may create here. 0 turns creating one
+ # into a 403 outright, so this single value is both the cap and the gate.
#
# It exists because workspace creation is an amplification vector rather
# than just a row: `all_tenant_ids()` drives a fan-out per tenant at boot
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 14fd49605..dd45e191f 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -294,8 +294,8 @@ async def get_authenticated_caller(
"""Like `get_authenticated_user_id`, but with the whole `users` row's worth
of the caller that routes with no tenant bound actually need.
- Backs `POST /invitations/accept` and `POST /tenants`
- (`gateway/tenants.py`): the first checks an email-bound invitation against
+ Backs `POST /invitations/accept` (`gateway/tenants.py`) and
+ `POST /organizations` (`gateway/organizations.py`): the first checks an email-bound invitation against
the caller's *current* address, the second asks whether the caller runs the
deployment. Both decide before any tenant is bound — the same "no tenant
chosen yet" shape as `get_authenticated_user_id` — and both read the same
@@ -503,6 +503,7 @@ async def _describe_memberships(
name=tenant.name,
role=role,
organization_role=organization_role,
+ organization_id=tenant.organization_id,
)
)
return memberships
@@ -553,20 +554,26 @@ async def initial_tenant_claim(
def workspace_creation_refusal(
- config: SwitchConfig, *, is_operator: bool, workspaces_created: int
+ config: SwitchConfig,
+ *,
+ is_operator: bool,
+ workspaces_created: int,
+ new_organization: bool,
) -> str | None:
"""Why this caller may not create a workspace, or None if they may.
- Operators always may. Otherwise `invite_only` sign-up refuses outright,
- and every other mode allows `gateway_max_workspaces_per_user` creations
- over a person's lifetime — each workspace is work for every per-tenant
- sweep (`docs/old/multi-tenancy-phase2-tenants.md`, §5). Returned as a
- message rather than raised so `GET /auth/session` can report the same
- answer `POST /tenants` enforces.
+ Operators always may. Otherwise every mode allows
+ `gateway_max_workspaces_per_user` creations over a person's lifetime —
+ each workspace is work for every per-tenant sweep
+ (`docs/old/multi-tenancy-phase2-tenants.md`, §5) — and `invite_only`
+ sign-up refuses a `new_organization` outright. It decides who comes onto
+ the server, not what an organization's `org_admin` adds to theirs.
+ Returned as a message rather than raised so `GET /auth/session` can report
+ the same answer `POST /organizations` enforces.
"""
if is_operator:
return None
- if config.gateway_signup_mode == "invite_only":
+ if new_organization and config.gateway_signup_mode == "invite_only":
return (
"Creating workspaces is turned off on this server. Ask a "
"workspace admin for an invitation."
@@ -594,7 +601,7 @@ def describe_session_state(
Follows its order exactly — a claim is honoured only if it names one of
`tenants`, and a bad claim is *not* rescued by a sole membership — so a
client told "ready" is never refused by the next request, and one told
- otherwise knows which of `/tenants/{id}/switch`, `POST /tenants` or
+ otherwise knows which of `/tenants/{id}/switch`, `POST /organizations` or
`/invitations/accept` gets it unstuck.
"""
tenant: TenantMembershipResponse | None = None
@@ -619,12 +626,13 @@ 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 /tenants` would refuse any name.
+ # 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,
invite_email_enabled=config.invite_email_enabled,
diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.py
index 7e7c338a8..e6d4f634f 100644
--- a/core/switch_core/gateway/organizations.py
+++ b/core/switch_core/gateway/organizations.py
@@ -1,39 +1,74 @@
-"""The organization above the bound workspace: its members and their roles.
-
-Every route acts on the organization the request's workspace belongs to
-(`current`), which the policy on `organization_members` derives from the bound
-workspace, and only its `org_admin`s may use them. The one exception is an
-organization with no `org_admin` left: the platform operator may list its
-members and make one of them `org_admin`, and being there on the operator
-flag alone, does so on `platform_access`, recorded as every operator write
-is (`gateway/auth.py`). Creating organizations and workspaces in them comes
-later; see `docs/design/organizations-v1.md`.
+"""Organizations: creating them, their workspaces, and their members.
+
+`GET` and `POST /organizations` need no workspace: they list the caller's
+organizations and create a new one. Every other route acts on the
+organization the request's workspace belongs to (`current`), which the policy
+on `organization_members` derives from the bound workspace. Its workspaces
+are listed to anyone in it; creating a workspace and managing members is for
+its `org_admin`s. The one exception is an organization with no `org_admin`
+left: the platform operator may list its members and make one of them
+`org_admin`, and being there on the operator flag alone, does so on
+`platform_access`, recorded as every operator write is (`gateway/auth.py`).
+See `docs/design/organizations-v1.md`.
"""
from __future__ import annotations
+import logging
+from collections import defaultdict
from typing import Annotated
-from fastapi import APIRouter, Depends, HTTPException
+from fastapi import APIRouter, Depends, HTTPException, Response
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.authz import ORGANIZATION_ADMIN_ROLE
+from switch_core.clients.client_lifecycle_service import ClientLifecycleService
+from switch_core.config import SwitchConfig
from switch_core.db.audit import AuditAction, record_audit_event
-from switch_core.db.models import OrganizationMember, Tenant, User, require_tenant_id
+from switch_core.db.models import (
+ Organization,
+ OrganizationMember,
+ Tenant,
+ User,
+ require_tenant_id,
+)
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.organization_store import OrganizationStore
from switch_core.db.stores.user_store import UserStore
-from switch_core.gateway.auth import get_current_user, workspaces_in_organization
+from switch_core.gateway.auth import (
+ AuthenticatedCaller,
+ get_authenticated_caller,
+ get_authenticated_user_id,
+ get_current_user,
+ list_tenant_memberships,
+ workspaces_in_organization,
+)
from switch_core.gateway.dependencies import (
+ get_client_lifecycle,
+ get_config,
get_organization_store,
get_session,
get_session_factory,
+ get_system_session,
get_user_store,
)
from switch_core.gateway.schemas import (
+ OrganizationCreateRequest,
+ OrganizationCreateResponse,
OrganizationMemberDetail,
OrganizationMemberUpdateRequest,
+ OrganizationSummary,
+ TenantMembershipResponse,
+ WorkspaceCreateRequest,
)
+from switch_core.gateway.workspace_creation import (
+ create_organization_for,
+ create_workspace,
+ lock_workspace_allowance,
+)
+
+logger = logging.getLogger(__name__)
router = APIRouter()
@@ -48,6 +83,16 @@ def _member_detail(user: User, member: OrganizationMember) -> OrganizationMember
)
+async def _current_organization_id(session: AsyncSession) -> str:
+ """The bound workspace's organization id; 404 when it belongs to none."""
+ tenant = await session.get(Tenant, require_tenant_id())
+ if tenant is None or tenant.organization_id is None:
+ raise HTTPException(
+ status_code=404, detail="This workspace belongs to no organization"
+ )
+ return tenant.organization_id
+
+
async def _require_organization_admin(
session: AsyncSession,
user_store: UserStore,
@@ -62,28 +107,195 @@ async def _require_organization_admin(
With `operator_restores`, the platform operator passes too while the
organization has no `org_admin`, so that someone can be made one.
"""
- tenant_id = require_tenant_id()
- tenant = await session.get(Tenant, tenant_id)
- if tenant is None or tenant.organization_id is None:
- raise HTTPException(
- status_code=404, detail="This workspace belongs to no organization"
- )
+ organization_id = await _current_organization_id(session)
if (
- await user_store.organization_role(session, tenant_id, user.id)
+ await user_store.organization_role(session, require_tenant_id(), user.id)
== ORGANIZATION_ADMIN_ROLE
):
- return tenant.organization_id
+ return organization_id
if (
operator_restores
and user.role == "admin"
- and await organization_store.count_admins(session, tenant.organization_id) == 0
+ and await organization_store.count_admins(session, organization_id) == 0
):
- return tenant.organization_id
+ return organization_id
raise HTTPException(
status_code=403, detail="Only an organization admin may do this"
)
[email protected]("/organizations")
+async def list_organizations(
+ user_id: Annotated[str, Depends(get_authenticated_user_id)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+) -> list[OrganizationSummary]:
+ """The organizations of the workspaces the caller may enter, and their
+ role 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.
+ """
+ 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))
+
+
[email protected]("/organizations", status_code=201)
+async def create_organization(
+ req: OrganizationCreateRequest,
+ response: Response,
+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],
+ session: Annotated[AsyncSession, Depends(get_system_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> OrganizationCreateResponse:
+ """Create an organization with its first workspace. The caller becomes the
+ organization's `org_admin` and the workspace's `owner`, and their session
+ switches into the workspace.
+
+ Anyone signed in may, as `workspace_creation_refusal` decides: sign-up
+ mode, and a per-person cap on workspaces created, with the platform
+ operator exempt. Authenticated with `get_authenticated_caller`, because
+ the caller who most needs this, someone who has just signed up, has no
+ workspace for `get_current_user` to bind.
+ """
+ return await create_organization_for(
+ response,
+ caller,
+ session,
+ session_factory,
+ user_store,
+ organization_store,
+ client_lifecycle,
+ config,
+ name=req.name,
+ workspace_name=req.workspace_name or req.name,
+ )
+
+
[email protected]("/organizations/current/workspaces")
+async def list_organization_workspaces(
+ session: Annotated[AsyncSession, Depends(get_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ 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."""
+ 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
+ ]
+
+
[email protected]("/organizations/current/workspaces", status_code=201)
+async def create_organization_workspace(
+ req: WorkspaceCreateRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],
+ client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> TenantMembershipResponse:
+ """Add a workspace to the organization. `org_admin` only; the creator
+ becomes its `owner`. The session stays where it is: an `org_admin` adds
+ workspaces for others as often as for themselves.
+
+ Counts against the creator's allowance as every workspace does, and is
+ refused where the deployment allows none, but not by `invite_only`
+ sign-up, which governs who comes onto the server rather than what an
+ organization adds. The platform operator is exempt, as everywhere.
+ """
+ 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(
+ 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
+ await session.commit()
+ return TenantMembershipResponse(
+ id=tenant.id,
+ slug=tenant.slug,
+ name=tenant.name,
+ role="owner",
+ organization_role=ORGANIZATION_ADMIN_ROLE,
+ organization_id=organization_id,
+ )
+
+
@router.get("/organizations/current/members")
async def list_organization_members(
session: Annotated[AsyncSession, Depends(get_session)],
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 4fb139bbd..ce01f084f 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -911,6 +911,9 @@ class TenantMembershipResponse(BaseModel):
# or not.
role: str
organization_role: str | None
+ # None only for a workspace from before organizations that no migration
+ # has given one yet.
+ organization_id: str | None
class OperatorWorkspaceResponse(BaseModel):
@@ -934,6 +937,33 @@ class TenantCreateRequest(BaseModel):
name: str
+class OrganizationCreateRequest(BaseModel):
+ name: str
+ # The first workspace's name; the organization's when left out.
+ workspace_name: str | None = None
+
+
+class OrganizationSummary(BaseModel):
+ """One organization the caller belongs to, and their role in it."""
+
+ id: str
+ slug: str
+ name: str
+ role: str
+
+
+class OrganizationCreateResponse(BaseModel):
+ """A new organization and its first workspace, which the session is now
+ bound to."""
+
+ organization: OrganizationSummary
+ workspace: TenantMembershipResponse
+
+
+class WorkspaceCreateRequest(BaseModel):
+ name: str
+
+
class SessionStateUser(BaseModel):
id: str
name: str
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index bcd44a86b..450969008 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -2,25 +2,18 @@ from __future__ import annotations
import hashlib
import logging
-import re
-import secrets
-import uuid
from datetime import UTC, datetime, timedelta
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import JSONResponse
-from sqlalchemy import select
-from sqlalchemy.exc import DBAPIError, IntegrityError
+from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.authz import ORGANIZATION_ADMIN_ROLE, ORGANIZATION_ADMIN_TENANT_ROLE
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.agent.registration_bootstrap import is_bootstrap_owner
-from switch_core.clients.client_lifecycle_service import (
- ClientLifecycleService,
- TenantIsolationNotInForce,
-)
+from switch_core.clients.client_lifecycle_service import ClientLifecycleService
from switch_core.config import SwitchConfig
from switch_core.connections.broker import (
ServiceBroker,
@@ -30,7 +23,6 @@ from switch_core.connections.broker import (
from switch_core.db.audit import AuditAction, list_audit_events, record_audit_event
from switch_core.db.models import (
Invitation,
- Organization,
OrganizationMember,
Tenant,
TenantJoinDomain,
@@ -38,7 +30,7 @@ from switch_core.db.models import (
User,
require_tenant_id,
)
-from switch_core.db.session_scope import organization_session, tenant_session
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.budget_store import (
@@ -55,11 +47,7 @@ from switch_core.db.stores.join_domain_store import (
JoinDomainNotFound,
JoinDomainStore,
)
-from switch_core.db.stores.organization_store import (
- OrganizationSlugTaken,
- OrganizationStore,
-)
-from switch_core.db.stores.tenant_store import TenantSlugTaken
+from switch_core.db.stores.organization_store import OrganizationStore
from switch_core.db.stores.usage_store import UsageStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.auth import (
@@ -78,7 +66,6 @@ from switch_core.gateway.auth import (
tenant_of_invitation_token,
tenants_open_to,
tenants_with_invitations_for,
- workspace_creation_refusal,
)
from switch_core.gateway.auth_routes import _session_response
from switch_core.gateway.dependencies import (
@@ -131,6 +118,7 @@ from switch_core.gateway.schemas import (
UsageTotalResponse,
)
from switch_core.gateway.service_connections import service_refusal
+from switch_core.gateway.workspace_creation import create_organization_for
from switch_core.telemetry import emit_safely
from switch_core.telemetry.ages import age_hours
from switch_core.tenant_context import current_tenant_id
@@ -142,30 +130,6 @@ router = APIRouter()
TENANT_MEMBER_ROLES = ("owner", "admin", "member")
-_SLUG_INVALID_CHARS = re.compile(r"[^a-z0-9]+")
-
-# A first choice and this many suffixed ones. Four hex characters make a
-# repeat collision on the same name vanishingly unlikely, so running out means
-# something other than bad luck is wrong.
-_SLUG_ATTEMPTS = 4
-
-
-def _derive_slug(name: str) -> str:
- """A URL-safe slug from a workspace name.
-
- The slug is an identifier, not the name: the workspace keeps the name its
- creator typed exactly, and a slug that is already taken gets a short
- random suffix (`_provision_workspace` below). Refusing instead would tell anyone
- who can sign up which workspace names exist on this server.
- """
- slug = _SLUG_INVALID_CHARS.sub("-", name.strip().lower()).strip("-")
- if not slug:
- raise HTTPException(
- status_code=400,
- detail="Name must contain at least one letter or digit",
- )
- return slug
-
def _require_bound_tenant(tenant_id: str) -> None:
"""Raise 403 unless `tenant_id` names the tenant this request is bound to.
@@ -338,171 +302,12 @@ async def current_tenant(
organization_role=await user_store.organization_role(
session, tenant_id, user.id
),
+ organization_id=tenant.organization_id,
administers=is_admin,
)
-_LOCK_NOT_AVAILABLE = "55P03"
-
-
-async def _lock_workspace_allowance(
- session: AsyncSession, caller: AuthenticatedCaller, config: SwitchConfig
-) -> User:
- """Lock the caller's row and raise 403 unless they may create one more
- workspace. Returns the locked row, for the caller to count the creation on.
-
- Creating a workspace is not just a row: `all_tenant_ids()` drives a fan-out
- per tenant at boot and a sweep every few seconds, so unbounded creation
- buys the deployment steady-state work
- (`docs/old/multi-tenancy-phase2-tenants.md`, §5). A limit of 0 closes the
- route entirely, which is how a deployment that is not ready to offer
- self-service says so; so does `invite_only` sign-up. What is refused, and
- why, is `workspace_creation_refusal`'s, so `GET /auth/session` reports the
- same answer this enforces.
-
- The bound is on workspaces created (`users.workspaces_created`), not on
- workspaces owned: ownership can be handed to another account, so a count of
- ownership could be reset by creating, handing over and stepping down, over
- and over. An invitation into someone else's workspace spends nothing.
-
- The row lock is what makes the check hold under concurrent requests. It
- is taken `NOWAIT`, so a second request from the same person is refused
- with 409 at once rather than holding a pool connection while it waits —
- the request holding the lock needs more connections to provision, and a
- burst of waiters could starve it of them. `FOR NO KEY UPDATE` rather than
- `FOR UPDATE`, because the new owner membership's foreign key takes a key
- share on this same row from another session, and `FOR UPDATE` would make
- the request wait on itself.
- """
- try:
- user = await session.scalar(
- select(User)
- .where(User.id == caller.id)
- .with_for_update(key_share=True, nowait=True)
- )
- except DBAPIError as exc:
- if getattr(exc.orig, "sqlstate", None) != _LOCK_NOT_AVAILABLE:
- raise
- raise HTTPException(
- status_code=409,
- detail="Another workspace is being created for you; try again shortly",
- ) from exc
- if user is None:
- raise HTTPException(status_code=401, detail="Unknown user")
- refusal = workspace_creation_refusal(
- config, is_operator=False, workspaces_created=user.workspaces_created
- )
- if refusal is not None:
- raise HTTPException(status_code=403, detail=refusal)
- return user
-
-
-async def _provision_workspace(
- session_factory: async_sessionmaker[AsyncSession],
- user_store: UserStore,
- organization_store: OrganizationStore,
- client_lifecycle: ClientLifecycleService,
- caller: AuthenticatedCaller,
- name: str,
-) -> Tenant:
- base_slug = _derive_slug(name)
- tenant: Tenant | None = None
- for attempt in range(_SLUG_ATTEMPTS):
- slug = base_slug if attempt == 0 else f"{base_slug}-{secrets.token_hex(2)}"
- organization = Organization(id=str(uuid.uuid4()), name=name, slug=slug)
- try:
- async with organization_session(
- session_factory, organization.id
- ) as session:
- await organization_store.create(session, organization)
- await session.commit()
- except OrganizationSlugTaken:
- continue
- try:
- tenant = await client_lifecycle.create_tenant(name, slug, organization.id)
- except TenantSlugTaken:
- await _discard_organization(
- session_factory, organization_store, organization.id
- )
- continue
- except TenantIsolationNotInForce as exc:
- await _discard_organization(
- 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(
- "Could not find a free slug for workspace %r after %d attempts",
- name,
- _SLUG_ATTEMPTS,
- )
- raise HTTPException(
- status_code=503,
- detail="Could not create the workspace; please try again",
- )
-
- try:
- async with tenant_session(session_factory, tenant.id) as session:
- await user_store.add_membership(
- session,
- tenant_id=tenant.id,
- user_id=caller.id,
- role="owner",
- organization_role="org_admin",
- )
- await record_audit_event(
- session,
- tenant_id=tenant.id,
- actor_user_id=caller.id,
- action=AuditAction.TENANT_CREATED,
- target_type="tenant",
- target_id=tenant.id,
- details={"name": tenant.name, "slug": tenant.slug},
- )
- await session.commit()
- except Exception:
- logger.error(
- "Workspace %s (slug %s) was created but its owner membership for "
- "user %s was not written: it now has no members and its slug is "
- "taken. Insert the membership to repair it.",
- tenant.id,
- slug,
- caller.id,
- )
- raise
- return tenant
-
-
-async def _discard_organization(
- session_factory: async_sessionmaker[AsyncSession],
- organization_store: OrganizationStore,
- organization_id: str,
-) -> None:
- """Delete the organization made for a workspace that could not be created."""
- async with organization_session(session_factory, organization_id) as session:
- await organization_store.delete_empty(session, organization_id)
- await session.commit()
-
-
[email protected]("/tenants", status_code=201)
[email protected]("/tenants", status_code=201, deprecated=True)
async def create_tenant(
req: TenantCreateRequest,
response: Response,
@@ -516,83 +321,24 @@ async def create_tenant(
client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> TenantMembershipResponse:
- """Create a workspace. The caller becomes its `owner`, and their session
- switches into it.
-
- The workspace comes with an organization of its own, of the same name,
- whose `org_admin` the caller becomes.
-
- Whether they may is `workspace_creation_refusal`'s decision: sign-up mode
- and a per-person cap on workspaces created, with operators exempt. It is
- authenticated with `get_authenticated_caller` because the caller who
- most needs this — someone who has just signed up — has no workspace for
- `get_current_user` to bind.
-
- How many workspaces one person may create is bounded, and the bound is
- checked before anything is provisioned — see `_lock_workspace_allowance`.
- Deployment operators are exempt, both because the bypass is what
- `is_operator` means everywhere else in this codebase (`authz.py`) and
- because the person provisioning workspaces for other people is the one
- caller a self-service bound must not stop; nothing is counted for them. This
- is the only route in this file with no tenant to authorize against, so the
- limit is what stands in for the role check its neighbours have.
-
- Provisioning goes through `ClientLifecycleService.create_tenant` — "the
- one seam a tenant comes into existence through" — rather than inserting a
- `Tenant` row here, so a workspace created through this route gets the same
- admin client every other tenant does. The membership row is not part of
- that call (it provisions the tenant, not any particular person's place in
- it), so it is written here, in its own session bound to the new tenant.
-
- Two transactions, therefore, and the gap between them is real: the tenant
- is committed before the membership is attempted, so a failure in the
- second leaves a workspace nobody belongs to and a slug nobody can reuse.
- It is not folded into one because the tenant row has to be committed
- before `ensure_system_client` can provision against it, and that call is
- inside the seam. What the gap gets instead is a log line naming the
- workspace and the person who should have owned it, because the alternative
- — a 500 with the orphan unrecorded — is the silent degradation this
- codebase refuses. An operator repairs it by inserting the membership.
+ """`POST /organizations` under its old name, kept for one release for
+ clients that still call it: an organization and its first workspace, both
+ named `name`, with the caller switched into the workspace. Answers with the
+ workspace alone, as it always has.
"""
- if caller.is_operator:
- user = await user_store.get(session, caller.id)
- if user is None:
- raise HTTPException(status_code=401, detail="User not found")
- # Not held across provisioning, which opens a session per tenant.
- await session.commit()
- tenant = await _provision_workspace(
- session_factory,
- user_store,
- organization_store,
- client_lifecycle,
- caller,
- req.name,
- )
- else:
- user = await _lock_workspace_allowance(session, caller, config)
- tenant = await _provision_workspace(
- session_factory,
- user_store,
- organization_store,
- client_lifecycle,
- caller,
- req.name,
- )
- user.workspaces_created += 1
- await session.commit()
-
- await user_store.record_last_tenant(session, user, tenant.id)
- await session.commit()
- set_session_cookie(
- response, user, config.keyring, config.gateway_cookie_secure, tenant.id
- )
- return TenantMembershipResponse(
- id=tenant.id,
- slug=tenant.slug,
- name=tenant.name,
- role="owner",
- organization_role="org_admin",
+ created = await create_organization_for(
+ response,
+ caller,
+ session,
+ session_factory,
+ user_store,
+ organization_store,
+ client_lifecycle,
+ config,
+ name=req.name,
+ workspace_name=req.name,
)
+ return created.workspace
@router.post("/tenants/{tenant_id}/switch")
@@ -1159,6 +905,7 @@ async def _enter(
organization_role=await user_store.organization_role(
session, tenant_id, caller.id
),
+ organization_id=tenant.organization_id,
)
# `users` is global, so the caller's row is writable from a session
# bound to any tenant — this one included.
diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.py
new file mode 100644
index 000000000..4bedaf5a0
--- /dev/null
+++ b/core/switch_core/gateway/workspace_creation.py
@@ -0,0 +1,404 @@
+"""Creating organizations and the workspaces in them.
+
+Two routes create: `POST /organizations` makes an organization and its first
+workspace for anyone signed in, and `POST /organizations/current/workspaces`
+adds a workspace to an organization its `org_admin` is in. `POST /tenants` is
+the first of those under its old name, kept for one release. What they share
+is here: the per-person allowance, slugs, and the provisioning itself.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import secrets
+import uuid
+
+from fastapi import HTTPException, Response
+from sqlalchemy import select
+from sqlalchemy.exc import DBAPIError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.authz import ORGANIZATION_ADMIN_ROLE
+from switch_core.clients.client_lifecycle_service import (
+ ClientLifecycleService,
+ TenantIsolationNotInForce,
+)
+from switch_core.config import SwitchConfig
+from switch_core.db.audit import AuditAction, record_audit_event
+from switch_core.db.models import Organization, Tenant, User
+from switch_core.db.session_scope import organization_session, tenant_session
+from switch_core.db.stores.organization_store import (
+ OrganizationSlugTaken,
+ OrganizationStore,
+)
+from switch_core.db.stores.tenant_store import TenantSlugTaken
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway.auth import (
+ AuthenticatedCaller,
+ set_session_cookie,
+ workspace_creation_refusal,
+)
+from switch_core.gateway.schemas import (
+ OrganizationCreateResponse,
+ OrganizationSummary,
+ TenantMembershipResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_SLUG_INVALID_CHARS = re.compile(r"[^a-z0-9]+")
+
+# A first choice and this many suffixed ones. Four hex characters make a
+# repeat collision on the same name vanishingly unlikely, so running out means
+# something other than bad luck is wrong.
+_SLUG_ATTEMPTS = 4
+
+_LOCK_NOT_AVAILABLE = "55P03"
+
+
+def _derive_slug(name: str) -> str:
+ """A URL-safe slug from an organization's or workspace's name.
+
+ The slug is an identifier, not the name: the row keeps the name its
+ creator typed exactly, and a slug that is already taken gets a short
+ random suffix (`_slugs` below). Refusing instead would tell anyone who can
+ sign up which names exist on this server.
+ """
+ slug = _SLUG_INVALID_CHARS.sub("-", name.strip().lower()).strip("-")
+ if not slug:
+ raise HTTPException(
+ status_code=400,
+ detail="Name must contain at least one letter or digit",
+ )
+ return slug
+
+
+def _slugs(name: str) -> list[str]:
+ base = _derive_slug(name)
+ return [base] + [
+ f"{base}-{secrets.token_hex(2)}" for _ in range(_SLUG_ATTEMPTS - 1)
+ ]
+
+
+def _no_free_slug(kind: str, name: str) -> HTTPException:
+ logger.error(
+ "Could not find a free slug for %s %r after %d attempts",
+ kind,
+ name,
+ _SLUG_ATTEMPTS,
+ )
+ return HTTPException(
+ status_code=503, detail=f"Could not create the {kind}; please try again"
+ )
+
+
+async def lock_workspace_allowance(
+ session: AsyncSession,
+ user_id: str,
+ config: SwitchConfig,
+ *,
+ new_organization: bool,
+) -> User:
+ """Lock the caller's row and raise 403 unless they may create one more
+ workspace. Returns the locked row, for the caller to count the creation on.
+
+ Creating a workspace is not just a row: `all_tenant_ids()` drives a fan-out
+ per tenant at boot and a sweep every few seconds, so unbounded creation
+ buys the deployment steady-state work
+ (`docs/old/multi-tenancy-phase2-tenants.md`, §5). A limit of 0 closes
+ creation entirely, which is how a deployment that is not ready to offer
+ self-service says so; `invite_only` sign-up closes creating organizations.
+ What is refused, and why, is `workspace_creation_refusal`'s, so
+ `GET /auth/session` reports the same answer this enforces.
+
+ The bound is on workspaces created (`users.workspaces_created`), not on
+ workspaces owned: ownership can be handed to another account, so a count of
+ ownership could be reset by creating, handing over and stepping down, over
+ and over. An invitation into someone else's workspace spends nothing.
+
+ The row lock is what makes the check hold under concurrent requests. It
+ is taken `NOWAIT`, so a second request from the same person is refused
+ with 409 at once rather than holding a pool connection while it waits —
+ the request holding the lock needs more connections to provision, and a
+ burst of waiters could starve it of them. `FOR NO KEY UPDATE` rather than
+ `FOR UPDATE`, because the new owner membership's foreign key takes a key
+ share on this same row from another session, and `FOR UPDATE` would make
+ the request wait on itself.
+ """
+ try:
+ user = await session.scalar(
+ select(User)
+ .where(User.id == user_id)
+ .with_for_update(key_share=True, nowait=True)
+ # The row may already be loaded on this session, read before the
+ # lock was taken.
+ .execution_options(populate_existing=True)
+ )
+ except DBAPIError as exc:
+ if getattr(exc.orig, "sqlstate", None) != _LOCK_NOT_AVAILABLE:
+ raise
+ raise HTTPException(
+ status_code=409,
+ detail="Another workspace is being created for you; try again shortly",
+ ) from exc
+ if user is None:
+ raise HTTPException(status_code=401, detail="Unknown user")
+ refusal = workspace_creation_refusal(
+ config,
+ is_operator=False,
+ workspaces_created=user.workspaces_created,
+ new_organization=new_organization,
+ )
+ if refusal is not None:
+ raise HTTPException(status_code=403, detail=refusal)
+ return user
+
+
+async def create_organization_for(
+ response: Response,
+ caller: AuthenticatedCaller,
+ session: AsyncSession,
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ organization_store: OrganizationStore,
+ client_lifecycle: ClientLifecycleService,
+ config: SwitchConfig,
+ *,
+ name: str,
+ workspace_name: str,
+) -> OrganizationCreateResponse:
+ """Create an organization and its first workspace for `caller`, count it
+ against their allowance, and switch their session into the workspace.
+
+ `session` is unbound: it reads and locks the caller's `users` row, which
+ carries no tenant, for the length of a creation that has no tenant yet.
+ The platform operator is exempt from the allowance, both because the
+ bypass is what `is_operator` means everywhere else (`authz.py`) and
+ because the person provisioning for other people is the one caller a
+ self-service bound must not stop; nothing is counted for them.
+ """
+ if caller.is_operator:
+ user = await user_store.get(session, caller.id)
+ if user is None:
+ raise HTTPException(status_code=401, detail="User not found")
+ # 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(
+ 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
+ await session.commit()
+
+ await user_store.record_last_tenant(session, user, tenant.id)
+ await session.commit()
+ set_session_cookie(
+ response, user, config.keyring, config.gateway_cookie_secure, tenant.id
+ )
+ return OrganizationCreateResponse(
+ organization=OrganizationSummary(
+ id=organization.id,
+ slug=organization.slug,
+ name=organization.name,
+ role=ORGANIZATION_ADMIN_ROLE,
+ ),
+ workspace=TenantMembershipResponse(
+ id=tenant.id,
+ slug=tenant.slug,
+ name=tenant.name,
+ role="owner",
+ organization_role=ORGANIZATION_ADMIN_ROLE,
+ organization_id=organization.id,
+ ),
+ )
+
+
+async def create_organization(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ organization_store: OrganizationStore,
+ client_lifecycle: ClientLifecycleService,
+ creator_id: str,
+ name: str,
+ workspace_name: str,
+) -> tuple[Organization, Tenant]:
+ """Create an organization named `name` and its first workspace, named
+ `workspace_name`. `creator_id` becomes the organization's `org_admin` and
+ the workspace's `owner`, a member there in their own right.
+
+ The organization is committed first, because the workspace references it.
+ If the workspace then cannot be created, for any reason, the organization
+ is deleted again, so a failed creation leaves nothing behind.
+ """
+ organization: Organization | None = None
+ for slug in _slugs(name):
+ candidate = Organization(id=str(uuid.uuid4()), name=name, slug=slug)
+ try:
+ async with organization_session(session_factory, candidate.id) as session:
+ await organization_store.create(session, candidate)
+ await session.commit()
+ except OrganizationSlugTaken:
+ continue
+ organization = candidate
+ break
+ if organization is None:
+ raise _no_free_slug("organization", name)
+
+ try:
+ tenant = await _create_tenant(client_lifecycle, organization.id, workspace_name)
+ 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 its first "
+ "workspace %r failed",
+ organization.id,
+ workspace_name,
+ )
+ raise
+
+ await _add_creator(
+ session_factory,
+ user_store,
+ tenant,
+ creator_id,
+ organization_role=ORGANIZATION_ADMIN_ROLE,
+ details={
+ "name": tenant.name,
+ "slug": tenant.slug,
+ "organization_id": organization.id,
+ "organization_created": True,
+ },
+ )
+ return organization, tenant
+
+
+async def create_workspace(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ client_lifecycle: ClientLifecycleService,
+ organization_id: str,
+ creator_id: str,
+ name: str,
+) -> Tenant:
+ """Create a workspace named `name` in `organization_id`, with `creator_id`,
+ its `org_admin`, as its `owner`.
+
+ The creator administers it through the organization already; the
+ membership row makes them a member there in their own right, as creating
+ an organization does for its first workspace, so it stays theirs if they
+ stop being `org_admin`.
+ """
+ tenant = await _create_tenant(client_lifecycle, organization_id, name)
+ await _add_creator(
+ session_factory,
+ user_store,
+ tenant,
+ creator_id,
+ # Already the organization's `org_admin`, a row joining leaves as it is.
+ organization_role="member",
+ details={
+ "name": tenant.name,
+ "slug": tenant.slug,
+ "organization_id": organization_id,
+ "organization_created": False,
+ },
+ )
+ return tenant
+
+
+async def _create_tenant(
+ client_lifecycle: ClientLifecycleService, organization_id: str, name: str
+) -> Tenant:
+ for slug in _slugs(name):
+ try:
+ return await client_lifecycle.create_tenant(name, slug, organization_id)
+ except TenantSlugTaken:
+ continue
+ except TenantIsolationNotInForce as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ raise _no_free_slug("workspace", name)
+
+
+async def _add_creator(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ tenant: Tenant,
+ creator_id: str,
+ *,
+ organization_role: str,
+ details: dict[str, object],
+) -> None:
+ """Make `creator_id` the new workspace's `owner` and record its creation.
+
+ A transaction of its own, after the workspace's: the tenant row has to be
+ committed before `ensure_system_client` can provision against it, and that
+ happens inside `ClientLifecycleService.create_tenant`. The gap is real — a
+ failure here leaves a workspace nobody belongs to — so it is logged with
+ what an operator needs to repair it.
+ """
+ try:
+ async with tenant_session(session_factory, tenant.id) as session:
+ await user_store.add_membership(
+ session,
+ tenant_id=tenant.id,
+ user_id=creator_id,
+ role="owner",
+ organization_role=organization_role,
+ )
+ await record_audit_event(
+ session,
+ tenant_id=tenant.id,
+ actor_user_id=creator_id,
+ action=AuditAction.TENANT_CREATED,
+ target_type="tenant",
+ target_id=tenant.id,
+ details=details,
+ )
+ await session.commit()
+ except Exception:
+ logger.error(
+ "Workspace %s (slug %s) was created but its owner membership for "
+ "user %s was not written: it now has no members and its slug is "
+ "taken. Insert the membership to repair it.",
+ tenant.id,
+ tenant.slug,
+ creator_id,
+ )
+ raise
+
+
+async def _discard_organization(
+ session_factory: async_sessionmaker[AsyncSession],
+ organization_store: OrganizationStore,
+ organization_id: str,
+) -> None:
+ """Delete the organization made for a workspace that could not be created."""
+ async with organization_session(session_factory, organization_id) as session:
+ await organization_store.delete_empty(session, organization_id)
+ await session.commit()
diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.py
index bfb16c7ae..ccdf74feb 100644
--- a/core/tests/switch_core/gateway/test_organization_routes.py
+++ b/core/tests/switch_core/gateway/test_organization_routes.py
@@ -24,9 +24,10 @@ from switch_core.db.models import (
)
from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.organization_store import OrganizationStore
+from switch_core.db.stores.tenant_store import TenantStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway import dependencies as gw_deps
-from switch_core.gateway.auth import create_jwt
+from switch_core.gateway.auth import create_jwt, decode_jwt
from switch_core.gateway.organizations import router as organizations_router
from switch_core.gateway.tenants import router as tenants_router
from switch_core.keys import Keyring
@@ -36,7 +37,29 @@ _KEYRING = Keyring.parse(
)
-def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+class _FakeClientLifecycle:
+ """`ClientLifecycleService.create_tenant`'s database half, without the
+ admin client it provisions."""
+
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._session_factory = session_factory
+
+ async def create_tenant(self, name: str, slug: str, organization_id: str) -> Tenant:
+ tenant = Tenant(
+ id=str(uuid.uuid4()), name=name, slug=slug, organization_id=organization_id
+ )
+ async with tenant_session(self._session_factory, tenant.id) as session:
+ await TenantStore().create(session, tenant)
+ await session.commit()
+ return tenant
+
+
+def _app(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ signup_mode: str = "open",
+ max_workspaces_per_user: int = 3,
+) -> FastAPI:
async def _session_dep():
async with session_factory() as session:
yield session
@@ -51,10 +74,15 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
app.dependency_overrides[gw_deps.get_organization_store] = lambda: (
OrganizationStore()
)
+ app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: (
+ _FakeClientLifecycle(session_factory)
+ )
app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
keyring=_KEYRING,
gateway_cookie_secure=False,
gateway_tenant_choice_enabled=False,
+ gateway_signup_mode=signup_mode,
+ gateway_max_workspaces_per_user=max_workspaces_per_user,
)
return app
@@ -463,3 +491,231 @@ class TestThePlatformOperator:
assert refused.status_code == 403
[event] = await _events(session_factory, orphaned, AuditAction.PLATFORM_ACCESS)
assert event.details is not None and event.details["method"] == "PATCH"
+
+
+async def _user(session_factory: async_sessionmaker[AsyncSession], role: str) -> str:
+ user_id = _name("newcomer")
+ async with session_factory() as session:
+ session.add(
+ User(
+ id=user_id,
+ name=user_id,
+ email=f"{user_id}@example.invalid",
+ role=role,
+ )
+ )
+ await session.commit()
+ return user_id
+
+
+async def _organization_id(
+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str
+) -> str | None:
+ async with tenant_session(session_factory, tenant_id) as session:
+ tenant = await session.get(Tenant, tenant_id)
+ assert tenant is not None
+ return tenant.organization_id
+
+
+async def _workspaces_created(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str
+) -> int:
+ async with session_factory() as session:
+ user = await session.get(User, user_id)
+ assert user is not None
+ return user.workspaces_created
+
+
+class TestCreatingAnOrganization:
+ async def test_anyone_signed_in_creates_one_with_its_first_workspace(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = await _user(session_factory, "user")
+
+ async with _client(_app(session_factory), ada, None) as client:
+ response = await client.post(
+ "/organizations", json={"name": "Acme", "workspace_name": "Research"}
+ )
+
+ assert response.status_code == 201, response.text
+ body = response.json()
+ organization, workspace = body["organization"], body["workspace"]
+ assert (organization["name"], organization["slug"], organization["role"]) == (
+ "Acme",
+ "acme",
+ "org_admin",
+ )
+ assert (workspace["name"], workspace["role"]) == ("Research", "owner")
+ assert workspace["organization_id"] == organization["id"]
+ assert (
+ await _organization_id(session_factory, workspace["id"])
+ == (organization["id"])
+ )
+ token = response.cookies.get("switch_auth")
+ assert token is not None
+ assert decode_jwt(token, _KEYRING)["tenant_id"] == workspace["id"]
+ assert await _workspaces_created(session_factory, ada) == 1
+ async with tenant_session(session_factory, workspace["id"]) as session:
+ membership = await session.get(TenantMember, (workspace["id"], ada))
+ organization_member = await session.get(
+ OrganizationMember, (organization["id"], ada)
+ )
+ assert membership is not None and membership.role == "owner"
+ assert organization_member is not None
+ assert organization_member.role == "org_admin"
+
+ async def test_the_first_workspace_takes_the_organization_name_by_default(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = await _user(session_factory, "user")
+
+ async with _client(_app(session_factory), ada, None) as client:
+ response = await client.post("/organizations", json={"name": "Globex"})
+
+ assert response.status_code == 201, response.text
+ assert response.json()["workspace"]["name"] == "Globex"
+
+ async def test_invite_only_sign_up_refuses_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = await _user(session_factory, "user")
+
+ app = _app(session_factory, signup_mode="invite_only")
+ async with _client(app, ada, None) as client:
+ response = await client.post("/organizations", json={"name": "Initech"})
+
+ assert response.status_code == 403
+ assert await _workspaces_created(session_factory, ada) == 0
+
+
+class TestCreatingAWorkspace:
+ async def test_an_org_admin_adds_one_to_the_organization(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = _name("ada")
+ tenant_id = await _workspace(session_factory, {ada: ("member", "org_admin")})
+
+ async with _client(_app(session_factory), ada, tenant_id) as client:
+ response = await client.post(
+ "/organizations/current/workspaces", json={"name": "Second"}
+ )
+
+ assert response.status_code == 201, response.text
+ workspace = response.json()
+ organization_id = await _organization_id(session_factory, tenant_id)
+ assert workspace["organization_id"] == organization_id
+ assert await _organization_id(session_factory, workspace["id"]) == (
+ organization_id
+ )
+ assert workspace["role"] == "owner"
+ # The session stays in the workspace it was in.
+ assert response.cookies.get("switch_auth") is None
+ assert await _workspaces_created(session_factory, ada) == 1
+ [event] = await _events(
+ session_factory, workspace["id"], AuditAction.TENANT_CREATED
+ )
+ assert event.actor_user_id == ada
+ assert event.details is not None
+ assert event.details["organization_created"] is False
+ async with tenant_session(session_factory, workspace["id"]) as session:
+ membership = await session.get(TenantMember, (workspace["id"], ada))
+ assert membership is not None and membership.role == "owner"
+
+ async def test_a_workspace_admin_who_is_no_org_admin_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}
+ )
+
+ async with _client(_app(session_factory), bob, tenant_id) as client:
+ response = await client.post(
+ "/organizations/current/workspaces", json={"name": "Second"}
+ )
+
+ assert response.status_code == 403
+ assert await _workspaces_created(session_factory, bob) == 0
+
+ async def test_invite_only_sign_up_does_not_stop_an_org_admin(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = _name("ada")
+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+
+ app = _app(session_factory, signup_mode="invite_only")
+ async with _client(app, ada, tenant_id) as client:
+ response = await client.post(
+ "/organizations/current/workspaces", json={"name": "Second"}
+ )
+
+ assert response.status_code == 201, response.text
+
+ async def test_it_counts_against_the_creator_allowance(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = _name("ada")
+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})
+
+ app = _app(session_factory, max_workspaces_per_user=1)
+ async with _client(app, ada, tenant_id) as client:
+ first = await client.post(
+ "/organizations/current/workspaces", json={"name": "Second"}
+ )
+ second = await client.post(
+ "/organizations/current/workspaces", json={"name": "Third"}
+ )
+
+ assert first.status_code == 201, first.text
+ assert second.status_code == 403
+
+
+class TestListingOrganizationsAndWorkspaces:
+ async def test_an_org_admin_sees_every_workspace_and_a_member_their_own(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada, bob = _name("ada"), _name("bob")
+ tenant_id = await _workspace(
+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}
+ )
+ 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
+ as_admin = await client.get("/organizations/current/workspaces")
+ async with _client(app, bob, tenant_id) as client:
+ as_member = await client.get("/organizations/current/workspaces")
+
+ assert as_admin.status_code == 200, as_admin.text
+ assert {row["id"] for row in as_admin.json()} == {
+ tenant_id,
+ created.json()["id"],
+ }
+ assert as_member.status_code == 200, as_member.text
+ assert [row["id"] for row in as_member.json()] == [tenant_id]
+
+ async def test_the_caller_sees_each_of_their_organizations_once(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ ada = await _user(session_factory, "user")
+ app = _app(session_factory)
+ async with _client(app, ada, None) as client:
+ acme = await client.post("/organizations", json={"name": "Acme"})
+ assert acme.status_code == 201, acme.text
+ acme_workspace = acme.json()["workspace"]["id"]
+ async with _client(app, ada, acme_workspace) as client:
+ second = await client.post(
+ "/organizations/current/workspaces", json={"name": "Second"}
+ )
+ assert second.status_code == 201, second.text
+ globex = await client.post("/organizations", json={"name": "Globex"})
+ assert globex.status_code == 201, globex.text
+ listed = await client.get("/organizations")
+
+ assert listed.status_code == 200, listed.text
+ assert [(row["name"], row["role"]) for row in listed.json()] == [
+ ("Acme", "org_admin"),
+ ("Globex", "org_admin"),
+ ]
diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.py
index c6a0e606a..454bd66aa 100644
--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py
+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py
@@ -62,6 +62,7 @@ _ROUTES_WITH_NO_TENANT_BOUND = {
# Locks the caller's `users` row, which has no tenant, while it creates a
# workspace that has none yet either.
("POST", "/tenants"),
+ ("POST", "/organizations"),
# Deletes the caller's `users` row and sign-in identities, which belong to
# no workspace; each workspace is left in a `tenant_session` of its own.
("DELETE", "/auth/me"),
@@ -112,6 +113,9 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {
("GET", "/tenants"),
("POST", "/tenants"),
("POST", "/tenants/{tenant_id}/switch"),
+ # The same for organizations: list the caller's, make one.
+ ("GET", "/organizations"),
+ ("POST", "/organizations"),
# Accepting an invitation binds the tenant the *token* names, which is
# neither the one on the caller's session nor one they belong to yet. It
# opens its own `tenant_session` around that id — see `accept_invitation`.
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 e1a4cbb59..27bcd51d7 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -1756,6 +1756,7 @@ class TestCurrentTenantRoute:
"name": TENANT_A,
"role": "member",
"organization_role": None,
+ "organization_id": None,
"administers": False,
}
@@ -1828,7 +1829,7 @@ class TestOrganizationAdmins:
admin_id = await _make_unaffiliated_user(
session_factory, name="org-admin", role="user"
)
- await self._organization_of(
+ organization_id = await self._organization_of(
session_factory, TENANT_A, members={admin_id: "org_admin"}
)
token = _token(admin_id, "[email protected]", TENANT_A)
@@ -1843,6 +1844,7 @@ class TestOrganizationAdmins:
"name": TENANT_A,
"role": "admin",
"organization_role": "org_admin",
+ "organization_id": organization_id,
"administers": True,
}
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 4e3db6f28..d13d97f63 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1167,8 +1167,15 @@ export async function fetchSession(): Promise<Session | null> {
}
}
+/** Create an organization with a first workspace of the same name, and switch
+ * the session into the workspace. */
export async function createTenant(name: string): Promise<TenantMembership> {
- return jsonRequest<TenantMembership>("/tenants", "POST", { name });
+ const created = await jsonRequest<{ workspace: TenantMembership }>(
+ "/organizations",
+ "POST",
+ { name },
+ );
+ return created.workspace;
}
export async function switchTenant(tenantId: string): Promise<void> {