Skip to content

[ISSUE]: Incorrect Content-Type Validation Logic in middleware.py #395

Closed

Description

@Aditya8369

Description

Description:
In safe_request_handler() decorator in backend/middleware.py, when require_json=True is set, it still incorrectly validates and allows application/x-www-form-urlencoded as valid content type:

# In safe_request_handler (lines 117-122):
if validate_content_type and request.method not in ['GET', 'HEAD']:
    ct = request.content_type
    if not ct or ct.split(';')[0].strip() not in ['application/json']:
        logger.warning(f"Content-Type validation failed for {request.path}")
        return invalid_json_error("Invalid or missing Content-Type header")

The logic not in ['application/json'] is correct, but when require_json=True is passed explicitly, it should strictly validate JSON only, not the broader type list. However, there's also another part that incorrectly allows urlencoded even when JSON is required.

Steps to fix:

  1. Open backend/middleware.py
  2. Find the safe_request_handler() function
  3. Modify the Content-Type validation to be more explicit when require_json=True:
    if validate_content_type and request.method not in ['GET', 'HEAD']:
        ct = request.content_type
        allowed = ['application/json'] if require_json else ['application/json', 'application/x-www-form-urlencoded']
        if not ct or ct.split(';')[0].strip() not in allowed:
            logger.warning(f"Content-Type validation failed for {request.path}")
            return invalid_json_error("Invalid or missing Content-Type header")

Additional Context

No response

Activity

  1. Aditya8369 commented on May 1, 2026

    @Aditya8369
    ContributorAuthor

    @devanshi14malhotra please assign me

  2. added
    NSoC'26For issues and PRs which are a part of the Nexus Spring of Code open source event
    on May 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

NSoC'26For issues and PRs which are a part of the Nexus Spring of Code open source eventbackendlevel25 points

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions