Skip to content

Conversation

@omertuc
Copy link
Contributor

@omertuc omertuc commented Aug 27, 2025

Description

Endpoints configured for the anybody (*) role should work without an Authorization header.

This change allows requests without the header to be processed, returning a default user identity, which will obviously receive the anybody role (*) (because everyone receives it), so if the configuration allows particular endpoints to be reachable by the * role, guests (no auth header) users will be authorized to use it.

This is good for the readiness/liveness endpoints

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

  • Related Issue #
  • Closes #

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

Summary by CodeRabbit

  • New Features
    • Unauthenticated requests without an Authorization header are now treated as “guest” access instead of returning an error.
    • Guest requests use a default user identity and carry no JWT claims, allowing public endpoints to function without authentication while maintaining restricted permissions.
  • Tests
    • Updated unit tests to validate guest behavior for missing Authorization headers and ensure consistent handling of default user identity and empty claims.

Endpoints configured for the anybody (`*`) authorization should work
without an Authorization header.

This change allows requests without the header to be processed,
returning a default user identity, which will obviously receive the
anybody role (`*`) (because everyone receives it), so if the
configuration allows particular endpoints to be reachable by the `*`
role, guests (no auth header) users will be authorized to use it.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

Adds a default no-auth tuple in the auth interface, updates JWK token dependency to return this tuple when the Authorization header is absent and to use a typed AuthTuple, adjusts JWT roles resolver to skip claims parsing for a no-user token, and updates unit tests accordingly.

Changes

Cohort / File(s) Summary of modifications
Auth interface defaults
src/auth/interface.py
Added public constant NO_AUTH_TUPLE: AuthTuple = (DEFAULT_USER_UID, DEFAULT_USER_NAME, NO_USER_TOKEN); imported DEFAULT_USER_NAME, DEFAULT_USER_UID, NO_USER_TOKEN. No changes to existing type aliases or abstract method.
JWK token auth dependency
src/auth/jwk_token.py
Updated to import AuthTuple and NO_AUTH_TUPLE. Changed JwkTokenAuthDependency.__call__ return type to AuthTuple. Added early return of NO_AUTH_TUPLE when Authorization header is missing. Deferred token extraction until after header presence check; retained decode/validate logic otherwise.
Authorization resolvers
src/authorization/resolvers.py
Imported constants. In JwtRolesResolver._get_claims, added guard: if token is NO_USER_TOKEN, return empty claims dict without JSON parsing.
Unit tests
tests/unit/auth/test_jwk_token.py
Imported DEFAULT_USER_NAME, DEFAULT_USER_UID, NO_USER_TOKEN. Updated test_no_auth_header to expect a default AuthTuple instead of an HTTPException for missing Authorization header.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant C as Client
    participant R as Request
    participant A as JwkTokenAuthDependency
    participant Z as Authorization Resolver

    C->>R: HTTP request
    R->>A: __call__(request)
    alt Authorization header missing
        A-->>R: NO_AUTH_TUPLE (DEFAULT_USER_UID, DEFAULT_USER_NAME, NO_USER_TOKEN)
    else Header present
        A->>A: Extract bearer token
        A->>A: Decode/validate JWT
        A-->>R: AuthTuple(user_id, user_name, token)
    end
    R->>Z: Resolve roles with (user_id, user_name, token)
    alt token == NO_USER_TOKEN
        Z->>Z: Return {} (empty claims)
    else token present
        Z->>Z: Parse claims from token
    end
    Z-->>C: Roles/authorization outcome
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through headers, light and quick,
No token? No panic—defaults do the trick.
Claims stay empty, silent as snow,
Yet flows align, onward we go.
With ears up high and tests that pass,
This bunny approves—ship it fast! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/auth/interface.py (1)

20-20: Solid addition: a single source of truth for the guest auth tuple.

Minor: consider a short docstring comment above NO_AUTH_TUPLE clarifying that NO_USER_TOKEN is a sentinel (not JSON) and is only compared by equality checks.

- NO_AUTH_TUPLE: AuthTuple = (DEFAULT_USER_UID, DEFAULT_USER_NAME, NO_USER_TOKEN)
+ # Guest identity used when no Authorization header is present; token is a sentinel.
+ NO_AUTH_TUPLE: AuthTuple = (DEFAULT_USER_UID, DEFAULT_USER_NAME, NO_USER_TOKEN)
tests/unit/auth/test_jwk_token.py (1)

271-276: Good assertions for guest tuple; add a test ensuring '*' access actually works.

This test validates the tuple only. Please add a test that proves endpoints (or resolvers/access) gated by '*' are reachable without headers (see suggestions in resolvers.py comment).

I can add a focused unit test for JwtRolesResolver or GenericAccessResolver to lock this behavior in CI—want me to push that?

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d89f7a3 and 8c24935.

📒 Files selected for processing (4)
  • src/auth/interface.py (1 hunks)
  • src/auth/jwk_token.py (2 hunks)
  • src/authorization/resolvers.py (2 hunks)
  • tests/unit/auth/test_jwk_token.py (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/auth/jwk_token.py (2)
src/auth/interface.py (1)
  • AuthInterface (23-28)
src/auth/utils.py (1)
  • extract_user_token (7-26)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests
🔇 Additional comments (6)
src/authorization/resolvers.py (2)

12-12: Import is appropriate and consistent with usage.


75-78: Review Comment Outdated: NO_USER_TOKEN Branch Not Present

I inspected src/authorization/resolvers.py and did not find any constants.NO_USER_TOKEN check or a _get_claims method in the current JwtRolesResolver. The code for resolve_roles simply pulls JWT claims and applies the configured rules:

async def resolve_roles(self, auth: AuthTuple) -> UserRoles:
    jwt_claims = self._get_claims(auth)
    return {
        role
        for rule in self.role_rules
        for role in self.evaluate_role_rules(rule, jwt_claims)
    }

Since there is no guest-token branch in this class (and no reference to NO_USER_TOKEN), the suggested diff cannot be applied as written. Please ignore the original comment or update it against the current implementation of claim extraction.

Likely an incorrect or invalid review comment.

src/auth/interface.py (1)

12-13: Imports of default guest constants look good.

src/auth/jwk_token.py (2)

22-22: Updated imports match the new return type and guest tuple usage.


123-129: Add debug log for missing Authorization header

  • Verified via ripgrep that every await dependency(...) call unpacks three values (no two-variable unpacking found), so no downstream changes are required.
  • Apply the following diff to emit a debug message when returning the guest tuple:
--- a/src/auth/jwk_token.py
+++ b/src/auth/jwk_token.py
@@ async def __call__(self, request: Request) -> AuthTuple:
-        if not request.headers.get("Authorization"):
-            return NO_AUTH_TUPLE
+        if not request.headers.get("Authorization"):
+            logger.debug("No Authorization header; returning guest auth tuple (NO_AUTH_TUPLE)")
+            return NO_AUTH_TUPLE
tests/unit/auth/test_jwk_token.py (1)

15-15: Constants import aligns tests with the new guest semantics.

Copy link
Contributor

@tisnik tisnik left a comment

Choose a reason for hiding this comment

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

LGTM

@tisnik tisnik merged commit 3e2d883 into lightspeed-core:main Aug 27, 2025
19 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.

2 participants