Skip to content

🧪 Add tests for GitHubOAuthDeviceFlowGateway - #55

Open
SayanthRock wants to merge 1 commit into
mainfrom
test-github-oauth-device-flow-17999001400602125602
Open

🧪 Add tests for GitHubOAuthDeviceFlowGateway#55
SayanthRock wants to merge 1 commit into
mainfrom
test-github-oauth-device-flow-17999001400602125602

Conversation

@SayanthRock

@SayanthRock SayanthRock commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

User description

🎯 What: The requestAuthorization function in GitHubOAuthDeviceFlowGateway was completely untested. This patch adds a comprehensive test suite for it using MockWebServer.

📊 Coverage: The following scenarios are now tested:

  • Happy path: Successful response parsing into DeviceAuthorization.
  • Edge case: Calling with an empty client ID (throws IllegalArgumentException).
  • Error condition: Handling HTTP error responses (e.g., 401 Unauthorized, throws GitHubOAuthException).
  • Error condition: Handling completely empty HTTP responses (throws GitHubOAuthException).
  • Error condition: Handling missing required JSON fields in the response (throws GitHubOAuthException).

Result: The core authorization flow request is now fully covered, ensuring network parsing, error mapping, and validation logic work as expected. Test coverage for core-network has significantly improved.


PR created automatically by Jules for task 17999001400602125602 started by @SayanthRock


CodeAnt-AI Description

Verify GitHub OAuth device authorization behavior across successful and failure scenarios

What Changed

  • Tests successful authorization response parsing, request method, and client ID submission
  • Verifies empty client IDs are rejected with a clear validation error
  • Verifies HTTP errors, empty responses, and missing required fields produce the expected OAuth errors

Impact

✅ Reliable device authorization response handling
✅ Clear errors for invalid OAuth requests
✅ Safer handling of GitHub API failures

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Co-authored-by: SayanthRock <202829406+SayanthRock@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@codeant-ai

codeant-ai Bot commented Jul 27, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR ef99a66 Jul 27, 2026 · 11:11 11:12

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@SayanthRock, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3503f5dc-ac02-4e85-8cb7-2f93f909f919

📥 Commits

Reviewing files that changed from the base of the PR and between 58cd675 and ef99a66.

📒 Files selected for processing (2)
  • core-network/src/main/java/com/sayanthrock/rockreleasehub/core/network/auth/GitHubOAuthDeviceFlow.kt
  • core-network/src/test/java/com/sayanthrock/rockreleasehub/core/network/auth/GitHubOAuthDeviceFlowGatewayTest.kt
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test-github-oauth-device-flow-17999001400602125602

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

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Jul 27, 2026

@ai-coding-guardrails ai-coding-guardrails Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I've got 2 comments for you to consider

Risk: 🟢 Low

Risk analysis

The highest scoring dimensions are operational_risk and blast_radius. operational_risk is elevated due to the introduction of shared mutable state in a singleton class by changing companion object fields from const val to var, which can lead to flaky tests or unexpected behavior if not properly managed. blast_radius is non-zero because the change affects a shared component used in authentication flows, potentially impacting any feature relying on GitHub OAuth device flow. Other dimensions score low as there are no direct security concerns, data integrity issues, or major test coverage gaps introduced by this diff.

Did you know we can integrate this feedback directly into 50+ IDEs? Get setup in just one command

Comment on lines +225 to +227
internal companion object {
var DEVICE_CODE_URL = "https://github.com/login/device/code"
var ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Mutable companion object vars expose production URL state to mutation, risking test pollution and thread-safety issues in production.

Changing DEVICE_CODE_URL and ACCESS_TOKEN_URL from const val to var in a @Singleton class introduces shared mutable state. If tests run in parallel or a test fails before tearDown, the URLs will remain overwritten, potentially affecting other tests or even production behavior if the singleton is reused across test boundaries.

A safer approach for testability would be to inject the base URL (or an OkHttpClient/HttpURLConnection factory) via the constructor, keeping the production constants immutable.

Why did I show this?

Category: bug
Comment Quality: high

Based on general best practices

Comment on lines +30 to +35
originalDeviceCodeUrl = GitHubOAuthDeviceFlowGateway.DEVICE_CODE_URL
originalAccessTokenUrl = GitHubOAuthDeviceFlowGateway.ACCESS_TOKEN_URL

// Reassign the URLs to the mock server
GitHubOAuthDeviceFlowGateway.DEVICE_CODE_URL = mockWebServer.url("/login/device/code").toString()
GitHubOAuthDeviceFlowGateway.ACCESS_TOKEN_URL = mockWebServer.url("/login/oauth/access_token").toString()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Mutable static state mutation in tests is not thread-safe and can leak between parallel test runs

The companion object URLs (DEVICE_CODE_URL, ACCESS_TOKEN_URL) are var fields on a shared companion object. Mutating them in @Before/@After is not thread-safe if tests ever run in parallel, and a test failure before tearDown (e.g., an uncaught exception outside the coroutine) could leave the URLs pointing at a stopped MockWebServer, corrupting subsequent tests. Consider using a try/finally in setUp or restructuring to avoid shared mutable static state for test configuration.

Why did I show this?

Category: bug
Comment Quality: high

Based on general best practices

@ai-coding-guardrails ai-coding-guardrails Bot added the zenable/risk:low Zenable assessed this PR as LOW risk. label Jul 27, 2026
Comment on lines +225 to +227
internal companion object {
var DEVICE_CODE_URL = "https://github.com/login/device/code"
var ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The endpoint values are process-global mutable state, while this class is a singleton and requests read these properties asynchronously. The test temporarily redirects them to its MockWebServer, so concurrent tests or in-process OAuth calls can be routed to the wrong server or to a URL that has already been shut down. Inject endpoint URLs into the gateway instance instead of mutating companion-object properties. [race condition]

Severity Level: Major ⚠️
- ❌ Concurrent tests can route requests to another MockWebServer.
- ⚠️ In-flight OAuth calls can use shut-down test endpoints.
- ⚠️ Singleton requests share mutable endpoint configuration.
Steps of Reproduction ✅
1. The production singleton is bound through `AuthNetworkModule.kt:15-17` to
`GitHubOAuthDeviceFlowGateway`, so its requests share the companion-object endpoint
variables at `GitHubOAuthDeviceFlow.kt:225-227`.

2. Start `GitHubOAuthDeviceFlowGatewayTest` from
`core-network/src/test/java/com/sayanthrock/rockreleasehub/core/network/auth/GitHubOAuthDeviceFlowGatewayTest.kt`;
`setUp()` globally replaces `DEVICE_CODE_URL` and `ACCESS_TOKEN_URL` at lines 30-35.

3. While `requestAuthorization()` is suspended in `withContext(Dispatchers.IO)` and before
it reads `DEVICE_CODE_URL` at `GitHubOAuthDeviceFlow.kt:36-41`, another test or in-process
gateway call changes the same companion property.

4. The first request then uses the other test's MockWebServer URL, or reads a URL after
that server is shut down by `tearDown()` at test lines 40-44, producing a connection
failure or consuming the wrong queued response. Injecting immutable endpoint values into
each gateway instance removes this shared-state race.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** core-network/src/main/java/com/sayanthrock/rockreleasehub/core/network/auth/GitHubOAuthDeviceFlow.kt
**Line:** 225:227
**Comment:**
	*Race Condition: The endpoint values are process-global mutable state, while this class is a singleton and requests read these properties asynchronously. The test temporarily redirects them to its MockWebServer, so concurrent tests or in-process OAuth calls can be routed to the wrong server or to a URL that has already been shut down. Inject endpoint URLs into the gateway instance instead of mutating companion-object properties.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +76 to +78
val request = mockWebServer.takeRequest()
assertEquals("POST", request.method)
assertTrue(request.body.readUtf8().contains("client_id=valid_client_id"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The test never verifies the request path, and MockWebServer dequeues the same response for any path. Consequently, a regression that sends the authorization request to the access-token endpoint or another incorrect path will still pass this test. Assert that the captured request uses the expected device-code path. [api mismatch]

Severity Level: Major ⚠️
- ⚠️ Authorization endpoint regressions remain undetected.
- ⚠️ Tests may accept access-token path mistakes.
- ⚠️ Mock responses do not validate GitHub route selection.
Steps of Reproduction ✅
1. The happy-path test configures the expected device-code URL as `/login/device/code` at
`GitHubOAuthDeviceFlowGatewayTest.kt:34`, then enqueues one response at lines 60-64.

2. `gateway.requestAuthorization("valid_client_id")` reaches
`GitHubOAuthDeviceFlow.kt:40-45`, which should use `DEVICE_CODE_URL`; the test captures
the request at test line 76.

3. Because `MockWebServer` returns the queued response regardless of request path,
changing the implementation to use `ACCESS_TOKEN_URL` from `GitHubOAuthDeviceFlow.kt:72`
or another path would still return the same successful JSON.

4. The assertions at test lines 77-78 verify only `POST` and the form body, so the test
passes without checking `/login/device/code`; asserting `request.path` catches this API
endpoint regression.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** core-network/src/test/java/com/sayanthrock/rockreleasehub/core/network/auth/GitHubOAuthDeviceFlowGatewayTest.kt
**Line:** 76:78
**Comment:**
	*Api Mismatch: The test never verifies the request path, and MockWebServer dequeues the same response for any path. Consequently, a regression that sends the authorization request to the access-token endpoint or another incorrect path will still pass this test. Assert that the captured request uses the expected device-code path.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files zenable/risk:low Zenable assessed this PR as LOW risk.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant