GuardAPI Logo
GuardAPI

Fix Mass Assignment in Pyramid

Mass Assignment in Pyramid occurs when an application takes user-provided input and binds it directly to internal database models without filtering. In Pyramid/SQLAlchemy stacks, this typically happens when developers iterate over `request.json_body` and call `setattr` on a model instance. An attacker can exploit this to overwrite sensitive fields like 'is_admin', 'role', or 'password_reset_token' by simply adding them to the JSON payload.

The Vulnerable Pattern

@view_config(route_name='profile_update', request_method='POST', renderer='json')
def profile_update(request):
    user = request.dbsession.query(User).filter(User.id == request.authenticated_userid).first()
    # VULNERABLE: Blindly applying all keys from the request to the model
    for key, value in request.json_body.items():
        setattr(user, key, value)
    return {'status': 'updated'}

The Secure Implementation

The vulnerable code uses a dynamic loop to map the entire HTTP request body to the SQLAlchemy model, allowing an attacker to inject 'is_admin: true' into the JSON. The secure implementation utilizes a 'Data Transfer Object' (DTO) pattern via Marshmallow. By defining a strict schema and setting 'unknown=EXCLUDE', we create an allow-list. Even if the attacker sends extra fields, the schema loader strips them before they ever reach the model layer, ensuring only intended fields are updated.

from marshmallow import Schema, fields, EXCLUDE

class UserProfileSchema(Schema): class Meta: unknown = EXCLUDE # Drop any fields not explicitly defined here email = fields.Email() bio = fields.Str() display_name = fields.Str()

@view_config(route_name=‘profile_update’, request_method=‘POST’, renderer=‘json’) def profile_update(request): user = request.dbsession.query(User).filter(User.id == request.authenticated_userid).first() schema = UserProfileSchema() # SECURE: Only validated and allowed fields are returned data = schema.load(request.json_body) for key, value in data.items(): setattr(user, key, value) return {‘status’: ‘updated’}

System Alert • ID: 2739
Target: Pyramid API
Potential Vulnerability

Your Pyramid API might be exposed to Mass Assignment

74% of Pyramid apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.