Selaa lähdekoodia

Moving a user out of Administrators takes the admin rights (#3533)

- The legacy role follows Administrators membership wherever groups
  change: user settings, the groups API, LDAP and OIDC sign-in
- The last-admin check covers leaving Administrators too
- The user edit form no longer sends the role back
- One-time startup backfill drops the admin role from users outside
  Administrators, or adds them to it if they are the only admins
- Tests, changelog entry
maziggy 1 viikko sitten
vanhempi
sitoutus
4b0ad7e60b

+ 1 - 0
CHANGELOG.md

@@ -27,6 +27,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **"Any model" jobs go to the printer with the fewest print hours (#3480, sponsor vote Q4 2026)** — When several printers of a model can take a job, the queue used to pick the first one in its list, so on a farm the same printer got most of the work. It now picks the one with the fewest print hours (the Maintenance counter, including baseline hours entered there), so jobs and wear spread across the farm. Preferred colours still come first, and the queue powers on the least used printer too when it has to switch one on with an Auto Power On plug.
 
 ### Fixed
+- **A user moved out of Administrators is no longer an admin (#3533)** — Users carry an older admin role next to their groups, and either one made them an admin. The account created during setup has both, so moving it from Administrators to Operators left it with every admin right, still showing the Admin badge, and the user settings had no way to remove the role. The groups now decide: the role follows them wherever they change, in the user settings, on the groups, through the API and at LDAP or OIDC sign-in. Removing the last admin from Administrators is refused, as deactivating them already was. On the first start after the update, users who are not in Administrators lose the old admin role. If they are the only admins, they are added to Administrators instead.
 - **Spool assignments survive a printer reconnecting mid-print (#3526, reported by @SaadShaya7)** — After a short network drop, the first report of a reconnecting printer can show a slot with no filament type and colour `00000000`. Bambuddy only recognised an empty colour as a blank slot, so it read this as a different spool and removed the inventory assignment, even during a print. All four assignments on an A1 mini's AMS lite and an A2L's external spool were lost that way and had to be made again. A slot reporting `00000000` with no type now counts as blank: during a print the assignment is kept as a possible runout, otherwise it is unlinked only if the slot stays blank for two minutes. A clear filament, which also reports `00000000` but with its type, is not affected. The support package also no longer contains a virtual printer's serial number: for the A2L, P2S, H2 series and X2D models it appeared in full in the certificate log lines.
 - **The slicer sidecars run as a non-root user again (#3524, reported by @cubic3d)** — Since 1.3.1, both the Bambu Studio and the OrcaSlicer sidecar failed to slice when the container runs as another user than root, as in a Kubernetes pod with `runAsNonRoot`: the log showed `bambu-studio: Permission denied`. The new slicer releases unpack with folders only root can open; the images now open them to every user, and the image build stops if any folder stays closed. Needs the updated sidecar images.
 - **The H2 series' and the H3C's exhaust fan is labelled Exhaust (#3521, reported by @Spegeli)** — The printer card called fan 3 "Chamber Fan" on the H2D, H2D Pro, H2C, H2S and H3C. On these printers it is the exhaust fan in the back wall, which Bambu Studio names "Exhaust", as on the P2S and X2D. Only the X1 series and P1S call it the chamber fan. The badge is still always shown on these printers, since the fan is built in, and the confirmation after setting the fan names it the exhaust fan too.

+ 2 - 0
backend/app/api/routes/auth.py

@@ -1491,6 +1491,7 @@ async def _provision_ldap_user(db: AsyncSession, ldap_user, ldap_config) -> User
     if mapped_group_names:
         groups_result = await db.execute(select(Group).where(Group.name.in_(mapped_group_names)))
         new_user.groups = list(groups_result.scalars().all())
+    new_user.sync_role_to_groups()
 
     db.add(new_user)
     await db.flush()
@@ -1556,6 +1557,7 @@ async def _sync_ldap_user(db: AsyncSession, user: User, ldap_user, ldap_config)
     groups_changed = current_group_ids != new_group_ids
     if groups_changed:
         user.groups = new_groups
+        user.sync_role_to_groups()
         changed = True
 
     if changed:

+ 15 - 1
backend/app/api/routes/groups.py

@@ -16,7 +16,7 @@ from backend.app.core.printer_scope import group_location_names, group_printer_i
 from backend.app.core.websocket import ws_manager
 from backend.app.models.group import Group, group_locations, group_printers
 from backend.app.models.printer import Printer
-from backend.app.models.user import User
+from backend.app.models.user import ADMIN_GROUP_NAME, User
 from backend.app.schemas.group import (
     GroupCreate,
     GroupDetailResponse,
@@ -407,6 +407,9 @@ async def add_user_to_group(
         )
 
     group.users.append(user)
+    # The legacy role follows Administrators membership (#3533).
+    if group.name == ADMIN_GROUP_NAME:
+        user.role = "admin"
     await db.commit()
     await ws_manager.refresh_printer_scopes()
 
@@ -445,6 +448,17 @@ async def remove_user_from_group(
             detail="User is not in this group",
         )
 
+    if group.name == ADMIN_GROUP_NAME:
+        # Leaving Administrators takes the admin rights with it, so the role
+        # follows (#3533) -- unless that leaves no active admin.
+        from backend.app.api.routes.users import _other_active_admins
+
+        if user.is_active and not await _other_active_admins(db, user.id):
+            raise HTTPException(
+                status_code=status.HTTP_400_BAD_REQUEST,
+                detail="Cannot remove admin rights from the last admin user",
+            )
+        user.role = "user"
     group.users.remove(user)
     await db.commit()
     # They may lose printers, or websocket:connect itself

+ 1 - 0
backend/app/api/routes/mfa.py

@@ -2102,6 +2102,7 @@ async def oidc_callback(
                         is_active=True,
                         groups=[default_group] if default_group else [],
                     )
+                    new_user.sync_role_to_groups()
                     db.add(new_user)
                     await db.flush()
 

+ 51 - 42
backend/app/api/routes/users.py

@@ -36,7 +36,7 @@ from backend.app.models.print_batch import PrintBatch
 from backend.app.models.print_log import PrintLogEntry
 from backend.app.models.print_queue import PrintQueueItem
 from backend.app.models.settings import Settings
-from backend.app.models.user import User
+from backend.app.models.user import ADMIN_GROUP_NAME, User
 from backend.app.models.user_otp_code import UserOTPCode
 from backend.app.models.user_totp import UserTOTP
 from backend.app.schemas.auth import (
@@ -197,6 +197,13 @@ async def create_user(
                 detail="One or more group IDs are invalid",
             )
         new_user.groups = list(groups)
+    elif user_data.role == "admin":
+        admin_group = (await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))).scalar_one_or_none()
+        new_user.groups = [admin_group] if admin_group else []
+    else:
+        new_user.groups = []
+    # As in update_user: the groups decide, role follows (#3533).
+    new_user.sync_role_to_groups()
 
     db.add(new_user)
     await db.flush()
@@ -267,6 +274,19 @@ async def get_user(
     return _user_to_response(user)
 
 
+async def _other_active_admins(db: AsyncSession, user_id: int) -> bool:
+    """Is there an active admin other than this user, by role or by group?"""
+    role_admin = await db.scalar(
+        select(User.id).where(User.role == "admin", User.is_active.is_(True), User.id != user_id).limit(1)
+    )
+    if role_admin is not None:
+        return True
+    admin_group = (
+        await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME).options(selectinload(Group.users)))
+    ).scalar_one_or_none()
+    return any(u.is_active and u.id != user_id for u in (admin_group.users if admin_group else []))
+
+
 @router.patch("/{user_id}", response_model=UserResponse)
 async def update_user(
     user_id: int,
@@ -286,35 +306,39 @@ async def update_user(
             detail="User not found",
         )
 
-    # Prevent deactivating the last admin
-    if user_data.is_active is False and user.is_admin:
-        # Count admins by role or Administrators group membership
-        admin_count_result = await db.execute(select(User).where(User.role == "admin", User.is_active.is_(True)))
-        role_admins = admin_count_result.scalars().all()
-
-        # Also check for users in Administrators group
-        admin_group_result = await db.execute(
-            select(Group).where(Group.name == "Administrators").options(selectinload(Group.users))
+    # The groups decide who is an admin, and role follows them (#3533). With
+    # both sent, the groups win; role alone moves the user in or out of
+    # Administrators.
+    if user_data.role is not None and user_data.role not in ["admin", "user"]:
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail="Role must be 'admin' or 'user'",
         )
-        admin_group = admin_group_result.scalar_one_or_none()
-        group_admins = [u for u in (admin_group.users if admin_group else []) if u.is_active]
-
-        # Combine unique admins
-        all_admins = {u.id for u in role_admins} | {u.id for u in group_admins}
-        if len(all_admins) <= 1 and user.id in all_admins:
+    new_groups: list[Group] | None = None
+    if user_data.group_ids is not None:
+        groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
+        new_groups = list(groups_result.scalars().all())
+        if len(new_groups) != len(user_data.group_ids):
             raise HTTPException(
                 status_code=status.HTTP_400_BAD_REQUEST,
-                detail="Cannot deactivate the last admin user",
+                detail="One or more group IDs are invalid",
             )
-
-    # Prevent changing role of last admin
-    if user_data.role and user_data.role != "admin" and user.role == "admin":
-        admin_count_result = await db.execute(select(User).where(User.role == "admin", User.is_active.is_(True)))
-        admin_count = len(admin_count_result.scalars().all())
-        if admin_count <= 1:
+    elif user_data.role is not None:
+        admin_group = (await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))).scalar_one_or_none()
+        others = [g for g in user.groups if g.name != ADMIN_GROUP_NAME]
+        new_groups = others + [admin_group] if user_data.role == "admin" and admin_group else others
+
+    # Prevent leaving no active admin: by deactivation, or by taking the
+    # admin rights away.
+    stays_active = user.is_active if user_data.is_active is None else user_data.is_active
+    stays_admin = user.is_admin if new_groups is None else any(g.name == ADMIN_GROUP_NAME for g in new_groups)
+    if user.is_admin and user.is_active and not (stays_active and stays_admin):
+        if not await _other_active_admins(db, user.id):
             raise HTTPException(
                 status_code=status.HTTP_400_BAD_REQUEST,
-                detail="Cannot change role of the last admin user",
+                detail="Cannot deactivate the last admin user"
+                if not stays_active
+                else "Cannot remove admin rights from the last admin user",
             )
 
     if user_data.username is not None:
@@ -385,14 +409,6 @@ async def update_user(
         user.password_changed_at = utcnow_naive()
         close_sockets = True
 
-    if user_data.role is not None:
-        if user_data.role not in ["admin", "user"]:
-            raise HTTPException(
-                status_code=status.HTTP_400_BAD_REQUEST,
-                detail="Role must be 'admin' or 'user'",
-            )
-        user.role = user_data.role
-
     if user_data.is_active is not None:
         if user.is_active and not user_data.is_active:
             # Deactivated: their printers go at the scope refresh below, but
@@ -410,16 +426,9 @@ async def update_user(
             close_sockets = True
         user.is_active = user_data.is_active
 
-    # Handle group assignments
-    if user_data.group_ids is not None:
-        groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
-        groups = groups_result.scalars().all()
-        if len(groups) != len(user_data.group_ids):
-            raise HTTPException(
-                status_code=status.HTTP_400_BAD_REQUEST,
-                detail="One or more group IDs are invalid",
-            )
-        user.groups = list(groups)
+    if new_groups is not None:
+        user.groups = new_groups
+        user.sync_role_to_groups()
 
     await ensure_user_finance_defaults(db, user)
 

+ 31 - 1
backend/app/core/database.py

@@ -7924,7 +7924,7 @@ async def seed_default_groups():
     from backend.app.core.permissions import ALL_PERMISSIONS, DEFAULT_GROUPS
     from backend.app.models.group import Group
     from backend.app.models.settings import Settings
-    from backend.app.models.user import User
+    from backend.app.models.user import ADMIN_GROUP_NAME, User
 
     logger = logging.getLogger(__name__)
 
@@ -8305,6 +8305,36 @@ async def seed_default_groups():
 
             await session.commit()
 
+        # #3533: a user moved out of Administrators kept role "admin", and with
+        # it every admin right. The role follows the groups now; this lines up
+        # the users demoted before that. Should they be the only admins left,
+        # they stay admins and join Administrators instead. One-shot.
+        role_flag = "_backfill_3533_admin_role_follows_groups_done"
+        if (await session.execute(select(Settings).where(Settings.key == role_flag))).scalar_one_or_none() is None:
+            admin_group = (
+                await session.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))
+            ).scalar_one_or_none()
+            stray = [
+                u
+                for u in (await session.execute(select(User).where(User.role == "admin"))).scalars().all()
+                if all(g.name != ADMIN_GROUP_NAME for g in u.groups)
+            ]
+            if stray and admin_group:
+                group_admins = [
+                    u
+                    for u in (await session.execute(select(User))).scalars().all()
+                    if u.is_active and any(g.name == ADMIN_GROUP_NAME for g in u.groups)
+                ]
+                for user in stray:
+                    if group_admins:
+                        user.role = "user"
+                        logger.info("User '%s' is not in Administrators: admin role removed (#3533)", user.username)
+                    else:
+                        user.groups.append(admin_group)
+                        logger.info("User '%s' is the only admin: added to Administrators (#3533)", user.username)
+            session.add(Settings(key=role_flag, value="true"))
+            await session.commit()
+
 
 async def seed_spool_catalog():
     """Seed the spool catalog with default entries if empty."""

+ 14 - 1
backend/app/models/user.py

@@ -13,6 +13,9 @@ if TYPE_CHECKING:
     from backend.app.models.group import Group
     from backend.app.models.user_email_pref import UserEmailPreference
 
+# The system group whose members are admins.
+ADMIN_GROUP_NAME = "Administrators"
+
 
 class User(Base):
     """User model for authentication and authorization.
@@ -100,7 +103,17 @@ class User(Base):
         """
         if self.role == "admin":
             return True
-        return any(g.name == "Administrators" for g in self.groups)
+        return any(g.name == ADMIN_GROUP_NAME for g in self.groups)
+
+    def sync_role_to_groups(self) -> None:
+        """Make the legacy ``role`` say what the groups say.
+
+        ``is_admin`` honours either, so a user moved out of Administrators
+        whose role still read "admin" stayed an admin, with nothing in the UI
+        to change it (#3533). Call after every change to ``groups``; needs
+        them loaded.
+        """
+        self.role = "admin" if any(g.name == ADMIN_GROUP_NAME for g in self.groups) else "user"
 
     def get_permissions(self) -> set[str]:
         """Get all permissions from all groups the user belongs to.

+ 1 - 0
backend/app/services/oidc_group_sync.py

@@ -141,6 +141,7 @@ async def sync_oidc_user_groups(
             return
 
         user.groups = new_groups
+        user.sync_role_to_groups()
         await db.commit()
         # The user's open dashboards may now see other printers (#1727)
         from backend.app.core.websocket import ws_manager

+ 276 - 0
backend/tests/integration/test_admin_role_follows_groups_3533.py

@@ -0,0 +1,276 @@
+"""Moving a user out of Administrators takes their admin rights (#3533).
+
+The setup admin is created with role "admin" and in Administrators, and
+``is_admin`` honours either. Moving them to Operators changed only the groups,
+the role kept them an admin, and the UI had no field for it. The groups decide
+now and the role follows them, from every path that changes them.
+"""
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.orm import selectinload
+
+from backend.app.models.group import Group
+from backend.app.models.settings import Settings
+from backend.app.models.user import User
+
+
+async def _groups(db_session) -> tuple[Group, Group]:
+    """The seeded system groups, created when the database has none yet."""
+    found = []
+    for name in ("Administrators", "Operators"):
+        group = await db_session.scalar(select(Group).where(Group.name == name))
+        if group is None:
+            group = Group(name=name, permissions=[], is_system=True)
+            db_session.add(group)
+            await db_session.commit()
+        found.append(group)
+    return found[0], found[1]
+
+
+async def _user(db_session, name: str, role: str, groups: list[Group], active: bool = True) -> int:
+    from backend.app.core.auth import get_password_hash
+
+    user = User(username=name, password_hash=get_password_hash("Whatever1!"), role=role, is_active=active)
+    user.groups = list(groups)
+    db_session.add(user)
+    await db_session.commit()
+    return user.id
+
+
+async def _load(db_session, user_id: int) -> User:
+    db_session.expire_all()
+    return (
+        await db_session.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
+    ).scalar_one()
+
+
+@pytest.mark.asyncio
+async def test_moving_an_admin_to_operators_takes_the_admin_rights(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    await _user(db_session, "admin", "admin", [admins])
+    demoted = await _user(db_session, "mike", "admin", [admins])
+
+    # What the edit form sent: the new groups, and the old role back.
+    response = await async_client.patch(f"/api/v1/users/{demoted}", json={"group_ids": [operators.id], "role": "admin"})
+
+    assert response.status_code == 200, response.text
+    assert response.json()["is_admin"] is False
+    user = await _load(db_session, demoted)
+    assert user.role == "user"
+    assert not user.is_admin
+
+
+@pytest.mark.asyncio
+async def test_moving_a_user_into_administrators_makes_them_admin(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    promoted = await _user(db_session, "jane", "user", [operators])
+
+    response = await async_client.patch(f"/api/v1/users/{promoted}", json={"group_ids": [admins.id]})
+
+    assert response.status_code == 200, response.text
+    assert (await _load(db_session, promoted)).role == "admin"
+
+
+@pytest.mark.asyncio
+async def test_role_alone_moves_the_user_out_of_administrators(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    await _user(db_session, "admin", "admin", [admins])
+    demoted = await _user(db_session, "mike", "admin", [admins, operators])
+
+    response = await async_client.patch(f"/api/v1/users/{demoted}", json={"role": "user"})
+
+    assert response.status_code == 200, response.text
+    user = await _load(db_session, demoted)
+    assert [g.name for g in user.groups] == ["Operators"]
+    assert not user.is_admin
+
+
+@pytest.mark.asyncio
+async def test_the_last_admin_cannot_be_moved_out_of_administrators(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    only = await _user(db_session, "admin", "admin", [admins])
+
+    response = await async_client.patch(f"/api/v1/users/{only}", json={"group_ids": [operators.id]})
+
+    assert response.status_code == 400
+    assert "last admin" in response.json()["detail"]
+    assert (await _load(db_session, only)).is_admin
+
+
+@pytest.mark.asyncio
+async def test_leaving_administrators_through_the_group_takes_the_admin_rights(async_client: AsyncClient, db_session):
+    admins, _ = await _groups(db_session)
+    await _user(db_session, "admin", "admin", [admins])
+    demoted = await _user(db_session, "mike", "admin", [admins])
+
+    response = await async_client.delete(f"/api/v1/groups/{admins.id}/users/{demoted}")
+
+    assert response.status_code == 204, response.text
+    user = await _load(db_session, demoted)
+    assert user.role == "user"
+    assert not user.is_admin
+
+
+@pytest.mark.asyncio
+async def test_the_last_admin_cannot_leave_administrators_through_the_group(async_client: AsyncClient, db_session):
+    admins, _ = await _groups(db_session)
+    only = await _user(db_session, "admin", "admin", [admins])
+
+    response = await async_client.delete(f"/api/v1/groups/{admins.id}/users/{only}")
+
+    assert response.status_code == 400
+    assert (await _load(db_session, only)).is_admin
+
+
+@pytest.mark.asyncio
+async def test_joining_administrators_through_the_group_sets_the_role(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    promoted = await _user(db_session, "jane", "user", [operators])
+
+    response = await async_client.post(f"/api/v1/groups/{admins.id}/users/{promoted}")
+
+    assert response.status_code == 204, response.text
+    assert (await _load(db_session, promoted)).role == "admin"
+
+
+@pytest.mark.asyncio
+async def test_a_new_user_gets_the_role_of_their_groups(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+
+    as_operator = await async_client.post(
+        "/api/v1/users", json={"username": "op", "password": "Whatever1!", "role": "admin", "group_ids": [operators.id]}
+    )
+    as_admin = await async_client.post(
+        "/api/v1/users", json={"username": "ad", "password": "Whatever1!", "role": "admin"}
+    )
+
+    assert as_operator.status_code == 201, as_operator.text
+    assert as_operator.json()["is_admin"] is False
+    assert as_admin.status_code == 201, as_admin.text
+    assert [g["name"] for g in as_admin.json()["groups"]] == ["Administrators"]
+
+
+class TestBackfill:
+    """Users demoted before the fix are lined up once at startup."""
+
+    FLAG = "_backfill_3533_admin_role_follows_groups_done"
+
+    @classmethod
+    async def _rearm(cls, db_session):
+        """The app's own startup in the fixture has already run it once."""
+        from sqlalchemy import delete
+
+        await db_session.execute(delete(Settings).where(Settings.key == cls.FLAG))
+        await db_session.commit()
+
+    @staticmethod
+    async def _run(db_session):
+        from backend.app.core.database import seed_default_groups
+
+        await seed_default_groups()
+        db_session.expire_all()
+
+    @pytest.mark.asyncio
+    async def test_a_demoted_admin_loses_the_admin_role(self, async_client: AsyncClient, db_session):
+        admins, operators = await _groups(db_session)
+        await _user(db_session, "admin", "admin", [admins])
+        demoted = await _user(db_session, "mike", "admin", [operators])
+        await self._rearm(db_session)
+
+        await self._run(db_session)
+
+        user = await _load(db_session, demoted)
+        assert user.role == "user"
+        assert not user.is_admin
+        flag = await db_session.scalar(select(Settings.value).where(Settings.key == self.FLAG))
+        assert flag == "true"
+
+    @pytest.mark.asyncio
+    async def test_the_only_admin_joins_administrators_instead(self, async_client: AsyncClient, db_session):
+        _, operators = await _groups(db_session)
+        only = await _user(db_session, "admin", "admin", [operators])
+        await self._rearm(db_session)
+
+        await self._run(db_session)
+
+        user = await _load(db_session, only)
+        assert user.is_admin
+        assert "Administrators" in [g.name for g in user.groups]
+
+    @pytest.mark.asyncio
+    async def test_runs_once(self, async_client: AsyncClient, db_session):
+        admins, operators = await _groups(db_session)
+        await _user(db_session, "admin", "admin", [admins])
+        await self._rearm(db_session)
+        db_session.add(Settings(key=self.FLAG, value="true"))
+        await db_session.commit()
+        kept = await _user(db_session, "mike", "admin", [operators])
+
+        await self._run(db_session)
+
+        assert (await _load(db_session, kept)).role == "admin"
+
+
+class TestIdentityProviderSync:
+    """LDAP and OIDC logins set the groups too, so the role follows there."""
+
+    @pytest.mark.asyncio
+    async def test_an_ldap_login_that_drops_administrators_drops_the_role(self, db_session):
+        from types import SimpleNamespace
+
+        from backend.app.api.routes.auth import _sync_ldap_user
+
+        admins, operators = await _groups(db_session)
+        user_id = await _user(db_session, "alice", "admin", [admins])
+        user = await _load(db_session, user_id)
+        user.auth_source = "ldap"
+        user.email = "alice@example.invalid"
+        await db_session.commit()
+
+        await _sync_ldap_user(
+            db_session,
+            user,
+            SimpleNamespace(username="alice", email="alice@example.invalid", groups=["cn=ops"]),
+            SimpleNamespace(group_mapping={"cn=admins": "Administrators", "cn=ops": "Operators"}, default_group=""),
+        )
+
+        user = await _load(db_session, user_id)
+        assert [g.name for g in user.groups] == ["Operators"]
+        assert user.role == "user"
+        assert not user.is_admin
+
+    @pytest.mark.asyncio
+    async def test_an_oidc_login_into_administrators_sets_the_role(self, db_session):
+        from backend.app.services.oidc_group_sync import sync_oidc_user_groups
+
+        admins, operators = await _groups(db_session)
+        user_id = await _user(db_session, "bob", "user", [operators])
+        user = await _load(db_session, user_id)
+
+        await sync_oidc_user_groups(
+            db_session,
+            user,
+            group_claim="groups",
+            group_mapping={"staff": "Administrators"},
+            claims={"groups": ["staff"]},
+        )
+
+        assert (await _load(db_session, user_id)).role == "admin"
+
+    @pytest.mark.asyncio
+    async def test_an_ldap_user_created_into_administrators_gets_the_role(self, db_session):
+        from types import SimpleNamespace
+
+        from backend.app.api.routes.auth import _provision_ldap_user
+
+        await _groups(db_session)
+
+        user = await _provision_ldap_user(
+            db_session,
+            SimpleNamespace(username="carol", email="carol@example.invalid", groups=["cn=admins"]),
+            SimpleNamespace(group_mapping={"cn=admins": "Administrators"}, default_group=""),
+        )
+
+        assert (await _load(db_session, user.id)).role == "admin"

+ 3 - 1
frontend/src/__tests__/pages/SettingsPageUsersWiring.test.tsx

@@ -156,10 +156,12 @@ describe('SettingsPage users & groups wiring', () => {
     expect(writes()[0].body).toEqual({
       username: 'alice2',
       email: 'alice@example.com',
-      role: 'user',
       group_ids: [4],
     });
     expect(writes()[0].body).not.toHaveProperty('password');
+    // The groups decide who is an admin; the old role sent back kept a
+    // demoted admin one (#3533).
+    expect(writes()[0].body).not.toHaveProperty('role');
   });
 
   it('edit user with the email field emptied sends an empty email, which removes it', async () => {

+ 2 - 1
frontend/src/pages/SettingsPage.tsx

@@ -1030,7 +1030,8 @@ export function SettingsPage() {
       password: userFormData.password || undefined,
       // Empty removes the email; the backend reads null as "unchanged".
       email: userFormData.email,
-      role: userFormData.role,
+      // No role: there is no field for it, and the backend derives it from
+      // the groups. Sending the old one back kept a demoted admin an admin (#3533).
       group_ids: userFormData.group_ids,
     };
     if (!updateData.password) {