Skip to content

Handle JSON Decoder errors #762

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

landonshumway-ia
Copy link
Collaborator

@landonshumway-ia landonshumway-ia commented Apr 23, 2025

In the event that a request is malformed JSON, we want to handle this issue gracefully and return a 400

This also sets the registration endpoint request schema to strict, to avoid allowing the user to specify any unrecognized fields.

Closes #761

Summary by CodeRabbit

  • Bug Fixes
    • Improved validation of provider registration requests by strictly enforcing accepted fields.
    • Enhanced API request handling to reject unsupported media types and malformed JSON payloads, returning clear error responses for each case.
  • New Features
    • Introduced specific error messaging for unsupported media types in API requests.
  • Tests
    • Added unit tests to verify error handling for unsupported media types and malformed JSON in API requests.
  • Style
    • Reformatted code for improved readability without affecting functionality.
  • Chores
    • Updated test resources to include the "Content-Type: application/json" header for consistency.

In the event that a request is malformed JSON, we want to handle this issue
gracefully and return a 400
Copy link
Contributor

coderabbitai bot commented Apr 23, 2025

Walkthrough

This set of changes enforces strict JSON request validation for API endpoints, particularly for provider registration. The code now rejects requests with unsupported media types and malformed JSON, returning appropriate HTTP error responses (415 for unsupported media type, 400 for malformed JSON). A new exception class is introduced to represent unsupported media types, and the schema for provider registration is made strict by switching its base class. Unit tests and test resources are updated to verify and reflect the new validation logic, while some code is reformatted for clarity.

Changes

File(s) Change Summary
backend/compact-connect/lambdas/python/common/cc_common/data_model/schema/provider/api.py Changed ProviderRegistrationRequestSchema base class from ForgivingSchema to strict Schema.
backend/compact-connect/lambdas/python/common/cc_common/exceptions.py Added new exception: CCUnsupportedMediaTypeException (inherits from CCInvalidRequestException).
backend/compact-connect/lambdas/python/common/cc_common/utils.py Enforced JSON-only content type in API handler, added handling for malformed JSON and unsupported media types.
backend/compact-connect/lambdas/python/common/tests/unit/test_api_handler.py Added unit tests for unsupported media type (415) and malformed JSON (400) error handling.
backend/compact-connect/lambdas/python/common/tests/resources/api-event.json
backend/compact-connect/lambdas/python/staff-users/tests/resources/api-event.json
Added "Content-Type": "application/json" header to test event resources.
backend/compact-connect/stacks/api_stack/v1_api/provider_users.py Reformatted LambdaIntegration instantiation for clarity; no functional changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API Gateway
    participant Lambda(api_handler)
    participant Schema

    Client->>API Gateway: POST /v1/provider-users/registration (with headers/body)
    API Gateway->>Lambda(api_handler): Invoke with event
    Lambda(api_handler)->>Lambda(api_handler): Check Content-Type header
    alt Content-Type is not application/json
        Lambda(api_handler)-->>Client: Return 415 Unsupported Media Type
    else Content-Type is application/json
        Lambda(api_handler)->>Lambda(api_handler): Parse JSON body
        alt Malformed JSON
            Lambda(api_handler)-->>Client: Return 400 Bad Request
        else Well-formed JSON
            Lambda(api_handler)->>Schema: Validate and load body
            alt Validation error
                Lambda(api_handler)-->>Client: Return 400 Bad Request
            else Valid
                Lambda(api_handler)-->>Client: Return 200 OK (or relevant response)
            end
        end
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Gracefully handle JSONDecodeError in registration endpoint and return 400 instead of 502 (#761)
Reject requests with unsupported Content-Type and return 415 (#761)
Make schema strict to prevent extra fields and enforce correct deserialization in registration (#761)

Poem

A rabbit hops with code so neat,
Now JSON errors face defeat!
If headers lie or bodies break,
A 415 or 400 you’ll take.
With tests in tow and schemas tight,
The API now handles things right.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2842dd8 and bb5d1c3.

📒 Files selected for processing (6)
  • backend/compact-connect/lambdas/python/common/cc_common/exceptions.py (1 hunks)
  • backend/compact-connect/lambdas/python/common/cc_common/utils.py (4 hunks)
  • backend/compact-connect/lambdas/python/common/tests/resources/api-event.json (1 hunks)
  • backend/compact-connect/lambdas/python/common/tests/unit/test_api_handler.py (1 hunks)
  • backend/compact-connect/lambdas/python/staff-users/tests/resources/api-event.json (1 hunks)
  • backend/compact-connect/stacks/api_stack/v1_api/provider_users.py (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • backend/compact-connect/lambdas/python/common/tests/resources/api-event.json
  • backend/compact-connect/lambdas/python/staff-users/tests/resources/api-event.json
  • backend/compact-connect/lambdas/python/common/cc_common/exceptions.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/compact-connect/stacks/api_stack/v1_api/provider_users.py
🧰 Additional context used
🧬 Code Graph Analysis (2)
backend/compact-connect/lambdas/python/common/cc_common/utils.py (1)
backend/compact-connect/lambdas/python/common/cc_common/exceptions.py (1)
  • CCUnsupportedMediaTypeException (23-24)
backend/compact-connect/lambdas/python/common/tests/unit/test_api_handler.py (1)
backend/compact-connect/lambdas/python/common/cc_common/utils.py (1)
  • api_handler (81-189)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: TestPython
🔇 Additional comments (8)
backend/compact-connect/lambdas/python/common/cc_common/utils.py (6)

26-26: Good addition of the new exception class to imports.

This new import supports the enhanced API validation logic to reject unsupported media types.


105-106: Good practice: Extracting the Content-Type header for validation.

Extracting the Content-Type header allows for proper validation of incoming requests and improves logging context.


112-112: Enhanced logging with content_type.

Adding content_type to the logging context improves request traceability and debugging capabilities.


120-123: Great implementation of content type validation.

This validation properly enforces that API requests with bodies must use the 'application/json' content type, improving the robustness of the API. The check correctly handles the case when the body is None.


150-156: Good implementation of the 415 Unsupported Media Type error response.

The handler for CCUnsupportedMediaTypeException correctly returns a 415 status code with appropriate headers and error message, following the pattern established by other exception handlers.


171-177: Excellent addition of JSON decode error handling.

This addresses the core PR objective by properly handling malformed JSON and returning a 400 Bad Request response. The error message is clear and informative.

backend/compact-connect/lambdas/python/common/tests/unit/test_api_handler.py (2)

148-164: Good test for the unsupported media type scenario.

This test properly verifies that requests with non-JSON content types are rejected with a 415 status code. The test setup is clear, setting the Content-Type to 'text/plain' and providing a non-JSON body.


165-179: Well-structured test for JSON decode errors.

This test correctly verifies that malformed JSON payloads are handled properly, returning a 400 status code. The test is thorough and directly tests the new functionality.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

This will prevent callers from setting invalid media types when
calling the registration endpoint.
@landonshumway-ia landonshumway-ia marked this pull request as ready for review April 24, 2025 13:39
@jusdino jusdino force-pushed the fix/registration-decode-error branch from 2842dd8 to bb5d1c3 Compare May 2, 2025 15:22
Copy link
Collaborator

@jusdino jusdino left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@landonshumway-ia , you want to review my contribution here, as well?

@landonshumway-ia
Copy link
Collaborator Author

@jusdino looks good. @jlkravitz This is ready for your review. Thanks

@landonshumway-ia landonshumway-ia requested a review from jlkravitz May 2, 2025 15:43
Copy link
Collaborator

@jlkravitz jlkravitz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! @isabeleliassen Good to merge.

@isabeleliassen isabeleliassen self-requested a review May 2, 2025 17:47
@isabeleliassen isabeleliassen merged commit 5dea247 into csg-org:development May 2, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

JSONDecode Error on registration endpoint
4 participants