Skip to content

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

feat(gateway): bound workspace creation per person (CHOO-2722)

Petr Bauchfc1ef8da4293
diff --git a/.env.example b/.env.example
index df892245d..b3492f652 100644
--- a/.env.example
+++ b/.env.example
@@ -144,6 +144,14 @@ GATEWAY_ADMIN_PASSWORD=
# docs/old/multi-tenancy-phase2-tenants.md, §4.
# GATEWAY_TENANT_CHOICE_ENABLED=false
+# How many workspaces one person may own here. Creating a workspace is an
+# amplification vector rather than a row — every tenant adds a fan-out at boot
+# and to a sweep that runs every few seconds — so the route is bounded. Set it
+# to 0 to refuse workspace creation outright; this one value is both the cap
+# and the gate. Counts owner memberships only, and deployment operators are
+# exempt. See docs/old/multi-tenancy-phase2-tenants.md, §5.
+# GATEWAY_MAX_WORKSPACES_PER_USER=3
+
# ── Frontend ─────────────────────────────────────────────────────────────────
FRONTEND_BASE_URL=http://localhost:5173
diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.py
index 9f58643bf..9291ed96b 100644
--- a/core/switch_core/clients/client_lifecycle_service.py
+++ b/core/switch_core/clients/client_lifecycle_service.py
@@ -119,9 +119,11 @@ 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 eventually offers tenant creation (there is no such
- endpoint yet — Phase 2's scope) has a single place to call rather
- than a row to insert and a checklist to remember. It reuses
+ that whatever offers tenant creation — `POST /tenants` 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
+ authorise. It reuses
`ensure_system_client` rather than duplicating its per-type,
per-tenant provisioning logic: the new tenant is simply the one gap
that enumeration has not filled yet.
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 67c9eb2ef..678e84a14 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -141,6 +141,23 @@ class SwitchConfig(BaseSettings):
# docs/old/multi-tenancy-phase2-tenants.md, §4.
gateway_tenant_choice_enabled: bool = False
+ # 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.
+ #
+ # 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
+ # and a sweep every few seconds, across clients, collaboration bridges,
+ # server connectors and rooms. Unbounded self-service creation therefore
+ # buys steady-state work in the deployment, not storage.
+ #
+ # Counts `owner` memberships only, so being invited into someone else's
+ # workspace never spends an allowance the invitee cannot get back. Deployment
+ # operators (`users.role == "admin"`) are exempt, on the same grounds as
+ # every other operator bypass in `authz.py`: this bounds self-service, and
+ # an operator provisioning workspaces for other people is not that.
+ # docs/old/multi-tenancy-phase2-tenants.md, §5.
+ gateway_max_workspaces_per_user: int = 3
+
# ── Logging ──────────────────────────────────────────────────────────────
# "text" for a terminal, "json" for a log pipeline that parses fields.
log_format: str = "text"
@@ -595,6 +612,16 @@ class SwitchConfig(BaseSettings):
def observability_enabled(self) -> bool:
return self.otlp_endpoint is not None
+ @model_validator(mode="after")
+ def _validate_max_workspaces_per_user(self) -> "SwitchConfig":
+ if self.gateway_max_workspaces_per_user < 0:
+ raise ValueError(
+ "GATEWAY_MAX_WORKSPACES_PER_USER must not be negative (0 "
+ "disables workspace creation), got "
+ f"{self.gateway_max_workspaces_per_user!r}."
+ )
+ return self
+
@model_validator(mode="after")
def _validate_db_user(self) -> "SwitchConfig":
# `db_user` is the runtime role name, and `db/runtime_role.py` builds
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 53010337d..4fda74632 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -165,11 +165,19 @@ async def get_authenticated_user_id(
@dataclass(frozen=True)
class AuthenticatedCaller:
- """An authenticated caller with no tenant bound — id and email, read from
- `users`, which carries neither a tenant nor a policy."""
+ """An authenticated caller with no tenant bound — read from `users`, which
+ carries neither a tenant nor a policy.
+
+ `is_operator` is `users.role == "admin"`, the same global bit
+ `require_admin` gates on and the same one `authz.administers_tenant` takes
+ as its bypass. It is meaningful here, before any tenant is bound, precisely
+ because it is not granted per tenant: a route that has no tenant to ask
+ about can still ask whether the caller runs the deployment.
+ """
id: str
email: str
+ is_operator: bool
async def get_authenticated_caller(
@@ -180,21 +188,26 @@ async def get_authenticated_caller(
user_store: Annotated[UserStore, Depends(get_user_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> AuthenticatedCaller:
- """Like `get_authenticated_user_id`, but with the caller's own email too.
-
- Backs `POST /invitations/accept` (`gateway/tenants.py`), which has
- to check an email-bound invitation against the caller's *current* address
- before any tenant is bound — the same "no tenant chosen yet" shape as
- `get_authenticated_user_id`, plus one more column of the same global,
- unscoped `users` row. Reads the row fresh rather than trusting the JWT's
- own `email` claim, which is a snapshot from login and can go stale.
+ """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
+ 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
+ global, unscoped `users` row. Read fresh rather than trusting the JWT's own
+ claims, which are a snapshot from login: an address can change, and a
+ revoked operator bit must not stay valid for the life of a cookie.
"""
payload = await _authenticate(request, session_factory, user_store, config)
async with session_factory() as system_session:
user = await user_store.get(system_session, payload["sub"])
if user is None:
raise HTTPException(status_code=401, detail="User not found")
- return AuthenticatedCaller(id=user.id, email=user.email)
+ return AuthenticatedCaller(
+ id=user.id, email=user.email, is_operator=user.role == "admin"
+ )
async def tenant_of_invitation_token(
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 30f6385c7..57e6b1464 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -201,18 +201,68 @@ async def list_tenants(
return await list_tenant_memberships(session_factory, user_store, user_id)
+async def _require_workspace_allowance(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ caller: AuthenticatedCaller,
+ limit: int,
+) -> None:
+ """Raise 403 unless `caller` may own one more workspace.
+
+ 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.
+
+ Operators are exempt before anything is read, 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.
+
+ Counts `owner` memberships, not memberships: an invitation into someone
+ else's workspace must not spend an allowance, since the invitee cannot get
+ it back without being removed. The count reuses `list_tenant_memberships`
+ rather than asking the database for a number — there is no exemption that
+ returns a caller's *roles* across tenants, only `tenants_of_user`, and
+ adding one would mean a tenth `SECURITY DEFINER` lookup and a migration for
+ an answer this bounds to a handful of rows by construction.
+ """
+ if caller.is_operator:
+ return
+ if limit == 0:
+ raise HTTPException(
+ status_code=403,
+ detail="Workspace creation is disabled on this deployment",
+ )
+ memberships = await list_tenant_memberships(session_factory, user_store, caller.id)
+ owned = sum(1 for membership in memberships if membership.role == "owner")
+ if owned >= limit:
+ raise HTTPException(
+ status_code=403,
+ detail=(f"You own {owned} workspaces, and this deployment allows {limit}"),
+ )
+
+
@router.post("/tenants", status_code=201)
async def create_tenant(
req: TenantCreateRequest,
- user_id: Annotated[str, Depends(get_authenticated_user_id)],
+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],
session_factory: Annotated[
async_sessionmaker[AsyncSession], Depends(get_session_factory)
],
user_store: Annotated[UserStore, Depends(get_user_store)],
client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
) -> TenantMembershipResponse:
"""Create a workspace. The caller becomes its `owner`.
+ How many workspaces one person may own is bounded, and the bound is checked
+ before anything is provisioned — see `_require_workspace_allowance`. 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
@@ -230,6 +280,9 @@ async def create_tenant(
— a 500 with the orphan unrecorded — is the silent degradation this
codebase refuses. An operator repairs it by inserting the membership.
"""
+ await _require_workspace_allowance(
+ session_factory, user_store, caller, config.gateway_max_workspaces_per_user
+ )
slug = _derive_slug(req.name)
try:
tenant = await client_lifecycle.create_tenant(req.name, slug)
@@ -241,7 +294,7 @@ async def create_tenant(
try:
async with tenant_session(session_factory, tenant.id) as session:
await user_store.add_membership(
- session, tenant_id=tenant.id, user_id=user_id, role="owner"
+ session, tenant_id=tenant.id, user_id=caller.id, role="owner"
)
await session.commit()
except Exception:
@@ -251,7 +304,7 @@ async def create_tenant(
"taken. Insert the membership to repair it.",
tenant.id,
slug,
- user_id,
+ caller.id,
)
raise
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 f023dd4d2..0991851dc 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -73,6 +73,7 @@ def _app(
session_factory: async_sessionmaker[AsyncSession],
*,
client_lifecycle: object | None = None,
+ max_workspaces_per_user: int = 3,
) -> FastAPI:
async def _session_dep():
async with session_factory() as session:
@@ -95,6 +96,7 @@ def _app(
jwt_secret_key=_SECRET,
gateway_cookie_secure=False,
gateway_tenant_choice_enabled=False,
+ gateway_max_workspaces_per_user=max_workspaces_per_user,
)
return app
@@ -122,9 +124,16 @@ async def _make_member(
tenant_id: str,
role: str,
email: str | None = None,
+ user_role: str = "user",
) -> str:
+ """A user with a membership in `tenant_id`.
+
+ `role` is the per-tenant membership role; `user_role` is the global
+ `users.role`, which is a different axis entirely — `"admin"` there is the
+ deployment operator bit, granted by nothing self-service.
+ """
async with session_factory() as session:
- user = User(name=name, email=email or f"{name}@example.invalid", role="user")
+ user = User(name=name, email=email or f"{name}@example.invalid", role=user_role)
session.add(user)
await session.flush()
session.add(TenantMember(tenant_id=tenant_id, user_id=user.id, role=role))
@@ -266,6 +275,148 @@ class TestCreateTenant:
assert response.status_code == 400
+class TestWorkspaceCreationLimit:
+ """`POST /tenants` is the one route here with no tenant to authorize
+ against, so what stands in for its neighbours' role check is a bound on how
+ many workspaces one person may own. It exists because a workspace is not
+ just a row: `all_tenant_ids()` drives a fan-out per tenant at boot and a
+ sweep every few seconds (`docs/old/multi-tenancy-phase2-tenants.md`, §5).
+ """
+
+ async def test_a_caller_at_the_limit_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ user_id = await _make_member(
+ session_factory, name="serial-founder", tenant_id=TENANT_A, role="member"
+ )
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ app = _app(session_factory, max_workspaces_per_user=2)
+ async with _client(app, token) as client:
+ assert (
+ await client.post("/tenants", json={"name": "First"})
+ ).status_code == 201
+ assert (
+ await client.post("/tenants", json={"name": "Second"})
+ ).status_code == 201
+ third = await client.post("/tenants", json={"name": "Third"})
+
+ assert third.status_code == 403
+ assert "own 2 workspaces" in third.json()["detail"]
+
+ async def test_nothing_is_provisioned_for_a_refused_caller(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The bound is checked before `create_tenant`, so a refusal must not
+ # leave the orphan workspace the handler's own docstring warns about.
+ await _make_tenant(session_factory, TENANT_A)
+ user_id = await _make_member(
+ session_factory, name="blocked-founder", tenant_id=TENANT_A, role="member"
+ )
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ app = _app(session_factory, max_workspaces_per_user=0)
+ async with _client(app, token) as client:
+ response = await client.post("/tenants", json={"name": "Never Made"})
+
+ assert response.status_code == 403
+ async with session_factory() as session:
+ found = await session.scalars(
+ select(Tenant).where(Tenant.slug == "never-made")
+ )
+ assert found.first() is None
+
+ async def test_a_limit_of_zero_says_creation_is_disabled(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Zero is how a deployment closes the route, and it must not be
+ # reported as though the caller had used up an allowance.
+ await _make_tenant(session_factory, TENANT_A)
+ user_id = await _make_member(
+ session_factory, name="early-bird", tenant_id=TENANT_A, role="member"
+ )
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ app = _app(session_factory, max_workspaces_per_user=0)
+ async with _client(app, token) as client:
+ response = await client.post("/tenants", json={"name": "Too Early"})
+
+ assert response.status_code == 403
+ assert response.json()["detail"] == (
+ "Workspace creation is disabled on this deployment"
+ )
+
+ async def test_memberships_the_caller_does_not_own_are_free(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Being invited into someone else's workspace must not spend an
+ # allowance: the invitee cannot get it back without being removed.
+ await _make_tenant(session_factory, TENANT_A)
+ await _make_tenant(session_factory, TENANT_B)
+ user_id = await _make_member(
+ session_factory, name="joiner", tenant_id=TENANT_A, role="admin"
+ )
+ async with session_factory() as session:
+ session.add(
+ TenantMember(tenant_id=TENANT_B, user_id=user_id, role="member")
+ )
+ await session.commit()
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ app = _app(session_factory, max_workspaces_per_user=1)
+ async with _client(app, token) as client:
+ response = await client.post("/tenants", json={"name": "Mine At Last"})
+
+ assert response.status_code == 201, response.text
+
+ async def test_an_operator_is_exempt(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # `users.role == "admin"` is the deployment operator bit, and this
+ # bound is about self-service. An operator provisioning workspaces for
+ # other people is exactly who it must not stop — the same bypass
+ # `authz.administers_tenant` and `authz.owns_tenant` already give them.
+ await _make_tenant(session_factory, TENANT_A)
+ user_id = await _make_member(
+ session_factory,
+ name="the-operator",
+ tenant_id=TENANT_A,
+ role="member",
+ user_role="admin",
+ )
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ app = _app(session_factory, max_workspaces_per_user=0)
+ async with _client(app, token) as client:
+ first = await client.post("/tenants", json={"name": "Customer One"})
+ second = await client.post("/tenants", json={"name": "Customer Two"})
+
+ assert first.status_code == 201, first.text
+ assert second.status_code == 201, second.text
+
+ async def test_the_operator_bit_is_read_fresh_not_from_the_token(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The JWT carries a role claim from login. Trusting it would keep a
+ # revoked operator exempt for the life of their cookie, so the bit
+ # comes from the `users` row on every request.
+ await _make_tenant(session_factory, TENANT_A)
+ user_id = await _make_member(
+ session_factory, name="demoted", tenant_id=TENANT_A, role="member"
+ )
+ stale_operator_token = create_jwt(
+ user_id, "[email protected]", "admin", _SECRET, TENANT_A
+ )
+
+ async with _client(
+ _app(session_factory, max_workspaces_per_user=0), stale_operator_token
+ ) as client:
+ response = await client.post("/tenants", json={"name": "Not Allowed"})
+
+ assert response.status_code == 403
+
+
class TestInvitationAuthorisation:
"""A member of workspace A cannot mint an invitation to workspace B —
each request is bound to exactly one tenant, and the path segment cannot
diff --git a/core/tests/switch_core/test_config_max_workspaces.py b/core/tests/switch_core/test_config_max_workspaces.py
new file mode 100644
index 000000000..d1362908f
--- /dev/null
+++ b/core/tests/switch_core/test_config_max_workspaces.py
@@ -0,0 +1,47 @@
+import pytest
+
+from switch_core.config import SwitchConfig
+
+_BASE_KWARGS = dict(
+ db_host="db",
+ db_port="5432",
+ db_user="postgres",
+ db_name="switch",
+ matrix_server_name="switch.local",
+ agent_registration_token="token",
+ jwt_secret_key="jwt",
+ gateway_admin_email="[email protected]",
+)
+
+
+def _config(**overrides: object) -> SwitchConfig:
+ return SwitchConfig( # type: ignore[arg-type]
+ **{
+ **_BASE_KWARGS,
+ "db_password": "placeholder", # gitleaks:allow
+ "gateway_admin_password": "placeholder", # gitleaks:allow
+ **overrides,
+ }
+ )
+
+
+def test_a_deployment_that_configures_nothing_gets_a_bound() -> None:
+ # The point of the default is that an unconfigured deployment is bounded
+ # anyway: an operator has to opt *out* of the cap, not into it.
+ assert _config().gateway_max_workspaces_per_user == 3
+
+
[email protected]("limit", [0, 1, 50])
+def test_zero_and_above_is_accepted(limit: int) -> None:
+ # Zero is meaningful rather than degenerate — it closes `POST /tenants`.
+ assert (
+ _config(gateway_max_workspaces_per_user=limit).gateway_max_workspaces_per_user
+ == limit
+ )
+
+
+def test_a_negative_limit_raises() -> None:
+ # A negative cap would read as "no workspaces ever" while looking like a
+ # typo for the value that says so, so it is refused at startup instead.
+ with pytest.raises(ValueError, match="GATEWAY_MAX_WORKSPACES_PER_USER"):
+ _config(gateway_max_workspaces_per_user=-1)
diff --git a/docs/old/multi-tenancy-phase2-tenants.md b/docs/old/multi-tenancy-phase2-tenants.md
index 6928ea199..37efb6d9c 100644
--- a/docs/old/multi-tenancy-phase2-tenants.md
+++ b/docs/old/multi-tenancy-phase2-tenants.md
@@ -184,7 +184,8 @@ this phase must prove it has removed.
- `GET /tenants` — the caller's workspaces: id, slug, name, their role. §7 is
about how this reads across the boundary.
- `POST /tenants` — create one; the creator becomes `owner` (meaningful only
- once §2 lands). Slug derived from the name; a taken slug is a 409.
+ once §2 lands). Slug derived from the name; a taken slug is a 409. Bounded —
+ see below.
- `POST /tenants/{id}/switch` — verify membership, re-mint the cookie.
- `POST /tenants/{id}/invitations`, `GET`, `DELETE …/{token_id}` — mint, list,
revoke. `owner` and `admin` only.
@@ -195,6 +196,18 @@ this phase must prove it has removed.
list, change a role, remove. The original design omitted these and then
assumed the role-change route existed.
+**Creating a workspace is bounded, because it is an amplification vector
+rather than a row.** `all_tenant_ids()` drives a fan-out per tenant at boot and
+a sweep every few seconds, across clients, collaboration bridges, server
+connectors and rooms, so unbounded self-service creation buys steady-state work
+in the deployment, not storage. `GATEWAY_MAX_WORKSPACES_PER_USER` is both the
+cap and the gate: at the limit `POST /tenants` is a 403, and `0` closes the
+route outright. It counts `owner` memberships only, so being invited into
+someone else's workspace never spends an allowance the invitee cannot get back.
+Deployment operators are exempt, on the same grounds as every other operator
+bypass — this bounds self-service, and an operator provisioning workspaces for
+other people is not that.
+
**A workspace must always have an owner.** Removing or demoting the last one
is refused; deletion of a workspace is not in this phase, so there is no
legitimate path to an ownerless one.
@@ -306,11 +319,13 @@ self-service should mint one.
## 9. What this does not cover
Per-tenant agent registration credentials, tenant switching in Console, the
-workspace-versus-server vocabulary question, workspace deletion, and quotas on
-workspace creation. That last one deserves a note: `all_tenant_ids()` drives
-fan-outs at boot and a sweep every few seconds, so unbounded self-service
-creation is an amplification vector. Either cap creation per user or gate the
-route by config.
+workspace-versus-server vocabulary question, and workspace deletion.
+
+The quota on workspace creation that this section used to defer is now in §5.
+What remains uncovered there is everything downstream of creation: a workspace
+that exists still costs its fan-out whether or not anyone uses it, and nothing
+reclaims an abandoned one — the cap bounds how many a person can open, not how
+many a deployment ends up carrying.
## 10. Done when
@@ -326,3 +341,5 @@ route by config.
- A domain cannot be claimed by two tenants, nor by an account that cannot
prove it uses it.
- The last owner of a workspace cannot be removed or demoted.
+- A person at the workspace limit is refused a new one and nothing is
+ provisioned for them, and a limit of zero closes the route.