HIGH mass assignmentfastapibasic auth

Mass Assignment in Fastapi with Basic Auth

Mass Assignment in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Mass assignment occurs when an API endpoint binds incoming request data directly to a model or data structure without explicit field filtering. In Fastapi, this commonly happens when developers use a Pydantic model with Field(..., include) or rely on models that accept a broad set of attributes, then pass parsed data directly to a database layer such as an ORM .create() or .update(). When Basic Authentication is used, the request may carry an Authorization header, but the presence of Basic Auth does not reduce the risk of mass assignment; in fact, it can create a false sense of security.

Consider an endpoint that updates a user profile. A naive implementation might parse credentials via Basic Auth to identify the user, then bind the request body to a model that includes sensitive fields such as is_admin or permissions. Because Fastapi trusts the incoming payload by default, an attacker who knows the field names can inject these attributes even when the UI does not expose them. The authentication layer confirms identity but does not enforce authorization or input whitelisting, so the mass assignment vulnerability remains fully exploitable.

With OpenAPI/Swagger spec analysis, middleBrick correlates the endpoint’s schema definitions with runtime behavior. If the spec defines a UserUpdate model that includes privileged fields but the endpoint does not explicitly exclude them, middleBrick flags this as a BFLA/Privilege Escalation check. The scanner highlights where unchecked input leads to potential privilege escalation, noting that Basic Auth headers are parsed but not used to constrain which fields are accepted. This combination increases the impact of the issue because authenticated requests are more likely to be processed by backend logic that performs database writes.

Real-world attack patterns mirror this scenario. For example, an attacker can send crafted JSON to an authenticated endpoint to modify is_admin or other sensitive attributes, referencing common OWASP API Top 10 API1:2023 — Broken Object Level Authorization. middleBrick’s checks include property authorization and input validation to detect when models lack explicit allowlists. Even with Basic Auth enforcing transport-level identity, without strict field filtering the API remains vulnerable to tampering and unintended data exposure.

middleBrick also inspects the spec for $ref resolution across definitions, ensuring that inherited models and inline schemas are evaluated for excessive attribute acceptance. This helps identify cases where nested models or arrays enable mass assignment across related resources. By cross-referencing spec definitions with actual endpoint behavior, the scanner surfaces gaps where authentication and authorization are misaligned, providing findings with severity and remediation guidance.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

To mitigate mass assignment in Fastapi with Basic Authentication, enforce strict input filtering and decouple authentication from data binding. Use explicit field lists or Pydantic’s exclude_unset and exclude_none strategies when updating models, and avoid passing the raw request body directly to ORM methods.

Example 1: Safe update with explicit field selection

from fastapi import FastAPI, Depends, HTTPException, status
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

class UserUpdate(BaseModel):
    email: Optional[str] = None
    full_name: Optional[str] = None
    # Do not include is_admin or other sensitive fields here

class AuthCredentials(BaseModel):
    username: str
    password: str

def get_current_user(auth: AuthCredentials = Depends()):
    # Validate credentials against a secure store
    if not (auth.username == "alice" and auth.password == "secret"):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials"
        )
    return {"username": auth.username}

@app.patch("/users/me")
def update_user(
    updates: UserUpdate,
    user: dict = Depends(get_current_user)
):
    # Only fields defined in UserUpdate are accepted
    # Here you would apply updates to the database using explicit fields
    return {"message": "ok", "data": updates.dict()}

Example 2: Using model_dump to exclude unset and controlling updates

from fastapi import FastAPI, Depends, HTTPException, status
from pydantic import BaseModel, ConfigDict
from typing import Optional

app = FastAPI()

class User(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    email: str
    full_name: str
    is_admin: bool = False

def get_current_user(auth: AuthCredentials = Depends()):
    # Validate credentials
    return {"username": auth.username}

@app.put("/users/{user_id}")
def update_user_safe(
    user_id: int,
    updates: UserUpdate,
    user: dict = Depends(get_current_user)
):
    # Convert to dict and only allow known safe fields
    update_data = updates.model_dump(exclude_unset=True)
    # Apply update_data to the ORM model explicitly
    return {"message": "updated", "fields": update_data}

These patterns ensure that the request body is bound only to a curated model, preventing attackers from injecting unexpected attributes. Basic Auth can still be used for identity verification, but authorization and data acceptance must be handled separately through explicit field handling and server-side checks.

middleBrick’s scans highlight endpoints where mass assignment risks exist alongside Basic Auth usage. By following the remediation guidance, you reduce the attack surface and align authentication with strict input validation.

Related CWEs: propertyAuthorization

CWE IDNameSeverity
CWE-915Mass Assignment HIGH

Frequently Asked Questions

Does using Basic Auth prevent mass assignment in Fastapi APIs?
No. Basic Authentication identifies the requestor but does not limit which fields the API accepts. Mass assignment depends on how the endpoint binds input data, not on authentication.
How does middleBrick detect mass assignment risks in Fastapi specs?
middleBrick compares the OpenAPI/Swagger model definitions with endpoint behavior, flagging cases where models include sensitive or broad fields without explicit allowlists or filtering in update/create operations.