Add validation to prevent privilege escalation via is_superuser field and enhance related tests
- Added explicit Pydantic validation to reject modifications to `is_superuser` in `UserUpdate` schema. - Updated backend logic in `users.py` to support defense-in-depth against privilege escalation. - Introduced comprehensive tests for `/users` and `/users/me` endpoints to ensure `is_superuser` validation works correctly. - Enhanced error handling and validation messages for better clarity and robustness.
This commit is contained in:
@@ -38,6 +38,7 @@ class UserUpdate(BaseModel):
|
||||
password: Optional[str] = None
|
||||
preferences: Optional[Dict[str, Any]] = None
|
||||
is_active: Optional[bool] = None # Changed default from True to None to avoid unintended updates
|
||||
is_superuser: Optional[bool] = None # Explicitly reject privilege escalation attempts
|
||||
|
||||
@field_validator('phone_number')
|
||||
@classmethod
|
||||
@@ -52,6 +53,14 @@ class UserUpdate(BaseModel):
|
||||
return v
|
||||
return validate_password_strength(v)
|
||||
|
||||
@field_validator('is_superuser')
|
||||
@classmethod
|
||||
def prevent_superuser_modification(cls, v: Optional[bool]) -> Optional[bool]:
|
||||
"""Prevent users from modifying their superuser status via this schema."""
|
||||
if v is not None:
|
||||
raise ValueError("Cannot modify superuser status through user update")
|
||||
return v
|
||||
|
||||
|
||||
class UserInDB(UserBase):
|
||||
id: UUID
|
||||
|
||||
Reference in New Issue
Block a user