Skip to content

[Bug] /setSession endpoint crashes on malformed or non-JSON requests #247

@parthdagia05

Description

@parthdagia05

Summary

The /setSession endpoint should safely validate incoming requests.

Expected behavior:

  • If the request body is not valid JSON → return 400 Bad Request
  • If the "case" field is missing → return 400 Bad Request
  • If "case" is empty or whitespace → return 400 Bad Request
  • If the request is valid → store the case in the session and return 200 OK

The endpoint should never crash due to malformed or invalid input.

Expected behavior


Proposed Solution

Improve input validation for the `/setSession` endpoint.

Key improvements:

1. Safely parse JSON using `request.get_json(silent=True)`
2. Validate presence of the `"case"` key
3. Reject empty or whitespace case names
4. Return consistent `400 Bad Request` responses for invalid input

Example implementation:

```python
body = request.get_json(silent=True)

if body is None:
    return jsonify({"message": "Invalid JSON payload."}), 400

cs = body.get("case")

if cs is None:
    return jsonify({"message": "Missing 'case' parameter."}), 400

if not isinstance(cs, str) or not cs.strip():
    return jsonify({"message": "Case name cannot be empty."}), 400

### Reproduction steps

1. Start the Flask server.
2. Send a POST request with invalid JSON:

curl -X POST http://localhost:5000/setSession \
-H "Content-Type: application/json" \
-d "hello"

Result: server returns **500 Internal Server Error**

3. Send malformed JSON:

curl -X POST http://localhost:5000/setSession \
-H "Content-Type: application/json" \
-d '{bad}'

Result: server crashes with JSON parsing error.

4. Send valid JSON but missing the `"case"` key:

curl -X POST http://localhost:5000/setSession \
-H "Content-Type: application/json" \
-d '{}'

Result: incorrect handling of input.

These cases should instead return **400 Bad Request** with a clear error message.

### Environment

OS: Windows 11  
Python: 3.11  
Repository: EAPD-DRB/MUIOGO  
Branch: main

### Logs or screenshots

Example error when sending non-JSON payload:

TypeError: 'NoneType' object is not subscriptable

This occurs because `request.json` returns `None` when the body is not valid JSON, but the code immediately tries to access `request.json['case']`.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    Status

    In progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions