supervisor icon indicating copy to clipboard operation
supervisor copied to clipboard

Return 401 Unauthorized when using json/url encoded auth fails

Open agners opened this issue 8 months ago • 3 comments

Proposed change

When authentication using JSON payload or URL encoded payload fails, use the generic HTTP response code 401 Unauthorized instead of 400 Bad Request.

This is a more appropriate response code for authentication errors and is consistent with the behavior of other authentication methods.

Type of change

  • [ ] Dependency upgrade
  • [ ] Bugfix (non-breaking change which fixes an issue)
  • [ ] New feature (which adds functionality to the supervisor)
  • [x] Breaking change (fix/feature causing existing functionality to break)
  • [x] Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to cli pull request:
  • Link to client library pull request:

Checklist

  • [ ] The code change is tested and works locally.
  • [ ] Local tests pass. Your PR cannot be merged unless tests pass
  • [ ] There is no commented out code in this PR.
  • [ ] I have followed the development checklist
  • [ ] The code has been formatted using Ruff (ruff format supervisor tests)
  • [ ] Tests have been added to verify that the new code works.

If API endpoints or add-on configuration are added/changed:

Summary by CodeRabbit

  • Bug Fixes
    • Improved authentication error handling to return 401 Unauthorized for failed JSON and URL-encoded authentication attempts.
    • Adjusted response headers to ensure the WWW_AUTHENTICATE header is only present when appropriate.
  • Tests
    • Updated authentication tests to reflect new status codes and header behaviors for failed login scenarios.

agners avatar Apr 25 '25 13:04 agners

This is something in between a bugfix and a breaking change. Depending on how the client which is using JSON or URL encoded authentication is coded, this change might lead to mishandling the unauthenticated case. Not sure how widely and by what consumers this API is used.

agners avatar Apr 25 '25 13:04 agners

📝 Walkthrough

Walkthrough

The changes update the authentication logic in the API by modifying how failed authentication attempts are handled for JSON and URL-encoded requests. The authentication method now explicitly raises an HTTP 401 Unauthorized error when credentials are invalid, instead of returning a falsy value. Corresponding test cases are updated to expect the new 401 status code and to verify the presence or absence of the WWW_AUTHENTICATE header as appropriate. Additionally, imports and comments are adjusted to align with these changes.

Changes

File(s) Change Summary
supervisor/api/auth.py Modified the auth method to raise HTTP 401 Unauthorized on failed authentication for JSON and URL-encoded content types; added clarifying comments.
tests/api/test_auth.py Updated tests to expect 401 status instead of 400 for failed authentication; added assertions for WWW_AUTHENTICATE header; imported WWW_AUTHENTICATE from aiohttp.hdrs.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API (auth method)
    participant _process_dict

    Client->>API (auth method): Send authentication request (JSON or URL-encoded)
    API (auth method)->>_process_dict: Validate credentials
    _process_dict-->>API (auth method): Return result (truthy or falsy)
    alt Credentials valid
        API (auth method)-->>Client: Return success (True)
    else Credentials invalid
        API (auth method)-->>Client: Raise HTTP 401 Unauthorized
    end

📜 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 0e7e4f8b42ca3d71222bb875e96be5f437314aeb and 14e2ddc6d392fb250d7ee8c293ae707e9baac59b.

📒 Files selected for processing (2)
  • supervisor/api/auth.py (1 hunks)
  • tests/api/test_auth.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
  • GitHub Check: Run tests Python 3.13.3
🔇 Additional comments (7)
supervisor/api/auth.py (3)

82-84: Improved HTTP status handling for JSON authentication.

The code now correctly raises HTTPUnauthorized (401) instead of implicitly returning a falsy value when JSON authentication fails. This follows HTTP protocol standards where 401 is the appropriate status code for authentication failures rather than 400.


89-91: Improved HTTP status handling for URL-encoded authentication.

The code now correctly raises HTTPUnauthorized (401) instead of implicitly returning a falsy value when URL-encoded authentication fails. This follows HTTP protocol standards where 401 is the appropriate status code for authentication failures rather than 400.


93-93: Good clarifying comment.

This comment helps explain why Basic authentication headers are added to the default case, making the code more maintainable and easier to understand.

tests/api/test_auth.py (4)

6-6: Good addition of WWW_AUTHENTICATE import.

Adding this import allows the tests to properly verify header presence, which is crucial for the updated behavior being tested.


141-142: Test case properly updated for JSON authentication failure.

The test now correctly asserts that:

  1. The WWW_AUTHENTICATE header is not present in the response
  2. The status code is 401 (Unauthorized) instead of the previous 400 (Bad Request)

This aligns with the implementation changes in auth.py and HTTP standards.


188-189: Test case properly updated for URL-encoded authentication failure.

The test now correctly asserts that:

  1. The WWW_AUTHENTICATE header is not present in the response
  2. The status code is 401 (Unauthorized) instead of the previous 400 (Bad Request)

This aligns with the implementation changes in auth.py and HTTP standards.


200-200: Test case properly updated for unsupported content type.

The test now correctly verifies that Basic authentication is being advertised in the WWW_AUTHENTICATE header when content type is unsupported, which aligns with the comment added in auth.py.

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

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 or @coderabbitai title 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.

coderabbitai[bot] avatar Apr 25 '25 13:04 coderabbitai[bot]

There hasn't been any activity on this pull request recently. This pull request has been automatically marked as stale because of that and will be closed if no further activity occurs within 7 days. Thank you for your contributions.

github-actions[bot] avatar May 25 '25 14:05 github-actions[bot]