Skip to content

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

fix: validate passwords consistently across account endpoints (#1036)

Soumojit Das0e0981a25e0e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9f2b3efed..b4670ca09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -151,6 +151,16 @@ version of their own to them without also giving them a release of their own.
Existing duplicates are left as they are and can be reached by id.
#### Fixed
+- **Every way of setting a password now applies the same rules.** Signup
+ already required 8 characters and at most 72 bytes. Changing your own
+ password checked only the 8 characters, and an admin creating a user checked
+ nothing, so a short or empty password went through, and a long passphrase
+ was saved as just its first 72 bytes, the most bcrypt reads. Both now refuse
+ what signup refuses, saying why. Creating a user also trims, lowercases and
+ checks the email the way signup does, so the same address with a stray
+ space no longer makes a second account, and an address with no dot in its
+ domain is refused. A script that creates users through `POST /users` gets a
+ 422 for either. Passwords already saved still work (#1035).
- **Full garbage collections no longer stall the server for hundreds of
milliseconds.** Once boot has built what lasts for the life of the process
(modules, the ORM's mappers, the app's routes), the server freezes it out of
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 7891067e9..fa6ad0b12 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -5,6 +5,7 @@ from typing import Annotated, Any, Literal
from urllib.parse import urlsplit
from pydantic import (
+ AfterValidator,
BaseModel,
ConfigDict,
Field,
@@ -812,19 +813,50 @@ class UserResponse(BaseModel):
created_at: str
+PASSWORD_MIN_LENGTH = 8
+PASSWORD_MAX_BYTES = 72
+
+
+def _bcrypt_sized_validator(password: str) -> str:
+ if len(password.encode()) > PASSWORD_MAX_BYTES:
+ raise ValueError(f"Password must be at most {PASSWORD_MAX_BYTES} bytes.")
+ return password
+
+
+# Every password the server is asked to store: long enough to mean something,
+# and no longer than the 72 bytes bcrypt reads. bcrypt 4 ignores the rest, so a
+# longer password would be stored as its first 72 bytes; bcrypt 5 raises.
+Password = Annotated[
+ str,
+ StringConstraints(min_length=PASSWORD_MIN_LENGTH),
+ AfterValidator(_bcrypt_sized_validator),
+]
+
+# The address an account is created with, trimmed, lowercased and
+# shape-checked, so the same address arriving through signup or the admin user
+# list resolves to one account, not near-duplicates. Login does not use it: an
+# account whose address does not fit the shape must still be able to sign in.
+Email = Annotated[
+ str,
+ StringConstraints(
+ strip_whitespace=True,
+ to_lower=True,
+ max_length=320,
+ pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$",
+ ),
+]
+
+
class CreateUserRequest(BaseModel):
name: str
- email: str
- password: str
+ email: Email
+ password: Password
role: str = "user"
-PASSWORD_MIN_LENGTH = 8
-
-
class ChangePasswordRequest(BaseModel):
current_password: str
- new_password: str = Field(min_length=PASSWORD_MIN_LENGTH)
+ new_password: Password
class DeleteAccountRequest(BaseModel):
@@ -836,16 +868,8 @@ class DeleteAccountRequest(BaseModel):
class SignupRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
- email: Annotated[
- str,
- StringConstraints(
- strip_whitespace=True,
- to_lower=True,
- max_length=320,
- pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$",
- ),
- ]
- password: str = Field(min_length=PASSWORD_MIN_LENGTH)
+ email: Email
+ password: Password
display_name: (
Annotated[
str, StringConstraints(strip_whitespace=True, min_length=1, max_length=255)
@@ -853,13 +877,6 @@ class SignupRequest(BaseModel):
| None
) = None
- @field_validator("password")
- @classmethod
- def bcrypt_sized(cls, password: str) -> str:
- if len(password.encode()) > 72:
- raise ValueError("Password must be at most 72 bytes.")
- return password
-
class SignupMachine(BaseModel):
status: Literal["starting", "unavailable"]
diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.py
index 4c91aac29..14e0c783d 100644
--- a/core/tests/switch_core/gateway/test_change_password.py
+++ b/core/tests/switch_core/gateway/test_change_password.py
@@ -192,6 +192,58 @@ class TestPasswordChangeIsRefused:
assert response.status_code == 403
assert await _stored_hash(session_factory, user_id) is None
+ async def test_an_overlong_new_password_is_422_and_writes_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email=email, password=_OLD_PASSWORD)
+ before = await _stored_hash(session_factory, user_id)
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ response = await client.put(
+ "/auth/me/password",
+ json={
+ "current_password": _OLD_PASSWORD,
+ "new_password": "correct horse battery staple " * 3,
+ },
+ )
+
+ assert response.status_code == 422, response.text
+ assert await _stored_hash(session_factory, user_id) == before
+
+
+class TestPasswordSavedOverTheLimit:
+ """An account whose password was saved before the 72-byte limit, and so is
+ longer than it, is not locked out: login and the current password are never
+ held to the limit, only a password about to be stored."""
+
+ _LONG = "correct horse battery staple " * 3
+
+ async def test_it_still_logs_in_and_can_be_changed(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email=email, password=self._LONG)
+ app = _app(session_factory)
+
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as anonymous:
+ logged_in = await anonymous.post(
+ "/auth/login", json={"email": email, "password": self._LONG}
+ )
+ async with _client(app, user_id, email) as client:
+ changed = await client.put(
+ "/auth/me/password",
+ json={"current_password": self._LONG, "new_password": _NEW_PASSWORD},
+ )
+
+ assert logged_in.status_code == 200, logged_in.text
+ assert changed.status_code == 200, changed.text
+ assert verify_password(
+ _NEW_PASSWORD, await _stored_hash(session_factory, user_id)
+ )
+
class TestSchemaValidation:
"""No database needed: the length floor is the schema's, not the route's."""
@@ -204,3 +256,17 @@ class TestSchemaValidation:
def test_empty_new_password_rejected(self) -> None:
with pytest.raises(ValidationError):
ChangePasswordRequest(current_password=_OLD_PASSWORD, new_password="")
+
+ def test_new_password_over_seventy_two_bytes_rejected(self) -> None:
+ # 40 characters clears the 8-character floor, but is 80 bytes —
+ # bcrypt's input limit is counted in bytes, so the schema counts
+ # bytes too.
+ with pytest.raises(ValidationError) as exc_info:
+ ChangePasswordRequest(current_password=_OLD_PASSWORD, new_password="é" * 40)
+ assert "at most 72 bytes" in str(exc_info.value.errors())
+
+ def test_new_password_of_exactly_seventy_two_bytes_accepted(self) -> None:
+ request = ChangePasswordRequest(
+ current_password=_OLD_PASSWORD, new_password="é" * 36
+ )
+ assert request.new_password == "é" * 36
diff --git a/core/tests/switch_core/gateway/test_create_user.py b/core/tests/switch_core/gateway/test_create_user.py
new file mode 100644
index 000000000..306b3c09d
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_create_user.py
@@ -0,0 +1,222 @@
+"""Admin user creation (POST /users): the same password and address rules as
+signup.
+
+bcrypt reads only the first 72 bytes of a password, so a longer one would be
+stored as a prefix of itself; the request schema refuses it instead, and
+refuses anything under 8 characters. The address is normalised the way signup
+normalises it, so the same address means the same account whichever way it
+was created (`SignupRequest` shares the constraints, and `test_signup.py`
+covers its HTTP behaviour end to end).
+
+The HTTP tests drive the real auth router against real Postgres, as
+`test_change_password.py` does; the schema tests need no database.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from pydantic import ValidationError
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import User
+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_routes import router
+from switch_core.gateway.schemas import CreateUserRequest
+from switch_core.keys import Keyring
+
+_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)
+
+_USER_STORE = UserStore()
+
+
+def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+ async def _session_dep():
+ async with session_factory() as session:
+ yield session
+
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[gw_deps.get_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
+ app.dependency_overrides[gw_deps.get_user_store] = lambda: _USER_STORE
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ keyring=_KEYRING,
+ gateway_cookie_secure=False,
+ gateway_password_login_enabled=True,
+ gateway_tenant_choice_enabled=False,
+ )
+ return app
+
+
+async def _admin_client(
+ session_factory: async_sessionmaker[AsyncSession], app: FastAPI
+) -> httpx.AsyncClient:
+ async with session_factory() as session:
+ admin = User(
+ name="Operator",
+ role="admin",
+ password_hash=None,
+ )
+ await _USER_STORE.create(session, admin)
+ await session.commit()
+ token = create_jwt(admin.id, admin.email, "admin", _KEYRING, None)
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://test",
+ cookies={"switch_auth": token},
+ )
+
+
+async def _emails_like(
+ session_factory: async_sessionmaker[AsyncSession], address: str
+) -> list[str]:
+ async with session_factory() as session:
+ rows = await session.scalars(
+ select(User.email).where(
+ func.lower(func.trim(User.email)) == address.strip().lower()
+ )
+ )
+ return list(rows)
+
+
+class TestCreateUserOverHttp:
+ async def test_a_short_password_is_422_and_creates_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ app = _app(session_factory)
+ async with await _admin_client(session_factory, app) as client:
+ response = await client.post(
+ "/users",
+ json={
+ "name": "Ada",
+ "email": "[email protected]",
+ "password": "hello",
+ },
+ )
+
+ assert response.status_code == 422, response.text
+ assert await _emails_like(session_factory, "[email protected]") == []
+
+ async def test_an_overlong_password_is_422_and_creates_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ app = _app(session_factory)
+ async with await _admin_client(session_factory, app) as client:
+ response = await client.post(
+ "/users",
+ json={
+ "name": "Bo",
+ "email": "[email protected]",
+ "password": "correct horse battery staple " * 3,
+ },
+ )
+
+ assert response.status_code == 422, response.text
+ assert "at most 72 bytes" in response.text
+ assert await _emails_like(session_factory, "[email protected]") == []
+
+ async def test_the_address_is_stored_normalised(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ app = _app(session_factory)
+ async with await _admin_client(session_factory, app) as client:
+ response = await client.post(
+ "/users",
+ json={
+ "name": "Cy",
+ "email": " [email protected] ",
+ "password": "good-pass-1",
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["email"] == "[email protected]"
+ assert await _emails_like(session_factory, "[email protected]") == [
+ ]
+
+ async def test_the_same_address_padded_or_recased_is_a_conflict(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ app = _app(session_factory)
+ async with await _admin_client(session_factory, app) as client:
+ first = await client.post(
+ "/users",
+ json={
+ "name": "Di",
+ "email": "[email protected]",
+ "password": "good-pass-1",
+ },
+ )
+ second = await client.post(
+ "/users",
+ json={
+ "name": "Di again",
+ "email": " [email protected] ",
+ "password": "good-pass-2",
+ },
+ )
+
+ assert first.status_code == 200, first.text
+ assert second.status_code == 409, second.text
+ assert await _emails_like(session_factory, "[email protected]") == [
+ ]
+
+
+class TestCreateUserSchemaValidation:
+ def test_email_is_normalised(self) -> None:
+ request = CreateUserRequest(
+ name="Ada", email=" [email protected] ", password="good-pass-1"
+ )
+ assert request.email == "[email protected]"
+
+ def test_role_defaults_to_user(self) -> None:
+ request = CreateUserRequest(
+ name="Ada", email="[email protected]", password="good-pass-1"
+ )
+ assert request.role == "user"
+
+ def test_short_password_rejected(self) -> None:
+ with pytest.raises(ValidationError) as exc_info:
+ CreateUserRequest(name="Ada", email="[email protected]", password="short")
+ assert any(e["type"] == "string_too_short" for e in exc_info.value.errors())
+
+ def test_empty_password_rejected(self) -> None:
+ with pytest.raises(ValidationError):
+ CreateUserRequest(name="Ada", email="[email protected]", password="")
+
+ def test_password_over_seventy_two_bytes_rejected(self) -> None:
+ with pytest.raises(ValidationError) as exc_info:
+ CreateUserRequest(name="Ada", email="[email protected]", password="x" * 73)
+ assert "at most 72 bytes" in str(exc_info.value.errors())
+
+ def test_password_over_seventy_two_bytes_rejected_even_when_few_characters(
+ self,
+ ) -> None:
+ # 40 characters clears the 8-character floor, but is 80 bytes —
+ # bcrypt's input limit is counted in bytes, so the schema counts
+ # bytes too.
+ with pytest.raises(ValidationError) as exc_info:
+ CreateUserRequest(name="Ada", email="[email protected]", password="é" * 40)
+ assert "at most 72 bytes" in str(exc_info.value.errors())
+
+ def test_password_of_exactly_seventy_two_bytes_accepted(self) -> None:
+ request = CreateUserRequest(
+ name="Ada", email="[email protected]", password="é" * 36
+ )
+ assert request.password == "é" * 36
+
+ def test_bad_email_rejected(self) -> None:
+ with pytest.raises(ValidationError):
+ CreateUserRequest(name="Ada", email="not-an-email", password="good-pass-1")
diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.ts
index 4a28e8b00..3c2a638c4 100644
--- a/gateway/src/data/api.test.ts
+++ b/gateway/src/data/api.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
ApiError,
addBridgeToTeam,
+ createUser,
errorText,
fetchSession,
fetchTeamPlacements,
@@ -61,6 +62,27 @@ describe("fetchSession", () => {
});
});
+describe("createUser", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("words a rejected password, not [object Object]", async () => {
+ respond(422, {
+ detail: [
+ {
+ type: "string_too_short",
+ loc: ["body", "password"],
+ msg: "String should have at least 8 characters",
+ },
+ ],
+ });
+ const err = await createUser("Ada", "[email protected]", "hello", "user").catch(
+ (e: unknown) => e,
+ );
+ expect(err).toBeInstanceOf(ApiError);
+ expect((err as ApiError).message).toBe("String should have at least 8 characters");
+ });
+});
+
describe("fetchTeamPlacements", () => {
afterEach(() => vi.unstubAllGlobals());
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index f12187c1d..78f6c371e 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1295,17 +1295,7 @@ export async function createUser(
password: string,
role: string,
): Promise<UserInfo> {
- const res = await fetch(`${BASE}/users`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- credentials: "include",
- body: JSON.stringify({ name, email, password, role }),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => null);
- throw new Error(body?.detail ?? `${res.status} ${res.statusText}`);
- }
- return (await res.json()) as UserInfo;
+ return jsonRequest<UserInfo>("/users", "POST", { name, email, password, role });
}
// ── Resources (References & Documents) ─────────────────────────────────────