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
fix: refuse an unknown role when creating a user (CHOO-3854) (#1078)
Christian McDermottbbe6c413c3d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f6b949120..1f5b52233 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -189,6 +189,16 @@ version of their own to them without also giving them a release of their own.does `read_context` (#1045). One whose offset moves it outside the years 1to 9999 in UTC is refused the same way instead of answering 404, and a timein the last millisecond of 9999 is no longer refused at all.+- **Creating a user refuses a role the server does not understand.** An+ account is a user or an admin, and only the exact role `admin` grants+ operator rights. `POST /users` accepted any role string, so `Admin` or+ `owner` created an account that was shown with that role, was stored with+ it, and had no operator rights. Anything other than `user` or `admin` is now+ a 422 and creates nothing. The Add User dialog offers only those two, so+ only scripts calling the API were affected. Accounts already stored with+ another role are left as they are, still listed with that role and still+ treated as ordinary users; `SELECT id, email, role FROM users WHERE role+ NOT IN ('user', 'admin')` finds them.- **Every way of setting a password now applies the same rules.** Signupalready required 8 characters and at most 72 bytes. Changing your ownpassword checked only the 8 characters, and an admin creating a user checkeddiff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex fa6ad0b12..f7ab47064 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -851,7 +851,9 @@ class CreateUserRequest(BaseModel):name: stremail: Emailpassword: Password- role: str = "user"+ # Only the exact string "admin" grants operator rights (`require_admin`),+ # so anything else would create an account claiming a role it lacks.+ role: Literal["user", "admin"] = "user"class ChangePasswordRequest(BaseModel):diff --git a/core/tests/switch_core/gateway/test_create_user.py b/core/tests/switch_core/gateway/test_create_user.pyindex 2a868befd..9c54f3873 100644--- a/core/tests/switch_core/gateway/test_create_user.py+++ b/core/tests/switch_core/gateway/test_create_user.py@@ -1,12 +1,14 @@"""Admin user creation (POST /users): the same password and address rules as-signup.+signup, and only the roles the server understands.bcrypt reads only the first 72 bytes of a password, so a longer one would bestored as a prefix of itself; the request schema refuses it instead, andrefuses anything under 8 characters. The address is normalised the way signupnormalises it, so the same address means the same account whichever way itwas created (`SignupRequest` shares the constraints, and `test_signup.py`-covers its HTTP behaviour end to end).+covers its HTTP behaviour end to end). The role is "user" or "admin" and+nothing else: only the exact string "admin" grants operator rights, so any+other value would create an account that claims a role it does not have.The HTTP tests drive the real auth router against real Postgres, as`test_change_password.py` does; the schema tests need no database.@@ -25,7 +27,7 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import User+from switch_core.db.models import TenantMember, Userfrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway import auth_routesfrom switch_core.gateway import dependencies as gw_deps@@ -185,6 +187,62 @@ class TestCreateUserOverHttp:]+ @pytest.mark.parametrize("role", ["Admin", "owner", "operator", ""])+ async def test_an_unknown_role_is_422_and_creates_nothing(+ self, session_factory: async_sessionmaker[AsyncSession], role: str+ ) -> None:+ app = _app(session_factory)+ async with await _admin_client(session_factory, app) as client:+ response = await client.post(+ "/users",+ json={+ "name": "Ed",+ "email": "[email protected]",+ "password": "good-pass-1",+ "role": role,+ },+ )++ assert response.status_code == 422, response.text+ assert [e["loc"] for e in response.json()["detail"]] == [["body", "role"]]+ assert await _emails_like(session_factory, "[email protected]") == []++ @pytest.mark.parametrize(+ ("role", "membership_role"), [("user", "member"), ("admin", "owner")]+ )+ async def test_a_known_role_is_stored_with_its_membership(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ role: str,+ membership_role: str,+ ) -> None:+ app = _app(session_factory)+ async with await _admin_client(session_factory, app) as client:+ response = await client.post(+ "/users",+ json={+ "name": "Fay",+ "email": "[email protected]",+ "password": "good-pass-1",+ "role": role,+ },+ )++ assert response.status_code == 200, response.text+ assert response.json()["role"] == role+ async with session_factory() as session:+ stored = await session.scalar(+ select(User.role).where(User.email == "[email protected]")+ )+ memberships = await session.scalars(+ select(TenantMember.role).where(+ TenantMember.user_id == response.json()["id"]+ )+ )+ membership_roles = list(memberships)+ assert stored == role+ assert membership_roles == [membership_role]+async def test_concurrent_creates_of_one_address_are_one_user_and_a_conflict(self,session_factory: async_sessionmaker[AsyncSession],@@ -262,6 +320,16 @@ class TestCreateUserSchemaValidation:)assert request.role == "user"+ def test_unknown_role_rejected(self) -> None:+ with pytest.raises(ValidationError) as exc_info:+ CreateUserRequest(+ name="Ada",+ email="[email protected]",+ password="good-pass-1",+ role="Admin",+ )+ assert [e["type"] for e in exc_info.value.errors()] == ["literal_error"]+def test_short_password_rejected(self) -> None:with pytest.raises(ValidationError) as exc_info:CreateUserRequest(name="Ada", email="[email protected]", password="short")diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 78f6c371e..4e3db6f28 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1289,11 +1289,14 @@ export async function fetchUsers(): Promise<UserInfo[] | null> {return fetchJson<UserInfo[]>("/users");}+// The roles `POST /users` accepts; `admin` makes a deployment operator.+export type UserRole = "user" | "admin";+export async function createUser(name: string,email: string,password: string,- role: string,+ role: UserRole,): Promise<UserInfo> {return jsonRequest<UserInfo>("/users", "POST", { name, email, password, role });}diff --git a/gateway/src/pages/users/CreateUserDialog.tsx b/gateway/src/pages/users/CreateUserDialog.tsxindex 2696e4801..b962ff729 100644--- a/gateway/src/pages/users/CreateUserDialog.tsx+++ b/gateway/src/pages/users/CreateUserDialog.tsx@@ -11,7 +11,7 @@ import {TextField,} from "@mui/material";import { useCallback, useState } from "react";-import { createUser } from "../../data/api";+import { createUser, type UserRole } from "../../data/api";interface Props {open: boolean;@@ -23,7 +23,7 @@ export default function CreateUserDialog({ open, onClose, onCreated }: Props) {const [name, setName] = useState("");const [email, setEmail] = useState("");const [password, setPassword] = useState("");- const [role, setRole] = useState("user");+ const [role, setRole] = useState<UserRole>("user");const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);@@ -85,7 +85,7 @@ export default function CreateUserDialog({ open, onClose, onCreated }: Props) {label="Role"selectvalue={role}- onChange={(e) => setRole(e.target.value)}+ onChange={(e) => setRole(e.target.value as UserRole)}><MenuItem value="user">User</MenuItem><MenuItem value="admin">Admin</MenuItem>